text
stringlengths 54
60.6k
|
|---|
<commit_before>#pragma once
#include "render/target.hpp"
#include "gui/gui.hpp"
namespace ve
{
class render::Target;
class Gui;
class Window final
{
public:
// Construct the window.
Window();
// Destruct the window.
~Window();
// Returns the gui.
Ptr<Gui> getGui() const;
// Sets the function to be called when the user has requested to close the window.
void setCloseRequestedHandler(std::function<void()> closeRequestedHandler);
// Internal. Gets the SDL Window handle.
void * getSDLWindow() const;
// Internal. Called when the user clicks the close button on the window or equivalent shortcut.
void onCloseRequested();
// Internal. Called when the user resizes the window.
void onResized(Vector2i size);
// Internal. Called when the user moves the cursor within the window or out of the window.
void onCursorPositionChanged(std::optional<Vector2i> cursorPosition);
// Internal. Updates the window and the contained gui.
void update(float dt);
// Internal. Called to render the window.
void render() const;
private:
void * sdlWindow;
std::function<void()> closeRequestedHandler;
OwnPtr<render::WindowTarget> target;
std::optional<Vector2i> cursorPosition;
OwnPtr<Gui> gui;
};
}<commit_msg>Fixed Window comments<commit_after>#pragma once
#include "render/target.hpp"
#include "gui/gui.hpp"
namespace ve
{
class render::Target;
class Gui;
class Window final
{
public:
// Construct the window.
Window();
// Destruct the window.
~Window();
// Returns the gui.
Ptr<Gui> getGui() const;
// Sets the function to be called when the user has requested to close the window.
void setCloseRequestedHandler(std::function<void()> closeRequestedHandler);
// Called by App to get the SDL Window handle.
void * getSDLWindow() const;
// Called by App when the user clicks the close button on the window or equivalent shortcut.
void onCloseRequested();
// Called by App when the user resizes the window.
void onResized(Vector2i size);
// Called by App when the user moves the cursor within the window or out of the window.
void onCursorPositionChanged(std::optional<Vector2i> cursorPosition);
// Called by App to updates the window and the contained gui.
void update(float dt);
// Called by App to render the window. dt is the number of seconds left over since the last update, used for extrapolation into the next frame.
void render(float dt) const;
private:
void * sdlWindow;
std::function<void()> closeRequestedHandler;
OwnPtr<render::WindowTarget> target;
std::optional<Vector2i> cursorPosition;
OwnPtr<Gui> gui;
};
}<|endoftext|>
|
<commit_before>#include "word_db.hh"
#include "utils.hh"
#include "line_modification.hh"
#include "utf8_iterator.hh"
namespace Kakoune
{
UsedLetters used_letters(StringView str)
{
UsedLetters res;
for (auto c : str)
{
if (c >= 'a' and c <= 'z')
res.set(c - 'a');
else if (c >= 'A' and c <= 'Z')
res.set(c - 'A' + 26);
else if (c == '_')
res.set(53);
else if (c == '-')
res.set(54);
else
res.set(63);
}
return res;
}
static WordDB::WordList get_words(const SharedString& content)
{
WordDB::WordList res;
using Iterator = utf8::iterator<const char*, utf8::InvalidPolicy::Pass>;
const char* word_start = content.begin();
bool in_word = false;
for (Iterator it{word_start}, end{content.end()}; it != end; ++it)
{
Codepoint c = *it;
const bool word = is_word(c);
if (not in_word and word)
{
word_start = it.base();
in_word = true;
}
else if (in_word and not word)
{
const ByteCount start = word_start - content.begin();
const ByteCount length = it.base() - word_start;
res.push_back(content.acquire_substr(start, length));
in_word = false;
}
}
return res;
}
void WordDB::add_words(const WordList& words)
{
for (auto& w : words)
{
WordDB::WordInfo& info = m_words[intern(w)];
++info.refcount;
if (info.letters.none())
info.letters = used_letters(w);
}
}
void WordDB::remove_words(const WordList& words)
{
for (auto& w : words)
{
auto it = m_words.find({w, SharedString::NoCopy()});
kak_assert(it != m_words.end() and it->second.refcount > 0);
if (--it->second.refcount == 0)
m_words.erase(it);
}
}
WordDB::WordDB(const Buffer& buffer)
: m_buffer{&buffer}, m_timestamp{buffer.timestamp()}
{
m_lines.reserve((int)buffer.line_count());
for (auto line = 0_line, end = buffer.line_count(); line < end; ++line)
{
m_lines.push_back(buffer.line_storage(line));
add_words(get_words(SharedString{m_lines.back()}));
}
}
void WordDB::update_db()
{
auto& buffer = *m_buffer;
auto modifs = compute_line_modifications(buffer, m_timestamp);
m_timestamp = buffer.timestamp();
if (modifs.empty())
return;
Lines new_lines;
new_lines.reserve((int)buffer.line_count());
auto old_line = 0_line;
for (auto& modif : modifs)
{
kak_assert(0_line <= modif.new_line and modif.new_line < buffer.line_count());
kak_assert(old_line <= modif.old_line);
while (old_line < modif.old_line)
new_lines.push_back(std::move(m_lines[(int)old_line++]));
kak_assert((int)new_lines.size() == (int)modif.new_line);
while (old_line < modif.old_line + modif.num_removed)
{
kak_assert(old_line < m_lines.size());
remove_words(get_words(SharedString{m_lines[(int)old_line++]}));
}
for (auto l = 0_line; l < modif.num_added; ++l)
{
if (modif.new_line + l >= buffer.line_count())
break;
new_lines.push_back(buffer.line_storage(modif.new_line + l));
add_words(get_words(SharedString{new_lines.back()}));
}
}
while (old_line != (int)m_lines.size())
new_lines.push_back(std::move(m_lines[(int)old_line++]));
m_lines = std::move(new_lines);
}
int WordDB::get_word_occurences(StringView word) const
{
auto it = m_words.find({word, SharedString::NoCopy()});
if (it != m_words.end())
return it->second.refcount;
return 0;
}
}
<commit_msg>Fix too strict assert and unneeded (lets hope) check<commit_after>#include "word_db.hh"
#include "utils.hh"
#include "line_modification.hh"
#include "utf8_iterator.hh"
namespace Kakoune
{
UsedLetters used_letters(StringView str)
{
UsedLetters res;
for (auto c : str)
{
if (c >= 'a' and c <= 'z')
res.set(c - 'a');
else if (c >= 'A' and c <= 'Z')
res.set(c - 'A' + 26);
else if (c == '_')
res.set(53);
else if (c == '-')
res.set(54);
else
res.set(63);
}
return res;
}
static WordDB::WordList get_words(const SharedString& content)
{
WordDB::WordList res;
using Iterator = utf8::iterator<const char*, utf8::InvalidPolicy::Pass>;
const char* word_start = content.begin();
bool in_word = false;
for (Iterator it{word_start}, end{content.end()}; it != end; ++it)
{
Codepoint c = *it;
const bool word = is_word(c);
if (not in_word and word)
{
word_start = it.base();
in_word = true;
}
else if (in_word and not word)
{
const ByteCount start = word_start - content.begin();
const ByteCount length = it.base() - word_start;
res.push_back(content.acquire_substr(start, length));
in_word = false;
}
}
return res;
}
void WordDB::add_words(const WordList& words)
{
for (auto& w : words)
{
WordDB::WordInfo& info = m_words[intern(w)];
++info.refcount;
if (info.letters.none())
info.letters = used_letters(w);
}
}
void WordDB::remove_words(const WordList& words)
{
for (auto& w : words)
{
auto it = m_words.find({w, SharedString::NoCopy()});
kak_assert(it != m_words.end() and it->second.refcount > 0);
if (--it->second.refcount == 0)
m_words.erase(it);
}
}
WordDB::WordDB(const Buffer& buffer)
: m_buffer{&buffer}, m_timestamp{buffer.timestamp()}
{
m_lines.reserve((int)buffer.line_count());
for (auto line = 0_line, end = buffer.line_count(); line < end; ++line)
{
m_lines.push_back(buffer.line_storage(line));
add_words(get_words(SharedString{m_lines.back()}));
}
}
void WordDB::update_db()
{
auto& buffer = *m_buffer;
auto modifs = compute_line_modifications(buffer, m_timestamp);
m_timestamp = buffer.timestamp();
if (modifs.empty())
return;
Lines new_lines;
new_lines.reserve((int)buffer.line_count());
auto old_line = 0_line;
for (auto& modif : modifs)
{
kak_assert(0_line <= modif.new_line and modif.new_line <= buffer.line_count());
kak_assert(modif.new_line < buffer.line_count() or modif.num_added == 0);
kak_assert(old_line <= modif.old_line);
while (old_line < modif.old_line)
new_lines.push_back(std::move(m_lines[(int)old_line++]));
kak_assert((int)new_lines.size() == (int)modif.new_line);
while (old_line < modif.old_line + modif.num_removed)
{
kak_assert(old_line < m_lines.size());
remove_words(get_words(SharedString{m_lines[(int)old_line++]}));
}
for (auto l = 0_line; l < modif.num_added; ++l)
{
new_lines.push_back(buffer.line_storage(modif.new_line + l));
add_words(get_words(SharedString{new_lines.back()}));
}
}
while (old_line != (int)m_lines.size())
new_lines.push_back(std::move(m_lines[(int)old_line++]));
m_lines = std::move(new_lines);
}
int WordDB::get_word_occurences(StringView word) const
{
auto it = m_words.find({word, SharedString::NoCopy()});
if (it != m_words.end())
return it->second.refcount;
return 0;
}
}
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#include <map>
#include <functional>
#include <experimental/optional>
#include "History.hpp"
#include "TerminalInfo.hpp"
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
// https://www.akkadia.org/drepper/tls.pdf
using namespace yb;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
thread_local History history;
thread_local History::const_iterator historyPos;
thread_local static char arrowIndicator = 0;
using ReadSignature = ssize_t (*)(int, void*, size_t);
using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
CharOpt newlineHandler(Char);
CharOpt tabHandler(Char);
CharOpt backspaceHandler(Char);
CharOpt regularCHarHandler(Char);
CharOpt arrowHandler1(Char);
CharOpt arrowHandler2(Char);
CharOpt arrowHandler3(Char);
thread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {
{0x06, tabHandler},
{0x0d, newlineHandler},
{0x17, newlineHandler}, // TODO: this should delete one word
{0x1b, arrowHandler1},
{0x5b, arrowHandler2},
{0x43, arrowHandler3},
{0x7f, backspaceHandler}
};
void clearTerminalLine() {
int pos, width;
if (!(pos = TerminalInfo::getCursorPosition())) return;
width = TerminalInfo::getWidth();
for (int i = 0; i < width - pos; i++)
printf(" ");
for (int i = 0; i < width - pos; i++)
cursor_backward(1);
fflush(stdout);
}
std::string findCompletion(History::const_iterator start, const std::string &pattern) {
for (auto it = start; it != history.end(); it++) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.begin();
return pattern;
}
void printCompletion(History::const_iterator startIterator, int offset) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
if (completion == pattern) return;
clearTerminalLine();
if (offset)
cursor_forward(offset);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + offset);
fflush(stdout);
}
CharOpt newlineHandler(Char) {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
return {};
}
CharOpt backspaceHandler(Char) {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
return {};
}
CharOpt regularCharHandler(Char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.begin(), 1);
return {};
}
CharOpt tabHandler(Char) {
printCompletion(std::next(historyPos, 1), 0);
return Char{0}; // TODO: this does not seem to work.
}
CharOpt arrowHandler1(Char) {
arrowIndicator = 1;
return {};
}
CharOpt arrowHandler2(Char c) {
if (arrowIndicator == 1) {
arrowIndicator = 2;
return {};
}
else {
return regularCharHandler(c);
}
}
CharOpt arrowHandler3(Char c) {
CharOpt return_value = {};
if (arrowIndicator == 2) {
arrowIndicator = 0;
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
}
else {
return_value = regularCharHandler(c);
}
return return_value;
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
history.read(std::string{getenv("HOME")} + "/.bash_history");
auto handler = handlers[c];
// TODO(Mrokkk): There would be a problem with processing all escape codes
// that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).
// It would be thoughtful if we just disable our yebash if any of these codes would
// occur and reenable it after a newline
CharOpt cReturned;
if (handler) {
cReturned = handler(c);
}
else {
if (c < 0x20) {
newlineHandler(c);
}
else {
regularCharHandler(c);
}
}
return cReturned.value_or(c);
}
static inline bool is_terminal_input(int fd) {
return isatty(fd);
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (is_terminal_input(fd)) { // TODO: make it look good
if (printBuffer.length()) {
// Return printBuffer to bash one char at time
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos++ = *printBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (is_terminal_input(fd))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<commit_msg>Make findCompletion return value optional<commit_after>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#include <map>
#include <functional>
#include <experimental/optional>
#include "History.hpp"
#include "TerminalInfo.hpp"
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
// https://www.akkadia.org/drepper/tls.pdf
using namespace yb;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
thread_local History history;
thread_local History::const_iterator historyPos;
thread_local static char arrowIndicator = 0;
using ReadSignature = ssize_t (*)(int, void*, size_t);
using Char = unsigned char;
using CharOpt = std::experimental::optional<Char>;
using StringOpt = std::experimental::optional<std::string>;
CharOpt newlineHandler(Char);
CharOpt tabHandler(Char);
CharOpt backspaceHandler(Char);
CharOpt regularCHarHandler(Char);
CharOpt arrowHandler1(Char);
CharOpt arrowHandler2(Char);
CharOpt arrowHandler3(Char);
thread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {
{0x06, tabHandler},
{0x0d, newlineHandler},
{0x17, newlineHandler}, // TODO: this should delete one word
{0x1b, arrowHandler1},
{0x5b, arrowHandler2},
{0x43, arrowHandler3},
{0x7f, backspaceHandler}
};
void clearTerminalLine() {
int pos, width;
if (!(pos = TerminalInfo::getCursorPosition())) return;
width = TerminalInfo::getWidth();
for (int i = 0; i < width - pos; i++)
printf(" ");
for (int i = 0; i < width - pos; i++)
cursor_backward(1);
fflush(stdout);
}
StringOpt findCompletion(History::const_iterator start, const std::string &pattern) {
for (auto it = start; it != history.end(); it++) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.begin();
return {};
}
void printCompletion(History::const_iterator startIterator, int offset) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
if (!completion) return;
clearTerminalLine();
if (offset)
cursor_forward(offset);
printf("\e[1;30m%s\e[0m", completion.value().c_str() + pattern.length());
cursor_backward(completion.value().length() - pattern.length() + offset);
fflush(stdout);
}
CharOpt newlineHandler(Char) {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
return {};
}
CharOpt backspaceHandler(Char) {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
return {};
}
CharOpt regularCharHandler(Char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.begin(), 1);
return {};
}
CharOpt tabHandler(Char) {
printCompletion(std::next(historyPos, 1), 0);
return Char{0}; // TODO: this does not seem to work.
}
CharOpt arrowHandler1(Char) {
arrowIndicator = 1;
return {};
}
CharOpt arrowHandler2(Char c) {
if (arrowIndicator == 1) {
arrowIndicator = 2;
return {};
}
else {
return regularCharHandler(c);
}
}
CharOpt arrowHandler3(Char c) {
CharOpt return_value = {};
if (arrowIndicator == 2) {
arrowIndicator = 0;
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
}
else {
return_value = regularCharHandler(c);
}
return return_value;
}
static unsigned char yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
history.read(std::string{getenv("HOME")} + "/.bash_history");
auto handler = handlers[c];
// TODO(Mrokkk): There would be a problem with processing all escape codes
// that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).
// It would be thoughtful if we just disable our yebash if any of these codes would
// occur and reenable it after a newline
CharOpt cReturned;
if (handler) {
cReturned = handler(c);
}
else {
if (c < 0x20) {
newlineHandler(c);
}
else {
regularCharHandler(c);
}
}
return cReturned.value_or(c);
}
static inline bool is_terminal_input(int fd) {
return isatty(fd);
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (is_terminal_input(fd)) { // TODO: make it look good
if (printBuffer.length()) {
// Return printBuffer to bash one char at time
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos++ = *printBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (is_terminal_input(fd))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<|endoftext|>
|
<commit_before>/*
* IceWM - C++ wrapper for locale/unicode conversion
* Copyright (C) 2001 The Authors of IceWM
*
* Released under terms of the GNU Library General Public License
*
* 2001/07/21: Mathias Hasselmann <mathias.hasselmann@gmx.net>
* - initial revision
*/
#include "config.h"
#include "ylocale.h"
#include "base.h"
#include "intl.h"
#include <string.h>
#ifdef CONFIG_I18N
#include <errno.h>
#include <langinfo.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
#include <assert.h>
#endif
#include "ylib.h"
#include "yprefs.h"
#ifdef CONFIG_I18N
YLocale * YLocale::instance(NULL);
#endif
#ifndef CONFIG_I18N
YLocale::YLocale(char const * ) {
#else
YLocale::YLocale(char const * localeName) {
assert(NULL == instance);
instance = this;
if (NULL == (fLocaleName = setlocale(LC_ALL, localeName))
/* || False == XSupportsLocale()*/) {
warn(_("Locale not supported by C library. "
"Falling back to 'C' locale'."));
fLocaleName = setlocale(LC_ALL, "C");
}
#ifndef NO_CONFIGURE
multiByte = true;
#endif
char const * codeset = NULL;
int const codesetItems[] = {
#ifdef CONFIG_NL_CODESETS
CONFIG_NL_CODESETS
#else
CODESET, _NL_CTYPE_CODESET_NAME, 0
#endif
};
for (unsigned int i = 0;
i + 1 < ACOUNT(codesetItems)
&& NULL != (codeset = nl_langinfo(codesetItems[i]))
&& '\0' == *codeset;
++i) {}
if (NULL == codeset || '\0' == *codeset) {
warn(_("Failed to determinate the current locale's codeset. "
"Assuming ISO-8859-1.\n"));
codeset = "ISO-8859-1";
}
union { int i; char c[sizeof(int)]; } endian; endian.i = 1;
MSG(("locale: %s, MB_CUR_MAX: %zd, "
"multibyte: %d, codeset: %s, endian: %c",
fLocaleName, MB_CUR_MAX, multiByte, codeset, *endian.c ? 'l' : 'b'));
/// TODO #warning "this is getting way too complicated"
char const * unicodeCharsets[] = {
#ifdef CONFIG_UNICODE_SET
CONFIG_UNICODE_SET,
#endif
// "WCHAR_T//TRANSLIT",
(*endian.c ? "UCS-4LE//TRANSLIT" : "UCS-4BE//TRANSLIT"),
// "WCHAR_T",
(*endian.c ? "UCS-4LE" : "UCS-4BE"),
"UCS-4//TRANSLIT",
"UCS-4",
NULL
};
char const * localeCharsets[] = {
cstrJoin(codeset, "//TRANSLIT", NULL), codeset, NULL
};
char const ** ucs(unicodeCharsets);
if ((iconv_t) -1 == (toUnicode = getConverter (localeCharsets[1], ucs)))
die(1, _("iconv doesn't supply (sufficient) "
"%s to %s converters."), localeCharsets[1], "Unicode");
MSG(("toUnicode converts from %s to %s", localeCharsets[1], *ucs));
char const ** lcs(localeCharsets);
if ((iconv_t) -1 == (toLocale = getConverter (*ucs, lcs)))
die(1, _("iconv doesn't supply (sufficient) "
"%s to %s converters."), "Unicode", localeCharsets[1]);
MSG(("toLocale converts from %s to %s", *ucs, *lcs));
delete[] localeCharsets[0];
#endif
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
}
YLocale::~YLocale() {
#ifdef CONFIG_I18N
instance = NULL;
if ((iconv_t) -1 != toUnicode) iconv_close(toUnicode);
if ((iconv_t) -1 != toLocale) iconv_close(toLocale);
#endif
}
#ifdef CONFIG_I18N
iconv_t YLocale::getConverter (const char *from, const char **&to) {
iconv_t cd = (iconv_t) -1;
while (NULL != *to)
if ((iconv_t) -1 != (cd = iconv_open(*to, from))) return cd;
else ++to;
return (iconv_t) -1;
}
/*
YLChar * YLocale::localeString(YUChar const * uStr) {
YLChar * lStr(NULL);
return lStr;
}
*/
YUChar *YLocale::unicodeString(const YLChar *lStr, size_t const lLen,
size_t & uLen)
{
PRECONDITION(instance != NULL);
if (NULL == lStr)
return NULL;
YUChar * uStr(new YUChar[lLen + 1]);
char * inbuf((char *) lStr), * outbuf((char *) uStr);
size_t inlen(lLen), outlen(4 * lLen);
if (0 > (int) iconv(instance->toUnicode, &inbuf, &inlen, &outbuf, &outlen))
warn(_("Invalid multibyte string \"%s\": %s"), lStr, strerror(errno));
*((YUChar *) outbuf) = 0;
uLen = ((YUChar *) outbuf) - uStr;
return uStr;
}
#endif
const char *YLocale::getLocaleName() {
#ifdef CONFIG_I18N
return instance->fLocaleName;
#else
return "C";
#endif
}
int YLocale::getRating(const char *localeStr) {
const char *s1 = getLocaleName();
const char *s2 = localeStr;
while (*s1 && *s1++ == *s2++) {}
if (*s1) while (--s2 > localeStr && !strchr("_@.", *s2)) {}
return s2 - localeStr;
}
<commit_msg>make sure X supports locale from start<commit_after>/*
* IceWM - C++ wrapper for locale/unicode conversion
* Copyright (C) 2001 The Authors of IceWM
*
* Released under terms of the GNU Library General Public License
*
* 2001/07/21: Mathias Hasselmann <mathias.hasselmann@gmx.net>
* - initial revision
*/
#include "config.h"
#include "ylocale.h"
#include "base.h"
#include "intl.h"
#include <string.h>
#ifdef CONFIG_I18N
#include <errno.h>
#include <langinfo.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
#include <assert.h>
#endif
#include "ylib.h"
#include "yprefs.h"
#ifdef CONFIG_I18N
YLocale * YLocale::instance(NULL);
#endif
#ifndef CONFIG_I18N
YLocale::YLocale(char const * ) {
#else
YLocale::YLocale(char const * localeName) {
assert(NULL == instance);
instance = this;
if (NULL == (fLocaleName = setlocale(LC_ALL, localeName))
|| False == XSupportsLocale()) {
warn(_("Locale not supported by C library or Xlib. "
"Falling back to 'C' locale'."));
fLocaleName = setlocale(LC_ALL, "C");
}
#ifndef NO_CONFIGURE
multiByte = true;
#endif
char const * codeset = NULL;
int const codesetItems[] = {
#ifdef CONFIG_NL_CODESETS
CONFIG_NL_CODESETS
#else
CODESET, _NL_CTYPE_CODESET_NAME, 0
#endif
};
for (unsigned int i = 0;
i + 1 < ACOUNT(codesetItems)
&& NULL != (codeset = nl_langinfo(codesetItems[i]))
&& '\0' == *codeset;
++i) {}
if (NULL == codeset || '\0' == *codeset) {
warn(_("Failed to determinate the current locale's codeset. "
"Assuming ISO-8859-1.\n"));
codeset = "ISO-8859-1";
}
union { int i; char c[sizeof(int)]; } endian; endian.i = 1;
MSG(("locale: %s, MB_CUR_MAX: %zd, "
"multibyte: %d, codeset: %s, endian: %c",
fLocaleName, MB_CUR_MAX, multiByte, codeset, *endian.c ? 'l' : 'b'));
/// TODO #warning "this is getting way too complicated"
char const * unicodeCharsets[] = {
#ifdef CONFIG_UNICODE_SET
CONFIG_UNICODE_SET,
#endif
// "WCHAR_T//TRANSLIT",
(*endian.c ? "UCS-4LE//TRANSLIT" : "UCS-4BE//TRANSLIT"),
// "WCHAR_T",
(*endian.c ? "UCS-4LE" : "UCS-4BE"),
"UCS-4//TRANSLIT",
"UCS-4",
NULL
};
char const * localeCharsets[] = {
cstrJoin(codeset, "//TRANSLIT", NULL), codeset, NULL
};
char const ** ucs(unicodeCharsets);
if ((iconv_t) -1 == (toUnicode = getConverter (localeCharsets[1], ucs)))
die(1, _("iconv doesn't supply (sufficient) "
"%s to %s converters."), localeCharsets[1], "Unicode");
MSG(("toUnicode converts from %s to %s", localeCharsets[1], *ucs));
char const ** lcs(localeCharsets);
if ((iconv_t) -1 == (toLocale = getConverter (*ucs, lcs)))
die(1, _("iconv doesn't supply (sufficient) "
"%s to %s converters."), "Unicode", localeCharsets[1]);
MSG(("toLocale converts from %s to %s", *ucs, *lcs));
delete[] localeCharsets[0];
#endif
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
}
YLocale::~YLocale() {
#ifdef CONFIG_I18N
instance = NULL;
if ((iconv_t) -1 != toUnicode) iconv_close(toUnicode);
if ((iconv_t) -1 != toLocale) iconv_close(toLocale);
#endif
}
#ifdef CONFIG_I18N
iconv_t YLocale::getConverter (const char *from, const char **&to) {
iconv_t cd = (iconv_t) -1;
while (NULL != *to)
if ((iconv_t) -1 != (cd = iconv_open(*to, from))) return cd;
else ++to;
return (iconv_t) -1;
}
/*
YLChar * YLocale::localeString(YUChar const * uStr) {
YLChar * lStr(NULL);
return lStr;
}
*/
YUChar *YLocale::unicodeString(const YLChar *lStr, size_t const lLen,
size_t & uLen)
{
PRECONDITION(instance != NULL);
if (NULL == lStr)
return NULL;
YUChar * uStr(new YUChar[lLen + 1]);
char * inbuf((char *) lStr), * outbuf((char *) uStr);
size_t inlen(lLen), outlen(4 * lLen);
if (0 > (int) iconv(instance->toUnicode, &inbuf, &inlen, &outbuf, &outlen))
warn(_("Invalid multibyte string \"%s\": %s"), lStr, strerror(errno));
*((YUChar *) outbuf) = 0;
uLen = ((YUChar *) outbuf) - uStr;
return uStr;
}
#endif
const char *YLocale::getLocaleName() {
#ifdef CONFIG_I18N
return instance->fLocaleName;
#else
return "C";
#endif
}
int YLocale::getRating(const char *localeStr) {
const char *s1 = getLocaleName();
const char *s2 = localeStr;
while (*s1 && *s1++ == *s2++) {}
if (*s1) while (--s2 > localeStr && !strchr("_@.", *s2)) {}
return s2 - localeStr;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: testresource.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2006-06-02 13:04:44 $
*
* 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 <smart/com/sun/star/registry/XImplementationRegistration.hxx>
#include <smart/com/sun/star/script/XInvocation.hxx>
#include <rtl/ustring.hxx>
#include <vos/dynload.hxx>
#include <vos/diagnose.hxx>
#include <usr/services.hxx>
#include <vcl/svapp.hxx>
using namespace rtl;
using namespace vos;
using namespace usr;
class MyApp : public Application
{
public:
void Main();
};
MyApp aMyApp;
// -----------------------------------------------------------------------
void MyApp::Main()
{
XMultiServiceFactoryRef xSMgr = createRegistryServiceManager();
registerUsrServices( xSMgr );
setProcessServiceManager( xSMgr );
XInterfaceRef x = xSMgr->createInstance( L"com.sun.star.registry.ImplementationRegistration" );
XImplementationRegistrationRef xReg( x, USR_QUERY );
sal_Char szBuf[1024];
ORealDynamicLoader::computeModuleName( "res", szBuf, 1024 );
UString aDllName( StringToOUString( szBuf, CHARSET_SYSTEM ) );
xReg->registerImplementation( L"com.sun.star.loader.SharedLibrary", aDllName, XSimpleRegistryRef() );
x = xSMgr->createInstance( L"com.sun.star.resource.VclStringResourceLoader" );
XInvocationRef xResLoader( x, USR_QUERY );
XIntrospectionAccessRef xIntrospection = xResLoader->getIntrospection();
UString aFileName( L"TestResource" );
UsrAny aVal;
aVal.setString( aFileName );
xResLoader->setValue( L"FileName", aVal );
Sequence< UsrAny > Args( 1 );
Sequence< INT16 > OutPos;
Sequence< UsrAny > OutArgs;
Args.getArray()[0].setINT32( 1000 );
BOOL b = xResLoader->invoke( L"hasString", Args, OutPos, OutArgs ).getBOOL();
VOS_ENSHURE( b, "hasString" );
UString aStr = xResLoader->invoke( L"getString", Args, OutPos, OutArgs ).getString();
VOS_ENSHURE( aStr == L"Hello", "getString" );
Args.getArray()[0].setINT32( 1001 );
b = xResLoader->invoke( L"hasString", Args, OutPos, OutArgs ).getBOOL();
VOS_ENSHURE( !b, "!hasString" );
xReg->revokeImplementation( aDllName, XSimpleRegistryRef() );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.46); FILE MERGED 2006/09/01 17:26:54 kaib 1.3.46.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: testresource.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-16 13:36:10 $
*
* 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_extensions.hxx"
#include <smart/com/sun/star/registry/XImplementationRegistration.hxx>
#include <smart/com/sun/star/script/XInvocation.hxx>
#include <rtl/ustring.hxx>
#include <vos/dynload.hxx>
#include <vos/diagnose.hxx>
#include <usr/services.hxx>
#include <vcl/svapp.hxx>
using namespace rtl;
using namespace vos;
using namespace usr;
class MyApp : public Application
{
public:
void Main();
};
MyApp aMyApp;
// -----------------------------------------------------------------------
void MyApp::Main()
{
XMultiServiceFactoryRef xSMgr = createRegistryServiceManager();
registerUsrServices( xSMgr );
setProcessServiceManager( xSMgr );
XInterfaceRef x = xSMgr->createInstance( L"com.sun.star.registry.ImplementationRegistration" );
XImplementationRegistrationRef xReg( x, USR_QUERY );
sal_Char szBuf[1024];
ORealDynamicLoader::computeModuleName( "res", szBuf, 1024 );
UString aDllName( StringToOUString( szBuf, CHARSET_SYSTEM ) );
xReg->registerImplementation( L"com.sun.star.loader.SharedLibrary", aDllName, XSimpleRegistryRef() );
x = xSMgr->createInstance( L"com.sun.star.resource.VclStringResourceLoader" );
XInvocationRef xResLoader( x, USR_QUERY );
XIntrospectionAccessRef xIntrospection = xResLoader->getIntrospection();
UString aFileName( L"TestResource" );
UsrAny aVal;
aVal.setString( aFileName );
xResLoader->setValue( L"FileName", aVal );
Sequence< UsrAny > Args( 1 );
Sequence< INT16 > OutPos;
Sequence< UsrAny > OutArgs;
Args.getArray()[0].setINT32( 1000 );
BOOL b = xResLoader->invoke( L"hasString", Args, OutPos, OutArgs ).getBOOL();
VOS_ENSHURE( b, "hasString" );
UString aStr = xResLoader->invoke( L"getString", Args, OutPos, OutArgs ).getString();
VOS_ENSHURE( aStr == L"Hello", "getString" );
Args.getArray()[0].setINT32( 1001 );
b = xResLoader->invoke( L"hasString", Args, OutPos, OutArgs ).getBOOL();
VOS_ENSHURE( !b, "!hasString" );
xReg->revokeImplementation( aDllName, XSimpleRegistryRef() );
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#735429 Logically dead code<commit_after><|endoftext|>
|
<commit_before>/**
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashGraph.
*
* 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 <signal.h>
#ifdef PROFILER
#include <google/profiler.h>
#endif
#include <vector>
#include "thread.h"
#include "io_interface.h"
#include "container.h"
#include "concurrency.h"
#include "vertex_index.h"
#include "graph_engine.h"
#include "graph_config.h"
edge_type traverse_edge = edge_type::OUT_EDGE;
class bfs_vertex: public compute_directed_vertex
{
enum {
VISITED,
};
atomic_flags<int> flags;
public:
bfs_vertex(vertex_id_t id): compute_directed_vertex(id) {
}
bool has_visited() const {
return flags.test_flag(VISITED);
}
bool set_visited(bool visited) {
if (visited)
return flags.set_flag(VISITED);
else
return flags.clear_flag(VISITED);
}
void run(vertex_program &prog) {
if (!has_visited()) {
directed_vertex_request req(get_id(), traverse_edge);
request_partial_vertices(&req, 1);
}
}
void run(vertex_program &prog, const page_vertex &vertex);
void run_on_message(vertex_program &prog, const vertex_message &msg) {
}
};
void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex)
{
assert(!has_visited());
set_visited(true);
int num_dests = vertex.get_num_edges(traverse_edge);
if (num_dests == 0)
return;
// We need to add the neighbors of the vertex to the queue of
// the next level.
#ifdef USE_ARRAY
stack_array<vertex_id_t, 1024> neighs(num_dests);
vertex.read_edges(traverse_edge, neighs.data(), num_dests);
prog.activate_vertices(neighs.data(), num_dests);
#else
edge_seq_iterator it = vertex.get_neigh_seq_it(traverse_edge, 0, num_dests);
prog.activate_vertices(it);
#endif
}
class count_vertex_query: public vertex_query
{
size_t num_visited;
public:
count_vertex_query() {
num_visited = 0;
}
virtual void run(graph_engine &graph, compute_vertex &v) {
bfs_vertex &bfs_v = (bfs_vertex &) v;
if (bfs_v.has_visited())
num_visited++;
}
virtual void merge(graph_engine &graph, vertex_query::ptr q) {
count_vertex_query *cvq = (count_vertex_query *) q.get();
num_visited += cvq->num_visited;
}
virtual ptr clone() {
return vertex_query::ptr(new count_vertex_query());
}
size_t get_num_visited() const {
return num_visited;
}
};
void int_handler(int sig_num)
{
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStop();
#endif
exit(0);
}
void print_usage()
{
fprintf(stderr,
"bfs [options] conf_file graph_file index_file start_vertex\n");
fprintf(stderr, "-c confs: add more configurations to the system\n");
fprintf(stderr, "-b: traverse with both in-edges and out-edges\n");
graph_conf.print_help();
params.print_help();
}
int main(int argc, char *argv[])
{
int opt;
std::string confs;
int num_opts = 0;
while ((opt = getopt(argc, argv, "c:b")) != -1) {
num_opts++;
switch (opt) {
case 'c':
confs = optarg;
num_opts++;
break;
case 'b':
traverse_edge = edge_type::BOTH_EDGES;
break;
default:
print_usage();
}
}
argv += 1 + num_opts;
argc -= 1 + num_opts;
if (argc < 4) {
print_usage();
exit(-1);
}
std::string conf_file = argv[0];
std::string graph_file = argv[1];
std::string index_file = argv[2];
vertex_id_t start_vertex = atoi(argv[3]);
config_map configs(conf_file);
configs.add_options(confs);
signal(SIGINT, int_handler);
graph_index::ptr index = NUMA_graph_index<bfs_vertex>::create(index_file);
graph_engine::ptr graph = graph_engine::create(graph_file, index, configs);
printf("BFS starts\n");
printf("prof_file: %s\n", graph_conf.get_prof_file().c_str());
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStart(graph_conf.get_prof_file().c_str());
#endif
struct timeval start, end;
gettimeofday(&start, NULL);
graph->start(&start_vertex, 1);
graph->wait4complete();
gettimeofday(&end, NULL);
vertex_query::ptr cvq(new count_vertex_query());
graph->query_on_all(cvq);
size_t num_visited = ((count_vertex_query *) cvq.get())->get_num_visited();
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStop();
#endif
printf("BFS from vertex %ld visits %ld vertices. It takes %f seconds\n",
(unsigned long) start_vertex, num_visited, time_diff(start, end));
}
<commit_msg>[Graph]: simplify bfs.<commit_after>/**
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashGraph.
*
* 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 <signal.h>
#ifdef PROFILER
#include <google/profiler.h>
#endif
#include <vector>
#include "thread.h"
#include "io_interface.h"
#include "container.h"
#include "concurrency.h"
#include "vertex_index.h"
#include "graph_engine.h"
#include "graph_config.h"
edge_type traverse_edge = edge_type::OUT_EDGE;
class bfs_vertex: public compute_directed_vertex
{
bool visited;
public:
bfs_vertex(vertex_id_t id): compute_directed_vertex(id) {
visited = false;
}
bool has_visited() const {
return visited;
}
bool set_visited(bool visited) {
this->visited = visited;
}
void run(vertex_program &prog) {
if (!has_visited()) {
directed_vertex_request req(get_id(), traverse_edge);
request_partial_vertices(&req, 1);
}
}
void run(vertex_program &prog, const page_vertex &vertex);
void run_on_message(vertex_program &prog, const vertex_message &msg) {
}
};
void bfs_vertex::run(vertex_program &prog, const page_vertex &vertex)
{
assert(!has_visited());
set_visited(true);
int num_dests = vertex.get_num_edges(traverse_edge);
if (num_dests == 0)
return;
// We need to add the neighbors of the vertex to the queue of
// the next level.
#ifdef USE_ARRAY
stack_array<vertex_id_t, 1024> neighs(num_dests);
vertex.read_edges(traverse_edge, neighs.data(), num_dests);
prog.activate_vertices(neighs.data(), num_dests);
#else
edge_seq_iterator it = vertex.get_neigh_seq_it(traverse_edge, 0, num_dests);
prog.activate_vertices(it);
#endif
}
class count_vertex_query: public vertex_query
{
size_t num_visited;
public:
count_vertex_query() {
num_visited = 0;
}
virtual void run(graph_engine &graph, compute_vertex &v) {
bfs_vertex &bfs_v = (bfs_vertex &) v;
if (bfs_v.has_visited())
num_visited++;
}
virtual void merge(graph_engine &graph, vertex_query::ptr q) {
count_vertex_query *cvq = (count_vertex_query *) q.get();
num_visited += cvq->num_visited;
}
virtual ptr clone() {
return vertex_query::ptr(new count_vertex_query());
}
size_t get_num_visited() const {
return num_visited;
}
};
void int_handler(int sig_num)
{
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStop();
#endif
exit(0);
}
void print_usage()
{
fprintf(stderr,
"bfs [options] conf_file graph_file index_file start_vertex\n");
fprintf(stderr, "-c confs: add more configurations to the system\n");
fprintf(stderr, "-b: traverse with both in-edges and out-edges\n");
graph_conf.print_help();
params.print_help();
}
int main(int argc, char *argv[])
{
int opt;
std::string confs;
int num_opts = 0;
while ((opt = getopt(argc, argv, "c:b")) != -1) {
num_opts++;
switch (opt) {
case 'c':
confs = optarg;
num_opts++;
break;
case 'b':
traverse_edge = edge_type::BOTH_EDGES;
break;
default:
print_usage();
}
}
argv += 1 + num_opts;
argc -= 1 + num_opts;
if (argc < 4) {
print_usage();
exit(-1);
}
std::string conf_file = argv[0];
std::string graph_file = argv[1];
std::string index_file = argv[2];
vertex_id_t start_vertex = atoi(argv[3]);
config_map configs(conf_file);
configs.add_options(confs);
signal(SIGINT, int_handler);
graph_index::ptr index = NUMA_graph_index<bfs_vertex>::create(index_file);
graph_engine::ptr graph = graph_engine::create(graph_file, index, configs);
printf("BFS starts\n");
printf("prof_file: %s\n", graph_conf.get_prof_file().c_str());
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStart(graph_conf.get_prof_file().c_str());
#endif
struct timeval start, end;
gettimeofday(&start, NULL);
graph->start(&start_vertex, 1);
graph->wait4complete();
gettimeofday(&end, NULL);
vertex_query::ptr cvq(new count_vertex_query());
graph->query_on_all(cvq);
size_t num_visited = ((count_vertex_query *) cvq.get())->get_num_visited();
#ifdef PROFILER
if (!graph_conf.get_prof_file().empty())
ProfilerStop();
#endif
printf("BFS from vertex %ld visits %ld vertices. It takes %f seconds\n",
(unsigned long) start_vertex, num_visited, time_diff(start, end));
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRandom.h"
namespace skiagm {
class EmptyPathGM : public GM {
public:
EmptyPathGM() {}
protected:
SkString onShortName() {
return SkString("emptypath");
}
SkISize onISize() { return SkISize::Make(600, 280); }
void drawEmpty(SkCanvas* canvas,
SkColor color,
const SkRect& clip,
SkPaint::Style style,
SkPath::FillType fill) {
SkPath path;
path.setFillType(fill);
SkPaint paint;
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&titlePaint);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Empty Paths Drawn Into Rectangle Clips With "
"Indicated Style and Fill";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
int i = 0;
canvas->save();
canvas->translate(10 * SK_Scalar1, 0);
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 == i % 4) {
canvas->restore();
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
canvas->save();
} else {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
++i;
SkColor color = rand.nextU();
color = 0xff000000 | color; // force solid
color = sk_tool_utils::color_to_565(color);
this->drawEmpty(canvas, color, rect,
gStyles[style].fStyle, gFills[fill].fFill);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&labelPaint);
labelPaint.setTextSize(12 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 15 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 28 * SK_Scalar1,
labelPaint);
}
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new EmptyPathGM; }
static GMRegistry reg(MyFactory);
}
<commit_msg>draw 3 moveTos followed by various others [moves, lines, closes]<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRandom.h"
namespace skiagm {
class EmptyPathGM : public GM {
public:
EmptyPathGM() {}
protected:
SkString onShortName() {
return SkString("emptypath");
}
SkISize onISize() { return SkISize::Make(600, 280); }
void drawEmpty(SkCanvas* canvas,
SkColor color,
const SkRect& clip,
SkPaint::Style style,
SkPath::FillType fill) {
SkPath path;
path.setFillType(fill);
SkPaint paint;
paint.setColor(color);
paint.setStyle(style);
canvas->save();
canvas->clipRect(clip);
canvas->drawPath(path, paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
struct FillAndName {
SkPath::FillType fFill;
const char* fName;
};
static const FillAndName gFills[] = {
{SkPath::kWinding_FillType, "Winding"},
{SkPath::kEvenOdd_FillType, "Even / Odd"},
{SkPath::kInverseWinding_FillType, "Inverse Winding"},
{SkPath::kInverseEvenOdd_FillType, "Inverse Even / Odd"},
};
struct StyleAndName {
SkPaint::Style fStyle;
const char* fName;
};
static const StyleAndName gStyles[] = {
{SkPaint::kFill_Style, "Fill"},
{SkPaint::kStroke_Style, "Stroke"},
{SkPaint::kStrokeAndFill_Style, "Stroke And Fill"},
};
SkPaint titlePaint;
titlePaint.setColor(SK_ColorBLACK);
titlePaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&titlePaint);
titlePaint.setTextSize(15 * SK_Scalar1);
const char title[] = "Empty Paths Drawn Into Rectangle Clips With "
"Indicated Style and Fill";
canvas->drawText(title, strlen(title),
20 * SK_Scalar1,
20 * SK_Scalar1,
titlePaint);
SkRandom rand;
SkRect rect = SkRect::MakeWH(100*SK_Scalar1, 30*SK_Scalar1);
int i = 0;
canvas->save();
canvas->translate(10 * SK_Scalar1, 0);
canvas->save();
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
if (0 == i % 4) {
canvas->restore();
canvas->translate(0, rect.height() + 40 * SK_Scalar1);
canvas->save();
} else {
canvas->translate(rect.width() + 40 * SK_Scalar1, 0);
}
++i;
SkColor color = rand.nextU();
color = 0xff000000 | color; // force solid
color = sk_tool_utils::color_to_565(color);
this->drawEmpty(canvas, color, rect,
gStyles[style].fStyle, gFills[fill].fFill);
SkPaint rectPaint;
rectPaint.setColor(SK_ColorBLACK);
rectPaint.setStyle(SkPaint::kStroke_Style);
rectPaint.setStrokeWidth(-1);
rectPaint.setAntiAlias(true);
canvas->drawRect(rect, rectPaint);
SkPaint labelPaint;
labelPaint.setColor(color);
labelPaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&labelPaint);
labelPaint.setTextSize(12 * SK_Scalar1);
canvas->drawText(gStyles[style].fName,
strlen(gStyles[style].fName),
0, rect.height() + 15 * SK_Scalar1,
labelPaint);
canvas->drawText(gFills[fill].fName,
strlen(gFills[fill].fName),
0, rect.height() + 28 * SK_Scalar1,
labelPaint);
}
}
canvas->restore();
canvas->restore();
}
private:
typedef GM INHERITED;
};
DEF_GM( return new EmptyPathGM; )
//////////////////////////////////////////////////////////////////////////////
static void make_path_move(SkPath* path, const SkPoint pts[3]) {
for (int i = 0; i < 3; ++i) {
path->moveTo(pts[i]);
}
}
static void make_path_move_close(SkPath* path, const SkPoint pts[3]) {
for (int i = 0; i < 3; ++i) {
path->moveTo(pts[i]);
path->close();
}
}
static void make_path_move_line(SkPath* path, const SkPoint pts[3]) {
for (int i = 0; i < 3; ++i) {
path->moveTo(pts[i]);
path->lineTo(pts[i]);
}
}
typedef void (*MakePathProc)(SkPath*, const SkPoint pts[3]);
static void make_path_move_mix(SkPath* path, const SkPoint pts[3]) {
path->moveTo(pts[0]);
path->moveTo(pts[1]); path->close();
path->moveTo(pts[2]); path->lineTo(pts[2]);
}
class EmptyStrokeGM : public GM {
SkPoint fPts[3];
public:
EmptyStrokeGM() {
fPts[0].set(40, 40);
fPts[1].set(80, 40);
fPts[2].set(120, 40);
}
protected:
SkString onShortName() {
return SkString("emptystroke");
}
SkISize onISize() override { return SkISize::Make(200, 240); }
void onDraw(SkCanvas* canvas) override {
const MakePathProc procs[] = {
make_path_move, // expect red red red
make_path_move_close, // expect black black black
make_path_move_line, // expect black black black
make_path_move_mix, // expect red black black,
};
SkPaint strokePaint;
strokePaint.setStyle(SkPaint::kStroke_Style);
strokePaint.setStrokeWidth(21);
strokePaint.setStrokeCap(SkPaint::kSquare_Cap);
SkPaint dotPaint;
dotPaint.setColor(SK_ColorRED);
strokePaint.setStyle(SkPaint::kStroke_Style);
dotPaint.setStrokeWidth(7);
for (size_t i = 0; i < SK_ARRAY_COUNT(procs); ++i) {
SkPath path;
procs[i](&path, fPts);
canvas->drawPoints(SkCanvas::kPoints_PointMode, 3, fPts, dotPaint);
canvas->drawPath(path, strokePaint);
canvas->translate(0, 40);
}
}
private:
typedef GM INHERITED;
};
DEF_GM( return new EmptyStrokeGM; )
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkGradientShader.h"
namespace skiagm {
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const SkScalar gPos0[] = { 0, SK_Scalar1 };
static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
static const SkScalar gPos2[] = {
0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 2, gColors, gPos0 },
{ 2, gColors, gPos1 },
{ 5, gColors, NULL },
{ 5, gColors, gPos2 }
};
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,
data.fCount, tm, mapper);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX, data.fColors,
data.fPos, data.fCount, tm, mapper);
}
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,
data.fPos, data.fCount, mapper);
}
static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointRadial(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm, mapper);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper);
static const GradMaker gGradMakers[] = {
MakeLinear, MakeRadial, MakeSweep, Make2Radial
};
///////////////////////////////////////////////////////////////////////////////
class GradientsGM : public GM {
public:
GradientsGM() {
this->setBGColor(0xFFDDDDDD);
}
protected:
SkString onShortName() {
return SkString("gradients");
}
virtual SkISize onISize() { return make_isize(640, 510); }
virtual void onDraw(SkCanvas* canvas) {
SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) }
};
SkShader::TileMode tm = SkShader::kClamp_TileMode;
SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) };
SkPaint paint;
paint.setAntiAlias(true);
canvas->translate(SkIntToScalar(20), SkIntToScalar(20));
for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) {
canvas->save();
for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) {
SkShader* shader = gGradMakers[j](pts, gGradData[i], tm, NULL);
paint.setShader(shader);
canvas->drawRect(r, paint);
shader->unref();
canvas->translate(0, SkIntToScalar(120));
}
canvas->restore();
canvas->translate(SkIntToScalar(120), 0);
}
}
private:
typedef GM INHERITED;
};
/*
Inspired by this <canvas> javascript, where we need to detect that we are not
solving a quadratic equation, but must instead solve a linear (since our X^2
coefficient is 0)
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150);
g.addColorStop(0, '#f00');
g.addColorStop(0.01, '#0f0');
g.addColorStop(0.99, '#0f0');
g.addColorStop(1, '#f00');
ctx.fillStyle = g;
ctx.fillRect(0, 0, 100, 50);
*/
class GradientsDegenrate2PointGM : public GM {
public:
GradientsDegenrate2PointGM() {}
protected:
SkString onShortName() {
return SkString("gradients_degenerate_2pt");
}
virtual SkISize onISize() { return make_isize(320, 320); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(SK_ColorBLUE);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED };
SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 };
SkPoint c0;
c0.iset(-80, 25);
SkScalar r0 = SkIntToScalar(70);
SkPoint c1;
c1.iset(0, 25);
SkScalar r1 = SkIntToScalar(150);
SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors,
pos, SK_ARRAY_COUNT(pos),
SkShader::kClamp_TileMode);
SkPaint paint;
paint.setShader(s)->unref();
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
/// Tests correctness of *optimized* codepaths in gradients.
class ClampedGradientsGM : public GM {
public:
ClampedGradientsGM() {}
protected:
SkString onShortName() { return SkString("clamped_gradients"); }
virtual SkISize onISize() { return make_isize(640, 510); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFFDDDDDD);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(300) };
SkPaint paint;
paint.setAntiAlias(true);
SkPoint center;
center.iset(0, 300);
canvas->translate(SkIntToScalar(20), SkIntToScalar(20));
SkShader* shader = SkGradientShader::CreateRadial(
SkPoint(center),
SkIntToScalar(200), gColors, NULL, 5,
SkShader::kClamp_TileMode, NULL);
paint.setShader(shader);
canvas->drawRect(r, paint);
shader->unref();
}
private:
typedef GM INHERITED;
};
/// Checks quality of large radial gradients, which may display
/// some banding.
class RadialGradientGM : public GM {
public:
RadialGradientGM() {}
protected:
SkString onShortName() { return SkString("radial_gradient"); }
virtual SkISize onISize() { return make_isize(1280, 1024); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFF000000);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkPaint paint;
paint.setDither(true);
SkPoint center;
center.set(SkIntToScalar(640), SkIntToScalar(512));
SkScalar radius = SkIntToScalar(640);
SkColor colors [3] = { 0x7f7f7f7f, 0x7f7f7f7f, 0xb2000000 };
SkScalar pos [3] = { 0.0, 0.35, 1.0 };
SkShader* shader =
SkGradientShader::CreateRadial(center, radius, colors,
pos, 3, SkShader::kClamp_TileMode);
paint.setShader(shader)->unref();
SkRect r = { 0, 0, SkIntToScalar(1280), SkIntToScalar(1024) };
canvas->drawRect(r, paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new GradientsGM; }
static GMRegistry reg(MyFactory);
static GM* MyFactory2(void*) { return new GradientsDegenrate2PointGM; }
static GMRegistry reg2(MyFactory2);
static GM* MyFactory3(void*) { return new ClampedGradientsGM; }
static GMRegistry reg3(MyFactory3);
static GM* MyFactory4(void*) { return new RadialGradientGM; }
static GMRegistry reg4(MyFactory4);
}
<commit_msg>Add missing SkFloatToScalar() calls to fix the build.<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkGradientShader.h"
namespace skiagm {
struct GradData {
int fCount;
const SkColor* fColors;
const SkScalar* fPos;
};
static const SkColor gColors[] = {
SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK
};
static const SkScalar gPos0[] = { 0, SK_Scalar1 };
static const SkScalar gPos1[] = { SK_Scalar1/4, SK_Scalar1*3/4 };
static const SkScalar gPos2[] = {
0, SK_Scalar1/8, SK_Scalar1/2, SK_Scalar1*7/8, SK_Scalar1
};
static const GradData gGradData[] = {
{ 2, gColors, NULL },
{ 2, gColors, gPos0 },
{ 2, gColors, gPos1 },
{ 5, gColors, NULL },
{ 5, gColors, gPos2 }
};
static SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,
data.fCount, tm, mapper);
}
static SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateRadial(center, center.fX, data.fColors,
data.fPos, data.fCount, tm, mapper);
}
static SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center;
center.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,
data.fPos, data.fCount, mapper);
}
static SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper) {
SkPoint center0, center1;
center0.set(SkScalarAve(pts[0].fX, pts[1].fX),
SkScalarAve(pts[0].fY, pts[1].fY));
center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)/5),
SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)/4));
return SkGradientShader::CreateTwoPointRadial(
center1, (pts[1].fX - pts[0].fX) / 7,
center0, (pts[1].fX - pts[0].fX) / 2,
data.fColors, data.fPos, data.fCount, tm, mapper);
}
typedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,
SkShader::TileMode tm, SkUnitMapper* mapper);
static const GradMaker gGradMakers[] = {
MakeLinear, MakeRadial, MakeSweep, Make2Radial
};
///////////////////////////////////////////////////////////////////////////////
class GradientsGM : public GM {
public:
GradientsGM() {
this->setBGColor(0xFFDDDDDD);
}
protected:
SkString onShortName() {
return SkString("gradients");
}
virtual SkISize onISize() { return make_isize(640, 510); }
virtual void onDraw(SkCanvas* canvas) {
SkPoint pts[2] = {
{ 0, 0 },
{ SkIntToScalar(100), SkIntToScalar(100) }
};
SkShader::TileMode tm = SkShader::kClamp_TileMode;
SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) };
SkPaint paint;
paint.setAntiAlias(true);
canvas->translate(SkIntToScalar(20), SkIntToScalar(20));
for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) {
canvas->save();
for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) {
SkShader* shader = gGradMakers[j](pts, gGradData[i], tm, NULL);
paint.setShader(shader);
canvas->drawRect(r, paint);
shader->unref();
canvas->translate(0, SkIntToScalar(120));
}
canvas->restore();
canvas->translate(SkIntToScalar(120), 0);
}
}
private:
typedef GM INHERITED;
};
/*
Inspired by this <canvas> javascript, where we need to detect that we are not
solving a quadratic equation, but must instead solve a linear (since our X^2
coefficient is 0)
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150);
g.addColorStop(0, '#f00');
g.addColorStop(0.01, '#0f0');
g.addColorStop(0.99, '#0f0');
g.addColorStop(1, '#f00');
ctx.fillStyle = g;
ctx.fillRect(0, 0, 100, 50);
*/
class GradientsDegenrate2PointGM : public GM {
public:
GradientsDegenrate2PointGM() {}
protected:
SkString onShortName() {
return SkString("gradients_degenerate_2pt");
}
virtual SkISize onISize() { return make_isize(320, 320); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(SK_ColorBLUE);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED };
SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 };
SkPoint c0;
c0.iset(-80, 25);
SkScalar r0 = SkIntToScalar(70);
SkPoint c1;
c1.iset(0, 25);
SkScalar r1 = SkIntToScalar(150);
SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors,
pos, SK_ARRAY_COUNT(pos),
SkShader::kClamp_TileMode);
SkPaint paint;
paint.setShader(s)->unref();
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
/// Tests correctness of *optimized* codepaths in gradients.
class ClampedGradientsGM : public GM {
public:
ClampedGradientsGM() {}
protected:
SkString onShortName() { return SkString("clamped_gradients"); }
virtual SkISize onISize() { return make_isize(640, 510); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFFDDDDDD);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(300) };
SkPaint paint;
paint.setAntiAlias(true);
SkPoint center;
center.iset(0, 300);
canvas->translate(SkIntToScalar(20), SkIntToScalar(20));
SkShader* shader = SkGradientShader::CreateRadial(
SkPoint(center),
SkIntToScalar(200), gColors, NULL, 5,
SkShader::kClamp_TileMode, NULL);
paint.setShader(shader);
canvas->drawRect(r, paint);
shader->unref();
}
private:
typedef GM INHERITED;
};
/// Checks quality of large radial gradients, which may display
/// some banding.
class RadialGradientGM : public GM {
public:
RadialGradientGM() {}
protected:
SkString onShortName() { return SkString("radial_gradient"); }
virtual SkISize onISize() { return make_isize(1280, 1024); }
void drawBG(SkCanvas* canvas) {
canvas->drawColor(0xFF000000);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkPaint paint;
paint.setDither(true);
SkPoint center;
center.set(SkIntToScalar(640), SkIntToScalar(512));
SkScalar radius = SkIntToScalar(640);
SkColor colors [3] = { 0x7f7f7f7f, 0x7f7f7f7f, 0xb2000000 };
SkScalar pos [3] = { SkFloatToScalar(0.0),
SkFloatToScalar(0.35),
SkFloatToScalar(1.0) };
SkShader* shader =
SkGradientShader::CreateRadial(center, radius, colors,
pos, 3, SkShader::kClamp_TileMode);
paint.setShader(shader)->unref();
SkRect r = { 0, 0, SkIntToScalar(1280), SkIntToScalar(1024) };
canvas->drawRect(r, paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new GradientsGM; }
static GMRegistry reg(MyFactory);
static GM* MyFactory2(void*) { return new GradientsDegenrate2PointGM; }
static GMRegistry reg2(MyFactory2);
static GM* MyFactory3(void*) { return new ClampedGradientsGM; }
static GMRegistry reg3(MyFactory3);
static GM* MyFactory4(void*) { return new RadialGradientGM; }
static GMRegistry reg4(MyFactory4);
}
<|endoftext|>
|
<commit_before>#include "ToolBase.h"
#include "NGSD.h"
#include "Exceptions.h"
#include "Helper.h"
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
}
virtual void setup()
{
setDescription("Imports Ensembl/CCDS transcript information into NGSD.");
addInfile("in", "Ensemble transcript file (download and unzip ftp://ftp.ensembl.org/pub/grch37/update/gff3/homo_sapiens/Homo_sapiens.GRCh37.87.gff3.gz).", false);
//optional
addFlag("all", "If set, all transcripts are imported (the default is to skip transcripts not labeled as with the 'GENCODE basic' tag).");
addFlag("test", "Uses the test database instead of on the production database.");
addFlag("force", "If set, overwrites old data.");
changeLog(2017, 7, 6, "Added first version");
}
QMap<QByteArray, QByteArray> parseAttributes(QByteArray attributes)
{
QMap<QByteArray, QByteArray> output;
QByteArrayList parts = attributes.split(';');
foreach(QByteArray part, parts)
{
int split_index = part.indexOf('=');
output[part.left(split_index)] = part.mid(split_index+1);
}
return output;
}
struct TranscriptData
{
QByteArray name;
QByteArray name_ccds;
QByteArray chr;
int start_coding = -1;
int end_coding = -1;
QByteArray strand;
BedFile exons;
int ngsd_gene_id;
};
int addTranscript(SqlQuery& query, int gene_id, QByteArray name, QByteArray source, const TranscriptData& t_data)
{
//TODO
QTextStream(stdout) << "Adding transcript name=" << name << " source=" << source << " gene=" << t_data.ngsd_gene_id << " start_coding=" << t_data.start_coding << " end_coding=" << t_data.end_coding << endl;
query.bindValue(0, gene_id);
query.bindValue(1, name);
query.bindValue(2, source);
query.bindValue(3, t_data.chr);
if (t_data.start_coding!=-1 && t_data.end_coding!=-1)
{
query.bindValue(4, t_data.start_coding);
query.bindValue(5, t_data.end_coding);
}
else
{
query.bindValue(4, QVariant());
query.bindValue(5, QVariant());
}
query.bindValue(6, t_data.strand);
query.exec();
return query.lastInsertId().toInt();
}
void addExons(SqlQuery& query, int transcript_id, const BedFile& exons)
{
//TODO
QTextStream(stdout) << " " << exons.count() << endl;
for (int i=0; i<exons.count(); ++i)
{
//out << " Adding exon start=" << exons[i].start() << " end=" <<exons[i].end() << endl;
query.bindValue(0, transcript_id);
query.bindValue(1, exons[i].start());
query.bindValue(2, exons[i].end());
query.exec();
}
}
virtual void main()
{
//init
NGSD db(getFlag("test"));
QTextStream out(stdout);
bool all = getFlag("all");
//check tables exist
db.tableExists("gene");
db.tableExists("gene_alias");
db.tableExists("gene_transcript");
db.tableExists("gene_exon");
//clear tables if not empty
if (!db.tableEmpty("gene_transcript") || !db.tableEmpty("gene_exon"))
{
if (getFlag("force"))
{
db.clearTable("gene_exon");
db.clearTable("gene_transcript");
}
else
{
THROW(DatabaseException, "Tables already contain data! Use '-force' to overwrite old data!");
}
}
//prepare queries
SqlQuery q_trans = db.getQuery();
q_trans.prepare("INSERT INTO gene_transcript (gene_id, name, source, chromosome, start_coding, end_coding, strand) VALUES (:0, :1, :2, :3, :4, :5, :6);");
SqlQuery q_exon = db.getQuery();
q_exon.prepare("INSERT INTO gene_exon (transcript_id, start, end) VALUES (:0, :1, :2);");
//parse input - format description at https://www.gencodegenes.org/data_format.html and http://www.ensembl.org/info/website/upload/gff3.html
QMap<QByteArray, int> gene_ensemble2ngsd;
QMap<QByteArray, TranscriptData> transcripts;
QSet<QByteArray> ccds_transcripts_added;
auto fp = Helper::openFileForReading(getInfile("in"));
while(!fp->atEnd())
{
QByteArray line = fp->readLine().trimmed();
if (line.isEmpty()) continue;
//section end => commit data
if (line=="###")
{
//import data
auto it = transcripts.begin();
while(it!=transcripts.end())
{
//add Ensembl transcript
TranscriptData& t_data = it.value();
int trans_id = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name , "ensembl", t_data);
//add exons
t_data.exons.merge();
addExons(q_exon, trans_id, t_data.exons);
//add CCDS transcript as well (only once)
if (t_data.name_ccds!="" && !ccds_transcripts_added.contains(t_data.name_ccds))
{
int trans_id_ccds = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name_ccds , "ccds", t_data);
//add exons (only coding part)
BedFile coding_part;
coding_part.append(BedLine(t_data.exons[0].chr() ,t_data.start_coding, t_data.end_coding));
t_data.exons.intersect(coding_part);
addExons(q_exon, trans_id_ccds, t_data.exons);
ccds_transcripts_added.insert(t_data.name_ccds);
}
++it;
}
//clear cache
gene_ensemble2ngsd.clear();
transcripts.clear();
continue;
}
//skip header lines
if (line.startsWith("#")) continue;
QByteArrayList parts = line.split('\t');
QByteArray type = parts[2];
QMap<QByteArray, QByteArray> data = parseAttributes(parts[8]);
//gene line
if (data.contains("gene_id"))
{
QByteArray gene = data["Name"];
//transform gene names to approved gene IDs
int ngsd_gene_id = db.geneToApprovedID(gene);
if (ngsd_gene_id==-1)
{
out << "ERROR " << data["gene_id"] << "/" << gene << ": no approved gene names found." << endl;
continue;
}
gene_ensemble2ngsd[data["ID"]] = ngsd_gene_id;
}
//transcript line
else if (data.contains("transcript_id"))
{
if (all || data.value("tag")=="basic")
{
TranscriptData tmp;
tmp.name = data["transcript_id"];
tmp.name_ccds = data.value("ccdsid", "");
tmp.chr = parts[0];
tmp.strand = parts[6];
tmp.ngsd_gene_id = gene_ensemble2ngsd[data["Parent"]];
transcripts[data["ID"]] = tmp;
}
}
//exon lines
else if (type=="CDS" || type=="exon" || type=="three_prime_UTR" || type=="five_prime_UTR" )
{
QByteArray parent_id = data["Parent"];
//skip exons of unhandled transcripts (not GENCODE basic)
if (!transcripts.contains(parent_id)) continue;
TranscriptData& t_data = transcripts[parent_id];
//check chromosome matches
QByteArray chr = parts[0];
if (chr!=t_data.chr)
{
THROW(FileParseException, "Chromosome mismach between transcript and exon!");
}
//update coding start/end
int start = Helper::toInt(parts[3], "start position");
int end = Helper::toInt(parts[4], "end position");
if (type=="CDS")
{
t_data.start_coding = (t_data.start_coding==-1) ? start : std::min(start, t_data.start_coding);
t_data.end_coding = (t_data.end_coding==-1) ? end : std::max(end, t_data.end_coding);
}
//add coding exon
t_data.exons.append(BedLine(chr, start, end));
}
}
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<commit_msg>removed accidentally committed debug output.<commit_after>#include "ToolBase.h"
#include "NGSD.h"
#include "Exceptions.h"
#include "Helper.h"
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
}
virtual void setup()
{
setDescription("Imports Ensembl/CCDS transcript information into NGSD.");
addInfile("in", "Ensemble transcript file (download and unzip ftp://ftp.ensembl.org/pub/grch37/update/gff3/homo_sapiens/Homo_sapiens.GRCh37.87.gff3.gz).", false);
//optional
addFlag("all", "If set, all transcripts are imported (the default is to skip transcripts not labeled as with the 'GENCODE basic' tag).");
addFlag("test", "Uses the test database instead of on the production database.");
addFlag("force", "If set, overwrites old data.");
changeLog(2017, 7, 6, "Added first version");
}
QMap<QByteArray, QByteArray> parseAttributes(QByteArray attributes)
{
QMap<QByteArray, QByteArray> output;
QByteArrayList parts = attributes.split(';');
foreach(QByteArray part, parts)
{
int split_index = part.indexOf('=');
output[part.left(split_index)] = part.mid(split_index+1);
}
return output;
}
struct TranscriptData
{
QByteArray name;
QByteArray name_ccds;
QByteArray chr;
int start_coding = -1;
int end_coding = -1;
QByteArray strand;
BedFile exons;
int ngsd_gene_id;
};
int addTranscript(SqlQuery& query, int gene_id, QByteArray name, QByteArray source, const TranscriptData& t_data)
{
//QTextStream(stdout) << "Adding transcript name=" << name << " source=" << source << " gene=" << t_data.ngsd_gene_id << " start_coding=" << t_data.start_coding << " end_coding=" << t_data.end_coding << endl;
query.bindValue(0, gene_id);
query.bindValue(1, name);
query.bindValue(2, source);
query.bindValue(3, t_data.chr);
if (t_data.start_coding!=-1 && t_data.end_coding!=-1)
{
query.bindValue(4, t_data.start_coding);
query.bindValue(5, t_data.end_coding);
}
else
{
query.bindValue(4, QVariant());
query.bindValue(5, QVariant());
}
query.bindValue(6, t_data.strand);
query.exec();
return query.lastInsertId().toInt();
}
void addExons(SqlQuery& query, int transcript_id, const BedFile& exons)
{
//QTextStream(stdout) << " " << exons.count() << endl;
for (int i=0; i<exons.count(); ++i)
{
//out << " Adding exon start=" << exons[i].start() << " end=" <<exons[i].end() << endl;
query.bindValue(0, transcript_id);
query.bindValue(1, exons[i].start());
query.bindValue(2, exons[i].end());
query.exec();
}
}
virtual void main()
{
//init
NGSD db(getFlag("test"));
QTextStream out(stdout);
bool all = getFlag("all");
//check tables exist
db.tableExists("gene");
db.tableExists("gene_alias");
db.tableExists("gene_transcript");
db.tableExists("gene_exon");
//clear tables if not empty
if (!db.tableEmpty("gene_transcript") || !db.tableEmpty("gene_exon"))
{
if (getFlag("force"))
{
db.clearTable("gene_exon");
db.clearTable("gene_transcript");
}
else
{
THROW(DatabaseException, "Tables already contain data! Use '-force' to overwrite old data!");
}
}
//prepare queries
SqlQuery q_trans = db.getQuery();
q_trans.prepare("INSERT INTO gene_transcript (gene_id, name, source, chromosome, start_coding, end_coding, strand) VALUES (:0, :1, :2, :3, :4, :5, :6);");
SqlQuery q_exon = db.getQuery();
q_exon.prepare("INSERT INTO gene_exon (transcript_id, start, end) VALUES (:0, :1, :2);");
//parse input - format description at https://www.gencodegenes.org/data_format.html and http://www.ensembl.org/info/website/upload/gff3.html
QMap<QByteArray, int> gene_ensemble2ngsd;
QMap<QByteArray, TranscriptData> transcripts;
QSet<QByteArray> ccds_transcripts_added;
auto fp = Helper::openFileForReading(getInfile("in"));
while(!fp->atEnd())
{
QByteArray line = fp->readLine().trimmed();
if (line.isEmpty()) continue;
//section end => commit data
if (line=="###")
{
//import data
auto it = transcripts.begin();
while(it!=transcripts.end())
{
//add Ensembl transcript
TranscriptData& t_data = it.value();
int trans_id = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name , "ensembl", t_data);
//add exons
t_data.exons.merge();
addExons(q_exon, trans_id, t_data.exons);
//add CCDS transcript as well (only once)
if (t_data.name_ccds!="" && !ccds_transcripts_added.contains(t_data.name_ccds))
{
int trans_id_ccds = addTranscript(q_trans, t_data.ngsd_gene_id, t_data.name_ccds , "ccds", t_data);
//add exons (only coding part)
BedFile coding_part;
coding_part.append(BedLine(t_data.exons[0].chr() ,t_data.start_coding, t_data.end_coding));
t_data.exons.intersect(coding_part);
addExons(q_exon, trans_id_ccds, t_data.exons);
ccds_transcripts_added.insert(t_data.name_ccds);
}
++it;
}
//clear cache
gene_ensemble2ngsd.clear();
transcripts.clear();
continue;
}
//skip header lines
if (line.startsWith("#")) continue;
QByteArrayList parts = line.split('\t');
QByteArray type = parts[2];
QMap<QByteArray, QByteArray> data = parseAttributes(parts[8]);
//gene line
if (data.contains("gene_id"))
{
QByteArray gene = data["Name"];
//transform gene names to approved gene IDs
int ngsd_gene_id = db.geneToApprovedID(gene);
if (ngsd_gene_id==-1)
{
out << "ERROR " << data["gene_id"] << "/" << gene << ": no approved gene names found." << endl;
continue;
}
gene_ensemble2ngsd[data["ID"]] = ngsd_gene_id;
}
//transcript line
else if (data.contains("transcript_id"))
{
if (all || data.value("tag")=="basic")
{
TranscriptData tmp;
tmp.name = data["transcript_id"];
tmp.name_ccds = data.value("ccdsid", "");
tmp.chr = parts[0];
tmp.strand = parts[6];
tmp.ngsd_gene_id = gene_ensemble2ngsd[data["Parent"]];
transcripts[data["ID"]] = tmp;
}
}
//exon lines
else if (type=="CDS" || type=="exon" || type=="three_prime_UTR" || type=="five_prime_UTR" )
{
QByteArray parent_id = data["Parent"];
//skip exons of unhandled transcripts (not GENCODE basic)
if (!transcripts.contains(parent_id)) continue;
TranscriptData& t_data = transcripts[parent_id];
//check chromosome matches
QByteArray chr = parts[0];
if (chr!=t_data.chr)
{
THROW(FileParseException, "Chromosome mismach between transcript and exon!");
}
//update coding start/end
int start = Helper::toInt(parts[3], "start position");
int end = Helper::toInt(parts[4], "end position");
if (type=="CDS")
{
t_data.start_coding = (t_data.start_coding==-1) ? start : std::min(start, t_data.start_coding);
t_data.end_coding = (t_data.end_coding==-1) ? end : std::max(end, t_data.end_coding);
}
//add coding exon
t_data.exons.append(BedLine(chr, start, end));
}
}
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "NaaliApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include "CoreStringUtils.h"
#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>
#include "MemoryLeakCheck.h"
namespace Foundation
{
NaaliApplication::NaaliApplication(Framework *framework_, int &argc, char **argv) :
QApplication(argc, argv),
framework(framework_),
appActivated(true),
nativeTranslator(new QTranslator),
appTranslator(new QTranslator)
{
QApplication::setApplicationName("realXtend-Naali");
#ifdef Q_WS_WIN
// On Windows the current directory have to be the application installation directory
// QDir::setCurrent(applicationDirPath());
// If under windows, add run_dir/plugins as library path
// unix users will get plugins from their OS Qt installation folder automatically
QString runDirectory = QString::fromStdString(ReplaceChar(framework->GetPlatform()->GetInstallDirectory(), '\\', '/'));
runDirectory += "/qtplugins";
addLibraryPath(runDirectory);
#endif
QDir dir("data/translations/qt_native_translations");
QStringList qmFiles = GetQmFiles(dir);
// Search then that is there corresponding native translations for system locals.
QString loc = QLocale::system().name();
loc.chop(3);
QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
QStringList lst = qmFiles.filter(name);
if (!lst.empty() )
nativeTranslator->load(lst[0]);
this->installTranslator(nativeTranslator);
std::string default_language = framework->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
"language", std::string("data/translations/naali_en"));
ChangeLanguage(QString::fromStdString(default_language));
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
}
NaaliApplication::~NaaliApplication()
{
SAFE_DELETE(nativeTranslator);
SAFE_DELETE(appTranslator);
}
QStringList NaaliApplication::GetQmFiles(const QDir& dir)
{
QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
QMutableStringListIterator i(fileNames);
while (i.hasNext())
{
i.next();
i.setValue(dir.filePath(i.value()));
}
return fileNames;
}
void NaaliApplication::Go()
{
installEventFilter(this);
QObject::connect(&frameUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
frameUpdateTimer.setSingleShot(true);
frameUpdateTimer.start(0);
try
{
exec ();
}
catch(const std::exception &e)
{
RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
throw;
}
}
bool NaaliApplication::eventFilter(QObject *obj, QEvent *event)
{
try
{
if (obj == this)
{
if (event->type() == QEvent::ApplicationActivate)
appActivated = true;
if (event->type() == QEvent::ApplicationDeactivate)
appActivated = false;
}
return QObject::eventFilter(obj, event);
}
catch(const std::exception &e)
{
std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
throw;
}
return true;
}
void NaaliApplication::ChangeLanguage(const QString& file)
{
QString filename = file;
if (!filename.endsWith(".qm", Qt::CaseInsensitive))
filename.append(".qm");
QString tmp = filename;
tmp.chop(3);
QString str = tmp.right(2);
QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";
// Remove old translators then change them to new.
removeTranslator(nativeTranslator);
if (QFile::exists(name))
{
if (nativeTranslator != 0)
{
nativeTranslator->load(name);
installTranslator(nativeTranslator);
}
}
else
{
if (nativeTranslator != 0 && nativeTranslator->isEmpty())
{
installTranslator(nativeTranslator);
}
else
{
SAFE_DELETE(nativeTranslator);
nativeTranslator = new QTranslator;
installTranslator(nativeTranslator);
}
}
// Remove old translators then change them to new.
removeTranslator(appTranslator);
if (appTranslator->load(filename))
{
installTranslator(appTranslator);
framework->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
}
emit LanguageChanged();
}
bool NaaliApplication::notify(QObject *receiver, QEvent *event)
{
try
{
return QApplication::notify(receiver, event);
} catch(const std::exception &e)
{
std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
throw;
}
}
void NaaliApplication::UpdateFrame()
{
try
{
QApplication::processEvents(QEventLoop::AllEvents, 1);
QApplication::sendPostedEvents();
framework->ProcessOneFrame();
// Reduce framerate when unfocused
if (appActivated)
frameUpdateTimer.start(0);
else
frameUpdateTimer.start(5);
}
catch(const std::exception &e)
{
std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
throw;
}
}
void NaaliApplication::AboutToExit()
{
emit ExitRequested();
// If no-one canceled the exit as a response to the signal, exit
if (framework->IsExiting())
quit();
}
}
<commit_msg>Removed wrongly applied setcwd command from startup.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "NaaliApplication.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include "CoreStringUtils.h"
#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>
#include "MemoryLeakCheck.h"
namespace Foundation
{
NaaliApplication::NaaliApplication(Framework *framework_, int &argc, char **argv) :
QApplication(argc, argv),
framework(framework_),
appActivated(true),
nativeTranslator(new QTranslator),
appTranslator(new QTranslator)
{
QApplication::setApplicationName("realXtend-Naali");
#ifdef Q_WS_WIN
// If under windows, add run_dir/plugins as library path
// unix users will get plugins from their OS Qt installation folder automatically
QString runDirectory = QString::fromStdString(ReplaceChar(framework->GetPlatform()->GetInstallDirectory(), '\\', '/'));
runDirectory += "/qtplugins";
addLibraryPath(runDirectory);
#endif
QDir dir("data/translations/qt_native_translations");
QStringList qmFiles = GetQmFiles(dir);
// Search then that is there corresponding native translations for system locals.
QString loc = QLocale::system().name();
loc.chop(3);
QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
QStringList lst = qmFiles.filter(name);
if (!lst.empty() )
nativeTranslator->load(lst[0]);
this->installTranslator(nativeTranslator);
std::string default_language = framework->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
"language", std::string("data/translations/naali_en"));
ChangeLanguage(QString::fromStdString(default_language));
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
}
NaaliApplication::~NaaliApplication()
{
SAFE_DELETE(nativeTranslator);
SAFE_DELETE(appTranslator);
}
QStringList NaaliApplication::GetQmFiles(const QDir& dir)
{
QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
QMutableStringListIterator i(fileNames);
while (i.hasNext())
{
i.next();
i.setValue(dir.filePath(i.value()));
}
return fileNames;
}
void NaaliApplication::Go()
{
installEventFilter(this);
QObject::connect(&frameUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
frameUpdateTimer.setSingleShot(true);
frameUpdateTimer.start(0);
try
{
exec ();
}
catch(const std::exception &e)
{
RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
throw;
}
}
bool NaaliApplication::eventFilter(QObject *obj, QEvent *event)
{
try
{
if (obj == this)
{
if (event->type() == QEvent::ApplicationActivate)
appActivated = true;
if (event->type() == QEvent::ApplicationDeactivate)
appActivated = false;
}
return QObject::eventFilter(obj, event);
}
catch(const std::exception &e)
{
std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
throw;
}
return true;
}
void NaaliApplication::ChangeLanguage(const QString& file)
{
QString filename = file;
if (!filename.endsWith(".qm", Qt::CaseInsensitive))
filename.append(".qm");
QString tmp = filename;
tmp.chop(3);
QString str = tmp.right(2);
QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";
// Remove old translators then change them to new.
removeTranslator(nativeTranslator);
if (QFile::exists(name))
{
if (nativeTranslator != 0)
{
nativeTranslator->load(name);
installTranslator(nativeTranslator);
}
}
else
{
if (nativeTranslator != 0 && nativeTranslator->isEmpty())
{
installTranslator(nativeTranslator);
}
else
{
SAFE_DELETE(nativeTranslator);
nativeTranslator = new QTranslator;
installTranslator(nativeTranslator);
}
}
// Remove old translators then change them to new.
removeTranslator(appTranslator);
if (appTranslator->load(filename))
{
installTranslator(appTranslator);
framework->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
}
emit LanguageChanged();
}
bool NaaliApplication::notify(QObject *receiver, QEvent *event)
{
try
{
return QApplication::notify(receiver, event);
} catch(const std::exception &e)
{
std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
} catch(...)
{
std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
throw;
}
}
void NaaliApplication::UpdateFrame()
{
try
{
QApplication::processEvents(QEventLoop::AllEvents, 1);
QApplication::sendPostedEvents();
framework->ProcessOneFrame();
// Reduce framerate when unfocused
if (appActivated)
frameUpdateTimer.start(0);
else
frameUpdateTimer.start(5);
}
catch(const std::exception &e)
{
std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
throw;
}
catch(...)
{
std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
throw;
}
}
void NaaliApplication::AboutToExit()
{
emit ExitRequested();
// If no-one canceled the exit as a response to the signal, exit
if (framework->IsExiting())
quit();
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"
HWND hWnd;
DWORD jmpAddress;
void patch_res();
void patch_res_x1(), patch_res_x2(), patch_res_x3(), patch_res_x4(), patch_res_x5(), patch_res_x6(), patch_res_x7(), patch_res_x8(), patch_res_x9(), patch_res_x10();
void patch_res_y1(), patch_res_y2(), patch_res_y3(), patch_res_y4(), patch_res_y5(), patch_res_y6(), patch_res_y7();
void patch_player_a(); void patch_player_a2();
int res_x;
int res_y;
int res_x43;
DWORD WINAPI Thread(LPVOID)
{
CPatch::RedirectJump(0x42B512, patch_player_a);
CPatch::RedirectJump(0x4274FF, patch_player_a2);
CIniReader iniReader("gta1_res.ini");
res_x = iniReader.ReadInteger("MAIN", "X", 0);
res_y = iniReader.ReadInteger("MAIN", "Y", 0);
if (!res_x || !res_y) {
HMONITOR monitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO info;
info.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &info);
res_x = info.rcMonitor.right - info.rcMonitor.left;
res_y = info.rcMonitor.bottom - info.rcMonitor.top;
}
CPatch::RedirectJump(0x491E4C, patch_res);
CPatch::RedirectJump(0x414FF7, patch_res_x1);
CPatch::RedirectJump(0x43B7CF, patch_res_x2);
res_x43 = static_cast<int>(res_y * (4.0f / 3.0f));
CPatch::RedirectJump(0x46453B, patch_res_x3);
//CPatch::RedirectJump(0x46452C, patch_res_x4);
//CPatch::RedirectJump(0x486848, patch_res_x5);
//CPatch::RedirectJump(0x486852, patch_res_x6);
/*CPatch::RedirectJump(0x48C137, patch_res_x7);
CPatch::RedirectJump(0x48C276, patch_res_x8);
CPatch::RedirectJump(0x48C159, patch_res_x9);*/
//CPatch::RedirectJump(0x49168B, patch_res_x10);
CPatch::RedirectJump(0x415008, patch_res_y1);
CPatch::RedirectJump(0x43B7D8, patch_res_y2);
CPatch::RedirectJump(0x464532, patch_res_y3);
CPatch::RedirectJump(0x48683A, patch_res_y4);
CPatch::RedirectJump(0x48C13D, patch_res_y5);
CPatch::RedirectJump(0x48C2B0, patch_res_y6);
//CPatch::RedirectJump(0x, patch_res_y7);
//menu
CPatch::SetUInt(0x4898C3 + 0x1, res_x);
return 0;
}
void __declspec(naked)patch_res()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787310], EAX
MOV DWORD PTR DS : [0x787370], EAX
MOV EAX, DWORD PTR DS : [EBX + 1B4h]
INC EAX
TEST ECX, ECX
mov eax, res_y
MOV DWORD PTR DS : [0x787314], EAX
MOV DWORD PTR DS : [0x787388], EAX
mov jmpAddress, 0x491E69
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x1()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x504CC0], EAX
mov jmpAddress, 0x414FFC
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x2()
{
_asm
{
mov edx, res_x
MOV DWORD PTR DS : [0x5C0C00], EDX
mov jmpAddress, 0x43B7D5
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x3()
{
_asm
{
mov esi, res_x43
MOV DWORD PTR DS : [ECX + 0x74F168], ESI
mov jmpAddress, 0x464541
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x4()
{
_asm
{
mov edx, res_x
MOV DWORD PTR DS : [ECX + 0x74F170], EDX
mov jmpAddress, 0x464532
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x5()
{
_asm
{
mov ecx, res_x
MOV DWORD PTR DS : [0x785170], ECX
mov jmpAddress, 0x48684E
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x6()
{
_asm
{
mov ecx, res_x
MOV DWORD PTR DS : [0x785178], ECX
mov jmpAddress, 0x486858
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x7()
{
_asm
{
mov esi, res_x
MOV DWORD PTR DS : [0x787AD4], ESI
mov jmpAddress, 0x48C13D
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x8()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787AEC], EAX
mov jmpAddress, 0x48C27B
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x9()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787CB0], EAX
mov jmpAddress, 0x48C15E
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x10()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [EDI + 16Ch], EAX
mov jmpAddress, 0x491691
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y1()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x504CC4], EAX
mov jmpAddress, 0x41500D
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y2()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x5BFAB0], EAX
mov jmpAddress, 0x43B7DD
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y3()
{
_asm
{
mov edi, res_y
MOV DWORD PTR DS : [ECX + 0x74F16C], EDI
mov jmpAddress, 0x464538
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y4()
{
_asm
{
mov edx, res_y
MOV DWORD PTR DS : [0x785174], EDX
mov jmpAddress, 0x486840
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y5()
{
_asm
{
mov edi, res_y
MOV DWORD PTR DS : [0x787AD8], EDI
mov jmpAddress, 0x48C143
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y6()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x787AF0], EAX
mov jmpAddress, 0x48C2B5
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y7()
{
_asm
{
mov edx, res_y
MOV DWORD PTR DS : [0x4B48C0], EDX
mov jmpAddress, 0x48AE8B
jmp jmpAddress
}
}
void __declspec(naked)patch_player_a()
{
_asm
{
MOV BYTE PTR DS : [0x51029C], 0x06
mov jmpAddress, 0x42B518
jmp jmpAddress
}
}
void __declspec(naked)patch_player_a2()
{
_asm
{
MOV BYTE PTR DS : [0x51029C], 0x06
mov jmpAddress, 0x427504
jmp jmpAddress
}
}
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
}
return TRUE;
}
<commit_msg>WFP v2.9.2<commit_after>#include "stdafx.h"
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"
HWND hWnd;
DWORD jmpAddress;
void patch_res();
void patch_res_x1(), patch_res_x2(), patch_res_x3(), patch_res_x4(), patch_res_x5(), patch_res_x6(), patch_res_x7(), patch_res_x8(), patch_res_x9(), patch_res_x10();
void patch_res_y1(), patch_res_y2(), patch_res_y3(), patch_res_y4(), patch_res_y5(), patch_res_y6(), patch_res_y7();
void patch_player_a(); void patch_player_a2();
int res_x;
int res_y;
int res_x43;
int Var_480 = 480;
DWORD WINAPI Thread(LPVOID)
{
CPatch::RedirectJump(0x42B512, patch_player_a);
CPatch::RedirectJump(0x4274FF, patch_player_a2);
CIniReader iniReader("gta1_res.ini");
res_x = iniReader.ReadInteger("MAIN", "X", 0);
res_y = iniReader.ReadInteger("MAIN", "Y", 0);
if (!res_x || !res_y) {
HMONITOR monitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO info;
info.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &info);
res_x = info.rcMonitor.right - info.rcMonitor.left;
res_y = info.rcMonitor.bottom - info.rcMonitor.top;
}
CPatch::RedirectJump(0x491E4C, patch_res);
CPatch::RedirectJump(0x414FF7, patch_res_x1);
CPatch::RedirectJump(0x43B7CF, patch_res_x2);
res_x43 = static_cast<int>(res_y * (4.0f / 3.0f));
CPatch::RedirectJump(0x46453B, patch_res_x3);
//CPatch::RedirectJump(0x46452C, patch_res_x4);
//CPatch::RedirectJump(0x486848, patch_res_x5);
//CPatch::RedirectJump(0x486852, patch_res_x6);
/*CPatch::RedirectJump(0x48C137, patch_res_x7);
CPatch::RedirectJump(0x48C276, patch_res_x8);
CPatch::RedirectJump(0x48C159, patch_res_x9);*/
//CPatch::RedirectJump(0x49168B, patch_res_x10);
CPatch::RedirectJump(0x415008, patch_res_y1);
CPatch::RedirectJump(0x43B7D8, patch_res_y2);
CPatch::RedirectJump(0x464532, patch_res_y3);
CPatch::RedirectJump(0x48683A, patch_res_y4);
CPatch::RedirectJump(0x48C13D, patch_res_y5);
CPatch::RedirectJump(0x48C2B0, patch_res_y6);
//CPatch::RedirectJump(0x, patch_res_y7);
//menu
CPatch::SetUInt(0x4898C3 + 0x1, res_x);
//FMV crashfix
//CPatch::SetPointer(0x4152D6 + 2, &Var_640);
//CPatch::SetPointer(0x4152E7 + 1, &Var_480);
CPatch::SetPointer(0x42D830 + 0xA + 1, &Var_480);
CPatch::SetPointer(0x42D830 + 0x5B + 2, &Var_480);
CPatch::SetPointer(0x42D830 + 0x9C + 2, &Var_480);
//CPatch::SetPointer(0x42D830 + 0x3B + 2, &Var_640);
//CPatch::SetPointer(0x42D830 + 0x71 + 2, &Var_640);
return 0;
}
void __declspec(naked)patch_res()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787310], EAX
MOV DWORD PTR DS : [0x787370], EAX
MOV EAX, DWORD PTR DS : [EBX + 1B4h]
INC EAX
TEST ECX, ECX
mov eax, res_y
MOV DWORD PTR DS : [0x787314], EAX
MOV DWORD PTR DS : [0x787388], EAX
mov jmpAddress, 0x491E69
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x1()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x504CC0], EAX
mov jmpAddress, 0x414FFC
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x2()
{
_asm
{
mov edx, res_x
MOV DWORD PTR DS : [0x5C0C00], EDX
mov jmpAddress, 0x43B7D5
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x3()
{
_asm
{
mov esi, res_x43
MOV DWORD PTR DS : [ECX + 0x74F168], ESI
mov jmpAddress, 0x464541
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x4()
{
_asm
{
mov edx, res_x
MOV DWORD PTR DS : [ECX + 0x74F170], EDX
mov jmpAddress, 0x464532
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x5()
{
_asm
{
mov ecx, res_x
MOV DWORD PTR DS : [0x785170], ECX
mov jmpAddress, 0x48684E
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x6()
{
_asm
{
mov ecx, res_x
MOV DWORD PTR DS : [0x785178], ECX
mov jmpAddress, 0x486858
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x7()
{
_asm
{
mov esi, res_x
MOV DWORD PTR DS : [0x787AD4], ESI
mov jmpAddress, 0x48C13D
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x8()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787AEC], EAX
mov jmpAddress, 0x48C27B
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x9()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [0x787CB0], EAX
mov jmpAddress, 0x48C15E
jmp jmpAddress
}
}
void __declspec(naked)patch_res_x10()
{
_asm
{
mov eax, res_x
MOV DWORD PTR DS : [EDI + 16Ch], EAX
mov jmpAddress, 0x491691
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y1()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x504CC4], EAX
mov jmpAddress, 0x41500D
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y2()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x5BFAB0], EAX
mov jmpAddress, 0x43B7DD
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y3()
{
_asm
{
mov edi, res_y
MOV DWORD PTR DS : [ECX + 0x74F16C], EDI
mov jmpAddress, 0x464538
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y4()
{
_asm
{
mov edx, res_y
MOV DWORD PTR DS : [0x785174], EDX
mov jmpAddress, 0x486840
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y5()
{
_asm
{
mov edi, res_y
MOV DWORD PTR DS : [0x787AD8], EDI
mov jmpAddress, 0x48C143
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y6()
{
_asm
{
mov eax, res_y
MOV DWORD PTR DS : [0x787AF0], EAX
mov jmpAddress, 0x48C2B5
jmp jmpAddress
}
}
void __declspec(naked)patch_res_y7()
{
_asm
{
mov edx, res_y
MOV DWORD PTR DS : [0x4B48C0], EDX
mov jmpAddress, 0x48AE8B
jmp jmpAddress
}
}
void __declspec(naked)patch_player_a()
{
_asm
{
MOV BYTE PTR DS : [0x51029C], 0x06
mov jmpAddress, 0x42B518
jmp jmpAddress
}
}
void __declspec(naked)patch_player_a2()
{
_asm
{
MOV BYTE PTR DS : [0x51029C], 0x06
mov jmpAddress, 0x427504
jmp jmpAddress
}
}
BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
if (reason == DLL_PROCESS_ATTACH)
{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
}
return TRUE;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"
#if !defined(OS_ANDROID)
namespace cc {
namespace {
class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green box is entirely behind a layer with background blur, so it
// should appear blurred on its edges.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
background->AddChild(green);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 436 pixels off by 1: crbug.com/259915
float percentage_pixels_large_error = 1.09f; // 436px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 1;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, DISABLED_BackgroundFilterBlurOutsets) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green border is outside the layer with background blur, but the
// background blur should use pixels from outside its layer borders, up to the
// radius of the blur effect. So the border should be blurred underneath the
// top layer causing the green to bleed under the transparent layer, but not
// in the 1px region between the transparent layer and the green border.
scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
background->AddChild(green_border);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(5.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 2250 pixels off by at most 2: crbug.com/259922
float percentage_pixels_large_error = 5.625f; // 2250px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_outsets.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// This verifies that the perspective of the clear layer (with black border)
// does not influence the blending of the green box behind it. Also verifies
// that the blur is correctly clipped inside the transformed clear layer.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
background->AddChild(green);
background->AddChild(blur);
background->SetPreserves3d(true);
gfx::Transform background_transform;
background_transform.ApplyPerspectiveDepth(200.0);
background->SetTransform(background_transform);
blur->SetPreserves3d(true);
gfx::Transform blur_transform;
blur_transform.Translate(55.0, 65.0);
blur_transform.RotateAboutXAxis(85.0);
blur_transform.RotateAboutYAxis(180.0);
blur_transform.RotateAboutZAxis(20.0);
blur_transform.Translate(-60.0, -60.0);
blur->SetTransform(blur_transform);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 151 pixels off by at most 2: crbug.com/225027
float percentage_pixels_large_error = 0.3775f; // 151px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_off_axis.png")));
}
} // namespace
} // namespace cc
#endif // OS_ANDROID
<commit_msg>Re-enable cc_unittest LayerTreeHostFiltersPixelTest.BackgroundFilterBlurOutsets, and adjust the fuzzy match threshold on Windows.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"
#if !defined(OS_ANDROID)
namespace cc {
namespace {
class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green box is entirely behind a layer with background blur, so it
// should appear blurred on its edges.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
background->AddChild(green);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 436 pixels off by 1: crbug.com/259915
float percentage_pixels_large_error = 1.09f; // 436px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 1;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOutsets) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// The green border is outside the layer with background blur, but the
// background blur should use pixels from outside its layer borders, up to the
// radius of the blur effect. So the border should be blurred underneath the
// top layer causing the green to bleed under the transparent layer, but not
// in the 1px region between the transparent layer and the green border.
scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
background->AddChild(green_border);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(5.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 2596 pixels off by at most 2: crbug.com/259922
float percentage_pixels_large_error = 6.49f; // 2596px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_outsets.png")));
}
TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(200, 200), SK_ColorWHITE);
// This verifies that the perspective of the clear layer (with black border)
// does not influence the blending of the green box behind it. Also verifies
// that the blur is correctly clipped inside the transformed clear layer.
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
gfx::Rect(50, 50, 100, 100), kCSSGreen);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
background->AddChild(green);
background->AddChild(blur);
background->SetPreserves3d(true);
gfx::Transform background_transform;
background_transform.ApplyPerspectiveDepth(200.0);
background->SetTransform(background_transform);
blur->SetPreserves3d(true);
gfx::Transform blur_transform;
blur_transform.Translate(55.0, 65.0);
blur_transform.RotateAboutXAxis(85.0);
blur_transform.RotateAboutYAxis(180.0);
blur_transform.RotateAboutZAxis(20.0);
blur_transform.Translate(-60.0, -60.0);
blur->SetTransform(blur_transform);
FilterOperations filters;
filters.Append(FilterOperation::CreateBlurFilter(2.f));
blur->SetBackgroundFilters(filters);
#if defined(OS_WIN)
// Windows has 151 pixels off by at most 2: crbug.com/225027
float percentage_pixels_large_error = 0.3775f; // 151px / (200*200)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 1.f;
int large_error_allowed = 2;
int small_error_allowed = 0;
pixel_comparator_.reset(new FuzzyPixelComparator(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed));
#endif
RunPixelTest(GL_WITH_BITMAP,
background,
base::FilePath(FILE_PATH_LITERAL(
"background_filter_blur_off_axis.png")));
}
} // namespace
} // namespace cc
#endif // OS_ANDROID
<|endoftext|>
|
<commit_before>/*
** Copyright 2014-2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <orange/VarExpr.h>
#include <orange/generator.h>
VarExpr* VarExpr::symtabVar() {
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
return tabVar ? (VarExpr*)tabVar : this;
}
Value* VarExpr::Codegen() {
// "Generating" a variable doesn't actually do anything;
// its creation is handled by other classes like BinOpExpr.
GE::runner()->topBlock()->symtab()->activate(m_name, this);
return getValue();
}
void VarExpr::initialize() {
// Initialization should happen after a variable is created for the first
// time. If we are a constant, we will set ourselves to "initialized,"
// which means that we can't have our value changed.
if (m_constant || symtabVar()->m_constant) {
m_initialized = true;
symtabVar()->m_initialized = true;
}
}
Value* VarExpr::getValue() {
// IF we have a value, just return it.
if (m_value) return m_value;
// If a variable exists in the symtab by this name,
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* node = tab->find(m_name);
if (node == nullptr) return m_value;
if (node->getClass() != getClass()) {
throw std::runtime_error(node->string() + " is not a variable!");
}
if (node == this) return nullptr;
return node->getValue();
}
std::string VarExpr::string() {
return "(" + getType()->string() + ")" + m_name;
}
OrangeTy* VarExpr::getType() {
// If we've been assigned a value, we'll return that, otherwise
// we'll return the default type from ASTNode.
if (m_type) {
return m_type;
}
if (GE::runner()->topBlock()->symtab()->find(m_name)) {
ASTNode* node = GE::runner()->topBlock()->symtab()->find(m_name);
if (node->getClass() != getClass()) {
throw std::runtime_error(node->string() + " is not a variable!");
}
VarExpr* nodeExpr = (VarExpr*)node;
if (nodeExpr != this) {
return nodeExpr->m_type ? nodeExpr->m_type : nodeExpr->getType();
}
}
return ASTNode::getType();
}
void VarExpr::setType(OrangeTy* type) {
m_type = type;
// If this variable exists in the symtab, set this type for that, too.
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
if (tabVar && tabVar->getClass() == "VarExpr" && tabVar != this) {
((VarExpr *)tabVar)->setType(type);
}
}
bool VarExpr::isLocked() {
if (m_locked) return true;
// we may not be referring to the VarExpr here; look in the symtab.
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
if (tabVar && tabVar->getClass() == "VarExpr" && tabVar != this) {
return ((VarExpr *)tabVar)->isLocked();
}
return false;
}
void VarExpr::resolve() {
if (m_resolved) return;
m_resolved = true;
if (getType()->isVariadicArray()) {
std::vector<Expression *> variadicElements;
auto ptr = getType();
while (ptr->isVariadicArray()) {
variadicElements.push_back(ptr->getVariadicArrayElement());
ptr = ptr->getArrayElementType();
}
for (auto expr : variadicElements) {
if (expr) expr->resolve();
}
}
}
void VarExpr::create(bool throwError) {
// Tries to add this variable to the symbol table.
// If it already exists in the symbol table, and it's not this, throw an error.
SymTable* tab = GE::runner()->topBlock()->symtab();
if (tab->create(m_name, this) == false && throwError) {
// We couldn't create it because it already exists.
// If the ASTNode in the table isn't this var, throw an error.
if (tab->find(m_name) && tab->find(m_name) != this) {
throw std::runtime_error("A variable by this name already exists!");
}
}
}
bool VarExpr::existsInParent() {
SymTable* tab = GE::runner()->topBlock()->symtab();
return tab->find(m_name) != nullptr;
}
void VarExpr::setValue(Value* value) {
if (m_initialized || symtabVar()->m_initialized) {
throw CompilerMessage(*this, "cannot modify the value of a constant!");
}
m_value = GE::builder()->CreateAlloca(value->getType(), nullptr, m_name);
GE::builder()->CreateStore(value, m_value);
}
void VarExpr::setValueTo(Value *value) {
if (m_initialized || symtabVar()->m_initialized) {
throw CompilerMessage(*this, "cannot modify the value of a constant!");
}
m_value = value;
}
bool VarExpr::returnsPtr() {
return true;
}
Value* VarExpr::allocate() {
if (m_value != nullptr) {
throw CompilerMessage(*this, "variable already allocated!");
}
// If we're variadic array, getLLVMType() will just return type*.
// However, we need to actually initialize ourselves with the number
// of elements, so handle that here
Type* llvmType = getLLVMType();
if (llvmType == nullptr) {
throw std::runtime_error("VarExpr::allocate(): getLLVMType returned nullptr!");
}
if (getType()->isVariadicArray()) {
Type* baseType = llvmType;
while (baseType->isPointerTy()) {
baseType = baseType->getPointerElementType();
}
std::vector<Expression *> variadicElements;
auto ptr = getType();
while (ptr->isVariadicArray()) {
variadicElements.push_back(ptr->getVariadicArrayElement());
ptr = ptr->getArrayElementType();
}
// Codegen all of the types into values
std::vector<Value*> values;
for (auto expr : variadicElements) {
auto value = expr->Codegen();
if (value == nullptr) {
throw std::runtime_error("VarExpr::allocate(): expr did not generate a value!");
}
if (expr->returnsPtr() == true) {
value = GE::builder()->CreateLoad(value);
}
if (value->getType()->isIntegerTy() == false) {
throw CompilerMessage(*expr, "Type is not an integer!");
}
values.push_back(value);
}
// The total size of this array is all the elements in the vector multiplied together.
Value *totSize = values[0];
for (int i = 1; i < values.size(); i++) {
totSize = GE::builder()->CreateMul(totSize, values[i]);
}
Value *v = GE::builder()->CreateAlloca(baseType, totSize, name());
setValueTo(v);
return v;
}
Value* v = GE::builder()->CreateAlloca(llvmType, nullptr, name());
setValueTo(v);
return v;
}
VarExpr::VarExpr(std::string name) : m_name(name) {
}
VarExpr::VarExpr(std::string name, bool constant) : m_name(name) {
m_constant = constant;
}
VarExpr::VarExpr(std::string name, OrangeTy* type) : m_name(name) {
m_locked = true;
m_type = type;
}
VarExpr::VarExpr(std::string name, OrangeTy* type, bool constant) : m_name(name) {
m_locked = true;
m_constant = constant;
m_type = type;
}
<commit_msg>Change VarExpr to cache type.<commit_after>/*
** Copyright 2014-2015 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/
#include <orange/VarExpr.h>
#include <orange/generator.h>
VarExpr* VarExpr::symtabVar() {
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
return tabVar ? (VarExpr*)tabVar : this;
}
Value* VarExpr::Codegen() {
// "Generating" a variable doesn't actually do anything;
// its creation is handled by other classes like BinOpExpr.
GE::runner()->topBlock()->symtab()->activate(m_name, this);
return getValue();
}
void VarExpr::initialize() {
// Initialization should happen after a variable is created for the first
// time. If we are a constant, we will set ourselves to "initialized,"
// which means that we can't have our value changed.
if (m_constant || symtabVar()->m_constant) {
m_initialized = true;
symtabVar()->m_initialized = true;
}
}
Value* VarExpr::getValue() {
// IF we have a value, just return it.
if (m_value) return m_value;
// If a variable exists in the symtab by this name,
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* node = tab->find(m_name);
if (node == nullptr) return m_value;
if (node->getClass() != getClass()) {
throw std::runtime_error(node->string() + " is not a variable!");
}
if (node == this) return nullptr;
m_value = node->getValue();
return m_value;
}
std::string VarExpr::string() {
return "(" + getType()->string() + ")" + m_name;
}
OrangeTy* VarExpr::getType() {
// If we've been assigned a value, we'll return that, otherwise
// we'll return the default type from ASTNode.
if (m_type) {
return m_type;
}
if (GE::runner()->topBlock()->symtab()->find(m_name)) {
ASTNode* node = GE::runner()->topBlock()->symtab()->find(m_name);
if (node->getClass() != getClass()) {
throw std::runtime_error(node->string() + " is not a variable!");
}
VarExpr* nodeExpr = (VarExpr*)node;
if (nodeExpr != this) {
return nodeExpr->m_type ? nodeExpr->m_type : nodeExpr->getType();
}
}
return ASTNode::getType();
}
void VarExpr::setType(OrangeTy* type) {
m_type = type;
// If this variable exists in the symtab, set this type for that, too.
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
if (tabVar && tabVar->getClass() == "VarExpr" && tabVar != this) {
((VarExpr *)tabVar)->setType(type);
}
}
bool VarExpr::isLocked() {
if (m_locked) return true;
// we may not be referring to the VarExpr here; look in the symtab.
SymTable* tab = GE::runner()->topBlock()->symtab();
ASTNode* tabVar = tab->find(m_name);
if (tabVar && tabVar->getClass() == "VarExpr" && tabVar != this) {
return ((VarExpr *)tabVar)->isLocked();
}
return false;
}
void VarExpr::resolve() {
if (m_resolved) return;
m_resolved = true;
if (getType()->isVariadicArray()) {
std::vector<Expression *> variadicElements;
auto ptr = getType();
while (ptr->isVariadicArray()) {
variadicElements.push_back(ptr->getVariadicArrayElement());
ptr = ptr->getArrayElementType();
}
for (auto expr : variadicElements) {
if (expr) expr->resolve();
}
}
}
void VarExpr::create(bool throwError) {
// Tries to add this variable to the symbol table.
// If it already exists in the symbol table, and it's not this, throw an error.
SymTable* tab = GE::runner()->topBlock()->symtab();
if (tab->create(m_name, this) == false && throwError) {
// We couldn't create it because it already exists.
// If the ASTNode in the table isn't this var, throw an error.
if (tab->find(m_name) && tab->find(m_name) != this) {
throw std::runtime_error("A variable by this name already exists!");
}
}
}
bool VarExpr::existsInParent() {
SymTable* tab = GE::runner()->topBlock()->symtab();
return tab->find(m_name) != nullptr;
}
void VarExpr::setValue(Value* value) {
if (m_initialized || symtabVar()->m_initialized) {
throw CompilerMessage(*this, "cannot modify the value of a constant!");
}
m_value = GE::builder()->CreateAlloca(value->getType(), nullptr, m_name);
GE::builder()->CreateStore(value, m_value);
}
void VarExpr::setValueTo(Value *value) {
if (m_initialized || symtabVar()->m_initialized) {
throw CompilerMessage(*this, "cannot modify the value of a constant!");
}
m_value = value;
}
bool VarExpr::returnsPtr() {
return true;
}
Value* VarExpr::allocate() {
if (m_value != nullptr) {
throw CompilerMessage(*this, "variable already allocated!");
}
// If we're variadic array, getLLVMType() will just return type*.
// However, we need to actually initialize ourselves with the number
// of elements, so handle that here
Type* llvmType = getLLVMType();
if (llvmType == nullptr) {
throw std::runtime_error("VarExpr::allocate(): getLLVMType returned nullptr!");
}
if (getType()->isVariadicArray()) {
Type* baseType = llvmType;
while (baseType->isPointerTy()) {
baseType = baseType->getPointerElementType();
}
std::vector<Expression *> variadicElements;
auto ptr = getType();
while (ptr->isVariadicArray()) {
variadicElements.push_back(ptr->getVariadicArrayElement());
ptr = ptr->getArrayElementType();
}
// Codegen all of the types into values
std::vector<Value*> values;
for (auto expr : variadicElements) {
auto value = expr->Codegen();
if (value == nullptr) {
throw std::runtime_error("VarExpr::allocate(): expr did not generate a value!");
}
if (expr->returnsPtr() == true) {
value = GE::builder()->CreateLoad(value);
}
if (value->getType()->isIntegerTy() == false) {
throw CompilerMessage(*expr, "Type is not an integer!");
}
values.push_back(value);
}
// The total size of this array is all the elements in the vector multiplied together.
Value *totSize = values[0];
for (int i = 1; i < values.size(); i++) {
totSize = GE::builder()->CreateMul(totSize, values[i]);
}
Value *v = GE::builder()->CreateAlloca(baseType, totSize, name());
setValueTo(v);
return v;
}
Value* v = GE::builder()->CreateAlloca(llvmType, nullptr, name());
setValueTo(v);
return v;
}
VarExpr::VarExpr(std::string name) : m_name(name) {
}
VarExpr::VarExpr(std::string name, bool constant) : m_name(name) {
m_constant = constant;
}
VarExpr::VarExpr(std::string name, OrangeTy* type) : m_name(name) {
m_locked = true;
m_type = type;
}
VarExpr::VarExpr(std::string name, OrangeTy* type, bool constant) : m_name(name) {
m_locked = true;
m_constant = constant;
m_type = type;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "convert.h"
#include "csv.h"
#include "scope.h"
#include "interactive.h"
#include "iterators.h"
#include "report.h"
#include "xact.h"
#include "print.h"
#include "lookup.h"
namespace ledger {
value_t convert_command(call_scope_t& scope)
{
interactive_t args(scope, "s");
report_t& report(find_scope<report_t>(scope));
journal_t& journal(*report.session.journal.get());
string bucket_name;
if (report.HANDLED(account_))
bucket_name = report.HANDLER(account_).str();
else
bucket_name = "Equity:Unknown";
account_t * bucket = journal.master->find_account(bucket_name);
account_t * unknown = journal.master->find_account(_("Expenses:Unknown"));
// Make an amounts mapping for the account under consideration
typedef std::map<value_t, std::list<post_t *> > post_map_t;
post_map_t post_map;
xacts_iterator journal_iter(journal);
while (xact_t * xact = journal_iter()) {
post_t * post = NULL;
xact_posts_iterator xact_iter(*xact);
while ((post = xact_iter()) != NULL) {
if (post->account == bucket)
break;
}
if (post) {
post_map_t::iterator i = post_map.find(post->amount);
if (i == post_map.end()) {
std::list<post_t *> post_list;
post_list.push_back(post);
post_map.insert(post_map_t::value_type(post->amount, post_list));
} else {
(*i).second.push_back(post);
}
}
}
// Create a flat list o
xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end());
// Read in the series of transactions from the CSV file
print_xacts formatter(report);
ifstream data(path(args.get<string>(0)));
csv_reader reader(data);
while (xact_t * xact = reader.read_xact(journal, bucket)) {
bool matched = false;
post_map_t::iterator i = post_map.find(- xact->posts.front()->amount);
if (i != post_map.end()) {
std::list<post_t *>& post_list((*i).second);
foreach (post_t * post, post_list) {
if (xact->code && post->xact->code &&
*xact->code == *post->xact->code) {
matched = true;
break;
}
else if (xact->actual_date() == post->actual_date()) {
matched = true;
break;
}
}
}
if (matched) {
DEBUG("convert.csv", "Ignored xact with code: " << *xact->code);
delete xact; // ignore it
}
else {
if (xact->posts.front()->account == NULL) {
xacts_iterator xi;
xi.xacts_i = current_xacts.begin();
xi.xacts_end = current_xacts.end();
xi.xacts_uninitialized = false;
// jww (2010-03-07): Bind this logic to an option: --auto-match
if (account_t * acct =
lookup_probable_account(xact->payee, xi, bucket).second)
xact->posts.front()->account = acct;
else
xact->posts.front()->account = unknown;
}
if (! journal.add_xact(xact)) {
delete xact;
throw_(std::runtime_error,
_("Failed to finalize derived transaction (check commodities)"));
}
else {
xact_posts_iterator xact_iter(*xact);
while (post_t * post = xact_iter())
formatter(*post);
}
}
}
formatter.flush();
// If not, transform the payee according to regexps
// Set the account to a default vaule, then transform the account according
// to the payee
// Print out the final form of the transaction
return true;
}
} // namespace ledger
<commit_msg>The --invert option now works with "convert"<commit_after>/*
* Copyright (c) 2003-2010, John Wiegley. 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 New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "convert.h"
#include "csv.h"
#include "scope.h"
#include "interactive.h"
#include "iterators.h"
#include "report.h"
#include "xact.h"
#include "print.h"
#include "lookup.h"
namespace ledger {
value_t convert_command(call_scope_t& scope)
{
interactive_t args(scope, "s");
report_t& report(find_scope<report_t>(scope));
journal_t& journal(*report.session.journal.get());
string bucket_name;
if (report.HANDLED(account_))
bucket_name = report.HANDLER(account_).str();
else
bucket_name = "Equity:Unknown";
account_t * bucket = journal.master->find_account(bucket_name);
account_t * unknown = journal.master->find_account(_("Expenses:Unknown"));
// Make an amounts mapping for the account under consideration
typedef std::map<value_t, std::list<post_t *> > post_map_t;
post_map_t post_map;
xacts_iterator journal_iter(journal);
while (xact_t * xact = journal_iter()) {
post_t * post = NULL;
xact_posts_iterator xact_iter(*xact);
while ((post = xact_iter()) != NULL) {
if (post->account == bucket)
break;
}
if (post) {
post_map_t::iterator i = post_map.find(post->amount);
if (i == post_map.end()) {
std::list<post_t *> post_list;
post_list.push_back(post);
post_map.insert(post_map_t::value_type(post->amount, post_list));
} else {
(*i).second.push_back(post);
}
}
}
// Create a flat list
xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end());
// Read in the series of transactions from the CSV file
print_xacts formatter(report);
ifstream data(path(args.get<string>(0)));
csv_reader reader(data);
while (xact_t * xact = reader.read_xact(journal, bucket)) {
if (report.HANDLED(invert)) {
foreach (post_t * post, xact->posts)
post->amount.in_place_negate();
}
bool matched = false;
post_map_t::iterator i = post_map.find(- xact->posts.front()->amount);
if (i != post_map.end()) {
std::list<post_t *>& post_list((*i).second);
foreach (post_t * post, post_list) {
if (xact->code && post->xact->code &&
*xact->code == *post->xact->code) {
matched = true;
break;
}
else if (xact->actual_date() == post->actual_date()) {
matched = true;
break;
}
}
}
if (matched) {
DEBUG("convert.csv", "Ignored xact with code: " << *xact->code);
delete xact; // ignore it
}
else {
if (xact->posts.front()->account == NULL) {
xacts_iterator xi;
xi.xacts_i = current_xacts.begin();
xi.xacts_end = current_xacts.end();
xi.xacts_uninitialized = false;
// jww (2010-03-07): Bind this logic to an option: --auto-match
if (account_t * acct =
lookup_probable_account(xact->payee, xi, bucket).second)
xact->posts.front()->account = acct;
else
xact->posts.front()->account = unknown;
}
if (! journal.add_xact(xact)) {
delete xact;
throw_(std::runtime_error,
_("Failed to finalize derived transaction (check commodities)"));
}
else {
xact_posts_iterator xact_iter(*xact);
while (post_t * post = xact_iter())
formatter(*post);
}
}
}
formatter.flush();
// If not, transform the payee according to regexps
// Set the account to a default vaule, then transform the account according
// to the payee
// Print out the final form of the transaction
return true;
}
} // namespace ledger
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2011 Lasath Fernando <kde@lasath.org>
Copyright (C) 2013 Dan Vrátil <dvratil@redhat.com>
Copyright (C) 2013 Aleix Pol Gonzalez <aleixpol@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 "qml-plugins.h"
#include <QQmlEngine>
#include <QQmlContext>
#include "conversation.h"
#include "conversations-model.h"
#include "messages-model.h"
#include "pinned-contacts-model.h"
#include "contact-pin.h"
#include "filtered-pinned-contacts-proxy-model.h"
#include "telepathy-manager.h"
#include <TelepathyQt/PendingChannelRequest>
#include "KTp/types.h"
#include "KTp/global-presence.h"
#include "KTp/Models/presence-model.h"
#include "KTp/Models/contacts-filter-model.h"
#include "KTp/Models/contacts-model.h"
#include "KTp/Models/accounts-list-model.h"
#include <QtQml>
void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *uri)
{
Q_UNUSED(uri)
engine->rootContext()->setContextProperty(QLatin1String("telepathyManager"), new TelepathyManager(engine));
}
void QmlPlugins::registerTypes(const char *uri)
{
qmlRegisterType<KTp::ContactsModel> (uri, 0, 1, "ContactsModel");
qmlRegisterType<KTp::AccountsListModel> (uri, 0, 1, "AccountsListModel");
qmlRegisterType<ConversationsModel> (uri, 0, 1, "ConversationsModel");
qmlRegisterType<Conversation>(uri, 0, 1, "Conversation");
qmlRegisterType<PinnedContactsModel>(uri, 0, 1, "PinnedContactsModel");
qmlRegisterType<ContactPin>(uri, 0, 1, "ContactPin");
qmlRegisterType<FilteredPinnedContactsProxyModel>(uri, 0, 1, "FilteredPinnedContactsProxyModel");
qmlRegisterType<KTp::GlobalPresence> (uri, 0, 1, "GlobalPresence");
qmlRegisterType<KTp::PresenceModel> (uri, 0, 1, "PresenceModel");
qmlRegisterUncreatableType<MessagesModel> (uri, 0, 1, "MessagesModel",
QLatin1String("It will be created once the conversation is created"));
qmlRegisterType<TelepathyManager>();
qmlRegisterType<ConversationsModel>();
qmlRegisterType<Tp::PendingChannelRequest>();
qRegisterMetaType<Tp::Presence>();
qRegisterMetaType<KTp::Presence>();
qRegisterMetaType<Tp::AccountManagerPtr>();
qRegisterMetaType<KTp::ContactPtr>();
qRegisterMetaType<Tp::AccountPtr>();
QMetaType::registerComparators<KTp::Presence>();
}
<commit_msg>qmlRegisterType Tp::PendingOperation<commit_after>/*
Copyright (C) 2011 Lasath Fernando <kde@lasath.org>
Copyright (C) 2013 Dan Vrátil <dvratil@redhat.com>
Copyright (C) 2013 Aleix Pol Gonzalez <aleixpol@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 "qml-plugins.h"
#include <QQmlEngine>
#include <QQmlContext>
#include "conversation.h"
#include "conversations-model.h"
#include "messages-model.h"
#include "pinned-contacts-model.h"
#include "contact-pin.h"
#include "filtered-pinned-contacts-proxy-model.h"
#include "telepathy-manager.h"
#include <TelepathyQt/PendingChannelRequest>
#include "KTp/types.h"
#include "KTp/global-presence.h"
#include "KTp/Models/presence-model.h"
#include "KTp/Models/contacts-filter-model.h"
#include "KTp/Models/contacts-model.h"
#include "KTp/Models/accounts-list-model.h"
#include <QtQml>
void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *uri)
{
Q_UNUSED(uri)
engine->rootContext()->setContextProperty(QLatin1String("telepathyManager"), new TelepathyManager(engine));
}
void QmlPlugins::registerTypes(const char *uri)
{
qmlRegisterType<KTp::ContactsModel> (uri, 0, 1, "ContactsModel");
qmlRegisterType<KTp::AccountsListModel> (uri, 0, 1, "AccountsListModel");
qmlRegisterType<ConversationsModel> (uri, 0, 1, "ConversationsModel");
qmlRegisterType<Conversation>(uri, 0, 1, "Conversation");
qmlRegisterType<PinnedContactsModel>(uri, 0, 1, "PinnedContactsModel");
qmlRegisterType<ContactPin>(uri, 0, 1, "ContactPin");
qmlRegisterType<FilteredPinnedContactsProxyModel>(uri, 0, 1, "FilteredPinnedContactsProxyModel");
qmlRegisterType<KTp::GlobalPresence> (uri, 0, 1, "GlobalPresence");
qmlRegisterType<KTp::PresenceModel> (uri, 0, 1, "PresenceModel");
qmlRegisterUncreatableType<MessagesModel> (uri, 0, 1, "MessagesModel",
QLatin1String("It will be created once the conversation is created"));
qmlRegisterType<TelepathyManager>();
qmlRegisterType<ConversationsModel>();
qmlRegisterType<Tp::PendingChannelRequest>();
qmlRegisterType<Tp::PendingOperation>();
qRegisterMetaType<Tp::Presence>();
qRegisterMetaType<KTp::Presence>();
qRegisterMetaType<Tp::AccountManagerPtr>();
qRegisterMetaType<KTp::ContactPtr>();
qRegisterMetaType<Tp::AccountPtr>();
QMetaType::registerComparators<KTp::Presence>();
}
<|endoftext|>
|
<commit_before>/* This file is part of Zanshin Todo.
Copyright 2008 Kevin Ottens <ervin@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "actionlistdelegate.h"
#include <QtGui/QLineEdit>
#include <QtGui/QAbstractItemView>
#include <QtGui/QStyledItemDelegate>
#include "combomodel.h"
#include "kdateedit.h"
#include "modelstack.h"
#include "todomodel.h"
using namespace KPIM;
ActionListDelegate::ActionListDelegate(ModelStack *models, QObject *parent)
: QStyledItemDelegate(parent)
, m_models(models)
{
}
ActionListDelegate::~ActionListDelegate()
{
}
QSize ActionListDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QSize res = QStyledItemDelegate::sizeHint(option, index);
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
if (!isInFocus(index)) {
res.setHeight(32);
} else if (type!=TodoModel::StandardTodo) {
res.setHeight(24);
}
return res;
}
void ActionListDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
QStyleOptionViewItemV4 opt = option;
if (!isInFocus(index)) {
opt.decorationSize = QSize(1, 1);
opt.displayAlignment = Qt::AlignHCenter|Qt::AlignBottom;
opt.font.setItalic(true);
opt.font.setPointSizeF(opt.font.pointSizeF()*0.75);
} else if (type!=TodoModel::StandardTodo) {
opt.decorationSize = QSize(22, 22);
opt.font.setWeight(QFont::Bold);
} else if (index.parent().isValid()) {
if (index.row()%2==0) {
opt.features|= QStyleOptionViewItemV4::Alternate;
}
}
if (isCompleted(index)) {
opt.font.setStrikeOut(true);
} else if (isOverdue(index)) {
opt.palette.setColor(QPalette::Text, QColor(Qt::red));
opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));
}
QStyledItemDelegate::paint(painter, opt, index);
}
KCal::Todo::Ptr ActionListDelegate::todoFromIndex(const QModelIndex &index) const
{
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
if (type!=TodoModel::StandardTodo) {
return KCal::Todo::Ptr();
}
Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
if (!item.isValid() || !item.hasPayload<KCal::Todo::Ptr>()) {
return KCal::Todo::Ptr();
}
return item.payload<KCal::Todo::Ptr>();
}
bool ActionListDelegate::isInFocus(const QModelIndex &index) const
{
return true;
}
bool ActionListDelegate::isCompleted(const QModelIndex &index) const
{
KCal::Todo::Ptr todo = todoFromIndex(index);
if (todo) {
return todo->isCompleted();
} else {
return false;
}
}
bool ActionListDelegate::isOverdue(const QModelIndex &index) const
{
KCal::Todo::Ptr todo = todoFromIndex(index);
if (todo) {
return todo->isOverdue();
} else {
return false;
}
}
QWidget *ActionListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.data(Qt::EditRole).type()==QVariant::Date) {
return new KDateEdit(parent);
} else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::CategoryType) {
return createComboBox(m_models->categoriesComboModel(), parent, index);
} else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::ProjectType) {
return createComboBox(m_models->treeComboModel(), parent, index);
} else {
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
QWidget *ActionListDelegate::createComboBox(QAbstractItemModel *model, QWidget *parent, const QModelIndex &selectedIndex) const
{
QComboBox *comboBox = new QComboBox(parent);
comboBox->view()->setTextElideMode(Qt::ElideNone);
comboBox->setStyleSheet("* { combobox-popup: true; }");
comboBox->setItemDelegate(new QStyledItemDelegate(comboBox));
ComboModel *comboModel = static_cast<ComboModel*>(model);
if (comboModel) {
comboModel->setSelectedItems(selectedIndex.data(TodoModel::CategoriesRole).value<QStringList>());
comboBox->setModel(model);
}
return comboBox;
}
void ActionListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);
if (dateEdit) {
dateEdit->setDate(index.data(Qt::EditRole).toDate());
if (dateEdit->lineEdit()->text().isEmpty()) {
dateEdit->setDate(QDate::currentDate());
}
dateEdit->lineEdit()->selectAll();
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
void ActionListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);
if (dateEdit) {
model->setData(index, dateEdit->date());
} else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
<commit_msg>Less hackish way to have a large enough popup for the delegate combobox. Thanks to David Faure for the idea.<commit_after>/* This file is part of Zanshin Todo.
Copyright 2008 Kevin Ottens <ervin@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "actionlistdelegate.h"
#include <QtGui/QLineEdit>
#include <QtGui/QAbstractItemView>
#include <QtGui/QStyledItemDelegate>
#include "combomodel.h"
#include "kdateedit.h"
#include "modelstack.h"
#include "todomodel.h"
class ActionListComboBox : public QComboBox
{
public:
ActionListComboBox(QWidget *parent = 0)
: QComboBox(parent) { }
public slots:
virtual void showPopup()
{
QComboBox::showPopup();
int width = 0;
const int itemCount = count();
const int iconWidth = iconSize().width() + 4;
const QFontMetrics &fm = fontMetrics();
for (int i = 0; i < itemCount; ++i) {
const int textWidth = fm.width(itemText(i));
if (itemIcon(i).isNull()) {
width = (qMax(width, textWidth));
} else {
width = (qMax(width, textWidth + iconWidth));
}
}
QStyleOptionComboBox opt;
initStyleOption(&opt);
QSize tmp(width, 0);
tmp = style()->sizeFromContents(QStyle::CT_ComboBox, &opt, tmp, this);
width = tmp.width();
if (width>view()->width()) {
QSize size = view()->parentWidget()->size();
size.setWidth(width + 10);
view()->parentWidget()->resize(size);
}
}
};
using namespace KPIM;
ActionListDelegate::ActionListDelegate(ModelStack *models, QObject *parent)
: QStyledItemDelegate(parent)
, m_models(models)
{
}
ActionListDelegate::~ActionListDelegate()
{
}
QSize ActionListDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QSize res = QStyledItemDelegate::sizeHint(option, index);
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
if (!isInFocus(index)) {
res.setHeight(32);
} else if (type!=TodoModel::StandardTodo) {
res.setHeight(24);
}
return res;
}
void ActionListDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
QStyleOptionViewItemV4 opt = option;
if (!isInFocus(index)) {
opt.decorationSize = QSize(1, 1);
opt.displayAlignment = Qt::AlignHCenter|Qt::AlignBottom;
opt.font.setItalic(true);
opt.font.setPointSizeF(opt.font.pointSizeF()*0.75);
} else if (type!=TodoModel::StandardTodo) {
opt.decorationSize = QSize(22, 22);
opt.font.setWeight(QFont::Bold);
} else if (index.parent().isValid()) {
if (index.row()%2==0) {
opt.features|= QStyleOptionViewItemV4::Alternate;
}
}
if (isCompleted(index)) {
opt.font.setStrikeOut(true);
} else if (isOverdue(index)) {
opt.palette.setColor(QPalette::Text, QColor(Qt::red));
opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));
}
QStyledItemDelegate::paint(painter, opt, index);
}
KCal::Todo::Ptr ActionListDelegate::todoFromIndex(const QModelIndex &index) const
{
TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();
if (type!=TodoModel::StandardTodo) {
return KCal::Todo::Ptr();
}
Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
if (!item.isValid() || !item.hasPayload<KCal::Todo::Ptr>()) {
return KCal::Todo::Ptr();
}
return item.payload<KCal::Todo::Ptr>();
}
bool ActionListDelegate::isInFocus(const QModelIndex &index) const
{
return true;
}
bool ActionListDelegate::isCompleted(const QModelIndex &index) const
{
KCal::Todo::Ptr todo = todoFromIndex(index);
if (todo) {
return todo->isCompleted();
} else {
return false;
}
}
bool ActionListDelegate::isOverdue(const QModelIndex &index) const
{
KCal::Todo::Ptr todo = todoFromIndex(index);
if (todo) {
return todo->isOverdue();
} else {
return false;
}
}
QWidget *ActionListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.data(Qt::EditRole).type()==QVariant::Date) {
return new KDateEdit(parent);
} else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::CategoryType) {
return createComboBox(m_models->categoriesComboModel(), parent, index);
} else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::ProjectType) {
return createComboBox(m_models->treeComboModel(), parent, index);
} else {
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
QWidget *ActionListDelegate::createComboBox(QAbstractItemModel *model, QWidget *parent, const QModelIndex &selectedIndex) const
{
QComboBox *comboBox = new ActionListComboBox(parent);
comboBox->view()->setTextElideMode(Qt::ElideNone);
ComboModel *comboModel = static_cast<ComboModel*>(model);
if (comboModel) {
comboModel->setSelectedItems(selectedIndex.data(TodoModel::CategoriesRole).value<QStringList>());
comboBox->setModel(model);
}
return comboBox;
}
void ActionListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);
if (dateEdit) {
dateEdit->setDate(index.data(Qt::EditRole).toDate());
if (dateEdit->lineEdit()->text().isEmpty()) {
dateEdit->setDate(QDate::currentDate());
}
dateEdit->lineEdit()->selectAll();
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
void ActionListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);
if (dateEdit) {
model->setData(index, dateEdit->date());
} else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
const std::string kAllUrlsTarget =
"files/extensions/api_test/all_urls/index.html";
typedef ExtensionApiTest AllUrlsApiTest;
// http://crbug.com/118293
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, DISABLED_WhitelistedExtension) {
// First setup the two extensions.
FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("content_script");
FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("execute_script");
// Then add the two extensions to the whitelist.
Extension::ScriptingWhitelist whitelist;
whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
Extension::SetScriptingWhitelist(whitelist);
// Then load extensions.
ExtensionService* service = browser()->profile()->GetExtensionService();
const size_t size_before = service->extensions()->size();
ASSERT_TRUE(LoadExtension(extension_dir1));
ASSERT_TRUE(LoadExtension(extension_dir2));
EXPECT_EQ(size_before + 2, service->extensions()->size());
std::string url;
// Now verify we run content scripts on chrome://newtab/.
url = "chrome://newtab/";
ExtensionTestMessageListener listener1a("content script: " + url, false);
ExtensionTestMessageListener listener1b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener1a.WaitUntilSatisfied());
ASSERT_TRUE(listener1b.WaitUntilSatisfied());
// Now verify data: urls.
url = "data:text/html;charset=utf-8,<html>asdf</html>";
ExtensionTestMessageListener listener2a("content script: " + url, false);
ExtensionTestMessageListener listener2b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener2a.WaitUntilSatisfied());
ASSERT_TRUE(listener2b.WaitUntilSatisfied());
// Now verify chrome://version/.
url = "chrome://version/";
ExtensionTestMessageListener listener3a("content script: " + url, false);
ExtensionTestMessageListener listener3b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener3a.WaitUntilSatisfied());
ASSERT_TRUE(listener3b.WaitUntilSatisfied());
// Now verify about:blank.
url = "about:blank";
ExtensionTestMessageListener listener4a("content script: " + url, false);
ExtensionTestMessageListener listener4b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener4a.WaitUntilSatisfied());
ASSERT_TRUE(listener4b.WaitUntilSatisfied());
// Now verify we can script a regular http page.
ASSERT_TRUE(test_server()->Start());
GURL page_url = test_server()->GetURL(kAllUrlsTarget);
ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
false);
ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
ui_test_utils::NavigateToURL(browser(), page_url);
ASSERT_TRUE(listener5a.WaitUntilSatisfied());
ASSERT_TRUE(listener5b.WaitUntilSatisfied());
}
// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
// First load the two extension.
FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("content_script");
FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("execute_script");
ExtensionService* service = browser()->profile()->GetExtensionService();
const size_t size_before = service->extensions()->size();
ASSERT_TRUE(LoadExtension(extension_dir1));
ASSERT_TRUE(LoadExtension(extension_dir2));
EXPECT_EQ(size_before + 2, service->extensions()->size());
// Now verify we can script a regular http page.
ASSERT_TRUE(test_server()->Start());
GURL page_url = test_server()->GetURL(kAllUrlsTarget);
ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
false);
ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
ui_test_utils::NavigateToURL(browser(), page_url);
ASSERT_TRUE(listener1a.WaitUntilSatisfied());
ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<commit_msg>re-enable AllUrlsApiTest.WhitelistedExtension<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
const std::string kAllUrlsTarget =
"files/extensions/api_test/all_urls/index.html";
typedef ExtensionApiTest AllUrlsApiTest;
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) {
// First setup the two extensions.
FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("content_script");
FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("execute_script");
// Then add the two extensions to the whitelist.
Extension::ScriptingWhitelist whitelist;
whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
Extension::SetScriptingWhitelist(whitelist);
// Then load extensions.
ExtensionService* service = browser()->profile()->GetExtensionService();
const size_t size_before = service->extensions()->size();
ASSERT_TRUE(LoadExtension(extension_dir1));
ASSERT_TRUE(LoadExtension(extension_dir2));
EXPECT_EQ(size_before + 2, service->extensions()->size());
std::string url;
// Now verify we run content scripts on chrome://newtab/.
url = "chrome://newtab/";
ExtensionTestMessageListener listener1a("content script: " + url, false);
ExtensionTestMessageListener listener1b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener1a.WaitUntilSatisfied());
ASSERT_TRUE(listener1b.WaitUntilSatisfied());
// Now verify data: urls.
url = "data:text/html;charset=utf-8,<html>asdf</html>";
ExtensionTestMessageListener listener2a("content script: " + url, false);
ExtensionTestMessageListener listener2b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener2a.WaitUntilSatisfied());
ASSERT_TRUE(listener2b.WaitUntilSatisfied());
// Now verify chrome://version/.
url = "chrome://version/";
ExtensionTestMessageListener listener3a("content script: " + url, false);
ExtensionTestMessageListener listener3b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener3a.WaitUntilSatisfied());
ASSERT_TRUE(listener3b.WaitUntilSatisfied());
// Now verify about:blank.
url = "about:blank";
ExtensionTestMessageListener listener4a("content script: " + url, false);
ExtensionTestMessageListener listener4b("execute: " + url, false);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ASSERT_TRUE(listener4a.WaitUntilSatisfied());
ASSERT_TRUE(listener4b.WaitUntilSatisfied());
// Now verify we can script a regular http page.
ASSERT_TRUE(test_server()->Start());
GURL page_url = test_server()->GetURL(kAllUrlsTarget);
ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
false);
ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
ui_test_utils::NavigateToURL(browser(), page_url);
ASSERT_TRUE(listener5a.WaitUntilSatisfied());
ASSERT_TRUE(listener5b.WaitUntilSatisfied());
}
// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
// First load the two extension.
FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("content_script");
FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
.AppendASCII("execute_script");
ExtensionService* service = browser()->profile()->GetExtensionService();
const size_t size_before = service->extensions()->size();
ASSERT_TRUE(LoadExtension(extension_dir1));
ASSERT_TRUE(LoadExtension(extension_dir2));
EXPECT_EQ(size_before + 2, service->extensions()->size());
// Now verify we can script a regular http page.
ASSERT_TRUE(test_server()->Start());
GURL page_url = test_server()->GetURL(kAllUrlsTarget);
ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
false);
ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
ui_test_utils::NavigateToURL(browser(), page_url);
ASSERT_TRUE(listener1a.WaitUntilSatisfied());
ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/ui_controls/ui_controls.h"
#include "ui/views/controls/menu/menu_listener.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace {
// An async version of SendKeyPressSync since we don't get notified when a
// menu is showing.
void SendKeyPress(Browser* browser, ui::KeyboardCode key) {
ASSERT_TRUE(ui_controls::SendKeyPress(
browser->window()->GetNativeHandle(), key, false, false, false, false));
}
// Helper class that waits until the focus has changed to a view other
// than the one with the provided view id.
class ViewFocusChangeWaiter : public views::FocusChangeListener {
public:
ViewFocusChangeWaiter(views::FocusManager* focus_manager,
int previous_view_id)
: focus_manager_(focus_manager),
previous_view_id_(previous_view_id),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
focus_manager_->AddFocusChangeListener(this);
// Call the focus change notification once in case the focus has
// already changed.
OnWillChangeFocus(NULL, focus_manager_->GetFocusedView());
}
virtual ~ViewFocusChangeWaiter() {
focus_manager_->RemoveFocusChangeListener(this);
}
void Wait() {
ui_test_utils::RunMessageLoop();
}
private:
// Inherited from FocusChangeListener
virtual void OnWillChangeFocus(views::View* focused_before,
views::View* focused_now) {
}
virtual void OnDidChangeFocus(views::View* focused_before,
views::View* focused_now) {
if (focused_now && focused_now->id() != previous_view_id_) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
}
views::FocusManager* focus_manager_;
int previous_view_id_;
base::WeakPtrFactory<ViewFocusChangeWaiter> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ViewFocusChangeWaiter);
};
class SendKeysMenuListener : public views::MenuListener {
public:
SendKeysMenuListener(ToolbarView* toolbar_view, Browser* browser)
: toolbar_view_(toolbar_view), browser_(browser) {
toolbar_view_->AddMenuListener(this);
}
virtual ~SendKeysMenuListener() {}
private:
// Overridden from views::MenuListener:
virtual void OnMenuOpened() OVERRIDE {
toolbar_view_->RemoveMenuListener(this);
// Press DOWN to select the first item, then RETURN to select it.
SendKeyPress(browser_, ui::VKEY_DOWN);
SendKeyPress(browser_, ui::VKEY_RETURN);
}
ToolbarView* toolbar_view_;
Browser* browser_;
DISALLOW_COPY_AND_ASSIGN(SendKeysMenuListener);
};
class KeyboardAccessTest : public InProcessBrowserTest {
public:
KeyboardAccessTest() {
EnableDOMAutomation();
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there is one menu and that
// New Tab is the first item in the menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence, bool shift);
int GetFocusedViewID() {
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
const views::FocusManager* focus_manager = widget->GetFocusManager();
const views::View* focused_view = focus_manager->GetFocusedView();
return focused_view ? focused_view->id() : -1;
}
void WaitForFocusedViewIDToChange(int original_view_id) {
if (GetFocusedViewID() != original_view_id)
return;
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
views::FocusManager* focus_manager = widget->GetFocusManager();
ViewFocusChangeWaiter waiter(focus_manager, original_view_id);
waiter.Wait();
}
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence,
bool shift) {
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
ui_test_utils::NavigateToURL(browser(), GURL("about:"));
// The initial tab index should be 0.
ASSERT_EQ(0, browser()->active_index());
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = GetFocusedViewID();
ui_test_utils::WindowedNotificationObserver new_tab_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(browser()));
BrowserView* browser_view = reinterpret_cast<BrowserView*>(
browser()->window());
ToolbarView* toolbar_view = browser_view->GetToolbarView();
SendKeysMenuListener menu_listener(toolbar_view, browser());
#if defined(OS_CHROMEOS)
// Chrome OS doesn't have a way to just focus the wrench menu, so we use Alt+F
// to bring up the menu.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_F, false, shift, true, false));
#else
ui::KeyboardCode menu_key =
alternate_key_sequence ? ui::VKEY_MENU : ui::VKEY_F10;
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), menu_key, false, shift, false, false));
#endif
if (shift) {
// Verify Chrome does not move the view focus. We should not move the view
// focus when typing a menu key with modifier keys, such as shift keys or
// control keys.
int new_view_id = GetFocusedViewID();
ASSERT_EQ(original_view_id, new_view_id);
return;
}
WaitForFocusedViewIDToChange(original_view_id);
// See above comment. Since we already brought up the menu, no need to do this
// on ChromeOS.
#if !defined(OS_CHROMEOS)
if (alternate_key_sequence)
SendKeyPress(browser(), ui::VKEY_DOWN);
else
SendKeyPress(browser(), ui::VKEY_RETURN);
#endif
// Wait for the new tab to appear.
new_tab_observer.Wait();
// Make sure that the new tab index is 1.
ASSERT_EQ(1, browser()->active_index());
}
// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false, false);
}
// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true, false);
}
// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestShiftAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true, true);
}
// Test that JavaScript cannot intercept reserved keyboard accelerators like
// ctrl-t to open a new tab or ctrl-f4 to close a tab.
// TODO(isherman): This test times out on ChromeOS. We should merge it with
// BrowserKeyEventsTest.ReservedAccelerators, but just disable for now.
// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, ReserveKeyboardAccelerators) {
const std::string kBadPage =
"<html><script>"
"document.onkeydown = function() {"
" event.preventDefault();"
" return false;"
"}"
"</script></html>";
GURL url("data:text/html," + kBadPage);
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_TAB, true, false, false, false));
ASSERT_EQ(0, browser()->active_index());
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ASSERT_EQ(2, browser()->active_index());
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_W, true, false, false, false));
ASSERT_EQ(0, browser()->active_index());
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<commit_msg>Mark KeyboardAccessTest.TestShiftAltMenuKeyboardAccess as flaky on Win<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/ui_controls/ui_controls.h"
#include "ui/views/controls/menu/menu_listener.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace {
// An async version of SendKeyPressSync since we don't get notified when a
// menu is showing.
void SendKeyPress(Browser* browser, ui::KeyboardCode key) {
ASSERT_TRUE(ui_controls::SendKeyPress(
browser->window()->GetNativeHandle(), key, false, false, false, false));
}
// Helper class that waits until the focus has changed to a view other
// than the one with the provided view id.
class ViewFocusChangeWaiter : public views::FocusChangeListener {
public:
ViewFocusChangeWaiter(views::FocusManager* focus_manager,
int previous_view_id)
: focus_manager_(focus_manager),
previous_view_id_(previous_view_id),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
focus_manager_->AddFocusChangeListener(this);
// Call the focus change notification once in case the focus has
// already changed.
OnWillChangeFocus(NULL, focus_manager_->GetFocusedView());
}
virtual ~ViewFocusChangeWaiter() {
focus_manager_->RemoveFocusChangeListener(this);
}
void Wait() {
ui_test_utils::RunMessageLoop();
}
private:
// Inherited from FocusChangeListener
virtual void OnWillChangeFocus(views::View* focused_before,
views::View* focused_now) {
}
virtual void OnDidChangeFocus(views::View* focused_before,
views::View* focused_now) {
if (focused_now && focused_now->id() != previous_view_id_) {
MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
}
views::FocusManager* focus_manager_;
int previous_view_id_;
base::WeakPtrFactory<ViewFocusChangeWaiter> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ViewFocusChangeWaiter);
};
class SendKeysMenuListener : public views::MenuListener {
public:
SendKeysMenuListener(ToolbarView* toolbar_view, Browser* browser)
: toolbar_view_(toolbar_view), browser_(browser) {
toolbar_view_->AddMenuListener(this);
}
virtual ~SendKeysMenuListener() {}
private:
// Overridden from views::MenuListener:
virtual void OnMenuOpened() OVERRIDE {
toolbar_view_->RemoveMenuListener(this);
// Press DOWN to select the first item, then RETURN to select it.
SendKeyPress(browser_, ui::VKEY_DOWN);
SendKeyPress(browser_, ui::VKEY_RETURN);
}
ToolbarView* toolbar_view_;
Browser* browser_;
DISALLOW_COPY_AND_ASSIGN(SendKeysMenuListener);
};
class KeyboardAccessTest : public InProcessBrowserTest {
public:
KeyboardAccessTest() {
EnableDOMAutomation();
}
// Use the keyboard to select "New Tab" from the app menu.
// This test depends on the fact that there is one menu and that
// New Tab is the first item in the menu. If the menus change,
// this test will need to be changed to reflect that.
//
// If alternate_key_sequence is true, use "Alt" instead of "F10" to
// open the menu bar, and "Down" instead of "Enter" to open a menu.
void TestMenuKeyboardAccess(bool alternate_key_sequence, bool shift);
int GetFocusedViewID() {
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
const views::FocusManager* focus_manager = widget->GetFocusManager();
const views::View* focused_view = focus_manager->GetFocusedView();
return focused_view ? focused_view->id() : -1;
}
void WaitForFocusedViewIDToChange(int original_view_id) {
if (GetFocusedViewID() != original_view_id)
return;
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
views::FocusManager* focus_manager = widget->GetFocusManager();
ViewFocusChangeWaiter waiter(focus_manager, original_view_id);
waiter.Wait();
}
DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};
void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence,
bool shift) {
// Navigate to a page in the first tab, which makes sure that focus is
// set to the browser window.
ui_test_utils::NavigateToURL(browser(), GURL("about:"));
// The initial tab index should be 0.
ASSERT_EQ(0, browser()->active_index());
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
// Get the focused view ID, then press a key to activate the
// page menu, then wait until the focused view changes.
int original_view_id = GetFocusedViewID();
ui_test_utils::WindowedNotificationObserver new_tab_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(browser()));
BrowserView* browser_view = reinterpret_cast<BrowserView*>(
browser()->window());
ToolbarView* toolbar_view = browser_view->GetToolbarView();
SendKeysMenuListener menu_listener(toolbar_view, browser());
#if defined(OS_CHROMEOS)
// Chrome OS doesn't have a way to just focus the wrench menu, so we use Alt+F
// to bring up the menu.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_F, false, shift, true, false));
#else
ui::KeyboardCode menu_key =
alternate_key_sequence ? ui::VKEY_MENU : ui::VKEY_F10;
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), menu_key, false, shift, false, false));
#endif
if (shift) {
// Verify Chrome does not move the view focus. We should not move the view
// focus when typing a menu key with modifier keys, such as shift keys or
// control keys.
int new_view_id = GetFocusedViewID();
ASSERT_EQ(original_view_id, new_view_id);
return;
}
WaitForFocusedViewIDToChange(original_view_id);
// See above comment. Since we already brought up the menu, no need to do this
// on ChromeOS.
#if !defined(OS_CHROMEOS)
if (alternate_key_sequence)
SendKeyPress(browser(), ui::VKEY_DOWN);
else
SendKeyPress(browser(), ui::VKEY_RETURN);
#endif
// Wait for the new tab to appear.
new_tab_observer.Wait();
// Make sure that the new tab index is 1.
ASSERT_EQ(1, browser()->active_index());
}
// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
TestMenuKeyboardAccess(false, false);
}
// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true, false);
}
// If this flakes, use http://crbug.com/62311.
#if defined(OS_WIN)
#define MAYBE_TestShiftAltMenuKeyboardAccess FLAKY_TestShiftAltMenuKeyboardAccess
#else
#define MAYBE_TestShiftAltMenuKeyboardAccess TestShiftAltMenuKeyboardAccess
#endif
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest,
MAYBE_TestShiftAltMenuKeyboardAccess) {
TestMenuKeyboardAccess(true, true);
}
// Test that JavaScript cannot intercept reserved keyboard accelerators like
// ctrl-t to open a new tab or ctrl-f4 to close a tab.
// TODO(isherman): This test times out on ChromeOS. We should merge it with
// BrowserKeyEventsTest.ReservedAccelerators, but just disable for now.
// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, ReserveKeyboardAccelerators) {
const std::string kBadPage =
"<html><script>"
"document.onkeydown = function() {"
" event.preventDefault();"
" return false;"
"}"
"</script></html>";
GURL url("data:text/html," + kBadPage);
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_TAB, true, false, false, false));
ASSERT_EQ(0, browser()->active_index());
ui_test_utils::NavigateToURLWithDisposition(
browser(), url, NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
ASSERT_EQ(2, browser()->active_index());
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_W, true, false, false, false));
ASSERT_EQ(0, browser()->active_index());
}
} // namespace
#endif // defined(TOOLKIT_VIEWS)
<|endoftext|>
|
<commit_before><commit_msg>Revert 73504 - fix for build break BUG=none TEST=none Review URL: http://codereview.chromium.org/6334063<commit_after><|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;
}
}
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>fix storage path<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.clear(); //= NULL; /*"/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) {
if(this->storagePath.empty()) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
continue;
}
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;
}
}
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) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "build/build_config.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "chrome/browser/ui/gtk/browser_toolbar_gtk.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/browser/ui/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/info_bubble_gtk.h"
#include "chrome/browser/ui/gtk/location_bar_view_gtk.h"
#include "chrome/common/url_constants.h"
#include "content/browser/certificate_viewer.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
class Profile;
namespace {
class PageInfoBubbleGtk : public PageInfoModel::PageInfoModelObserver,
public InfoBubbleGtkDelegate,
public NotificationObserver {
public:
PageInfoBubbleGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history);
virtual ~PageInfoBubbleGtk();
// PageInfoModelObserver implementation:
virtual void ModelChanged();
// NotificationObserver implementation:
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
// InfoBubbleGtkDelegate implementation:
virtual void InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape);
private:
// Layouts the different sections retrieved from the model.
void InitContents();
// Returns a widget that contains the UI for the passed |section|.
GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);
// Link button callbacks.
CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnViewCertLinkClicked);
CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnHelpLinkClicked);
// The model containing the different sections to display.
PageInfoModel model_;
// The url for this dialog. Should be unique among active dialogs.
GURL url_;
// The id of the certificate for this page.
int cert_id_;
// Parent window.
GtkWindow* parent_;
// The virtual box containing the sections.
GtkWidget* contents_;
// The widget relative to which we are positioned.
GtkWidget* anchor_;
// Provides colors and stuff.
GtkThemeService* theme_service_;
// The various elements in the interface we keep track of for theme changes.
std::vector<GtkWidget*> labels_;
std::vector<GtkWidget*> links_;
InfoBubbleGtk* bubble_;
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(PageInfoBubbleGtk);
};
PageInfoBubbleGtk::PageInfoBubbleGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
url_(url),
cert_id_(ssl.cert_id()),
parent_(parent),
contents_(NULL),
theme_service_(GtkThemeService::GetFrom(profile)) {
BrowserWindowGtk* browser_window =
BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent);
anchor_ = browser_window->
GetToolbar()->GetLocationBarView()->location_icon_widget();
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
InitContents();
InfoBubbleGtk::ArrowLocationGtk arrow_location = base::i18n::IsRTL() ?
InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
bubble_ = InfoBubbleGtk::Show(anchor_,
NULL, // |rect|
contents_,
arrow_location,
true, // |match_system_theme|
true, // |grab_input|
theme_service_,
this); // |delegate|
if (!bubble_) {
NOTREACHED();
return;
}
}
PageInfoBubbleGtk::~PageInfoBubbleGtk() {
}
void PageInfoBubbleGtk::ModelChanged() {
InitContents();
}
void PageInfoBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);
for (std::vector<GtkWidget*>::iterator it = links_.begin();
it != links_.end(); ++it) {
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(*it),
theme_service_->UseGtkTheme());
}
if (theme_service_->UseGtkTheme()) {
for (std::vector<GtkWidget*>::iterator it = labels_.begin();
it != labels_.end(); ++it) {
gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, NULL);
}
} else {
for (std::vector<GtkWidget*>::iterator it = labels_.begin();
it != labels_.end(); ++it) {
gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, >k_util::kGdkBlack);
}
}
}
void PageInfoBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape) {
delete this;
}
void PageInfoBubbleGtk::InitContents() {
if (!contents_) {
contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
gtk_container_set_border_width(GTK_CONTAINER(contents_),
gtk_util::kContentAreaBorder);
} else {
labels_.clear();
links_.clear();
gtk_util::RemoveAllChildren(contents_);
}
for (int i = 0; i < model_.GetSectionCount(); i++) {
gtk_box_pack_start(GTK_BOX(contents_),
CreateSection(model_.GetSectionInfo(i)),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(contents_),
gtk_hseparator_new(),
FALSE, FALSE, 0);
}
GtkWidget* help_link = gtk_chrome_link_button_new(
l10n_util::GetStringUTF8(IDS_PAGE_INFO_HELP_CENTER_LINK).c_str());
links_.push_back(help_link);
GtkWidget* help_link_hbox = gtk_hbox_new(FALSE, 0);
// Stick it in an hbox so it doesn't expand to the whole width.
gtk_box_pack_start(GTK_BOX(help_link_hbox), help_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(contents_), help_link_hbox, FALSE, FALSE, 0);
g_signal_connect(help_link, "clicked",
G_CALLBACK(OnHelpLinkClickedThunk), this);
theme_service_->InitThemesFor(this);
gtk_widget_show_all(contents_);
}
GtkWidget* PageInfoBubbleGtk::CreateSection(
const PageInfoModel::SectionInfo& section) {
GtkWidget* section_box = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);
GdkPixbuf* pixbuf = *model_.GetIconImage(section.icon_id);
if (pixbuf) {
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, 0);
gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
}
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(section_box), vbox, TRUE, TRUE, 0);
if (!section.headline.empty()) {
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
labels_.push_back(label);
PangoAttrList* attributes = pango_attr_list_new();
pango_attr_list_insert(attributes,
pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(GTK_LABEL(label), attributes);
pango_attr_list_unref(attributes);
gtk_util::SetLabelWidth(label, 400);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
}
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
labels_.push_back(label);
gtk_util::SetLabelWidth(label, 400);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
if (section.type == PageInfoModel::SECTION_INFO_IDENTITY && cert_id_ > 0) {
GtkWidget* view_cert_link = gtk_chrome_link_button_new(
l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
links_.push_back(view_cert_link);
GtkWidget* cert_link_hbox = gtk_hbox_new(FALSE, 0);
// Stick it in an hbox so it doesn't expand to the whole width.
gtk_box_pack_start(GTK_BOX(cert_link_hbox), view_cert_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), cert_link_hbox, FALSE, FALSE, 0);
g_signal_connect(view_cert_link, "clicked",
G_CALLBACK(OnViewCertLinkClickedThunk), this);
}
return section_box;
}
void PageInfoBubbleGtk::OnViewCertLinkClicked(GtkWidget* widget) {
ShowCertificateViewerByID(GTK_WINDOW(parent_), cert_id_);
bubble_->Close();
}
void PageInfoBubbleGtk::OnHelpLinkClicked(GtkWidget* widget) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kPageInfoHelpCenterURL));
Browser* browser = BrowserList::GetLastActive();
browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
bubble_->Close();
}
} // namespace
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
new PageInfoBubbleGtk(parent, profile, url, ssl, show_history);
}
} // namespace browser
<commit_msg>gtk: Allow text selection in the page info bubble.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtk/gtk.h>
#include "build/build_config.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "chrome/browser/ui/gtk/browser_toolbar_gtk.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/browser/ui/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/info_bubble_gtk.h"
#include "chrome/browser/ui/gtk/location_bar_view_gtk.h"
#include "chrome/common/url_constants.h"
#include "content/browser/certificate_viewer.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
class Profile;
namespace {
class PageInfoBubbleGtk : public PageInfoModel::PageInfoModelObserver,
public InfoBubbleGtkDelegate,
public NotificationObserver {
public:
PageInfoBubbleGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history);
virtual ~PageInfoBubbleGtk();
// PageInfoModelObserver implementation:
virtual void ModelChanged();
// NotificationObserver implementation:
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
// InfoBubbleGtkDelegate implementation:
virtual void InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape);
private:
// Layouts the different sections retrieved from the model.
void InitContents();
// Returns a widget that contains the UI for the passed |section|.
GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);
// Link button callbacks.
CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnViewCertLinkClicked);
CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnHelpLinkClicked);
// The model containing the different sections to display.
PageInfoModel model_;
// The url for this dialog. Should be unique among active dialogs.
GURL url_;
// The id of the certificate for this page.
int cert_id_;
// Parent window.
GtkWindow* parent_;
// The virtual box containing the sections.
GtkWidget* contents_;
// The widget relative to which we are positioned.
GtkWidget* anchor_;
// Provides colors and stuff.
GtkThemeService* theme_service_;
// The various elements in the interface we keep track of for theme changes.
std::vector<GtkWidget*> labels_;
std::vector<GtkWidget*> links_;
InfoBubbleGtk* bubble_;
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(PageInfoBubbleGtk);
};
PageInfoBubbleGtk::PageInfoBubbleGtk(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history)
: ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
show_history, this)),
url_(url),
cert_id_(ssl.cert_id()),
parent_(parent),
contents_(NULL),
theme_service_(GtkThemeService::GetFrom(profile)) {
BrowserWindowGtk* browser_window =
BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent);
anchor_ = browser_window->
GetToolbar()->GetLocationBarView()->location_icon_widget();
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
InitContents();
InfoBubbleGtk::ArrowLocationGtk arrow_location = base::i18n::IsRTL() ?
InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
bubble_ = InfoBubbleGtk::Show(anchor_,
NULL, // |rect|
contents_,
arrow_location,
true, // |match_system_theme|
true, // |grab_input|
theme_service_,
this); // |delegate|
if (!bubble_) {
NOTREACHED();
return;
}
}
PageInfoBubbleGtk::~PageInfoBubbleGtk() {
}
void PageInfoBubbleGtk::ModelChanged() {
InitContents();
}
void PageInfoBubbleGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);
for (std::vector<GtkWidget*>::iterator it = links_.begin();
it != links_.end(); ++it) {
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(*it),
theme_service_->UseGtkTheme());
}
if (theme_service_->UseGtkTheme()) {
for (std::vector<GtkWidget*>::iterator it = labels_.begin();
it != labels_.end(); ++it) {
gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, NULL);
}
} else {
for (std::vector<GtkWidget*>::iterator it = labels_.begin();
it != labels_.end(); ++it) {
gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, >k_util::kGdkBlack);
}
}
}
void PageInfoBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
bool closed_by_escape) {
delete this;
}
void PageInfoBubbleGtk::InitContents() {
if (!contents_) {
contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
gtk_container_set_border_width(GTK_CONTAINER(contents_),
gtk_util::kContentAreaBorder);
} else {
labels_.clear();
links_.clear();
gtk_util::RemoveAllChildren(contents_);
}
for (int i = 0; i < model_.GetSectionCount(); i++) {
gtk_box_pack_start(GTK_BOX(contents_),
CreateSection(model_.GetSectionInfo(i)),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(contents_),
gtk_hseparator_new(),
FALSE, FALSE, 0);
}
GtkWidget* help_link = gtk_chrome_link_button_new(
l10n_util::GetStringUTF8(IDS_PAGE_INFO_HELP_CENTER_LINK).c_str());
links_.push_back(help_link);
GtkWidget* help_link_hbox = gtk_hbox_new(FALSE, 0);
// Stick it in an hbox so it doesn't expand to the whole width.
gtk_box_pack_start(GTK_BOX(help_link_hbox), help_link, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(contents_), help_link_hbox, FALSE, FALSE, 0);
g_signal_connect(help_link, "clicked",
G_CALLBACK(OnHelpLinkClickedThunk), this);
theme_service_->InitThemesFor(this);
gtk_widget_show_all(contents_);
}
GtkWidget* PageInfoBubbleGtk::CreateSection(
const PageInfoModel::SectionInfo& section) {
GtkWidget* section_box = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);
GdkPixbuf* pixbuf = *model_.GetIconImage(section.icon_id);
if (pixbuf) {
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, 0);
gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
}
GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(section_box), vbox, TRUE, TRUE, 0);
if (!section.headline.empty()) {
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
gtk_label_set_selectable(GTK_LABEL(label), TRUE);
labels_.push_back(label);
PangoAttrList* attributes = pango_attr_list_new();
pango_attr_list_insert(attributes,
pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(GTK_LABEL(label), attributes);
pango_attr_list_unref(attributes);
gtk_util::SetLabelWidth(label, 400);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
}
GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
gtk_label_set_selectable(GTK_LABEL(label), TRUE);
labels_.push_back(label);
gtk_util::SetLabelWidth(label, 400);
// Allow linebreaking in the middle of words if necessary, so that extremely
// long hostnames (longer than one line) will still be completely shown.
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
if (section.type == PageInfoModel::SECTION_INFO_IDENTITY && cert_id_ > 0) {
GtkWidget* view_cert_link = gtk_chrome_link_button_new(
l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
links_.push_back(view_cert_link);
GtkWidget* cert_link_hbox = gtk_hbox_new(FALSE, 0);
// Stick it in an hbox so it doesn't expand to the whole width.
gtk_box_pack_start(GTK_BOX(cert_link_hbox), view_cert_link,
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), cert_link_hbox, FALSE, FALSE, 0);
g_signal_connect(view_cert_link, "clicked",
G_CALLBACK(OnViewCertLinkClickedThunk), this);
}
return section_box;
}
void PageInfoBubbleGtk::OnViewCertLinkClicked(GtkWidget* widget) {
ShowCertificateViewerByID(GTK_WINDOW(parent_), cert_id_);
bubble_->Close();
}
void PageInfoBubbleGtk::OnHelpLinkClicked(GtkWidget* widget) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kPageInfoHelpCenterURL));
Browser* browser = BrowserList::GetLastActive();
browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
bubble_->Close();
}
} // namespace
namespace browser {
void ShowPageInfoBubble(gfx::NativeWindow parent,
Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history) {
new PageInfoBubbleGtk(parent, profile, url, ssl, show_history);
}
} // namespace browser
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/controls/textfield/textfield.h"
#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"
namespace views {
// static
const char Textfield::kViewClassName[] = "views/Textfield";
/////////////////////////////////////////////////////////////////////////////
// Textfield
Textfield::Textfield()
: native_wrapper_(NULL),
controller_(NULL),
style_(STYLE_DEFAULT),
read_only_(false),
default_width_in_chars_(0),
draw_border_(true),
background_color_(SK_ColorWHITE),
use_default_background_color_(true),
num_lines_(1),
initialized_(false) {
SetFocusable(true);
}
Textfield::Textfield(StyleFlags style)
: native_wrapper_(NULL),
controller_(NULL),
style_(style),
read_only_(false),
default_width_in_chars_(0),
draw_border_(true),
background_color_(SK_ColorWHITE),
use_default_background_color_(true),
num_lines_(1),
initialized_(false) {
SetFocusable(true);
}
Textfield::~Textfield() {
if (native_wrapper_)
delete native_wrapper_;
}
void Textfield::SetController(Controller* controller) {
controller_ = controller;
}
Textfield::Controller* Textfield::GetController() const {
return controller_;
}
void Textfield::SetReadOnly(bool read_only) {
read_only_ = read_only;
if (native_wrapper_) {
native_wrapper_->UpdateReadOnly();
native_wrapper_->UpdateBackgroundColor();
}
}
bool Textfield::IsPassword() const {
return style_ & STYLE_PASSWORD;
}
bool Textfield::IsMultiLine() const {
return !!(style_ & STYLE_MULTILINE);
}
void Textfield::SetText(const std::wstring& text) {
text_ = text;
if (native_wrapper_)
native_wrapper_->UpdateText();
}
void Textfield::AppendText(const std::wstring& text) {
text_ += text;
if (native_wrapper_)
native_wrapper_->AppendText(text);
}
void Textfield::SelectAll() {
if (native_wrapper_)
native_wrapper_->SelectAll();
}
void Textfield::ClearSelection() const {
if (native_wrapper_)
native_wrapper_->ClearSelection();
}
void Textfield::SetBackgroundColor(SkColor color) {
background_color_ = color;
use_default_background_color_ = false;
if (native_wrapper_)
native_wrapper_->UpdateBackgroundColor();
}
void Textfield::UseDefaultBackgroundColor() {
use_default_background_color_ = true;
if (native_wrapper_)
native_wrapper_->UpdateBackgroundColor();
}
void Textfield::SetFont(const gfx::Font& font) {
font_ = font;
if (native_wrapper_)
native_wrapper_->UpdateFont();
}
void Textfield::SetHorizontalMargins(int left, int right) {
if (native_wrapper_)
native_wrapper_->SetHorizontalMargins(left, right);
}
void Textfield::SetHeightInLines(int num_lines) {
DCHECK(IsMultiLine());
num_lines_ = num_lines;
}
void Textfield::RemoveBorder() {
if (!draw_border_)
return;
draw_border_ = false;
if (native_wrapper_)
native_wrapper_->UpdateBorder();
}
void Textfield::CalculateInsets(gfx::Insets* insets) {
DCHECK(insets);
if (!draw_border_)
return;
// NOTE: One would think GetThemeMargins would return the insets we should
// use, but it doesn't. The margins returned by GetThemeMargins are always
// 0.
// This appears to be the insets used by Windows.
insets->Set(3, 3, 3, 3);
}
void Textfield::SyncText() {
if (native_wrapper_)
text_ = native_wrapper_->GetText();
}
// static
bool Textfield::IsKeystrokeEnter(const Keystroke& key) {
#if defined(OS_WIN)
return key.key == VK_RETURN;
#else
// TODO(port): figure out VK_constants
NOTIMPLEMENTED();
return false;
#endif
}
// static
bool Textfield::IsKeystrokeEscape(const Keystroke& key) {
#if defined(OS_WIN)
return key.key == VK_ESCAPE;
#else
// TODO(port): figure out VK_constants
NOTIMPLEMENTED();
return false;
#endif
}
////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:
void Textfield::Layout() {
if (native_wrapper_) {
native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
native_wrapper_->GetView()->Layout();
}
}
gfx::Size Textfield::GetPreferredSize() {
gfx::Insets insets;
CalculateInsets(&insets);
return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
insets.width(),
num_lines_ * font_.height() + insets.height());
}
bool Textfield::IsFocusable() const {
return IsEnabled() && !read_only_;
}
void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
SelectAll();
}
bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
// TODO(hamaji): Figure out which keyboard combinations we need to add here,
// similar to LocationBarView::SkipDefaultKeyEventProcessing.
const int c = e.GetCharacter();
if (c == VK_BACK)
return true; // We'll handle BackSpace ourselves.
// We don't translate accelerators for ALT + NumPad digit, they are used for
// entering special characters. We do translate alt-home.
if (e.IsAltDown() && (c != VK_HOME) &&
win_util::IsNumPadDigit(c, e.IsExtendedKey()))
return true;
#endif
return false;
}
void Textfield::SetEnabled(bool enabled) {
View::SetEnabled(enabled);
if (native_wrapper_)
native_wrapper_->UpdateEnabled();
}
void Textfield::Focus() {
if (native_wrapper_) {
// Forward the focus to the wrapper if it exists.
native_wrapper_->SetFocus();
} else {
// If there is no wrapper, cause the RootView to be focused so that we still
// get keyboard messages.
View::Focus();
}
}
void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
initialized_ = true;
native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
//AddChildView(native_wrapper_->GetView());
// TODO(beng): Move this initialization to NativeTextfieldWin once it
// subclasses NativeControlWin.
native_wrapper_->UpdateText();
native_wrapper_->UpdateBackgroundColor();
native_wrapper_->UpdateReadOnly();
native_wrapper_->UpdateFont();
native_wrapper_->UpdateEnabled();
native_wrapper_->UpdateBorder();
}
}
std::string Textfield::GetClassName() const {
return kViewClassName;
}
} // namespace views
<commit_msg>Lands http://codereview.chromium.org/131064 for tedoc2000.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/controls/textfield/textfield.h"
#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"
namespace views {
// static
const char Textfield::kViewClassName[] = "views/Textfield";
/////////////////////////////////////////////////////////////////////////////
// Textfield
Textfield::Textfield()
: native_wrapper_(NULL),
controller_(NULL),
style_(STYLE_DEFAULT),
read_only_(false),
default_width_in_chars_(0),
draw_border_(true),
background_color_(SK_ColorWHITE),
use_default_background_color_(true),
num_lines_(1),
initialized_(false) {
SetFocusable(true);
}
Textfield::Textfield(StyleFlags style)
: native_wrapper_(NULL),
controller_(NULL),
style_(style),
read_only_(false),
default_width_in_chars_(0),
draw_border_(true),
background_color_(SK_ColorWHITE),
use_default_background_color_(true),
num_lines_(1),
initialized_(false) {
SetFocusable(true);
}
Textfield::~Textfield() {
if (native_wrapper_)
delete native_wrapper_;
}
void Textfield::SetController(Controller* controller) {
controller_ = controller;
}
Textfield::Controller* Textfield::GetController() const {
return controller_;
}
void Textfield::SetReadOnly(bool read_only) {
read_only_ = read_only;
if (native_wrapper_) {
native_wrapper_->UpdateReadOnly();
native_wrapper_->UpdateBackgroundColor();
}
}
bool Textfield::IsPassword() const {
return style_ & STYLE_PASSWORD;
}
bool Textfield::IsMultiLine() const {
return !!(style_ & STYLE_MULTILINE);
}
void Textfield::SetText(const std::wstring& text) {
text_ = text;
if (native_wrapper_)
native_wrapper_->UpdateText();
}
void Textfield::AppendText(const std::wstring& text) {
text_ += text;
if (native_wrapper_)
native_wrapper_->AppendText(text);
}
void Textfield::SelectAll() {
if (native_wrapper_)
native_wrapper_->SelectAll();
}
void Textfield::ClearSelection() const {
if (native_wrapper_)
native_wrapper_->ClearSelection();
}
void Textfield::SetBackgroundColor(SkColor color) {
background_color_ = color;
use_default_background_color_ = false;
if (native_wrapper_)
native_wrapper_->UpdateBackgroundColor();
}
void Textfield::UseDefaultBackgroundColor() {
use_default_background_color_ = true;
if (native_wrapper_)
native_wrapper_->UpdateBackgroundColor();
}
void Textfield::SetFont(const gfx::Font& font) {
font_ = font;
if (native_wrapper_)
native_wrapper_->UpdateFont();
}
void Textfield::SetHorizontalMargins(int left, int right) {
if (native_wrapper_)
native_wrapper_->SetHorizontalMargins(left, right);
}
void Textfield::SetHeightInLines(int num_lines) {
DCHECK(IsMultiLine());
num_lines_ = num_lines;
}
void Textfield::RemoveBorder() {
if (!draw_border_)
return;
draw_border_ = false;
if (native_wrapper_)
native_wrapper_->UpdateBorder();
}
void Textfield::CalculateInsets(gfx::Insets* insets) {
DCHECK(insets);
if (!draw_border_)
return;
// NOTE: One would think GetThemeMargins would return the insets we should
// use, but it doesn't. The margins returned by GetThemeMargins are always
// 0.
// This appears to be the insets used by Windows.
insets->Set(3, 3, 3, 3);
}
void Textfield::SyncText() {
if (native_wrapper_)
text_ = native_wrapper_->GetText();
}
// static
bool Textfield::IsKeystrokeEnter(const Keystroke& key) {
#if defined(OS_WIN)
return key.key == VK_RETURN;
#else
// TODO(port): figure out VK_constants
NOTIMPLEMENTED();
return false;
#endif
}
// static
bool Textfield::IsKeystrokeEscape(const Keystroke& key) {
#if defined(OS_WIN)
return key.key == VK_ESCAPE;
#else
// TODO(port): figure out VK_constants
NOTIMPLEMENTED();
return false;
#endif
}
////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:
void Textfield::Layout() {
if (native_wrapper_) {
native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
native_wrapper_->GetView()->Layout();
}
}
gfx::Size Textfield::GetPreferredSize() {
gfx::Insets insets;
CalculateInsets(&insets);
return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
insets.width(),
num_lines_ * font_.height() + insets.height());
}
bool Textfield::IsFocusable() const {
return IsEnabled() && !read_only_;
}
void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
SelectAll();
}
bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
// TODO(hamaji): Figure out which keyboard combinations we need to add here,
// similar to LocationBarView::SkipDefaultKeyEventProcessing.
const int c = e.GetCharacter();
if (c == VK_BACK)
return true; // We'll handle BackSpace ourselves.
// We don't translate accelerators for ALT + NumPad digit, they are used for
// entering special characters. We do translate alt-home.
if (e.IsAltDown() && (c != VK_HOME) &&
win_util::IsNumPadDigit(c, e.IsExtendedKey()))
return true;
#endif
return false;
}
void Textfield::SetEnabled(bool enabled) {
View::SetEnabled(enabled);
if (native_wrapper_)
native_wrapper_->UpdateEnabled();
}
void Textfield::Focus() {
if (native_wrapper_) {
// Forward the focus to the wrapper if it exists.
native_wrapper_->SetFocus();
} else {
// If there is no wrapper, cause the RootView to be focused so that we still
// get keyboard messages.
View::Focus();
}
}
void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
initialized_ = true;
native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
//AddChildView(native_wrapper_->GetView());
// TODO(beng): Move this initialization to NativeTextfieldWin once it
// subclasses NativeControlWin.
native_wrapper_->UpdateText();
native_wrapper_->UpdateBackgroundColor();
native_wrapper_->UpdateReadOnly();
native_wrapper_->UpdateFont();
native_wrapper_->UpdateEnabled();
native_wrapper_->UpdateBorder();
// We need to call Layout here because any previous calls to Layout
// will have short-circuited and we don't call AddChildView.
Layout();
}
}
std::string Textfield::GetClassName() const {
return kViewClassName;
}
} // namespace views
<|endoftext|>
|
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#include "../../core/Setup.h"
#if OUZEL_COMPILE_OPENAL
#if defined(__APPLE__)
# include <TargetConditionals.h>
#endif
#if TARGET_OS_IOS || TARGET_OS_TV
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
extern "C" id const AVAudioSessionCategoryAmbient;
#endif
#include "OALAudioDevice.hpp"
#include "OALErrorCategory.hpp"
#include "ALCErrorCategory.hpp"
#include "../../core/Engine.hpp"
#include "../../utils/Log.hpp"
#ifndef AL_FORMAT_MONO_FLOAT32
# define AL_FORMAT_MONO_FLOAT32 0x10010
#endif
#ifndef AL_FORMAT_STEREO_FLOAT32
# define AL_FORMAT_STEREO_FLOAT32 0x10011
#endif
namespace ouzel::audio::openal
{
namespace
{
const ErrorCategory openALErrorCategory{};
const alc::ErrorCategory alcErrorCategory{};
}
AudioDevice::AudioDevice(const Settings& settings,
const std::function<void(std::uint32_t frames,
std::uint32_t channels,
std::uint32_t sampleRate,
std::vector<float>& samples)>& initDataGetter):
audio::AudioDevice(Driver::openAL, settings, initDataGetter)
{
#if TARGET_OS_IOS || TARGET_OS_TV
id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); // [AVAudioSession sharedInstance]
if (!reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil)) // [audioSession setCategory:AVAudioSessionCategoryAmbient error:nil]
throw std::runtime_error("Failed to set audio session category");
id currentRoute = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(audioSession, sel_getUid("currentRoute")); // [audioSession currentRoute]
id outputs = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(currentRoute, sel_getUid("outputs")); // [currentRoute outputs]
const auto count = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(outputs, sel_getUid("count")); // [outputs count]
NSUInteger maxChannelCount = 0;
for (NSUInteger outputIndex = 0; outputIndex < count; ++outputIndex)
{
id output = reinterpret_cast<id (*)(id, SEL, NSUInteger)>(&objc_msgSend)(outputs, sel_getUid("objectAtIndex:"), outputIndex); // [outputs objectAtIndex:outputIndex]
id channels = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(output, sel_getUid("channels")); // [output channels]
const auto channelCount = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(channels, sel_getUid("count")); // [channels count]
if (channelCount > maxChannelCount)
maxChannelCount = channelCount;
}
if (channels > maxChannelCount)
channels = static_cast<std::uint32_t>(maxChannelCount);
#endif
const auto deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
logger.log(Log::Level::info) << "Using " << deviceName << " for audio";
device = alcOpenDevice(deviceName);
if (!device)
throw std::runtime_error("Failed to open ALC device");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to create ALC device");
ALCint majorVersion;
alcGetIntegerv(device, ALC_MAJOR_VERSION, sizeof(majorVersion), &majorVersion);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to get major version");
apiMajorVersion = static_cast<std::uint16_t>(majorVersion);
ALCint minorVersion;
alcGetIntegerv(device, ALC_MINOR_VERSION, sizeof(minorVersion), &minorVersion);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to get minor version");
apiMinorVersion = static_cast<std::uint16_t>(minorVersion);
logger.log(Log::Level::info) << "OpenAL version " << apiMajorVersion << '.' << apiMinorVersion;
context = alcCreateContext(device, nullptr);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to create ALC context");
if (!context)
throw std::runtime_error("Failed to create ALC context");
if (!alcMakeContextCurrent(context))
throw std::runtime_error("Failed to make ALC context current");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current");
const auto audioRenderer = alGetString(AL_RENDERER);
if (const auto error = alGetError(); error != AL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenAL renderer, error: " + std::to_string(error);
else if (!audioRenderer)
logger.log(Log::Level::warning) << "Failed to get OpenAL renderer";
else
logger.log(Log::Level::info) << "Using " << audioRenderer << " audio renderer";
std::vector<std::string> extensions;
const auto extensionsPtr = alGetString(AL_EXTENSIONS);
if (const auto error = alGetError(); error != AL_NO_ERROR || !extensionsPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions";
else
extensions = explodeString(std::string(extensionsPtr), ' ');
logger.log(Log::Level::all) << "Supported OpenAL extensions: " << extensions;
auto float32Supported = false;
for (const std::string& extension : extensions)
{
if (extension == "AL_EXT_float32")
float32Supported = true;
}
alGenSources(1, &sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL source");
alGenBuffers(static_cast<ALsizei>(bufferIds.size()),
bufferIds.data());
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL buffers");
switch (channels)
{
case 1:
{
if (float32Supported)
{
format = AL_FORMAT_MONO_FLOAT32;
sampleFormat = SampleFormat::float32;
sampleSize = sizeof(float);
}
else
{
format = AL_FORMAT_MONO16;
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
}
break;
}
case 2:
{
if (float32Supported)
{
format = AL_FORMAT_STEREO_FLOAT32;
sampleFormat = SampleFormat::float32;
sampleSize = sizeof(float);
}
else
{
format = AL_FORMAT_STEREO16;
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
}
break;
}
case 4:
{
format = alGetEnumValue("AL_FORMAT_QUAD16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 6:
{
format = alGetEnumValue("AL_FORMAT_51CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 7:
{
format = alGetEnumValue("AL_FORMAT_61CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 8:
{
format = alGetEnumValue("AL_FORMAT_71CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
default:
throw std::runtime_error("Invalid channel count");
}
}
AudioDevice::~AudioDevice()
{
#if !defined(__EMSCRIPTEN__)
running = false;
if (audioThread.isJoinable()) audioThread.join();
#endif
if (context)
{
alcMakeContextCurrent(context);
if (sourceId)
{
alSourceStop(sourceId);
alSourcei(sourceId, AL_BUFFER, 0);
alDeleteSources(1, &sourceId);
alGetError();
}
for (const auto bufferId : bufferIds)
{
if (bufferId)
{
alDeleteBuffers(1, &bufferId);
alGetError();
}
}
alcMakeContextCurrent(nullptr);
alcDestroyContext(context);
}
if (device)
alcCloseDevice(device);
}
void AudioDevice::start()
{
getData(bufferSize / (channels * sampleSize), data);
alBufferData(bufferIds[0], format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
getData(bufferSize / (channels * sampleSize), data);
alBufferData(bufferIds[1], format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
alSourceQueueBuffers(sourceId,
static_cast<ALsizei>(bufferIds.size()),
bufferIds.data());
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffers");
alSourcePlay(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source");
if (!alcMakeContextCurrent(nullptr))
throw std::runtime_error("Failed to unset current ALC context");
#if !defined(__EMSCRIPTEN__)
running = true;
audioThread = thread::Thread(&AudioDevice::run, this);
#endif
}
void AudioDevice::stop()
{
#if !defined(__EMSCRIPTEN__)
running = false;
if (audioThread.isJoinable()) audioThread.join();
#endif
alSourceStop(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to stop OpenAL source");
}
void AudioDevice::process()
{
ALint buffersProcessed;
alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to get processed buffer count");
// requeue all processed buffers
for (ALint i = 0; i < buffersProcessed; ++i)
{
ALuint buffer;
alSourceUnqueueBuffers(sourceId, 1, &buffer);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to unqueue OpenAL buffer");
getData(bufferSize / (channels * sampleSize), data);
alBufferData(buffer, format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
alSourceQueueBuffers(sourceId, 1, &buffer);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffer");
}
if (buffersProcessed == bufferIds.size())
{
ALint state;
alGetSourcei(sourceId, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING)
{
alSourcePlay(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source");
}
}
}
void AudioDevice::run()
{
thread::setCurrentThreadName("Audio");
if (!alcMakeContextCurrent(context))
throw std::runtime_error("Failed to make ALC context current");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current");
#if !defined(__EMSCRIPTEN__)
while (running)
{
try
{
process();
}
catch (const std::exception& e)
{
ouzel::logger.log(ouzel::Log::Level::error) << e.what();
}
}
#endif
}
}
#endif
<commit_msg>Cast the buffer ids size to ALint to silence warnings<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.
#include "../../core/Setup.h"
#if OUZEL_COMPILE_OPENAL
#if defined(__APPLE__)
# include <TargetConditionals.h>
#endif
#if TARGET_OS_IOS || TARGET_OS_TV
# include <objc/message.h>
# include <objc/NSObjCRuntime.h>
extern "C" id const AVAudioSessionCategoryAmbient;
#endif
#include "OALAudioDevice.hpp"
#include "OALErrorCategory.hpp"
#include "ALCErrorCategory.hpp"
#include "../../core/Engine.hpp"
#include "../../utils/Log.hpp"
#ifndef AL_FORMAT_MONO_FLOAT32
# define AL_FORMAT_MONO_FLOAT32 0x10010
#endif
#ifndef AL_FORMAT_STEREO_FLOAT32
# define AL_FORMAT_STEREO_FLOAT32 0x10011
#endif
namespace ouzel::audio::openal
{
namespace
{
const ErrorCategory openALErrorCategory{};
const alc::ErrorCategory alcErrorCategory{};
}
AudioDevice::AudioDevice(const Settings& settings,
const std::function<void(std::uint32_t frames,
std::uint32_t channels,
std::uint32_t sampleRate,
std::vector<float>& samples)>& initDataGetter):
audio::AudioDevice(Driver::openAL, settings, initDataGetter)
{
#if TARGET_OS_IOS || TARGET_OS_TV
id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); // [AVAudioSession sharedInstance]
if (!reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil)) // [audioSession setCategory:AVAudioSessionCategoryAmbient error:nil]
throw std::runtime_error("Failed to set audio session category");
id currentRoute = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(audioSession, sel_getUid("currentRoute")); // [audioSession currentRoute]
id outputs = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(currentRoute, sel_getUid("outputs")); // [currentRoute outputs]
const auto count = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(outputs, sel_getUid("count")); // [outputs count]
NSUInteger maxChannelCount = 0;
for (NSUInteger outputIndex = 0; outputIndex < count; ++outputIndex)
{
id output = reinterpret_cast<id (*)(id, SEL, NSUInteger)>(&objc_msgSend)(outputs, sel_getUid("objectAtIndex:"), outputIndex); // [outputs objectAtIndex:outputIndex]
id channels = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(output, sel_getUid("channels")); // [output channels]
const auto channelCount = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(channels, sel_getUid("count")); // [channels count]
if (channelCount > maxChannelCount)
maxChannelCount = channelCount;
}
if (channels > maxChannelCount)
channels = static_cast<std::uint32_t>(maxChannelCount);
#endif
const auto deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);
logger.log(Log::Level::info) << "Using " << deviceName << " for audio";
device = alcOpenDevice(deviceName);
if (!device)
throw std::runtime_error("Failed to open ALC device");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to create ALC device");
ALCint majorVersion;
alcGetIntegerv(device, ALC_MAJOR_VERSION, sizeof(majorVersion), &majorVersion);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to get major version");
apiMajorVersion = static_cast<std::uint16_t>(majorVersion);
ALCint minorVersion;
alcGetIntegerv(device, ALC_MINOR_VERSION, sizeof(minorVersion), &minorVersion);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to get minor version");
apiMinorVersion = static_cast<std::uint16_t>(minorVersion);
logger.log(Log::Level::info) << "OpenAL version " << apiMajorVersion << '.' << apiMinorVersion;
context = alcCreateContext(device, nullptr);
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to create ALC context");
if (!context)
throw std::runtime_error("Failed to create ALC context");
if (!alcMakeContextCurrent(context))
throw std::runtime_error("Failed to make ALC context current");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current");
const auto audioRenderer = alGetString(AL_RENDERER);
if (const auto error = alGetError(); error != AL_NO_ERROR)
logger.log(Log::Level::warning) << "Failed to get OpenAL renderer, error: " + std::to_string(error);
else if (!audioRenderer)
logger.log(Log::Level::warning) << "Failed to get OpenAL renderer";
else
logger.log(Log::Level::info) << "Using " << audioRenderer << " audio renderer";
std::vector<std::string> extensions;
const auto extensionsPtr = alGetString(AL_EXTENSIONS);
if (const auto error = alGetError(); error != AL_NO_ERROR || !extensionsPtr)
logger.log(Log::Level::warning) << "Failed to get OpenGL extensions";
else
extensions = explodeString(std::string(extensionsPtr), ' ');
logger.log(Log::Level::all) << "Supported OpenAL extensions: " << extensions;
auto float32Supported = false;
for (const std::string& extension : extensions)
{
if (extension == "AL_EXT_float32")
float32Supported = true;
}
alGenSources(1, &sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL source");
alGenBuffers(static_cast<ALsizei>(bufferIds.size()),
bufferIds.data());
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL buffers");
switch (channels)
{
case 1:
{
if (float32Supported)
{
format = AL_FORMAT_MONO_FLOAT32;
sampleFormat = SampleFormat::float32;
sampleSize = sizeof(float);
}
else
{
format = AL_FORMAT_MONO16;
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
}
break;
}
case 2:
{
if (float32Supported)
{
format = AL_FORMAT_STEREO_FLOAT32;
sampleFormat = SampleFormat::float32;
sampleSize = sizeof(float);
}
else
{
format = AL_FORMAT_STEREO16;
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
}
break;
}
case 4:
{
format = alGetEnumValue("AL_FORMAT_QUAD16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 6:
{
format = alGetEnumValue("AL_FORMAT_51CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 7:
{
format = alGetEnumValue("AL_FORMAT_61CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
case 8:
{
format = alGetEnumValue("AL_FORMAT_71CHN16");
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value");
sampleFormat = SampleFormat::signedInt16;
sampleSize = sizeof(std::int16_t);
break;
}
default:
throw std::runtime_error("Invalid channel count");
}
}
AudioDevice::~AudioDevice()
{
#if !defined(__EMSCRIPTEN__)
running = false;
if (audioThread.isJoinable()) audioThread.join();
#endif
if (context)
{
alcMakeContextCurrent(context);
if (sourceId)
{
alSourceStop(sourceId);
alSourcei(sourceId, AL_BUFFER, 0);
alDeleteSources(1, &sourceId);
alGetError();
}
for (const auto bufferId : bufferIds)
{
if (bufferId)
{
alDeleteBuffers(1, &bufferId);
alGetError();
}
}
alcMakeContextCurrent(nullptr);
alcDestroyContext(context);
}
if (device)
alcCloseDevice(device);
}
void AudioDevice::start()
{
getData(bufferSize / (channels * sampleSize), data);
alBufferData(bufferIds[0], format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
getData(bufferSize / (channels * sampleSize), data);
alBufferData(bufferIds[1], format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
alSourceQueueBuffers(sourceId,
static_cast<ALsizei>(bufferIds.size()),
bufferIds.data());
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffers");
alSourcePlay(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source");
if (!alcMakeContextCurrent(nullptr))
throw std::runtime_error("Failed to unset current ALC context");
#if !defined(__EMSCRIPTEN__)
running = true;
audioThread = thread::Thread(&AudioDevice::run, this);
#endif
}
void AudioDevice::stop()
{
#if !defined(__EMSCRIPTEN__)
running = false;
if (audioThread.isJoinable()) audioThread.join();
#endif
alSourceStop(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to stop OpenAL source");
}
void AudioDevice::process()
{
ALint buffersProcessed;
alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to get processed buffer count");
// requeue all processed buffers
for (ALint i = 0; i < buffersProcessed; ++i)
{
ALuint buffer;
alSourceUnqueueBuffers(sourceId, 1, &buffer);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to unqueue OpenAL buffer");
getData(bufferSize / (channels * sampleSize), data);
alBufferData(buffer, format,
data.data(),
static_cast<ALsizei>(data.size()),
static_cast<ALsizei>(sampleRate));
alSourceQueueBuffers(sourceId, 1, &buffer);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffer");
}
if (buffersProcessed == static_cast<ALint>(bufferIds.size()))
{
ALint state;
alGetSourcei(sourceId, AL_SOURCE_STATE, &state);
if (state != AL_PLAYING)
{
alSourcePlay(sourceId);
if (const auto error = alGetError(); error != AL_NO_ERROR)
throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source");
}
}
}
void AudioDevice::run()
{
thread::setCurrentThreadName("Audio");
if (!alcMakeContextCurrent(context))
throw std::runtime_error("Failed to make ALC context current");
if (const auto error = alcGetError(device); error != ALC_NO_ERROR)
throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current");
#if !defined(__EMSCRIPTEN__)
while (running)
{
try
{
process();
}
catch (const std::exception& e)
{
ouzel::logger.log(ouzel::Log::Level::error) << e.what();
}
}
#endif
}
}
#endif
<|endoftext|>
|
<commit_before>#include "Players/Alan_Turing_AI.h"
#include <vector>
#include <cmath>
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Pieces/Piece.h"
#include "Game/Game_Result.h"
#include "Game/Color.h"
#include "Moves/Threat_Generator.h"
const Move& Alan_Turing_AI::choose_move(const Board& board, const Clock&) const
{
// Every possible first move is considerable
std::pair<double, double> best_first_move_score = {-1001.0, -1001.0}; // maximize
auto best_first_move = board.legal_moves().front();
for(auto first_move : board.legal_moves())
{
auto first_board = board;
auto first_move_result = first_board.submit_move(*first_move);
std::pair<double, double> first_move_score;
if(first_move_result.game_has_ended())
{
first_move_score = position_value(first_board, board.whose_turn(), first_move_result);
}
else
{
// Every possible reply is considerable
std::pair<double, double> worst_second_move_score = {1001.0, 1001.0}; // minimize
for(auto second_move : first_board.legal_moves())
{
auto second_board = first_board;
std::pair<double, double> second_move_score;
auto second_move_result = second_board.submit_move(*second_move);
if(second_move_result.game_has_ended())
{
second_move_score = position_value(second_board, board.whose_turn(), second_move_result);
}
else
{
std::pair<double, double> best_third_move_score = {-1001.0, -1001.0}; // maximize
for(auto third_move : second_board.legal_moves())
{
auto third_board = second_board;
auto third_move_result = third_board.submit_move(*third_move);
auto third_move_score = position_value(third_board, board.whose_turn(), third_move_result);
best_third_move_score = std::max(best_third_move_score, third_move_score);
}
second_move_score = best_third_move_score;
}
worst_second_move_score = std::min(worst_second_move_score, second_move_score);
}
first_move_score = worst_second_move_score;
}
if(first_move_score > best_first_move_score)
{
best_first_move = first_move;
best_first_move_score = first_move_score;
}
}
return *best_first_move;
}
std::string Alan_Turing_AI::name() const
{
return "Turbocomp";
}
std::string Alan_Turing_AI::author() const
{
return "Alan Turing";
}
std::vector<const Move*> Alan_Turing_AI::considerable_moves(const Board& board) const
{
std::vector<const Move*> result;
for(auto move : board.legal_moves())
{
if(is_considerable(*move, board))
{
result.push_back(move);
}
}
return result;
}
bool Alan_Turing_AI::is_considerable(const Move& move, const Board& board) const
{
// Recapture is considerable
if(board.last_move_captured() && board.move_captures(move))
{
auto last_move = board.game_record().back();
if(last_move->end_file() == move.end_file() && last_move->end_rank() == move.end_rank())
{
return true;
}
}
auto attacking_piece = board.piece_on_square(move.start_file(), move.start_rank());
auto attacked_piece = board.piece_on_square(move.end_file(), move.end_rank());
if(attacked_piece)
{
// Capturing an undefended piece is considerable
auto temp_board = board;
auto result = temp_board.submit_move(move);
if(temp_board.safe_for_king(move.end_file(), move.end_rank(), attacking_piece->color()))
{
return true;
}
// Capturing with a less valuable piece is considerable
if(piece_value(attacked_piece) > piece_value(attacking_piece))
{
return true;
}
// A mvoe resulting in checkmate is considerable
if(result.winner() == board.whose_turn())
{
return true;
}
}
return false;
}
double Alan_Turing_AI::material_value(const Board& board, Color perspective) const
{
double player_score = 0.0;
double opponent_score = 0.0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(piece)
{
if(piece->color() == perspective)
{
player_score += piece_value(piece);
}
else
{
opponent_score += piece_value(piece);
}
}
}
}
return player_score/opponent_score;
}
double Alan_Turing_AI::piece_value(const Piece* piece) const
{
if(!piece)
{
return 0.0;
}
switch(piece->type())
{
case PAWN:
return 1.0;
case KNIGHT:
return 3.0;
case BISHOP:
return 3.5;
case ROOK:
return 5.0;
case QUEEN:
return 10.0;
default:
return 0.0;
}
}
double Alan_Turing_AI::position_play_value(const Board& board, Color perspective) const
{
double total_score = 0.0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(!piece)
{
continue;
}
if(piece->color() == perspective)
{
if(piece->type() == QUEEN || piece->type() == ROOK || piece->type() == BISHOP || piece->type() == KNIGHT)
{
// Number of moves score
double move_score = 0.0;
for(auto move : board.legal_moves())
{
if(move->start_file() == file || move->start_rank() == rank)
{
move_score += 1.0;
if(board.move_captures(*move))
{
move_score += 1.0;
}
}
}
total_score += std::sqrt(move_score);
// Non-queen pieces defended
if(piece->type() != QUEEN)
{
Square defending_square{};
for(auto defender : Threat_Generator(file, rank, opposite(perspective), board))
{
if(defending_square)
{
total_score += 0.5;
}
else
{
total_score += 1.0;
defending_square = defender;
}
}
}
}
else if(piece->type() == KING)
{
// King move scores
double move_score = 0.0;
for(auto move : board.legal_moves())
{
if(move->start_file() != file || move->start_rank() != rank)
{
continue;
}
if(std::abs(move->file_change()) < 2)
{
move_score += 1.0;
}
}
total_score += std::sqrt(move_score);
// King vulnerability
double king_squares = 0.0;
for(int file_step = -1; file_step <= 1; ++file_step)
{
for(int rank_step = -1; rank_step <= 1; ++rank_step)
{
if(file_step == 0 && rank_step == 0)
{
continue;
}
for(int steps = 1; steps <= 7; ++steps)
{
char attack_file = file + steps*file_step;
int attack_rank = rank + steps*rank_step;
if(!board.inside_board(attack_file, attack_rank))
{
break;
}
auto other_piece = board.piece_on_square(attack_file, attack_rank);
if( ! other_piece)
{
king_squares += 1.0;
}
else
{
if(other_piece->color() != perspective)
{
king_squares += 1.0;
}
break;
}
}
}
}
total_score -= std::sqrt(king_squares);
// Castline score
if(!board.piece_has_moved(file, rank))
{
// Queenside castling
if(!board.piece_has_moved('a', rank))
{
total_score += 1.0;
// Can castle on next move
if(board.all_empty_between('a', rank, file, rank))
{
total_score += 1.0;
}
}
// Kingside castling
if(!board.piece_has_moved('h', rank))
{
total_score += 1.0;
// Can castle on next move
if(board.all_empty_between('h', rank, file, rank))
{
total_score += 1.0;
}
}
}
// Last move was castling
if(board.castling_move_index(perspective) < board.game_record().size())
{
total_score += 1.0;
}
}
else if(piece->type() == PAWN)
{
// Pawn advancement
auto base_rank = (perspective == WHITE ? 2 : 7);
total_score += 0.2*std::abs(base_rank - rank);
// Pawn defended
auto pawn_defended = false;
for(auto piece_type :{QUEEN, ROOK, BISHOP, KNIGHT, KING})
{
if(pawn_defended)
{
break;
}
auto defending_piece = board.piece_instance(piece_type, perspective);
for(auto move : defending_piece->move_list(file, rank))
{
if(defending_piece == board.piece_on_square(move->end_file(), move->end_rank()))
{
if(piece_type == KNIGHT || board.all_empty_between(file, rank, move->end_file(), move->end_rank()))
{
pawn_defended = true;
break;
}
}
}
}
if(pawn_defended)
{
total_score += 0.3;
}
}
}
else // piece->color() == opposite(perpsective)
{
if(piece->type() == KING)
{
auto temp_board = board;
temp_board.set_turn(opposite(perspective));
if(temp_board.king_is_in_check())
{
total_score += 0.5;
}
else
{
temp_board.set_turn(perspective);
for(auto move : temp_board.legal_moves())
{
auto temp_temp_board = temp_board;
if(temp_temp_board.submit_move(*move).winner() != NONE)
{
total_score += 1.0;
}
}
}
}
}
}
}
return total_score;
}
std::pair<double, double> Alan_Turing_AI::position_value(const Board& board, Color perspective, const Game_Result& move_result) const
{
auto best_score = score_board(board, perspective, move_result);
if(move_result.game_has_ended())
{
return best_score;
}
auto considerable_move_list = considerable_moves(board);
// Skip if every move is considerable
if(considerable_move_list.size() < board.legal_moves().size())
{
for(auto move : considerable_moves(board))
{
auto temp_board = board;
auto result = temp_board.submit_move(*move);
best_score = std::max(best_score, score_board(temp_board, perspective, result));
}
}
return best_score;
}
std::pair<double, double> Alan_Turing_AI::score_board(const Board& board, Color perspective, const Game_Result& move_result) const
{
if(move_result.game_has_ended())
{
if(move_result.winner() == perspective)
{
return {1000.0, 1000.0};
}
else if(move_result.winner() == opposite(perspective))
{
return {-1000.0, -1000.0};
}
else
{
return {0.0, 0.0};
}
}
return std::make_pair(material_value(board, perspective), position_play_value(board, perspective));
}
<commit_msg>Fix errors in Alan Turing AI valuations<commit_after>#include "Players/Alan_Turing_AI.h"
#include <vector>
#include <cmath>
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Pieces/Piece.h"
#include "Game/Game_Result.h"
#include "Game/Color.h"
#include "Moves/Threat_Generator.h"
const Move& Alan_Turing_AI::choose_move(const Board& board, const Clock&) const
{
// Every possible first move is considerable
std::pair<double, double> best_first_move_score = {-1001.0, -1001.0}; // maximize
auto best_first_move = board.legal_moves().front();
for(auto first_move : board.legal_moves())
{
auto first_board = board;
auto first_move_result = first_board.submit_move(*first_move);
std::pair<double, double> first_move_score;
if(first_move_result.game_has_ended())
{
first_move_score = position_value(first_board, board.whose_turn(), first_move_result);
}
else
{
// Every possible reply is considerable
std::pair<double, double> worst_second_move_score = {1001.0, 1001.0}; // minimize
for(auto second_move : first_board.legal_moves())
{
auto second_board = first_board;
std::pair<double, double> second_move_score;
auto second_move_result = second_board.submit_move(*second_move);
if(second_move_result.game_has_ended())
{
second_move_score = position_value(second_board, board.whose_turn(), second_move_result);
}
else
{
std::pair<double, double> best_third_move_score = {-1001.0, -1001.0}; // maximize
for(auto third_move : second_board.legal_moves())
{
auto third_board = second_board;
auto third_move_result = third_board.submit_move(*third_move);
auto third_move_score = position_value(third_board, board.whose_turn(), third_move_result);
best_third_move_score = std::max(best_third_move_score, third_move_score);
}
second_move_score = best_third_move_score;
}
worst_second_move_score = std::min(worst_second_move_score, second_move_score);
}
first_move_score = worst_second_move_score;
}
if(first_move_score > best_first_move_score)
{
best_first_move = first_move;
best_first_move_score = first_move_score;
}
}
return *best_first_move;
}
std::string Alan_Turing_AI::name() const
{
return "Turbocomp";
}
std::string Alan_Turing_AI::author() const
{
return "Alan Turing";
}
std::vector<const Move*> Alan_Turing_AI::considerable_moves(const Board& board) const
{
std::vector<const Move*> result;
for(auto move : board.legal_moves())
{
if(is_considerable(*move, board))
{
result.push_back(move);
}
}
return result;
}
bool Alan_Turing_AI::is_considerable(const Move& move, const Board& board) const
{
// Recapture is considerable
if(board.last_move_captured() && board.move_captures(move))
{
auto last_move = board.game_record().back();
if(last_move->end_file() == move.end_file() && last_move->end_rank() == move.end_rank())
{
return true;
}
}
auto attacking_piece = board.piece_on_square(move.start_file(), move.start_rank());
auto attacked_piece = board.piece_on_square(move.end_file(), move.end_rank());
if(attacked_piece)
{
// Capturing an undefended piece is considerable
auto temp_board = board;
auto result = temp_board.submit_move(move);
if(temp_board.safe_for_king(move.end_file(), move.end_rank(), attacking_piece->color()))
{
return true;
}
// Capturing with a less valuable piece is considerable
if(piece_value(attacked_piece) > piece_value(attacking_piece))
{
return true;
}
// A mvoe resulting in checkmate is considerable
if(result.winner() == board.whose_turn())
{
return true;
}
}
return false;
}
double Alan_Turing_AI::material_value(const Board& board, Color perspective) const
{
double player_score = 0.0;
double opponent_score = 0.0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(piece)
{
if(piece->color() == perspective)
{
player_score += piece_value(piece);
}
else
{
opponent_score += piece_value(piece);
}
}
}
}
return player_score/opponent_score;
}
double Alan_Turing_AI::piece_value(const Piece* piece) const
{
if(!piece)
{
return 0.0;
}
switch(piece->type())
{
case PAWN:
return 1.0;
case KNIGHT:
return 3.0;
case BISHOP:
return 3.5;
case ROOK:
return 5.0;
case QUEEN:
return 10.0;
default:
return 0.0;
}
}
double Alan_Turing_AI::position_play_value(const Board& board, Color perspective) const
{
double total_score = 0.0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(!piece)
{
continue;
}
if(piece->color() == perspective)
{
if(piece->type() == QUEEN || piece->type() == ROOK || piece->type() == BISHOP || piece->type() == KNIGHT)
{
// Number of moves score
double move_score = 0.0;
for(auto move : board.legal_moves())
{
if(move->start_file() == file && move->start_rank() == rank)
{
move_score += 1.0;
if(board.move_captures(*move))
{
move_score += 1.0;
}
}
}
total_score += std::sqrt(move_score);
// Non-queen pieces defended
if(piece->type() != QUEEN)
{
Square defending_square{};
for(auto defender : Threat_Generator(file, rank, opposite(perspective), board))
{
if(defending_square)
{
total_score += 0.5;
}
else
{
total_score += 1.0;
defending_square = defender;
}
}
}
}
else if(piece->type() == KING)
{
// King move scores
double move_score = 0.0;
double castling_moves = 0.0;
for(auto move : board.legal_moves())
{
if(move->start_file() != file || move->start_rank() != rank)
{
continue;
}
if(move->is_castling())
{
castling_moves += 1.0;
}
else
{
move_score += 1.0;
}
}
total_score += std::sqrt(move_score) + castling_moves;
// King vulnerability (count number of queen moves from king square and subtract)
double king_squares = 0.0;
for(int file_step = -1; file_step <= 1; ++file_step)
{
for(int rank_step = -1; rank_step <= 1; ++rank_step)
{
if(file_step == 0 && rank_step == 0)
{
continue;
}
for(int steps = 1; steps <= 7; ++steps)
{
char attack_file = file + steps*file_step;
int attack_rank = rank + steps*rank_step;
if(!board.inside_board(attack_file, attack_rank))
{
break;
}
auto other_piece = board.piece_on_square(attack_file, attack_rank);
if( ! other_piece)
{
king_squares += 1.0;
}
else
{
if(other_piece->color() != perspective)
{
king_squares += 1.0;
}
break;
}
}
}
}
total_score -= std::sqrt(king_squares);
// Castline score
if(!board.piece_has_moved(file, rank))
{
// Queenside castling
if(!board.piece_has_moved('a', rank))
{
total_score += 1.0;
// Can castle on next move
if(board.all_empty_between('a', rank, file, rank))
{
total_score += 1.0;
}
}
// Kingside castling
if(!board.piece_has_moved('h', rank))
{
total_score += 1.0;
// Can castle on next move
if(board.all_empty_between('h', rank, file, rank))
{
total_score += 1.0;
}
}
}
// Last move was castling
if(board.castling_move_index(perspective) < board.game_record().size())
{
total_score += 1.0;
}
}
else if(piece->type() == PAWN)
{
// Pawn advancement
auto base_rank = (perspective == WHITE ? 2 : 7);
total_score += 0.2*std::abs(base_rank - rank);
// Pawn defended
auto pawn_defended = false;
for(auto piece_type :{QUEEN, ROOK, BISHOP, KNIGHT, KING})
{
if(pawn_defended)
{
break;
}
auto defending_piece = board.piece_instance(piece_type, perspective);
for(auto move : defending_piece->move_list(file, rank))
{
if(defending_piece == board.piece_on_square(move->end_file(), move->end_rank()))
{
if(piece_type == KNIGHT || board.all_empty_between(file, rank, move->end_file(), move->end_rank()))
{
pawn_defended = true;
break;
}
}
}
}
if(pawn_defended)
{
total_score += 0.3;
}
}
}
else // piece->color() == opposite(perpsective)
{
if(piece->type() == KING)
{
auto temp_board = board;
temp_board.set_turn(opposite(perspective));
if(temp_board.king_is_in_check())
{
total_score += 0.5;
}
else
{
temp_board.set_turn(perspective);
for(auto move : temp_board.legal_moves())
{
auto temp_temp_board = temp_board;
if(temp_temp_board.submit_move(*move).winner() != NONE)
{
total_score += 1.0;
}
}
}
}
}
}
}
return total_score;
}
std::pair<double, double> Alan_Turing_AI::position_value(const Board& board, Color perspective, const Game_Result& move_result) const
{
auto best_score = score_board(board, perspective, move_result);
if(move_result.game_has_ended())
{
return best_score;
}
auto considerable_move_list = considerable_moves(board);
// Skip if every move is considerable
if(considerable_move_list.size() < board.legal_moves().size())
{
for(auto move : considerable_moves(board))
{
auto temp_board = board;
auto result = temp_board.submit_move(*move);
best_score = std::max(best_score, score_board(temp_board, perspective, result));
}
}
return best_score;
}
std::pair<double, double> Alan_Turing_AI::score_board(const Board& board, Color perspective, const Game_Result& move_result) const
{
if(move_result.game_has_ended())
{
if(move_result.winner() == perspective)
{
return {1000.0, 1000.0};
}
else if(move_result.winner() == opposite(perspective))
{
return {-1000.0, -1000.0};
}
else
{
return {0.0, 0.0};
}
}
return std::make_pair(material_value(board, perspective), position_play_value(board, perspective));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
#include "blackwing_lair.h"
#include "GameObject.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "Player.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
DoorData const doorData[] =
{
{ GO_PORTCULLIS_RAZORGORE, DATA_RAZORGORE_THE_UNTAMED, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175946 || GUID 7230
{ GO_PORTCULLIS_VAELASTRASZ, DATA_VAELASTRAZ_THE_CORRUPT, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175185 || GUID 7229
{ GO_PORTCULLIS_BROODLORD, DATA_BROODLORD_LASHLAYER, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179365 || GUID 75159
{ GO_PORTCULLIS_THREEDRAGONS, DATA_FIREMAW, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_THREEDRAGONS, DATA_EBONROC, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_THREEDRAGONS, DATA_FLAMEGOR, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_CHROMAGGUS, DATA_CHROMAGGUS, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179116 || GUID 75161
{ GO_PORTCULLIS_NEFARIAN, DATA_NEFARIAN, DOOR_TYPE_ROOM, BOUNDARY_NONE}, // ID 179117 || GUID 75164
{ 0, 0, DOOR_TYPE_ROOM, BOUNDARY_NONE} // END
};
Position const SummonPosition[8] =
{
{-7661.207520f, -1043.268188f, 407.199554f, 6.280452f},
{-7644.145020f, -1065.628052f, 407.204956f, 0.501492f},
{-7624.260742f, -1095.196899f, 407.205017f, 0.544694f},
{-7608.501953f, -1116.077271f, 407.199921f, 0.816443f},
{-7531.841797f, -1063.765381f, 407.199615f, 2.874187f},
{-7547.319336f, -1040.971924f, 407.205078f, 3.789175f},
{-7568.547852f, -1013.112488f, 407.204926f, 3.773467f},
{-7584.175781f, -989.6691289f, 407.199585f, 4.527447f},
};
uint32 const Entry[5] = {12422, 12458, 12416, 12420, 12459};
class instance_blackwing_lair : public InstanceMapScript
{
public:
instance_blackwing_lair() : InstanceMapScript(BWLScriptName, 469) { }
struct instance_blackwing_lair_InstanceMapScript : public InstanceScript
{
instance_blackwing_lair_InstanceMapScript(Map* map) : InstanceScript(map)
{
//SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadDoorData(doorData);
//LoadObjectData(creatureData, gameObjectData);
}
void Initialize() override
{
// Razorgore
EggCount = 0;
EggEvent = 0;
}
void OnCreatureCreate(Creature* creature) override
{
InstanceScript::OnCreatureCreate(creature);
switch (creature->GetEntry())
{
case NPC_BLACKWING_DRAGON:
case NPC_BLACKWING_TASKMASTER:
case NPC_BLACKWING_LEGIONAIRE:
case NPC_BLACKWING_WARLOCK:
if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
if (CreatureAI* razorAI = razor->AI())
razorAI->JustSummoned(creature);
break;
default:
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
InstanceScript::OnGameObjectCreate(go);
switch(go->GetEntry())
{
case GO_BLACK_DRAGON_EGG:
if (GetBossState(DATA_FIREMAW) == DONE)
go->SetPhaseMask(2, true);
else
EggList.push_back(go->GetGUID());
break;
case GO_PORTCULLIS_RAZORGORE:
case GO_PORTCULLIS_VAELASTRASZ:
case GO_PORTCULLIS_BROODLORD:
case GO_PORTCULLIS_THREEDRAGONS:
case GO_PORTCULLIS_CHROMAGGUS:
case GO_PORTCULLIS_NEFARIAN:
AddDoor(go, true);
break;
default:
break;
}
}
void OnGameObjectRemove(GameObject* go) override
{
InstanceScript::OnGameObjectRemove(go);
if (go->GetEntry() == GO_BLACK_DRAGON_EGG)
EggList.remove(go->GetGUID());
switch (go->GetEntry())
{
case GO_PORTCULLIS_RAZORGORE:
case GO_PORTCULLIS_VAELASTRASZ:
case GO_PORTCULLIS_BROODLORD:
case GO_PORTCULLIS_THREEDRAGONS:
case GO_PORTCULLIS_CHROMAGGUS:
case GO_PORTCULLIS_NEFARIAN:
AddDoor(go, false);
break;
default:
break;
}
}
bool CheckRequiredBosses(uint32 bossId, Player const* /* player */) const override
{
switch (bossId)
{
case DATA_BROODLORD_LASHLAYER:
if (GetBossState(DATA_VAELASTRAZ_THE_CORRUPT) != DONE)
return false;
break;
case DATA_CHROMAGGUS:
if (GetBossState(DATA_FIREMAW) != DONE
|| GetBossState(DATA_EBONROC) != DONE
|| GetBossState(DATA_FLAMEGOR) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_RAZORGORE_THE_UNTAMED:
if (state == DONE)
{
for (ObjectGuid const& guid : EggList)
if (GameObject* egg = instance->GetGameObject(guid))
egg->SetPhaseMask(2, true);
}
SetData(DATA_EGG_EVENT, NOT_STARTED);
break;
case DATA_NEFARIAN:
switch (state)
{
case NOT_STARTED:
if (Creature* nefarian = instance->GetCreature(GetGuidData(DATA_NEFARIAN)))
nefarian->DespawnOrUnsummon();
break;
case FAIL:
_events.ScheduleEvent(EVENT_RESPAWN_NEFARIUS, 15 * 60 * IN_MILLISECONDS); //15min
SetBossState(DATA_NEFARIAN, NOT_STARTED);
break;
default:
break;
}
break;
}
return true;
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_EGG_EVENT)
{
switch (data)
{
case IN_PROGRESS:
_events.ScheduleEvent(EVENT_RAZOR_SPAWN, 45000);
EggEvent = data;
EggCount = 0;
break;
case NOT_STARTED:
_events.CancelEvent(EVENT_RAZOR_SPAWN);
EggEvent = data;
EggCount = 0;
break;
case SPECIAL:
if (++EggCount == 15)
{
if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
{
SetData(DATA_EGG_EVENT, DONE);
razor->RemoveAurasDueToSpell(42013); // MindControl
DoRemoveAurasDueToSpellOnPlayers(42013);
}
_events.ScheduleEvent(EVENT_RAZOR_PHASE_TWO, 1000);
_events.CancelEvent(EVENT_RAZOR_SPAWN);
}
if (EggEvent == NOT_STARTED)
SetData(DATA_EGG_EVENT, IN_PROGRESS);
break;
}
}
}
void OnUnitDeath(Unit* unit) override
{
//! HACK, needed because of buggy CreatureAI after charm
if (unit->GetEntry() == NPC_RAZORGORE && GetBossState(DATA_RAZORGORE_THE_UNTAMED) != DONE)
SetBossState(DATA_RAZORGORE_THE_UNTAMED, DONE);
}
void Update(uint32 diff) override
{
if (_events.Empty())
return;
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_RAZOR_SPAWN:
for (uint8 i = urand(2, 5); i > 0; --i)
if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)]))
summon->AI()->DoZoneInCombat();
_events.ScheduleEvent(EVENT_RAZOR_SPAWN, 12000, 17000);
break;
case EVENT_RAZOR_PHASE_TWO:
_events.CancelEvent(EVENT_RAZOR_SPAWN);
if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
razor->AI()->DoAction(ACTION_PHASE_TWO);
break;
case EVENT_RESPAWN_NEFARIUS:
if (Creature* nefarius = instance->GetCreature(GetGuidData(DATA_LORD_VICTOR_NEFARIUS)))
{
nefarius->SetPhaseMask(1, true);
nefarius->setActive(true);
nefarius->Respawn();
nefarius->GetMotionMaster()->MoveTargetedHome();
}
break;
}
}
}
protected:
// Misc
EventMap _events;
// Razorgore
uint8 EggCount;
uint32 EggEvent;
GuidList EggList;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_blackwing_lair_InstanceMapScript(map);
}
};
enum ShadowFlame
{
SPELL_ONYXIA_SCALE_CLOAK = 22683,
SPELL_SHADOW_FLAME_DOT = 22682
};
// 22539 - Shadowflame (used in Blackwing Lair)
class spell_bwl_shadowflame : public SpellScriptLoader
{
public:
spell_bwl_shadowflame() : SpellScriptLoader("spell_bwl_shadowflame") { }
class spell_bwl_shadowflame_SpellScript : public SpellScript
{
PrepareSpellScript(spell_bwl_shadowflame_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
return ValidateSpellInfo({ SPELL_ONYXIA_SCALE_CLOAK, SPELL_SHADOW_FLAME_DOT });
}
void HandleEffectScriptEffect(SpellEffIndex /*effIndex*/)
{
// If the victim of the spell does not have "Onyxia Scale Cloak" - add the Shadow Flame DoT (22682)
if (Unit* victim = GetHitUnit())
if (!victim->HasAura(SPELL_ONYXIA_SCALE_CLOAK))
victim->AddAura(SPELL_SHADOW_FLAME_DOT, victim);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_bwl_shadowflame_SpellScript::HandleEffectScriptEffect, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
}
};
SpellScript* GetSpellScript() const
{
return new spell_bwl_shadowflame_SpellScript;
}
};
void AddSC_instance_blackwing_lair()
{
new instance_blackwing_lair();
new spell_bwl_shadowflame();
}
<commit_msg>fix(Scripts/BlackwingLair): starting Razorgore the Untamed fight (#7783)<commit_after>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
#include "blackwing_lair.h"
#include "GameObject.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "Player.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
DoorData const doorData[] =
{
{ GO_PORTCULLIS_RAZORGORE, DATA_RAZORGORE_THE_UNTAMED, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175946 || GUID 7230
{ GO_PORTCULLIS_VAELASTRASZ, DATA_VAELASTRAZ_THE_CORRUPT, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175185 || GUID 7229
{ GO_PORTCULLIS_BROODLORD, DATA_BROODLORD_LASHLAYER, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179365 || GUID 75159
{ GO_PORTCULLIS_THREEDRAGONS, DATA_FIREMAW, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_THREEDRAGONS, DATA_EBONROC, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_THREEDRAGONS, DATA_FLAMEGOR, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
{ GO_PORTCULLIS_CHROMAGGUS, DATA_CHROMAGGUS, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179116 || GUID 75161
{ GO_PORTCULLIS_NEFARIAN, DATA_NEFARIAN, DOOR_TYPE_ROOM, BOUNDARY_NONE}, // ID 179117 || GUID 75164
{ 0, 0, DOOR_TYPE_ROOM, BOUNDARY_NONE} // END
};
Position const SummonPosition[8] =
{
{-7661.207520f, -1043.268188f, 407.199554f, 6.280452f},
{-7644.145020f, -1065.628052f, 407.204956f, 0.501492f},
{-7624.260742f, -1095.196899f, 407.205017f, 0.544694f},
{-7608.501953f, -1116.077271f, 407.199921f, 0.816443f},
{-7531.841797f, -1063.765381f, 407.199615f, 2.874187f},
{-7547.319336f, -1040.971924f, 407.205078f, 3.789175f},
{-7568.547852f, -1013.112488f, 407.204926f, 3.773467f},
{-7584.175781f, -989.6691289f, 407.199585f, 4.527447f},
};
uint32 const Entry[5] = {12422, 12458, 12416, 12420, 12459};
class instance_blackwing_lair : public InstanceMapScript
{
public:
instance_blackwing_lair() : InstanceMapScript(BWLScriptName, 469) { }
struct instance_blackwing_lair_InstanceMapScript : public InstanceScript
{
instance_blackwing_lair_InstanceMapScript(Map* map) : InstanceScript(map)
{
//SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadDoorData(doorData);
//LoadObjectData(creatureData, gameObjectData);
}
void Initialize() override
{
// Razorgore
EggCount = 0;
EggEvent = 0;
}
void OnCreatureCreate(Creature* creature) override
{
InstanceScript::OnCreatureCreate(creature);
switch (creature->GetEntry())
{
case NPC_RAZORGORE:
razorgoreGUID = creature->GetGUID();
break;
case NPC_BLACKWING_DRAGON:
case NPC_BLACKWING_TASKMASTER:
case NPC_BLACKWING_LEGIONAIRE:
case NPC_BLACKWING_WARLOCK:
if (Creature* razor = instance->GetCreature(razorgoreGUID))
if (CreatureAI* razorAI = razor->AI())
razorAI->JustSummoned(creature);
break;
default:
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
InstanceScript::OnGameObjectCreate(go);
switch(go->GetEntry())
{
case GO_BLACK_DRAGON_EGG:
if (GetBossState(DATA_FIREMAW) == DONE)
go->SetPhaseMask(2, true);
else
EggList.push_back(go->GetGUID());
break;
case GO_PORTCULLIS_RAZORGORE:
case GO_PORTCULLIS_VAELASTRASZ:
case GO_PORTCULLIS_BROODLORD:
case GO_PORTCULLIS_THREEDRAGONS:
case GO_PORTCULLIS_CHROMAGGUS:
case GO_PORTCULLIS_NEFARIAN:
AddDoor(go, true);
break;
default:
break;
}
}
void OnGameObjectRemove(GameObject* go) override
{
InstanceScript::OnGameObjectRemove(go);
if (go->GetEntry() == GO_BLACK_DRAGON_EGG)
EggList.remove(go->GetGUID());
switch (go->GetEntry())
{
case GO_PORTCULLIS_RAZORGORE:
case GO_PORTCULLIS_VAELASTRASZ:
case GO_PORTCULLIS_BROODLORD:
case GO_PORTCULLIS_THREEDRAGONS:
case GO_PORTCULLIS_CHROMAGGUS:
case GO_PORTCULLIS_NEFARIAN:
AddDoor(go, false);
break;
default:
break;
}
}
bool CheckRequiredBosses(uint32 bossId, Player const* /* player */) const override
{
switch (bossId)
{
case DATA_BROODLORD_LASHLAYER:
if (GetBossState(DATA_VAELASTRAZ_THE_CORRUPT) != DONE)
return false;
break;
case DATA_CHROMAGGUS:
if (GetBossState(DATA_FIREMAW) != DONE
|| GetBossState(DATA_EBONROC) != DONE
|| GetBossState(DATA_FLAMEGOR) != DONE)
return false;
break;
default:
break;
}
return true;
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_RAZORGORE_THE_UNTAMED:
if (state == DONE)
{
for (ObjectGuid const& guid : EggList)
if (GameObject* egg = instance->GetGameObject(guid))
egg->SetPhaseMask(2, true);
}
SetData(DATA_EGG_EVENT, NOT_STARTED);
break;
case DATA_NEFARIAN:
switch (state)
{
case NOT_STARTED:
if (Creature* nefarian = instance->GetCreature(GetGuidData(DATA_NEFARIAN)))
nefarian->DespawnOrUnsummon();
break;
case FAIL:
_events.ScheduleEvent(EVENT_RESPAWN_NEFARIUS, 15 * 60 * IN_MILLISECONDS); //15min
SetBossState(DATA_NEFARIAN, NOT_STARTED);
break;
default:
break;
}
break;
}
return true;
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_EGG_EVENT)
{
switch (data)
{
case IN_PROGRESS:
_events.ScheduleEvent(EVENT_RAZOR_SPAWN, 45000);
EggEvent = data;
EggCount = 0;
break;
case NOT_STARTED:
_events.CancelEvent(EVENT_RAZOR_SPAWN);
EggEvent = data;
EggCount = 0;
break;
case SPECIAL:
if (++EggCount == 15)
{
if (Creature* razor = instance->GetCreature(razorgoreGUID))
{
SetData(DATA_EGG_EVENT, DONE);
razor->RemoveAurasDueToSpell(42013); // MindControl
DoRemoveAurasDueToSpellOnPlayers(42013);
}
_events.ScheduleEvent(EVENT_RAZOR_PHASE_TWO, 1000);
_events.CancelEvent(EVENT_RAZOR_SPAWN);
}
if (EggEvent == NOT_STARTED)
SetData(DATA_EGG_EVENT, IN_PROGRESS);
break;
}
}
}
ObjectGuid GetGuidData(uint32 type) const override
{
switch (type)
{
case DATA_RAZORGORE_THE_UNTAMED:
return razorgoreGUID;
default:
break;
}
return ObjectGuid::Empty;
}
void OnUnitDeath(Unit* unit) override
{
//! HACK, needed because of buggy CreatureAI after charm
if (unit->GetEntry() == NPC_RAZORGORE && GetBossState(DATA_RAZORGORE_THE_UNTAMED) != DONE)
SetBossState(DATA_RAZORGORE_THE_UNTAMED, DONE);
}
void Update(uint32 diff) override
{
if (_events.Empty())
return;
_events.Update(diff);
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_RAZOR_SPAWN:
for (uint8 i = urand(2, 5); i > 0; --i)
if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)]))
summon->AI()->DoZoneInCombat();
_events.ScheduleEvent(EVENT_RAZOR_SPAWN, 12000, 17000);
break;
case EVENT_RAZOR_PHASE_TWO:
_events.CancelEvent(EVENT_RAZOR_SPAWN);
if (Creature* razor = instance->GetCreature(razorgoreGUID))
razor->AI()->DoAction(ACTION_PHASE_TWO);
break;
case EVENT_RESPAWN_NEFARIUS:
if (Creature* nefarius = instance->GetCreature(GetGuidData(DATA_LORD_VICTOR_NEFARIUS)))
{
nefarius->SetPhaseMask(1, true);
nefarius->setActive(true);
nefarius->Respawn();
nefarius->GetMotionMaster()->MoveTargetedHome();
}
break;
}
}
}
protected:
// Misc
EventMap _events;
// Razorgore
ObjectGuid razorgoreGUID;
uint8 EggCount;
uint32 EggEvent;
GuidList EggList;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_blackwing_lair_InstanceMapScript(map);
}
};
enum ShadowFlame
{
SPELL_ONYXIA_SCALE_CLOAK = 22683,
SPELL_SHADOW_FLAME_DOT = 22682
};
// 22539 - Shadowflame (used in Blackwing Lair)
class spell_bwl_shadowflame : public SpellScriptLoader
{
public:
spell_bwl_shadowflame() : SpellScriptLoader("spell_bwl_shadowflame") { }
class spell_bwl_shadowflame_SpellScript : public SpellScript
{
PrepareSpellScript(spell_bwl_shadowflame_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
return ValidateSpellInfo({ SPELL_ONYXIA_SCALE_CLOAK, SPELL_SHADOW_FLAME_DOT });
}
void HandleEffectScriptEffect(SpellEffIndex /*effIndex*/)
{
// If the victim of the spell does not have "Onyxia Scale Cloak" - add the Shadow Flame DoT (22682)
if (Unit* victim = GetHitUnit())
if (!victim->HasAura(SPELL_ONYXIA_SCALE_CLOAK))
victim->AddAura(SPELL_SHADOW_FLAME_DOT, victim);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_bwl_shadowflame_SpellScript::HandleEffectScriptEffect, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
}
};
SpellScript* GetSpellScript() const
{
return new spell_bwl_shadowflame_SpellScript;
}
};
void AddSC_instance_blackwing_lair()
{
new instance_blackwing_lair();
new spell_bwl_shadowflame();
}
<|endoftext|>
|
<commit_before>
#include "stdafx.h"
#include "vertexbuffer.h"
using namespace graphic;
cVertexBuffer::cVertexBuffer()
: m_sizeOfVertex(0)
, m_vertexCount(0)
, m_vtxBuff(NULL)
{
}
// Copy Constructor
cVertexBuffer::cVertexBuffer(const cVertexBuffer &rhs)
{
operator = (rhs);
}
cVertexBuffer::~cVertexBuffer()
{
Clear();
}
bool cVertexBuffer::Create(cRenderer &renderer, const int vertexCount, const int sizeofVertex
, const D3D11_USAGE usage //= D3D11_USAGE_DEFAULT
)
{
SAFE_RELEASE(m_vtxBuff);
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = usage;
bd.ByteWidth = sizeofVertex * vertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
switch (usage)
{
case D3D11_USAGE_DEFAULT:
bd.CPUAccessFlags = 0;
break;
case D3D11_USAGE_DYNAMIC:
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case D3D11_USAGE_STAGING:
assert(0); // very slow flag
break;
}
if (FAILED(renderer.GetDevice()->CreateBuffer(&bd, NULL, &m_vtxBuff)))
{
assert(0);
return false;
}
m_vertexCount = vertexCount;
m_sizeOfVertex = sizeofVertex;
return true;
}
bool cVertexBuffer::Create(cRenderer &renderer, const int vertexCount, const int sizeofVertex
, const void *vertices
, const D3D11_USAGE usage //= D3D11_USAGE_DEFAULT
)
{
SAFE_RELEASE(m_vtxBuff);
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = usage;
bd.ByteWidth = sizeofVertex * vertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
switch (usage)
{
case D3D11_USAGE_DEFAULT:
bd.CPUAccessFlags = 0;
break;
case D3D11_USAGE_DYNAMIC:
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case D3D11_USAGE_STAGING:
assert(0); // very slow flag
break;
}
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = vertices;
if (FAILED(renderer.GetDevice()->CreateBuffer(&bd, &InitData, &m_vtxBuff)))
{
assert(0);
return false;
}
m_vertexCount = vertexCount;
m_sizeOfVertex = sizeofVertex;
return true;
}
void* cVertexBuffer::Lock(cRenderer &renderer
, const D3D11_MAP flag //= D3D11_MAP_WRITE_DISCARD
)
{
RETV(!m_vtxBuff, NULL);
D3D11_MAPPED_SUBRESOURCE res;
ZeroMemory(&res, sizeof(res));
HRESULT hr = renderer.GetDevContext()->Map(m_vtxBuff, 0, flag, 0, &res);
if (FAILED(hr))
return NULL;
return res.pData;
}
void cVertexBuffer::Unlock(cRenderer &renderer)
{
RET(!m_vtxBuff);
renderer.GetDevContext()->Unmap(m_vtxBuff, 0);
}
void cVertexBuffer::Bind(cRenderer &renderer) const
{
const UINT offset = 0;
const UINT stride = (UINT)m_sizeOfVertex;
renderer.GetDevContext()->IASetVertexBuffers(0, 1, &m_vtxBuff, &stride, &offset);
}
inline DWORD FtoDW(FLOAT f) { return *((DWORD*)&f); }
void cVertexBuffer::RenderLineStrip(cRenderer &renderer)
{
//RET(!m_vtxBuff);
//renderer.GetDevice()->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&Matrix44::Identity);
//DWORD lighting;
//renderer.GetDevice()->GetRenderState(D3DRS_LIGHTING, &lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSIZE_MAX, FtoDW(10));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSIZE_MIN, FtoDW(1.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_A, FtoDW(0.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_B, FtoDW(0.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_C, FtoDW(1.0f));
//Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_LINESTRIP, 0, m_vertexCount - 1);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, TRUE);
}
void cVertexBuffer::RenderLineList(cRenderer &renderer)
{
//RET(!m_vtxBuff);
//renderer.GetDevice()->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&Matrix44::Identity);
//DWORD lighting;
//renderer.GetDevice()->GetRenderState(D3DRS_LIGHTING, &lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, FALSE);
//Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_LINELIST, 0, m_vertexCount /2);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, TRUE);
}
// ZBuffer Enable
void cVertexBuffer::RenderLineList2(cRenderer &renderer)
{
//RET(!m_vtxBuff);
//DWORD lighting;
//renderer.GetDevice()->GetRenderState(D3DRS_LIGHTING, &lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, FALSE);
//Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_LINELIST, 0, m_vertexCount / 2);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, lighting);
}
void cVertexBuffer::RenderPointList2(cRenderer &renderer, const int count) // count=0
{
//RET(!m_vtxBuff);
//DWORD lighting;
//renderer.GetDevice()->GetRenderState(D3DRS_LIGHTING, &lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSIZE_MAX, FtoDW(10));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSIZE_MIN, FtoDW(1.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_A, FtoDW(0.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_B, FtoDW(0.0f));
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALE_C, FtoDW(1.0f));
////renderer.GetDevice()->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&Matrix44::Identity);
//Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_POINTLIST, 0, (count == 0) ? m_vertexCount : count);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);
//renderer.GetDevice()->SetRenderState(D3DRS_LIGHTING, lighting);
//renderer.GetDevice()->SetRenderState(D3DRS_ZENABLE, TRUE);
}
void cVertexBuffer::RenderPointList(cRenderer &renderer, const int count) // count=0
{
//RET(!m_vtxBuff);
//renderer.GetDevice()->SetTransform( D3DTS_WORLD, (D3DXMATRIX*)&Matrix44::Identity );
//Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_POINTLIST, 0, (count == 0) ? m_vertexCount : count);
}
void cVertexBuffer::RenderTriangleStrip(cRenderer &renderer)
{
//RET(!m_vtxBuff);
Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, m_vertexCount - 2);
}
void cVertexBuffer::RenderTriangleList(cRenderer &renderer)
{
//RET(!m_vtxBuff);
Bind(renderer);
//renderer.GetDevice()->DrawPrimitive(D3DPT_TRIANGLELIST, 0, m_vertexCount/3);
}
void cVertexBuffer::Clear()
{
m_vertexCount = 0;
m_sizeOfVertex = 0;
SAFE_RELEASE(m_vtxBuff);
}
void cVertexBuffer::Set(cRenderer &renderer, const cVertexBuffer &rhs)
{
if (this != &rhs)
{
Clear();
m_sizeOfVertex = rhs.m_sizeOfVertex;
m_vertexCount = rhs.m_vertexCount;
Create(renderer, rhs.m_vertexCount, rhs.m_sizeOfVertex);
renderer.GetDevContext()->CopyResource(m_vtxBuff, rhs.m_vtxBuff);
}
}
cVertexBuffer& cVertexBuffer::operator=(const cVertexBuffer &rhs)
{
if (this != &rhs)
{
Clear();
m_sizeOfVertex = rhs.m_sizeOfVertex;
m_vertexCount = rhs.m_vertexCount;
m_vtxBuff = NULL; // No Copy
}
return *this;
}
<commit_msg>update graphic refactoring<commit_after>
#include "stdafx.h"
#include "vertexbuffer.h"
using namespace graphic;
cVertexBuffer::cVertexBuffer()
: m_sizeOfVertex(0)
, m_vertexCount(0)
, m_vtxBuff(NULL)
{
}
// Copy Constructor
cVertexBuffer::cVertexBuffer(const cVertexBuffer &rhs)
{
operator = (rhs);
}
cVertexBuffer::~cVertexBuffer()
{
Clear();
}
bool cVertexBuffer::Create(cRenderer &renderer, const int vertexCount, const int sizeofVertex
, const D3D11_USAGE usage //= D3D11_USAGE_DEFAULT
)
{
SAFE_RELEASE(m_vtxBuff);
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = usage;
bd.ByteWidth = sizeofVertex * vertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
switch (usage)
{
case D3D11_USAGE_DEFAULT:
bd.CPUAccessFlags = 0;
break;
case D3D11_USAGE_DYNAMIC:
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case D3D11_USAGE_STAGING:
assert(0); // very slow flag
break;
}
if (FAILED(renderer.GetDevice()->CreateBuffer(&bd, NULL, &m_vtxBuff)))
{
assert(0);
return false;
}
m_vertexCount = vertexCount;
m_sizeOfVertex = sizeofVertex;
return true;
}
bool cVertexBuffer::Create(cRenderer &renderer, const int vertexCount, const int sizeofVertex
, const void *vertices
, const D3D11_USAGE usage //= D3D11_USAGE_DEFAULT
)
{
SAFE_RELEASE(m_vtxBuff);
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = usage;
bd.ByteWidth = sizeofVertex * vertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
switch (usage)
{
case D3D11_USAGE_DEFAULT:
bd.CPUAccessFlags = 0;
break;
case D3D11_USAGE_DYNAMIC:
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
break;
case D3D11_USAGE_STAGING:
assert(0); // very slow flag
break;
}
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = vertices;
if (FAILED(renderer.GetDevice()->CreateBuffer(&bd, &InitData, &m_vtxBuff)))
{
assert(0);
return false;
}
m_vertexCount = vertexCount;
m_sizeOfVertex = sizeofVertex;
return true;
}
void* cVertexBuffer::Lock(cRenderer &renderer
, const D3D11_MAP flag //= D3D11_MAP_WRITE_DISCARD
)
{
RETV(!m_vtxBuff, NULL);
D3D11_MAPPED_SUBRESOURCE res;
ZeroMemory(&res, sizeof(res));
HRESULT hr = renderer.GetDevContext()->Map(m_vtxBuff, 0, flag, 0, &res);
if (FAILED(hr))
return NULL;
return res.pData;
}
void cVertexBuffer::Unlock(cRenderer &renderer)
{
RET(!m_vtxBuff);
renderer.GetDevContext()->Unmap(m_vtxBuff, 0);
}
void cVertexBuffer::Bind(cRenderer &renderer) const
{
const UINT offset = 0;
const UINT stride = (UINT)m_sizeOfVertex;
renderer.GetDevContext()->IASetVertexBuffers(0, 1, &m_vtxBuff, &stride, &offset);
}
inline DWORD FtoDW(FLOAT f) { return *((DWORD*)&f); }
void cVertexBuffer::RenderLineStrip(cRenderer &renderer)
{
}
void cVertexBuffer::RenderLineList(cRenderer &renderer)
{
}
// ZBuffer Enable
void cVertexBuffer::RenderLineList2(cRenderer &renderer)
{
}
void cVertexBuffer::RenderPointList2(cRenderer &renderer, const int count) // count=0
{
}
void cVertexBuffer::RenderPointList(cRenderer &renderer, const int count) // count=0
{
}
void cVertexBuffer::RenderTriangleStrip(cRenderer &renderer)
{
}
void cVertexBuffer::RenderTriangleList(cRenderer &renderer)
{
}
void cVertexBuffer::Clear()
{
m_vertexCount = 0;
m_sizeOfVertex = 0;
SAFE_RELEASE(m_vtxBuff);
}
void cVertexBuffer::Set(cRenderer &renderer, const cVertexBuffer &rhs)
{
if (this != &rhs)
{
Clear();
m_sizeOfVertex = rhs.m_sizeOfVertex;
m_vertexCount = rhs.m_vertexCount;
Create(renderer, rhs.m_vertexCount, rhs.m_sizeOfVertex);
renderer.GetDevContext()->CopyResource(m_vtxBuff, rhs.m_vtxBuff);
}
}
cVertexBuffer& cVertexBuffer::operator=(const cVertexBuffer &rhs)
{
if (this != &rhs)
{
Clear();
m_sizeOfVertex = rhs.m_sizeOfVertex;
m_vertexCount = rhs.m_vertexCount;
m_vtxBuff = NULL; // No Copy
}
return *this;
}
<|endoftext|>
|
<commit_before>/*
* OneToManyProcessor.cpp
*/
#include "OneToManyProcessor.h"
#include <map>
#include <string>
#include "./MediaStream.h"
#include "rtp/RtpHeaders.h"
#include "rtp/RtpUtils.h"
namespace erizo {
DEFINE_LOGGER(OneToManyProcessor, "OneToManyProcessor");
OneToManyProcessor::OneToManyProcessor() : feedbackSink_{nullptr} {
ELOG_DEBUG("OneToManyProcessor constructor");
}
OneToManyProcessor::~OneToManyProcessor() {
}
int OneToManyProcessor::deliverAudioData_(std::shared_ptr<DataPacket> audio_packet) {
if (audio_packet->length <= 0)
return 0;
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
RtpHeader* head = reinterpret_cast<RtpHeader*>(audio_packet->data);
RtcpHeader* chead = reinterpret_cast<RtcpHeader*>(audio_packet->data);
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
if (chead->isRtcp()) {
chead->setSSRC((*it).second->getAudioSinkSSRC());
} else {
head->setSSRC((*it).second->getAudioSinkSSRC());
}
// Note: deliverAudioData must copy the packet inmediately
(*it).second->deliverAudioData(audio_packet);
}
}
return 0;
}
bool OneToManyProcessor::isSSRCFromAudio(uint32_t ssrc) {
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second->getAudioSinkSSRC() == ssrc) {
return true;
}
}
return false;
}
int OneToManyProcessor::deliverVideoData_(std::shared_ptr<DataPacket> video_packet) {
if (video_packet->length <= 0)
return 0;
RtcpHeader* head = reinterpret_cast<RtcpHeader*>(video_packet->data);
if (head->isFeedback()) {
ELOG_WARN("Receiving Feedback in wrong path: %d", head->packettype);
deliverFeedback_(video_packet);
return 0;
}
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
RtpHeader* rhead = reinterpret_cast<RtpHeader*>(video_packet->data);
uint32_t ssrc = head->isRtcp() ? head->getSSRC() : rhead->getSSRC();
uint32_t ssrc_offset = translateAndMaybeAdaptForSimulcast(ssrc);
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
uint32_t base_ssrc = (*it).second->getVideoSinkSSRC();
if (head->isRtcp()) {
head->setSSRC(base_ssrc + ssrc_offset);
} else {
rhead->setSSRC(base_ssrc + ssrc_offset);
}
// Note: deliverVideoData must copy the packet inmediately
(*it).second->deliverVideoData(video_packet);
}
}
return 0;
}
uint32_t OneToManyProcessor::translateAndMaybeAdaptForSimulcast(uint32_t orig_ssrc) {
return orig_ssrc - publisher->getVideoSourceSSRC();
}
void OneToManyProcessor::setPublisher(std::shared_ptr<MediaSource> publisher_stream) {
boost::mutex::scoped_lock lock(monitor_mutex_);
this->publisher = publisher_stream;
feedbackSink_ = publisher->getFeedbackSink();
}
int OneToManyProcessor::deliverFeedback_(std::shared_ptr<DataPacket> fb_packet) {
if (feedbackSink_ != nullptr) {
RtpUtils::forEachRtcpBlock(fb_packet, [this](RtcpHeader *chead) {
if (chead->isREMB()) {
for (uint8_t index = 0; index < chead->getREMBNumSSRC(); index++) {
if (isSSRCFromAudio(chead->getREMBFeedSSRC(index))) {
chead->setREMBFeedSSRC(index, publisher->getAudioSourceSSRC());
} else {
chead->setREMBFeedSSRC(index, publisher->getVideoSourceSSRC());
}
}
}
if (isSSRCFromAudio(chead->getSourceSSRC())) {
chead->setSourceSSRC(publisher->getAudioSourceSSRC());
} else {
chead->setSourceSSRC(publisher->getVideoSourceSSRC());
}
});
feedbackSink_->deliverFeedback(fb_packet);
}
return 0;
}
int OneToManyProcessor::deliverEvent_(MediaEventPtr event) {
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
(*it).second->deliverEvent(event);
}
}
return 0;
}
void OneToManyProcessor::addSubscriber(std::shared_ptr<MediaSink> subscriber_stream,
const std::string& peer_id) {
ELOG_DEBUG("Adding subscriber");
boost::mutex::scoped_lock lock(monitor_mutex_);
ELOG_DEBUG("From %u, %u ", publisher->getAudioSourceSSRC(), publisher->getVideoSourceSSRC());
ELOG_DEBUG("Subscribers ssrcs: Audio %u, video, %u from %u, %u ",
subscriber_stream->getAudioSinkSSRC(), subscriber_stream->getVideoSinkSSRC(),
this->publisher->getAudioSourceSSRC() , this->publisher->getVideoSourceSSRC());
FeedbackSource* fbsource = subscriber_stream->getFeedbackSource();
if (fbsource != nullptr) {
ELOG_DEBUG("adding fbsource");
fbsource->setFeedbackSink(this);
}
if (this->subscribers.find(peer_id) != subscribers.end()) {
ELOG_WARN("This OTM already has a subscriber with peer_id %s, substituting it", peer_id.c_str());
this->subscribers.erase(peer_id);
}
this->subscribers[peer_id] = subscriber_stream;
}
void OneToManyProcessor::removeSubscriber(const std::string& peer_id) {
ELOG_DEBUG("Remove subscriber %s", peer_id.c_str());
boost::mutex::scoped_lock lock(monitor_mutex_);
if (this->subscribers.find(peer_id) != subscribers.end()) {
this->subscribers.erase(peer_id);
}
}
boost::future<void> OneToManyProcessor::close() {
return closeAll();
}
boost::future<void> OneToManyProcessor::closeAll() {
ELOG_DEBUG("OneToManyProcessor closeAll");
std::shared_ptr<boost::promise<void>> p = std::make_shared<boost::promise<void>>();
boost::future<void> f = p->get_future();
feedbackSink_ = nullptr;
publisher.reset();
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it = subscribers.begin();
while (it != subscribers.end()) {
if ((*it).second != nullptr) {
FeedbackSource* fbsource = (*it).second->getFeedbackSource();
if (fbsource != nullptr) {
fbsource->setFeedbackSink(nullptr);
}
}
subscribers.erase(it++);
}
subscribers.clear();
p->set_value();
ELOG_DEBUG("ClosedAll media in this OneToMany");
return f;
}
} // namespace erizo
<commit_msg>Avoid audio drifting by updating audio SRs (#1487)<commit_after>/*
* OneToManyProcessor.cpp
*/
#include "OneToManyProcessor.h"
#include <map>
#include <string>
#include "./MediaStream.h"
#include "rtp/RtpHeaders.h"
#include "rtp/RtpUtils.h"
namespace erizo {
DEFINE_LOGGER(OneToManyProcessor, "OneToManyProcessor");
OneToManyProcessor::OneToManyProcessor() : feedbackSink_{nullptr} {
ELOG_DEBUG("OneToManyProcessor constructor");
}
OneToManyProcessor::~OneToManyProcessor() {
}
int OneToManyProcessor::deliverAudioData_(std::shared_ptr<DataPacket> audio_packet) {
if (audio_packet->length <= 0)
return 0;
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
RtpHeader* head = reinterpret_cast<RtpHeader*>(audio_packet->data);
RtcpHeader* chead = reinterpret_cast<RtcpHeader*>(audio_packet->data);
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
// Hack to avoid audio drifting in Chrome.
if (chead->isRtcp() && chead->isSDES()) {
chead->setSSRC((*it).second->getAudioSinkSSRC());
} else {
head->setSSRC((*it).second->getAudioSinkSSRC());
}
// Note: deliverAudioData must copy the packet inmediately
(*it).second->deliverAudioData(audio_packet);
}
}
return 0;
}
bool OneToManyProcessor::isSSRCFromAudio(uint32_t ssrc) {
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second->getAudioSinkSSRC() == ssrc) {
return true;
}
}
return false;
}
int OneToManyProcessor::deliverVideoData_(std::shared_ptr<DataPacket> video_packet) {
if (video_packet->length <= 0)
return 0;
RtcpHeader* head = reinterpret_cast<RtcpHeader*>(video_packet->data);
if (head->isFeedback()) {
ELOG_WARN("Receiving Feedback in wrong path: %d", head->packettype);
deliverFeedback_(video_packet);
return 0;
}
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
RtpHeader* rhead = reinterpret_cast<RtpHeader*>(video_packet->data);
uint32_t ssrc = head->isRtcp() ? head->getSSRC() : rhead->getSSRC();
uint32_t ssrc_offset = translateAndMaybeAdaptForSimulcast(ssrc);
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
uint32_t base_ssrc = (*it).second->getVideoSinkSSRC();
if (head->isRtcp()) {
head->setSSRC(base_ssrc + ssrc_offset);
} else {
rhead->setSSRC(base_ssrc + ssrc_offset);
}
// Note: deliverVideoData must copy the packet inmediately
(*it).second->deliverVideoData(video_packet);
}
}
return 0;
}
uint32_t OneToManyProcessor::translateAndMaybeAdaptForSimulcast(uint32_t orig_ssrc) {
return orig_ssrc - publisher->getVideoSourceSSRC();
}
void OneToManyProcessor::setPublisher(std::shared_ptr<MediaSource> publisher_stream) {
boost::mutex::scoped_lock lock(monitor_mutex_);
this->publisher = publisher_stream;
feedbackSink_ = publisher->getFeedbackSink();
}
int OneToManyProcessor::deliverFeedback_(std::shared_ptr<DataPacket> fb_packet) {
if (feedbackSink_ != nullptr) {
RtpUtils::forEachRtcpBlock(fb_packet, [this](RtcpHeader *chead) {
if (chead->isREMB()) {
for (uint8_t index = 0; index < chead->getREMBNumSSRC(); index++) {
if (isSSRCFromAudio(chead->getREMBFeedSSRC(index))) {
chead->setREMBFeedSSRC(index, publisher->getAudioSourceSSRC());
} else {
chead->setREMBFeedSSRC(index, publisher->getVideoSourceSSRC());
}
}
}
if (isSSRCFromAudio(chead->getSourceSSRC())) {
chead->setSourceSSRC(publisher->getAudioSourceSSRC());
} else {
chead->setSourceSSRC(publisher->getVideoSourceSSRC());
}
});
feedbackSink_->deliverFeedback(fb_packet);
}
return 0;
}
int OneToManyProcessor::deliverEvent_(MediaEventPtr event) {
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
if (subscribers.empty())
return 0;
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it;
for (it = subscribers.begin(); it != subscribers.end(); ++it) {
if ((*it).second != nullptr) {
(*it).second->deliverEvent(event);
}
}
return 0;
}
void OneToManyProcessor::addSubscriber(std::shared_ptr<MediaSink> subscriber_stream,
const std::string& peer_id) {
ELOG_DEBUG("Adding subscriber");
boost::mutex::scoped_lock lock(monitor_mutex_);
ELOG_DEBUG("From %u, %u ", publisher->getAudioSourceSSRC(), publisher->getVideoSourceSSRC());
ELOG_DEBUG("Subscribers ssrcs: Audio %u, video, %u from %u, %u ",
subscriber_stream->getAudioSinkSSRC(), subscriber_stream->getVideoSinkSSRC(),
this->publisher->getAudioSourceSSRC() , this->publisher->getVideoSourceSSRC());
FeedbackSource* fbsource = subscriber_stream->getFeedbackSource();
if (fbsource != nullptr) {
ELOG_DEBUG("adding fbsource");
fbsource->setFeedbackSink(this);
}
if (this->subscribers.find(peer_id) != subscribers.end()) {
ELOG_WARN("This OTM already has a subscriber with peer_id %s, substituting it", peer_id.c_str());
this->subscribers.erase(peer_id);
}
this->subscribers[peer_id] = subscriber_stream;
}
void OneToManyProcessor::removeSubscriber(const std::string& peer_id) {
ELOG_DEBUG("Remove subscriber %s", peer_id.c_str());
boost::mutex::scoped_lock lock(monitor_mutex_);
if (this->subscribers.find(peer_id) != subscribers.end()) {
this->subscribers.erase(peer_id);
}
}
boost::future<void> OneToManyProcessor::close() {
return closeAll();
}
boost::future<void> OneToManyProcessor::closeAll() {
ELOG_DEBUG("OneToManyProcessor closeAll");
std::shared_ptr<boost::promise<void>> p = std::make_shared<boost::promise<void>>();
boost::future<void> f = p->get_future();
feedbackSink_ = nullptr;
publisher.reset();
boost::unique_lock<boost::mutex> lock(monitor_mutex_);
std::map<std::string, std::shared_ptr<MediaSink>>::iterator it = subscribers.begin();
while (it != subscribers.end()) {
if ((*it).second != nullptr) {
FeedbackSource* fbsource = (*it).second->getFeedbackSource();
if (fbsource != nullptr) {
fbsource->setFeedbackSink(nullptr);
}
}
subscribers.erase(it++);
}
subscribers.clear();
p->set_value();
ELOG_DEBUG("ClosedAll media in this OneToMany");
return f;
}
} // namespace erizo
<|endoftext|>
|
<commit_before>/**
* testApp.cpp is part of ofxXmlDefaultSettings.
*
* Copyright (c) 2012, Paul Vollmer http://www.wrong-entertainment.com
* All rights reserved.
*
*
* The MIT License
*
* 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.
*
*
* @testet_oF 0071
* @testet_plattform MacOs 10.6+
* ??? Win
* ??? Linux
* @dependencies ofxXmlSettings
* @contributor(s) Paul Vollmer <paul.vollmer@fh-potsdam.de>
* @modified 2012.09.20
* @version 0.1.2b
*/
#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
/* Load our default xml file.
*/
XML.load();
/* Get a status message
*/
cout << "STATUS: " << XML.statusMessage << endl;
/* and set the openFrameworks core settings from it.
*/
XML.setSettings();
cout << "STATUS: " << XML.statusMessage << endl;
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
switch (key) {
/* if key 'f' is pressed, toffle fullscreen mode.
*/
case 'f':
ofToggleFullscreen();
break;
}
}
//--------------------------------------------------------------
void testApp::exit(){
/* Save the current settings to xml.
*/
XML.saveSettings();
cout << "STATUS: " << XML.statusMessage << endl;
}
<commit_msg>small syntax fix, changes at description<commit_after>/**
* testApp.cpp is part of ofxXmlDefaultSettings.
*
* Copyright (c) 2012, Paul Vollmer http://www.wrong-entertainment.com
* All rights reserved.
*
*
* The MIT License
*
* 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.
*
*
* @testet_oF 0071
* @testet_plattform MacOs 10.6+
* ??? Win
* ??? Linux
* @dependencies ofxXmlSettings
* @contributor(s) Paul Vollmer <paul.vollmer@fh-potsdam.de>
* @modified 2012.09.20
* @version 0.1.2b
*/
#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
/* Load the xml file from default path.
*/
XML.load();
/* Get a status message from last method.
*/
cout << "STATUS: " << XML.getStatusMessage() << endl;
/* Set the openFrameworks app settings.
*/
XML.setSettings();
cout << "STATUS: " << XML.getStatusMessage() << endl;
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
switch (key) {
/* If key 'f' is pressed, toggle fullscreen mode.
*/
case 'f':
ofToggleFullscreen();
break;
}
}
//--------------------------------------------------------------
void testApp::exit(){
/* Save the current settings to xml file.
*/
XML.save();
cout << "STATUS: " << XML.getStatusMessage() << endl;
}
<|endoftext|>
|
<commit_before><commit_msg>fix a memory leak in the custom unpacker in the merger<commit_after><|endoftext|>
|
<commit_before>#include "zmq.h"
#include <iostream>
#include "AliHLTDataTypes.h"
#include "AliHLTComponent.h"
#include "AliHLTMessage.h"
#include "TClass.h"
#include "TCanvas.h"
#include "TMap.h"
#include "TPRegexp.h"
#include "TObjString.h"
#include "TDirectory.h"
#include "TList.h"
#include "AliZMQhelpers.h"
#include "TMessage.h"
#include "TSystem.h"
#include "TApplication.h"
#include "TH1.h"
#include "TH1F.h"
#include <time.h>
#include <string>
#include <map>
#include "TFile.h"
#include "TSystem.h"
#include "TStyle.h"
#include "signal.h"
class MySignalHandler;
//this is meant to become a class, hence the structure with global vars etc.
//Also the code is rather flat - it is a bit of a playground to test ideas.
//TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling
//zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide
//easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)
//methods
int ProcessOptionString(TString arguments);
int UpdatePad(TObject*);
int DumpToFile(TObject* object);
void* run(void* arg);
//configuration vars
Bool_t fVerbose = kFALSE;
TString fZMQconfigIN = "PULL>tcp://localhost:60211";
int fZMQsocketModeIN=-1;
TString fZMQsubscriptionIN = "";
TString fFilter = "";
TString fFileName="";
TFile* fFile=NULL;
int fPollInterval = 0;
int fPollTimeout = 1000; //1s
Bool_t fSort = kTRUE;
//internal state
void* fZMQcontext = NULL; //ze zmq context
void* fZMQin = NULL; //the in socket - entry point for the data to be merged.
TApplication* gApp;
TCanvas* fCanvas;
TObjArray fDrawables;
TString fStatus = "";
Int_t fRunNumber = 0;
TPRegexp* fSelectionRegexp = NULL;
TPRegexp* fUnSelectionRegexp = NULL;
TString fDrawOptions;
Bool_t fScaleLogX = kFALSE;
Bool_t fScaleLogY = kFALSE;
Bool_t fScaleLogZ = kFALSE;
Bool_t fResetOnRequest = kFALSE;
Int_t fHistStats = 0;
Bool_t fAllowResetAtSOR = kTRUE;
ULong64_t iterations=0;
const char* fUSAGE =
"ZMQhstViewer: Draw() all ROOT drawables in a message\n"
"options: \n"
" -in : data in\n"
" -sleep : how long to sleep in between requests for data in s (if applicable)\n"
" -timeout : how long to wait for the server to reply (s)\n"
" -Verbose : be verbose\n"
" -select : only show selected histograms (by regexp)\n"
" -unselect : as select, only inverted\n"
" -drawoptions : what draw option to use\n"
" -file : dump input to file and exit\n"
" -log[xyz] : use log scale on [xyz] dimension\n"
" -histstats : histogram stat box options (default 0)\n"
" -AllowResetAtSOR : 0/1 to reset at change of run\n"
;
//_______________________________________________________________________________________
class MySignalHandler : public TSignalHandler
{
public:
MySignalHandler(ESignals sig) : TSignalHandler(sig) {}
Bool_t Notify()
{
Printf("signal received, exiting");
fgTerminationSignaled = true;
return TSignalHandler::Notify();
}
static bool TerminationSignaled() { return fgTerminationSignaled; }
static bool fgTerminationSignaled;
};
bool MySignalHandler::fgTerminationSignaled = false;
void sig_handler(int signo)
{
if (signo == SIGINT)
printf("received SIGINT\n");
MySignalHandler::fgTerminationSignaled=true;
}
//_______________________________________________________________________________________
void* run(void* arg)
{
//main loop
while(!MySignalHandler::TerminationSignaled())
{
errno=0;
//send a request if we are using REQ
if (fZMQsocketModeIN==ZMQ_REQ)
{
string request;
if (fSelectionRegexp || fUnSelectionRegexp)
{
if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern();
if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern();
if (fResetOnRequest) request += " ResetOnRequest";
alizmq_msg_send("CONFIG", request, fZMQin, ZMQ_SNDMORE);
}
if (fVerbose) Printf("sending request CONFIG %s", request.c_str());
alizmq_msg_send("", "", fZMQin, 0);
}
//wait for the data
zmq_pollitem_t sockets[] = {
{ fZMQin, 0, ZMQ_POLLIN, 0 },
};
int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1);
if (rc==-1 && errno==ETERM)
{
Printf("jumping out of main loop");
break;
}
if (!(sockets[0].revents & ZMQ_POLLIN))
{
//server died
Printf("connection timed out, server %s died?", fZMQconfigIN.Data());
fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data());
if (fZMQsocketModeIN < 0) return NULL;
continue;
}
else
{
//get all data (topic+body), possibly many of them
aliZMQmsg message;
alizmq_msg_recv(&message, fZMQin, 0);
for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i)
{
if (alizmq_msg_iter_check(i, "INFO")==0)
{
//check if we have a runnumber in the string
string info;
alizmq_msg_iter_data(i,info);
if (fVerbose) Printf("processing INFO %s", info.c_str());
fCanvas->SetTitle(info.c_str());
size_t runTagPos = info.find("run");
if (runTagPos != std::string::npos)
{
size_t runStartPos = info.find("=",runTagPos);
size_t runEndPos = info.find(" ");
string runString = info.substr(runStartPos+1,runEndPos-runStartPos-1);
if (fVerbose) printf("received run=%s\n",runString.c_str());
int runnumber = atoi(runString.c_str());
if (runnumber!=fRunNumber && fAllowResetAtSOR)
{
if (fVerbose) printf("Run changed, resetting!\n");
fDrawables.Delete();
fCanvas->Clear();
}
fRunNumber = runnumber;
}
continue;
}
TObject* object;
alizmq_msg_iter_data(i, object);
if (object) UpdatePad(object);
if (!fFileName.IsNull())
{
if (object) DumpToFile(object);
}
}
alizmq_msg_close(&message);
}//socket 0
gSystem->ProcessEvents();
usleep(fPollInterval);
}//main loop
return NULL;
}
//_______________________________________________________________________________________
int main(int argc, char** argv)
{
//process args
int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv));
if (noptions<=0)
{
printf("%s",fUSAGE);
return 1;
}
TH1::AddDirectory(kFALSE);
TDirectory::AddDirectory(kFALSE);
gApp = new TApplication("viewer", &argc, argv);
gApp->SetReturnFromRun(true);
//gApp->Run();
gStyle->SetOptStat(fHistStats);
fCanvas = new TCanvas();
gSystem->ProcessEvents();
int mainReturnCode=0;
//init stuff
//globally enable schema evolution for serializing ROOT objects
TMessage::EnableSchemaEvolutionForAll(kTRUE);
//ZMQ init
fZMQcontext = zmq_ctx_new();
fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2);
if (fZMQsocketModeIN < 0) return 1;
gSystem->ResetSignal(kSigPipe);
gSystem->ResetSignal(kSigQuit);
gSystem->ResetSignal(kSigInterrupt);
gSystem->ResetSignal(kSigTermination);
//gSystem->AddSignalHandler(new MySignalHandler(kSigPipe));
//gSystem->AddSignalHandler(new MySignalHandler(kSigQuit));
//gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt));
//gSystem->AddSignalHandler(new MySignalHandler(kSigTermination));
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
run(NULL);
Printf("exiting...");
if (fFile) fFile->Close();
delete fFile; fFile=0;
//destroy ZMQ sockets
int linger=0;
zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(fZMQin);
zmq_ctx_term(fZMQcontext);
return mainReturnCode;
}
//______________________________________________________________________________
int DumpToFile(TObject* object)
{
Option_t* fileMode="RECREATE";
if (!fFile) fFile = new TFile(fFileName,fileMode);
if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data());
int rc = object->Write(object->GetName(),TObject::kOverwrite);
MySignalHandler::fgTerminationSignaled=true;
return rc;
}
//______________________________________________________________________________
int UpdatePad(TObject* object)
{
if (!object) return -1;
const char* name = object->GetName();
TObject* drawable = fDrawables.FindObject(name);
int padIndex = fDrawables.IndexOf(drawable);
if (fVerbose) Printf("in: %s (%s)", name, object->ClassName());
Bool_t selected = kTRUE;
Bool_t unselected = kFALSE;
if (fSelectionRegexp) selected = fSelectionRegexp->Match(name);
if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name);
if (!selected || unselected)
{
delete object;
return 0;
}
if (drawable)
{
//only redraw the one thing
if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex);
fCanvas->cd(padIndex+1);
gPad->GetListOfPrimitives()->Remove(drawable);
gPad->Clear();
fDrawables.RemoveAt(padIndex);
delete drawable;
fDrawables.AddAt(object, padIndex);
object->Draw(fDrawOptions);
gPad->Modified(kTRUE);
}
else
{
if (fVerbose) Printf(" new object %s", name);
//add the new object to the collection, restructure the canvas
//and redraw everything
fDrawables.AddLast(object);
if (fSort)
{
TObjArray sortedTitles(fDrawables.GetEntries());
for (int i=0; i<fDrawables.GetEntries(); i++)
{ sortedTitles.AddAt(new TNamed(fDrawables[i]->GetTitle(),fDrawables[i]->GetName()),i); }
sortedTitles.Sort();
TObjArray sortedDrawables(fDrawables.GetEntries());
for (int i=0; i<fDrawables.GetEntries(); i++)
{
const char* name = sortedTitles[i]->GetTitle();
TObject* tmp = fDrawables.FindObject(name);
int index = fDrawables.IndexOf(tmp);
sortedDrawables.AddAt(fDrawables[index],i);
}
for (int i=0; i<sortedDrawables.GetEntries(); i++)
{ fDrawables.AddAt(sortedDrawables[i],i); }
sortedTitles.Delete();
}
//after we clear the canvas, the pads are gone, clear the pad cache as well
fCanvas->Clear();
fCanvas->DivideSquare(fDrawables.GetLast()+1);
//redraw all objects at their old places and the new one as last
for (int i=0; i<fDrawables.GetLast()+1; i++)
{
TObject* obj = fDrawables[i];
fCanvas->cd(i+1);
if (fScaleLogX) gPad->SetLogx();
if (fScaleLogY) gPad->SetLogy();
if (fScaleLogZ) gPad->SetLogz();
if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i);
if (obj) obj->Draw(fDrawOptions);
}
}
gSystem->ProcessEvents();
fCanvas->Update();
return 0;
}
//______________________________________________________________________________
int ProcessOptionString(TString arguments)
{
//process passed options
aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);
int nOptions = 0;
for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)
{
//Printf(" %s : %s", i->first.data(), i->second.data());
const TString& option = i->first;
const TString& value = i->second;
if (option.EqualTo("PollInterval") || option.EqualTo("sleep"))
{
fPollInterval = round(value.Atof()*1e6);
}
else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout"))
{
fPollTimeout = round(value.Atof()*1e3);
}
else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") )
{
fZMQconfigIN = value;
}
else if (option.EqualTo("Verbose"))
{
fVerbose=kTRUE;
}
else if (option.EqualTo("select"))
{
delete fSelectionRegexp;
fSelectionRegexp=new TPRegexp(value);
}
else if (option.EqualTo("unselect"))
{
delete fUnSelectionRegexp;
fUnSelectionRegexp=new TPRegexp(value);
}
else if (option.EqualTo("ResetOnRequest"))
{
fResetOnRequest = kTRUE;
}
else if (option.EqualTo("drawoptions"))
{
fDrawOptions = value;
}
else if (option.EqualTo("logx"))
{
fScaleLogX=kTRUE;
}
else if (option.EqualTo("logy"))
{
fScaleLogY=kTRUE;
}
else if (option.EqualTo("logz"))
{
fScaleLogZ=kTRUE;
}
else if (option.EqualTo("file"))
{
fFileName = value;
}
else if (option.EqualTo("sort"))
{
fSort=value.Contains(0)?kFALSE:kTRUE;
}
else if (option.EqualTo("histstats"))
{
fHistStats = value.Atoi();
}
else if (option.EqualTo("AllowResetAtSOR"))
{
fAllowResetAtSOR = (option.Contains("0")||option.Contains("no"))?kFALSE:kTRUE;
}
else
{
nOptions=-1;
break;
}
nOptions++;
}
delete options; //tidy up
return nOptions;
}
<commit_msg>process events after reset<commit_after>#include "zmq.h"
#include <iostream>
#include "AliHLTDataTypes.h"
#include "AliHLTComponent.h"
#include "AliHLTMessage.h"
#include "TClass.h"
#include "TCanvas.h"
#include "TMap.h"
#include "TPRegexp.h"
#include "TObjString.h"
#include "TDirectory.h"
#include "TList.h"
#include "AliZMQhelpers.h"
#include "TMessage.h"
#include "TSystem.h"
#include "TApplication.h"
#include "TH1.h"
#include "TH1F.h"
#include <time.h>
#include <string>
#include <map>
#include "TFile.h"
#include "TSystem.h"
#include "TStyle.h"
#include "signal.h"
class MySignalHandler;
//this is meant to become a class, hence the structure with global vars etc.
//Also the code is rather flat - it is a bit of a playground to test ideas.
//TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling
//zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide
//easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...)
//methods
int ProcessOptionString(TString arguments);
int UpdatePad(TObject*);
int DumpToFile(TObject* object);
void* run(void* arg);
//configuration vars
Bool_t fVerbose = kFALSE;
TString fZMQconfigIN = "PULL>tcp://localhost:60211";
int fZMQsocketModeIN=-1;
TString fZMQsubscriptionIN = "";
TString fFilter = "";
TString fFileName="";
TFile* fFile=NULL;
int fPollInterval = 0;
int fPollTimeout = 1000; //1s
Bool_t fSort = kTRUE;
//internal state
void* fZMQcontext = NULL; //ze zmq context
void* fZMQin = NULL; //the in socket - entry point for the data to be merged.
TApplication* gApp;
TCanvas* fCanvas;
TObjArray fDrawables;
TString fStatus = "";
Int_t fRunNumber = 0;
TPRegexp* fSelectionRegexp = NULL;
TPRegexp* fUnSelectionRegexp = NULL;
TString fDrawOptions;
Bool_t fScaleLogX = kFALSE;
Bool_t fScaleLogY = kFALSE;
Bool_t fScaleLogZ = kFALSE;
Bool_t fResetOnRequest = kFALSE;
Int_t fHistStats = 0;
Bool_t fAllowResetAtSOR = kTRUE;
ULong64_t iterations=0;
const char* fUSAGE =
"ZMQhstViewer: Draw() all ROOT drawables in a message\n"
"options: \n"
" -in : data in\n"
" -sleep : how long to sleep in between requests for data in s (if applicable)\n"
" -timeout : how long to wait for the server to reply (s)\n"
" -Verbose : be verbose\n"
" -select : only show selected histograms (by regexp)\n"
" -unselect : as select, only inverted\n"
" -drawoptions : what draw option to use\n"
" -file : dump input to file and exit\n"
" -log[xyz] : use log scale on [xyz] dimension\n"
" -histstats : histogram stat box options (default 0)\n"
" -AllowResetAtSOR : 0/1 to reset at change of run\n"
;
//_______________________________________________________________________________________
class MySignalHandler : public TSignalHandler
{
public:
MySignalHandler(ESignals sig) : TSignalHandler(sig) {}
Bool_t Notify()
{
Printf("signal received, exiting");
fgTerminationSignaled = true;
return TSignalHandler::Notify();
}
static bool TerminationSignaled() { return fgTerminationSignaled; }
static bool fgTerminationSignaled;
};
bool MySignalHandler::fgTerminationSignaled = false;
void sig_handler(int signo)
{
if (signo == SIGINT)
printf("received SIGINT\n");
MySignalHandler::fgTerminationSignaled=true;
}
//_______________________________________________________________________________________
void* run(void* arg)
{
//main loop
while(!MySignalHandler::TerminationSignaled())
{
errno=0;
//send a request if we are using REQ
if (fZMQsocketModeIN==ZMQ_REQ)
{
string request;
if (fSelectionRegexp || fUnSelectionRegexp)
{
if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern();
if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern();
if (fResetOnRequest) request += " ResetOnRequest";
alizmq_msg_send("CONFIG", request, fZMQin, ZMQ_SNDMORE);
}
if (fVerbose) Printf("sending request CONFIG %s", request.c_str());
alizmq_msg_send("", "", fZMQin, 0);
}
//wait for the data
zmq_pollitem_t sockets[] = {
{ fZMQin, 0, ZMQ_POLLIN, 0 },
};
int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1);
if (rc==-1 && errno==ETERM)
{
Printf("jumping out of main loop");
break;
}
if (!(sockets[0].revents & ZMQ_POLLIN))
{
//server died
Printf("connection timed out, server %s died?", fZMQconfigIN.Data());
fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data());
if (fZMQsocketModeIN < 0) return NULL;
continue;
}
else
{
//get all data (topic+body), possibly many of them
aliZMQmsg message;
alizmq_msg_recv(&message, fZMQin, 0);
for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i)
{
if (alizmq_msg_iter_check(i, "INFO")==0)
{
//check if we have a runnumber in the string
string info;
alizmq_msg_iter_data(i,info);
if (fVerbose) Printf("processing INFO %s", info.c_str());
fCanvas->SetTitle(info.c_str());
size_t runTagPos = info.find("run");
if (runTagPos != std::string::npos)
{
size_t runStartPos = info.find("=",runTagPos);
size_t runEndPos = info.find(" ");
string runString = info.substr(runStartPos+1,runEndPos-runStartPos-1);
if (fVerbose) printf("received run=%s\n",runString.c_str());
int runnumber = atoi(runString.c_str());
if (runnumber!=fRunNumber && fAllowResetAtSOR)
{
if (fVerbose) printf("Run changed, resetting!\n");
fDrawables.Delete();
fCanvas->Clear();
gSystem->ProcessEvents();
}
fRunNumber = runnumber;
}
continue;
}
TObject* object;
alizmq_msg_iter_data(i, object);
if (object) UpdatePad(object);
if (!fFileName.IsNull())
{
if (object) DumpToFile(object);
}
}
alizmq_msg_close(&message);
}//socket 0
gSystem->ProcessEvents();
usleep(fPollInterval);
}//main loop
return NULL;
}
//_______________________________________________________________________________________
int main(int argc, char** argv)
{
//process args
int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv));
if (noptions<=0)
{
printf("%s",fUSAGE);
return 1;
}
TH1::AddDirectory(kFALSE);
TDirectory::AddDirectory(kFALSE);
gApp = new TApplication("viewer", &argc, argv);
gApp->SetReturnFromRun(true);
//gApp->Run();
gStyle->SetOptStat(fHistStats);
fCanvas = new TCanvas();
gSystem->ProcessEvents();
int mainReturnCode=0;
//init stuff
//globally enable schema evolution for serializing ROOT objects
TMessage::EnableSchemaEvolutionForAll(kTRUE);
//ZMQ init
fZMQcontext = zmq_ctx_new();
fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2);
if (fZMQsocketModeIN < 0) return 1;
gSystem->ResetSignal(kSigPipe);
gSystem->ResetSignal(kSigQuit);
gSystem->ResetSignal(kSigInterrupt);
gSystem->ResetSignal(kSigTermination);
//gSystem->AddSignalHandler(new MySignalHandler(kSigPipe));
//gSystem->AddSignalHandler(new MySignalHandler(kSigQuit));
//gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt));
//gSystem->AddSignalHandler(new MySignalHandler(kSigTermination));
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
run(NULL);
Printf("exiting...");
if (fFile) fFile->Close();
delete fFile; fFile=0;
//destroy ZMQ sockets
int linger=0;
zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(fZMQin);
zmq_ctx_term(fZMQcontext);
return mainReturnCode;
}
//______________________________________________________________________________
int DumpToFile(TObject* object)
{
Option_t* fileMode="RECREATE";
if (!fFile) fFile = new TFile(fFileName,fileMode);
if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data());
int rc = object->Write(object->GetName(),TObject::kOverwrite);
MySignalHandler::fgTerminationSignaled=true;
return rc;
}
//______________________________________________________________________________
int UpdatePad(TObject* object)
{
if (!object) return -1;
const char* name = object->GetName();
TObject* drawable = fDrawables.FindObject(name);
int padIndex = fDrawables.IndexOf(drawable);
if (fVerbose) Printf("in: %s (%s)", name, object->ClassName());
Bool_t selected = kTRUE;
Bool_t unselected = kFALSE;
if (fSelectionRegexp) selected = fSelectionRegexp->Match(name);
if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name);
if (!selected || unselected)
{
delete object;
return 0;
}
if (drawable)
{
//only redraw the one thing
if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex);
fCanvas->cd(padIndex+1);
gPad->GetListOfPrimitives()->Remove(drawable);
gPad->Clear();
fDrawables.RemoveAt(padIndex);
delete drawable;
fDrawables.AddAt(object, padIndex);
object->Draw(fDrawOptions);
gPad->Modified(kTRUE);
}
else
{
if (fVerbose) Printf(" new object %s", name);
//add the new object to the collection, restructure the canvas
//and redraw everything
fDrawables.AddLast(object);
if (fSort)
{
TObjArray sortedTitles(fDrawables.GetEntries());
for (int i=0; i<fDrawables.GetEntries(); i++)
{ sortedTitles.AddAt(new TNamed(fDrawables[i]->GetTitle(),fDrawables[i]->GetName()),i); }
sortedTitles.Sort();
TObjArray sortedDrawables(fDrawables.GetEntries());
for (int i=0; i<fDrawables.GetEntries(); i++)
{
const char* name = sortedTitles[i]->GetTitle();
TObject* tmp = fDrawables.FindObject(name);
int index = fDrawables.IndexOf(tmp);
sortedDrawables.AddAt(fDrawables[index],i);
}
for (int i=0; i<sortedDrawables.GetEntries(); i++)
{ fDrawables.AddAt(sortedDrawables[i],i); }
sortedTitles.Delete();
}
//after we clear the canvas, the pads are gone, clear the pad cache as well
fCanvas->Clear();
fCanvas->DivideSquare(fDrawables.GetLast()+1);
//redraw all objects at their old places and the new one as last
for (int i=0; i<fDrawables.GetLast()+1; i++)
{
TObject* obj = fDrawables[i];
fCanvas->cd(i+1);
if (fScaleLogX) gPad->SetLogx();
if (fScaleLogY) gPad->SetLogy();
if (fScaleLogZ) gPad->SetLogz();
if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i);
if (obj) obj->Draw(fDrawOptions);
}
}
gSystem->ProcessEvents();
fCanvas->Update();
return 0;
}
//______________________________________________________________________________
int ProcessOptionString(TString arguments)
{
//process passed options
aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments);
int nOptions = 0;
for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i)
{
//Printf(" %s : %s", i->first.data(), i->second.data());
const TString& option = i->first;
const TString& value = i->second;
if (option.EqualTo("PollInterval") || option.EqualTo("sleep"))
{
fPollInterval = round(value.Atof()*1e6);
}
else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout"))
{
fPollTimeout = round(value.Atof()*1e3);
}
else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") )
{
fZMQconfigIN = value;
}
else if (option.EqualTo("Verbose"))
{
fVerbose=kTRUE;
}
else if (option.EqualTo("select"))
{
delete fSelectionRegexp;
fSelectionRegexp=new TPRegexp(value);
}
else if (option.EqualTo("unselect"))
{
delete fUnSelectionRegexp;
fUnSelectionRegexp=new TPRegexp(value);
}
else if (option.EqualTo("ResetOnRequest"))
{
fResetOnRequest = kTRUE;
}
else if (option.EqualTo("drawoptions"))
{
fDrawOptions = value;
}
else if (option.EqualTo("logx"))
{
fScaleLogX=kTRUE;
}
else if (option.EqualTo("logy"))
{
fScaleLogY=kTRUE;
}
else if (option.EqualTo("logz"))
{
fScaleLogZ=kTRUE;
}
else if (option.EqualTo("file"))
{
fFileName = value;
}
else if (option.EqualTo("sort"))
{
fSort=value.Contains(0)?kFALSE:kTRUE;
}
else if (option.EqualTo("histstats"))
{
fHistStats = value.Atoi();
}
else if (option.EqualTo("AllowResetAtSOR"))
{
fAllowResetAtSOR = (option.Contains("0")||option.Contains("no"))?kFALSE:kTRUE;
}
else
{
nOptions=-1;
break;
}
nOptions++;
}
delete options; //tidy up
return nOptions;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-2012 Stanford University
*
* Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "ClientException.h"
#include "Cycles.h"
#include "Logger.h"
#include "MasterService.h"
#include "Memory.h"
#include "SegmentIterator.h"
#include "Seglet.h"
#include "Tablets.pb.h"
namespace RAMCloud {
class RecoverSegmentBenchmark {
public:
Context context;
ServerConfig config;
ServerList serverList;
MasterService* service;
RecoverSegmentBenchmark(string logSize, string hashTableSize,
int numSegments)
: context()
, config(ServerConfig::forTesting())
, serverList(&context)
, service(NULL)
{
Logger::get().setLogLevels(SILENT_LOG_LEVEL);
config.localLocator = "bogus";
config.coordinatorLocator = "bogus";
config.setLogAndHashTableSize(logSize, hashTableSize);
config.services = {WireFormat::MASTER_SERVICE};
config.master.numReplicas = 0;
config.segmentSize = Segment::DEFAULT_SEGMENT_SIZE;
config.segletSize = Seglet::DEFAULT_SEGLET_SIZE;
service = new MasterService(&context, config);
service->init({1, 0});
}
~RecoverSegmentBenchmark()
{
delete service;
}
void
run(int numSegments, int dataBytes)
{
/*
* Allocate numSegments Segments and fill them up with objects of
* size dataBytes. These will be the Segments that we recover.
*/
uint64_t numObjects = 0;
uint64_t nextKeyVal = 0;
Segment *segments[numSegments];
for (int i = 0; i < numSegments; i++) {
segments[i] = new Segment();
while (1) {
Key key(0, &nextKeyVal, sizeof(nextKeyVal));
char objectData[dataBytes];
Object object(key, objectData, dataBytes, 0, 0);
Buffer buffer;
object.serializeToBuffer(buffer);
if (!segments[i]->append(LOG_ENTRY_TYPE_OBJ, buffer))
break;
nextKeyVal++;
numObjects++;
}
segments[i]->close();
}
/* Update the list of Tablets */
ProtoBuf::Tablets_Tablet tablet;
tablet.set_table_id(0);
tablet.set_start_key_hash(0);
tablet.set_end_key_hash(~0UL);
tablet.set_state(ProtoBuf::Tablets_Tablet_State_NORMAL);
tablet.set_server_id(service->serverId.getId());
*service->tablets.add_tablet() = tablet;
/*
* Now run a fake recovery.
*/
uint64_t before = Cycles::rdtsc();
for (int i = 0; i < numSegments; i++) {
Segment* s = segments[i];
Buffer buffer;
s->appendToBuffer(buffer);
Segment::Certificate certificate;
s->getAppendedLength(certificate);
const void* contigSeg = buffer.getRange(0, buffer.getTotalLength());
SegmentIterator it(contigSeg, buffer.getTotalLength(), certificate);
service->recoverSegment(it);
}
uint64_t ticks = Cycles::rdtsc() - before;
uint64_t totalObjectBytes = numObjects * dataBytes;
uint64_t totalSegmentBytes = numSegments *
Segment::DEFAULT_SEGMENT_SIZE;
printf("Recovery of %d %dKB Segments with %d byte Objects took %lu "
"milliseconds\n", numSegments, Segment::DEFAULT_SEGMENT_SIZE / 1024,
dataBytes, RAMCloud::Cycles::toNanoseconds(ticks) / 1000 / 1000);
printf("Actual total object count: %lu (%lu bytes in Objects, %.2f%% "
"overhead)\n", numObjects, totalObjectBytes,
100.0 *
static_cast<double>(totalSegmentBytes - totalObjectBytes) /
static_cast<double>(totalSegmentBytes));
// clean up
for (int i = 0; i < numSegments; i++) {
delete segments[i];
}
}
DISALLOW_COPY_AND_ASSIGN(RecoverSegmentBenchmark);
};
} // namespace RAMCloud
int
main()
{
int numSegments = 80;
int dataBytes[] = { 64, 128, 256, 512, 1024, 2048, 8192, 0 };
for (int i = 0; dataBytes[i] != 0; i++) {
printf("==========================\n");
RAMCloud::RecoverSegmentBenchmark rsb("2048", "10%", numSegments);
rsb.run(numSegments, dataBytes[i]);
}
return 0;
}
<commit_msg>Temp metrics support for RecoverSegmentBenchmark.<commit_after>/* Copyright (c) 2010-2012 Stanford University
*
* Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "ClientException.h"
#include "Cycles.h"
#include "Logger.h"
#include "MasterService.h"
#include "Memory.h"
#include "SegmentIterator.h"
#include "Seglet.h"
#include "Tablets.pb.h"
namespace RAMCloud {
class RecoverSegmentBenchmark {
public:
Context context;
ServerConfig config;
ServerList serverList;
MasterService* service;
RecoverSegmentBenchmark(string logSize, string hashTableSize,
int numSegments)
: context()
, config(ServerConfig::forTesting())
, serverList(&context)
, service(NULL)
{
Logger::get().setLogLevels(WARNING);
config.localLocator = "bogus";
config.coordinatorLocator = "bogus";
config.setLogAndHashTableSize(logSize, hashTableSize);
config.services = {WireFormat::MASTER_SERVICE};
config.master.numReplicas = 0;
config.segmentSize = Segment::DEFAULT_SEGMENT_SIZE;
config.segletSize = Seglet::DEFAULT_SEGLET_SIZE;
service = new MasterService(&context, config);
service->init({1, 0});
}
~RecoverSegmentBenchmark()
{
delete service;
}
void
run(int numSegments, int dataBytes)
{
/*
* Allocate numSegments Segments and fill them up with objects of
* size dataBytes. These will be the Segments that we recover.
*/
uint64_t numObjects = 0;
uint64_t nextKeyVal = 0;
Segment *segments[numSegments];
for (int i = 0; i < numSegments; i++) {
segments[i] = new Segment();
while (1) {
Key key(0, &nextKeyVal, sizeof(nextKeyVal));
char objectData[dataBytes];
Object object(key, objectData, dataBytes, 0, 0);
Buffer buffer;
object.serializeToBuffer(buffer);
if (!segments[i]->append(LOG_ENTRY_TYPE_OBJ, buffer))
break;
nextKeyVal++;
numObjects++;
}
segments[i]->close();
}
/* Update the list of Tablets */
ProtoBuf::Tablets_Tablet tablet;
tablet.set_table_id(0);
tablet.set_start_key_hash(0);
tablet.set_end_key_hash(~0UL);
tablet.set_state(ProtoBuf::Tablets_Tablet_State_NORMAL);
tablet.set_server_id(service->serverId.getId());
*service->tablets.add_tablet() = tablet;
metrics->temp.ticks0 =
metrics->temp.ticks1 =
metrics->temp.ticks2 =
metrics->temp.ticks3 =
metrics->temp.ticks4 =
metrics->temp.ticks5 =
metrics->temp.ticks6 =
metrics->temp.ticks7 =
metrics->temp.ticks8 =
metrics->temp.ticks9 = 0;
metrics->temp.count0 =
metrics->temp.count1 =
metrics->temp.count2 =
metrics->temp.count3 =
metrics->temp.count4 =
metrics->temp.count5 =
metrics->temp.count6 =
metrics->temp.count7 =
metrics->temp.count8 =
metrics->temp.count9 = 0;
/*
* Now run a fake recovery.
*/
uint64_t before = Cycles::rdtsc();
for (int i = 0; i < numSegments; i++) {
Segment* s = segments[i];
Buffer buffer;
s->appendToBuffer(buffer);
Segment::Certificate certificate;
s->getAppendedLength(certificate);
const void* contigSeg = buffer.getRange(0, buffer.getTotalLength());
SegmentIterator it(contigSeg, buffer.getTotalLength(), certificate);
service->recoverSegment(it);
}
uint64_t ticks = Cycles::rdtsc() - before;
uint64_t totalObjectBytes = numObjects * dataBytes;
uint64_t totalSegmentBytes = numSegments *
Segment::DEFAULT_SEGMENT_SIZE;
printf("Recovery of %d %dKB Segments with %d byte Objects took %lu "
"ms\n", numSegments, Segment::DEFAULT_SEGMENT_SIZE / 1024,
dataBytes, RAMCloud::Cycles::toNanoseconds(ticks) / 1000 / 1000);
printf("Actual total object count: %lu (%lu bytes in Objects, %.2f%% "
"overhead)\n", numObjects, totalObjectBytes,
100.0 *
static_cast<double>(totalSegmentBytes - totalObjectBytes) /
static_cast<double>(totalSegmentBytes));
printf("\n");
printf("Verify object checksums: %.2f ms\n",
Cycles::toSeconds(metrics->master.verifyChecksumTicks.load()) *
1000.);
metrics->master.verifyChecksumTicks = 0;
#define DUMP_TEMP_TICKS(i) \
if (metrics->temp.ticks##i.load()) { \
printf("temp.ticks%d: %.2f ms\n", i, \
Cycles::toSeconds(metrics->temp.ticks##i.load()) * \
1000.); \
metrics->temp.ticks##i = 0; \
}
#define DUMP_TEMP_COUNT(i) \
if (metrics->temp.count##i.load()) { \
printf("temp.count%d: %lu\n", i, \
metrics->temp.count##i.load()); \
metrics->temp.count##i = 0; \
}
DUMP_TEMP_TICKS(0);
DUMP_TEMP_TICKS(1);
DUMP_TEMP_TICKS(2);
DUMP_TEMP_TICKS(3);
DUMP_TEMP_TICKS(4);
DUMP_TEMP_TICKS(5);
DUMP_TEMP_TICKS(6);
DUMP_TEMP_TICKS(7);
DUMP_TEMP_TICKS(8);
DUMP_TEMP_TICKS(9);
DUMP_TEMP_COUNT(0);
DUMP_TEMP_COUNT(1);
DUMP_TEMP_COUNT(2);
DUMP_TEMP_COUNT(3);
DUMP_TEMP_COUNT(4);
DUMP_TEMP_COUNT(5);
DUMP_TEMP_COUNT(6);
DUMP_TEMP_COUNT(7);
DUMP_TEMP_COUNT(8);
DUMP_TEMP_COUNT(9);
// clean up
for (int i = 0; i < numSegments; i++) {
delete segments[i];
}
}
DISALLOW_COPY_AND_ASSIGN(RecoverSegmentBenchmark);
};
} // namespace RAMCloud
int
main()
{
int numSegments = 80;
int dataBytes[] = { 64, 128, 256, 512, 1024, 2048, 8192, 0 };
for (int i = 0; dataBytes[i] != 0; i++) {
printf("==========================\n");
RAMCloud::RecoverSegmentBenchmark rsb("2048", "10%", numSegments);
rsb.run(numSegments, dataBytes[i]);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, 2012 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"
// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>
#include <new>
#include <iostream>
#include "Box.h"
#include "ViewCSSImp.h"
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 = item->nextSibling = item->previousSibling = 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(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
count(0),
style(style),
needStaticPosition(false),
auto_(auto_),
zIndex(zIndex),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
positioned(0),
firstBase(0),
lastBase(0),
clipBox(0),
firstFloat(0),
lastFloat(0),
currentFloat(0),
relativeX(0.0f),
relativeY(0.0f)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
if (item)
insertContext(item);
return item;
}
void StackingContext::insertContext(StackingContext* item)
{
assert(item);
if (isAuto()) {
parent->insertContext(item);
item->positioned = this;
return;
}
// TODO: Preserve the order in the DOM tree
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (item->zIndex < i->zIndex) {
after = i;
break;
}
}
insertBefore(item, after);
item->positioned = this;
}
void StackingContext::reparent(StackingContext* target)
{
auto child = parent->getFirstChild();
while (child) {
auto next = child->getNextSibling();
if (child->positioned == target) {
parent->removeChild(child);
target->insertContext(child);
if (child->isAuto())
reparent(child);
}
child = next;
}
}
void StackingContext::setZIndex(bool auto_, int index)
{
if (isAuto() == auto_ && zIndex == index)
return;
bool updateChildren = (this->auto_ != auto_);
this->auto_ = auto_;
zIndex = index;
if (parent) {
parent->removeChild(this);
positioned->insertContext(this);
if (updateChildren) {
if (isAuto()) {
while (StackingContext* child = getFirstChild()) {
removeChild(child);
child->positioned->insertContext(child);
}
} else
reparent(this);
}
}
}
void StackingContext::resetScrollSize()
{
for (Box* base = firstBase; base; base = base->nextBase)
base->resetScrollSize();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->resetScrollSize();
}
void StackingContext::resolveScrollSize(ViewCSSImp* view)
{
relativeX = relativeY = 0.0f;
for (StackingContext* s = this; s != parent; s = s->positioned) {
assert(s->style);
CSSStyleDeclarationImp* style = s->style;
if (!style->isResolved()) {
if (Box* b = style->getBox()) {
if (auto c = b->getContainingBlock(view)) {
style->left.resolve(view, style, c->width);
style->right.resolve(view, style, c->width);
style->top.resolve(view, style, c->height);
style->bottom.resolve(view, style, c->height);
}
}
}
style->resolveRelativeOffset(relativeX, relativeY);
}
if (parent) {
relativeX += parent->relativeX;
relativeY += parent->relativeY;
}
for (Box* base = firstBase; base; base = base->nextBase)
base->updateScrollSize();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->resolveScrollSize(view);
}
void StackingContext::updateClipBox(StackingContext* s)
{
float scrollLeft = 0.0f;
float scrollTop = 0.0f;
for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
if (clip->stackingContext == s || !clip->getParentBox())
continue;
Element element = interface_cast<Element>(clip->node);
scrollLeft += element.getScrollLeft();
scrollTop += element.getScrollTop();
if (clipWidth == HUGE_VALF) {
clipLeft = scrollLeft + clip->x + clip->marginLeft + clip->borderLeft + clip->stackingContext->relativeX;
clipTop = scrollTop + clip->y + clip->marginTop + clip->borderTop + clip->stackingContext->relativeY;
clipWidth = clip->getPaddingWidth();
clipHeight = clip->getPaddingHeight();
} else {
Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
scrollLeft + clip->x + clip->marginLeft + clip->borderLeft + clip->stackingContext->relativeX,
scrollTop + clip->y + clip->marginTop + clip->borderTop + clip->stackingContext->relativeY,
clip->getPaddingWidth(), clip->getPaddingHeight());
}
}
glTranslatef(-scrollLeft, -scrollTop, 0.0f);
}
bool StackingContext::hasClipBox()
{
clipLeft = clipTop = 0.0f;
clipWidth = clipHeight = HUGE_VALF;
for (StackingContext* s = this; s != parent; s = s->positioned)
updateClipBox(s);
return clipWidth != HUGE_VALF && clipHeight != HUGE_VALF;
}
void StackingContext::render(ViewCSSImp* view)
{
glPushMatrix();
if (hasClipBox())
view->clip(clipLeft, clipTop, clipWidth, clipHeight);
if (parent)
glTranslatef(relativeX - parent->relativeX, relativeY - parent->relativeY, 0.0f);
else
glTranslatef(relativeX, relativeY, 0.0f);
if (firstBase) {
currentFloat = firstFloat = lastFloat = 0;
GLfloat mtx[16];
glGetFloatv(GL_MODELVIEW_MATRIX, mtx);
for (Box* base = firstBase; base; base = base->nextBase) {
glPushMatrix();
Block* block = dynamic_cast<Block*>(base);
unsigned overflow = CSSOverflowValueImp::Visible;
if (block)
overflow = block->renderBegin(view);
StackingContext* childContext = getFirstChild();
for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) {
glPushMatrix();
glLoadMatrixf(mtx);
childContext->render(view);
glPopMatrix();
}
if (block) {
block->renderNonInline(view, this);
renderFloats(view, 0, 0);
block->renderInline(view, this);
} else
base->render(view, this);
for (; childContext; childContext = childContext->getNextSibling()) {
glPushMatrix();
glLoadMatrixf(mtx);
childContext->render(view);
glPopMatrix();
}
if (block) {
if (0.0f < block->getOutlineWidth())
block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
block->renderEnd(view, overflow);
}
glPopMatrix();
}
} else {
glPushMatrix();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->render(view);
glPopMatrix();
}
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
glPopMatrix();
}
void StackingContext::renderFloats(ViewCSSImp* view, Box* last, Box* current)
{
if (current && current == currentFloat)
return;
if (!last)
currentFloat = firstFloat;
else if (last->nextFloat)
currentFloat = last->nextFloat;
else
return;
while (currentFloat) {
currentFloat->render(view, this);;
currentFloat = currentFloat->nextFloat;
}
if (!last)
firstFloat = lastFloat = 0;
else {
last->nextFloat = 0;
lastFloat = last;
}
currentFloat = 0;
}
void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstBase; i; i = i->nextBase)
assert(box != i);
#endif
if (!firstBase)
firstBase = lastBase = box;
else {
lastBase->nextBase = box;
lastBase = box;
}
box->nextBase = 0;
}
void StackingContext::addBox(Box* box, Box* parentBox)
{
assert(parentBox);
if (parentBox->stackingContext != this)
addBase(box);
}
void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstFloat; i; i = i->nextFloat) {
assert(box != i);
}
#endif
if (currentFloat) {
box->nextFloat = currentFloat->nextFloat;
currentFloat->nextFloat = box;
return;
}
if (!firstFloat)
firstFloat = lastFloat = box;
else {
lastFloat->nextFloat = box;
lastFloat = box;
}
box->nextFloat = 0;
}
void StackingContext::removeBox(Box* box)
{
Box* p = 0;
for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
if (i == box) {
if (!p)
firstBase = i->nextBase;
else
p->nextBase = i->nextBase;
if (lastBase == box)
lastBase = p;
break;
}
}
}
void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
for (Box* base = firstBase; base; base = base->nextBase) {
Block* block = dynamic_cast<Block*>(base);
if (!block || !block->isAbsolutelyPositioned())
continue;
block->layOutAbsolute(view);
block->resolveXY(view, block->x, block->y, block->clipBox ? block->clipBox : ((view->getTree() == block) ? 0 : view->getTree()));
}
needStaticPosition = false;
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->needStaticPosition = true;
bool repeat;
do {
repeat = false;
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling()) {
if (childContext->needStaticPosition) {
if (!childContext->positioned->needStaticPosition)
childContext->layOutAbsolute(view);
else
repeat = true;
}
}
} while (repeat);
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: ";
if (isAuto())
std::cout << "auto";
else
std::cout << zIndex;
std::cout << '\n';
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(StackingContext::renderFloats) : Fix a bug<commit_after>/*
* Copyright 2011, 2012 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"
// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>
#include <new>
#include <iostream>
#include "Box.h"
#include "ViewCSSImp.h"
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 = item->nextSibling = item->previousSibling = 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(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
count(0),
style(style),
needStaticPosition(false),
auto_(auto_),
zIndex(zIndex),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
positioned(0),
firstBase(0),
lastBase(0),
clipBox(0),
firstFloat(0),
lastFloat(0),
currentFloat(0),
relativeX(0.0f),
relativeY(0.0f)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
if (item)
insertContext(item);
return item;
}
void StackingContext::insertContext(StackingContext* item)
{
assert(item);
if (isAuto()) {
parent->insertContext(item);
item->positioned = this;
return;
}
// TODO: Preserve the order in the DOM tree
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (item->zIndex < i->zIndex) {
after = i;
break;
}
}
insertBefore(item, after);
item->positioned = this;
}
void StackingContext::reparent(StackingContext* target)
{
auto child = parent->getFirstChild();
while (child) {
auto next = child->getNextSibling();
if (child->positioned == target) {
parent->removeChild(child);
target->insertContext(child);
if (child->isAuto())
reparent(child);
}
child = next;
}
}
void StackingContext::setZIndex(bool auto_, int index)
{
if (isAuto() == auto_ && zIndex == index)
return;
bool updateChildren = (this->auto_ != auto_);
this->auto_ = auto_;
zIndex = index;
if (parent) {
parent->removeChild(this);
positioned->insertContext(this);
if (updateChildren) {
if (isAuto()) {
while (StackingContext* child = getFirstChild()) {
removeChild(child);
child->positioned->insertContext(child);
}
} else
reparent(this);
}
}
}
void StackingContext::resetScrollSize()
{
for (Box* base = firstBase; base; base = base->nextBase)
base->resetScrollSize();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->resetScrollSize();
}
void StackingContext::resolveScrollSize(ViewCSSImp* view)
{
relativeX = relativeY = 0.0f;
for (StackingContext* s = this; s != parent; s = s->positioned) {
assert(s->style);
CSSStyleDeclarationImp* style = s->style;
if (!style->isResolved()) {
if (Box* b = style->getBox()) {
if (auto c = b->getContainingBlock(view)) {
style->left.resolve(view, style, c->width);
style->right.resolve(view, style, c->width);
style->top.resolve(view, style, c->height);
style->bottom.resolve(view, style, c->height);
}
}
}
style->resolveRelativeOffset(relativeX, relativeY);
}
if (parent) {
relativeX += parent->relativeX;
relativeY += parent->relativeY;
}
for (Box* base = firstBase; base; base = base->nextBase)
base->updateScrollSize();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->resolveScrollSize(view);
}
void StackingContext::updateClipBox(StackingContext* s)
{
float scrollLeft = 0.0f;
float scrollTop = 0.0f;
for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
if (clip->stackingContext == s || !clip->getParentBox())
continue;
Element element = interface_cast<Element>(clip->node);
scrollLeft += element.getScrollLeft();
scrollTop += element.getScrollTop();
if (clipWidth == HUGE_VALF) {
clipLeft = scrollLeft + clip->x + clip->marginLeft + clip->borderLeft + clip->stackingContext->relativeX;
clipTop = scrollTop + clip->y + clip->marginTop + clip->borderTop + clip->stackingContext->relativeY;
clipWidth = clip->getPaddingWidth();
clipHeight = clip->getPaddingHeight();
} else {
Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
scrollLeft + clip->x + clip->marginLeft + clip->borderLeft + clip->stackingContext->relativeX,
scrollTop + clip->y + clip->marginTop + clip->borderTop + clip->stackingContext->relativeY,
clip->getPaddingWidth(), clip->getPaddingHeight());
}
}
glTranslatef(-scrollLeft, -scrollTop, 0.0f);
}
bool StackingContext::hasClipBox()
{
clipLeft = clipTop = 0.0f;
clipWidth = clipHeight = HUGE_VALF;
for (StackingContext* s = this; s != parent; s = s->positioned)
updateClipBox(s);
return clipWidth != HUGE_VALF && clipHeight != HUGE_VALF;
}
void StackingContext::render(ViewCSSImp* view)
{
glPushMatrix();
if (hasClipBox())
view->clip(clipLeft, clipTop, clipWidth, clipHeight);
if (parent)
glTranslatef(relativeX - parent->relativeX, relativeY - parent->relativeY, 0.0f);
else
glTranslatef(relativeX, relativeY, 0.0f);
if (firstBase) {
currentFloat = firstFloat = lastFloat = 0;
GLfloat mtx[16];
glGetFloatv(GL_MODELVIEW_MATRIX, mtx);
for (Box* base = firstBase; base; base = base->nextBase) {
glPushMatrix();
Block* block = dynamic_cast<Block*>(base);
unsigned overflow = CSSOverflowValueImp::Visible;
if (block)
overflow = block->renderBegin(view);
StackingContext* childContext = getFirstChild();
for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling()) {
glPushMatrix();
glLoadMatrixf(mtx);
childContext->render(view);
glPopMatrix();
}
if (block) {
block->renderNonInline(view, this);
renderFloats(view, 0, 0);
block->renderInline(view, this);
} else
base->render(view, this);
for (; childContext; childContext = childContext->getNextSibling()) {
glPushMatrix();
glLoadMatrixf(mtx);
childContext->render(view);
glPopMatrix();
}
if (block) {
if (0.0f < block->getOutlineWidth())
block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
block->renderEnd(view, overflow);
}
glPopMatrix();
}
} else {
glPushMatrix();
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->render(view);
glPopMatrix();
}
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
glPopMatrix();
}
void StackingContext::renderFloats(ViewCSSImp* view, Box* last, Box* current)
{
if (current && current == currentFloat)
return;
Box* saved = currentFloat;
if (!current || !last)
currentFloat = firstFloat;
else if (last->nextFloat)
currentFloat = last->nextFloat;
else
return;
while (currentFloat) {
currentFloat->render(view, this);
assert(currentFloat);
currentFloat = currentFloat->nextFloat;
}
if (!current || !last)
firstFloat = lastFloat = 0;
else {
last->nextFloat = 0;
lastFloat = last;
}
currentFloat = saved;
}
void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstBase; i; i = i->nextBase)
assert(box != i);
#endif
if (!firstBase)
firstBase = lastBase = box;
else {
lastBase->nextBase = box;
lastBase = box;
}
box->nextBase = 0;
}
void StackingContext::addBox(Box* box, Box* parentBox)
{
assert(parentBox);
if (parentBox->stackingContext != this)
addBase(box);
}
void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstFloat; i; i = i->nextFloat) {
assert(box != i);
}
#endif
if (currentFloat) {
box->nextFloat = currentFloat->nextFloat;
currentFloat->nextFloat = box;
return;
}
if (!firstFloat)
firstFloat = lastFloat = box;
else {
lastFloat->nextFloat = box;
lastFloat = box;
}
box->nextFloat = 0;
}
void StackingContext::removeBox(Box* box)
{
Box* p = 0;
for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
if (i == box) {
if (!p)
firstBase = i->nextBase;
else
p->nextBase = i->nextBase;
if (lastBase == box)
lastBase = p;
break;
}
}
}
void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
for (Box* base = firstBase; base; base = base->nextBase) {
Block* block = dynamic_cast<Block*>(base);
if (!block || !block->isAbsolutelyPositioned())
continue;
block->layOutAbsolute(view);
block->resolveXY(view, block->x, block->y, block->clipBox ? block->clipBox : ((view->getTree() == block) ? 0 : view->getTree()));
}
needStaticPosition = false;
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->needStaticPosition = true;
bool repeat;
do {
repeat = false;
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling()) {
if (childContext->needStaticPosition) {
if (!childContext->positioned->needStaticPosition)
childContext->layOutAbsolute(view);
else
repeat = true;
}
}
} while (repeat);
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: ";
if (isAuto())
std::cout << "auto";
else
std::cout << zIndex;
std::cout << '\n';
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_
////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//
// not part of the EDSL but convenient for command line applications
#include "CompilePPZK_query.hpp"
#include "CompilePPZK_witness.hpp"
#include "CompileQAP.hpp"
#include "Getopt.hpp"
// the basic language
#include "DSL_base.hpp"
#include "DSL_bless.hpp"
#include "DSL_identity.hpp"
#include "DSL_ppzk.hpp"
#include "DSL_utility.hpp"
// progress bar for proof generation and verification
#include "GenericProgressBar.hpp"
// input and printing of hexadecimal text
#include "HexUtil.hpp"
// initialize elliptic curves
#include "InitPairing.hpp"
// Merkle tree
#include "MerkleAuthPath.hpp"
#include "MerkleBundle.hpp"
#include "MerkleTree.hpp"
// Secure Hash Algorithms
#include "SHA_1.hpp"
#include "SHA_224.hpp"
#include "SHA_256.hpp"
#include "SHA_384.hpp"
#include "SHA_512.hpp"
#include "SHA_512_224.hpp"
#include "SHA_512_256.hpp"
// Advanced Encryption Algorithm
#include "AES_Cipher.hpp"
#include "AES_InvCipher.hpp"
#include "AES_InvSBox.hpp"
#include "AES_KeyExpansion.hpp"
#include "AES_SBox.hpp"
#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_
////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//
// not part of the EDSL but convenient for command line applications
#include <snarkfront/CompilePPZK_query.hpp>
#include <snarkfront/CompilePPZK_witness.hpp>
#include <snarkfront/CompileQAP.hpp>
#include <snarkfront/Getopt.hpp>
// the basic language
#include <snarkfront/DSL_base.hpp>
#include <snarkfront/DSL_bless.hpp>
#include <snarkfront/DSL_identity.hpp>
#include <snarkfront/DSL_ppzk.hpp>
#include <snarkfront/DSL_utility.hpp>
// progress bar for proof generation and verification
#include <snarkfront/GenericProgressBar.hpp>
// input and printing of hexadecimal text
#include <snarkfront/HexUtil.hpp>
// initialize elliptic curves
#include <snarkfront/InitPairing.hpp>
// Merkle tree
#include <snarkfront/MerkleAuthPath.hpp>
#include <snarkfront/MerkleBundle.hpp>
#include <snarkfront/MerkleTree.hpp>
// Secure Hash Algorithms
#include <snarkfront/SHA_1.hpp>
#include <snarkfront/SHA_224.hpp>
#include <snarkfront/SHA_256.hpp>
#include <snarkfront/SHA_384.hpp>
#include <snarkfront/SHA_512.hpp>
#include <snarkfront/SHA_512_224.hpp>
#include <snarkfront/SHA_512_256.hpp>
// Advanced Encryption Algorithm
#include <snarkfront/AES_Cipher.hpp>
#include <snarkfront/AES_InvCipher.hpp>
#include <snarkfront/AES_InvSBox.hpp>
#include <snarkfront/AES_KeyExpansion.hpp>
#include <snarkfront/AES_SBox.hpp>
#endif
<|endoftext|>
|
<commit_before>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* 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 "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
using v8::NewStringType;
#if V8_MAJOR_VERSION >= 7
#define CHECK_SET(X) X.Check()
#else
#define CHECK_SET(X) (void)X
#endif
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
//tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet"));
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet", NewStringType::kNormal).ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
CHECK_SET(exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "HashSetecp", NewStringType::kNormal).ToLocalChecked(),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()));
// exports->Set(String::NewFromUtf8(isolate, "HashSet"),
// tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<commit_msg>cleanup<commit_after>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* 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 "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
using v8::NewStringType;
#if V8_MAJOR_VERSION >= 7
#define CHECK_SET(X) X.Check()
#else
#define CHECK_SET(X) (void)X
#endif
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet", NewStringType::kNormal).ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
CHECK_SET(exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "HashSetecp", NewStringType::kNormal).ToLocalChecked(),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()));
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<|endoftext|>
|
<commit_before>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* 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 "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
exports->Set(String::NewFromUtf8(isolate, "HashSet"),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<commit_msg>change export set<commit_after>/* Copyright (c) 2015 Brian R. Bondy. Distributed under the MPL2 license.
* 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 "./hash_set_wrap.h"
namespace HashSetWrap {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Boolean;
using v8::Value;
using v8::NewStringType;
#if V8_MAJOR_VERSION >= 7
#define CHECK_SET(X) X.Check()
#else
#define CHECK_SET(X) (void)X
#endif
Persistent<Function> HashSetWrap::constructor;
HashSetWrap::HashSetWrap(uint32_t bucket_count, bool multi_set)
: HashSet(bucket_count, multi_set) {
}
HashSetWrap::~HashSetWrap() {
}
void HashSetWrap::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "HashSet"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "add", HashSetWrap::AddItem);
NODE_SET_PROTOTYPE_METHOD(tpl, "exists", HashSetWrap::ItemExists);
constructor.Reset(isolate,
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
CHECK_SET(exports->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "HashSet", NewStringType::kNormal).ToLocalChecked(),
tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()));
// exports->Set(String::NewFromUtf8(isolate, "HashSet"),
// tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
}
void HashSetWrap::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new HashSet(...)`
HashSetWrap* obj = new HashSetWrap(1024, false);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `HashSet(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(
cons->NewInstance(isolate->GetCurrentContext(), argc, argv)
.ToLocalChecked());
}
}
void HashSetWrap::AddItem(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
obj->Add(ExampleData(buffer));
}
void HashSetWrap::ItemExists(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
String::Utf8Value str(isolate,
args[0]->ToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
const char * buffer = *str;
HashSetWrap* obj = ObjectWrap::Unwrap<HashSetWrap>(args.Holder());
bool exists = obj->Exists(ExampleData(buffer));
args.GetReturnValue().Set(Boolean::New(isolate, exists));
}
} // namespace HashSetWrap
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* IO_ADIOS2.cpp
*
* Created on: Feb 2017
* Author: Norbert Podhorszki
*/
#include "IO.h"
#include <string>
#include <stdexcept>
#include <hdf5.h>
#include <memory>
#include <ios>
#include <iostream>
class HDF5NativeWriter
{
public:
HDF5NativeWriter(const std::string &fileName);
~HDF5NativeWriter();
bool Advance();
void Close();
void CheckWriteGroup();
void WriteScalar(const std::string &varName, const void *data,
hid_t h5Type);
void WriteSimple(const std::string &varName, int dimSize, const void *data,
hid_t h5Type, const hsize_t *shape, const hsize_t *offset,
const hsize_t *count);
int m_CurrentTimeStep;
unsigned int m_TotalTimeSteps;
private:
hid_t m_FilePropertyListId;
hid_t m_FileId;
hid_t m_GroupId;
};
HDF5NativeWriter::HDF5NativeWriter(const std::string &fileName)
: m_CurrentTimeStep(0), m_TotalTimeSteps(0)
{
m_FilePropertyListId = H5Pcreate(H5P_FILE_ACCESS);
#ifdef ADIOS2_HAVE_MPI
// read a file collectively
H5Pset_fapl_mpio(m_FilePropertyListId, MPI_COMM_WORLD, MPI_INFO_NULL);
#endif
m_FileId = H5Fcreate(fileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT,
m_FilePropertyListId);
if (m_FileId < 0)
{
throw std::runtime_error("Unable to open " + fileName + " for reading");
}
std::string ts0 = "/TimeStep0";
m_GroupId = H5Gcreate2(m_FileId, ts0.c_str(), H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
if (m_GroupId < 0)
{
throw std::runtime_error("HDF5: Unable to create group " + ts0);
}
}
HDF5NativeWriter::~HDF5NativeWriter() { Close(); }
void HDF5NativeWriter::Close()
{
if (m_FileId < 0)
return;
hid_t s = H5Screate(H5S_SCALAR);
hid_t attr = H5Acreate(m_FileId, "NumTimeSteps", H5T_NATIVE_UINT, s,
H5P_DEFAULT, H5P_DEFAULT);
uint totalTimeSteps = m_CurrentTimeStep + 1;
if (m_GroupId < 0)
{
totalTimeSteps = m_CurrentTimeStep;
}
H5Awrite(attr, H5T_NATIVE_UINT, &totalTimeSteps);
H5Sclose(s);
H5Aclose(attr);
if (m_GroupId >= 0)
{
H5Gclose(m_GroupId);
m_GroupId = -1;
}
H5Fclose(m_FileId);
m_FileId = -1;
H5Pclose(m_FilePropertyListId);
}
bool HDF5NativeWriter::Advance()
{
if (m_GroupId >= 0)
{
H5Gclose(m_GroupId);
m_GroupId = -1;
}
++m_CurrentTimeStep;
return true;
}
void HDF5NativeWriter::CheckWriteGroup()
{
if (m_GroupId >= 0)
{
return;
}
std::string timeStepName = "/TimeStep" + std::to_string(m_CurrentTimeStep);
m_GroupId = H5Gcreate2(m_FileId, timeStepName.c_str(), H5P_DEFAULT,
H5P_DEFAULT, H5P_DEFAULT);
if (m_GroupId < 0)
{
throw std::runtime_error("HDF5: Unable to create group " +
timeStepName);
}
}
void HDF5NativeWriter::WriteScalar(const std::string &varName, const void *data,
hid_t h5Type)
{
CheckWriteGroup();
// scalar
hid_t filespaceID = H5Screate(H5S_SCALAR);
hid_t dsetID = H5Dcreate(m_GroupId, varName.c_str(), h5Type, filespaceID,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
herr_t status =
H5Dwrite(dsetID, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, data);
H5Sclose(filespaceID);
H5Dclose(dsetID);
}
void HDF5NativeWriter::WriteSimple(const std::string &varName, int dimSize,
const void *data, hid_t h5Type,
const hsize_t *shape, const hsize_t *offset,
const hsize_t *count)
{
CheckWriteGroup();
hid_t fileSpace = H5Screate_simple(dimSize, shape, NULL);
hid_t dsetID = H5Dcreate(m_GroupId, varName.c_str(), h5Type, fileSpace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
hid_t memSpace = H5Screate_simple(dimSize, count, NULL);
// Select hyperslab
fileSpace = H5Dget_space(dsetID);
H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, offset, NULL, count, NULL);
// Create property list for collective dataset write.
hid_t plistID = H5Pcreate(H5P_DATASET_XFER);
#ifdef ADIOS2_HAVE_MPI
H5Pset_dxpl_mpio(plistID, H5FD_MPIO_COLLECTIVE);
#endif
herr_t status;
status = H5Dwrite(dsetID, h5Type, memSpace, fileSpace, plistID, data);
if (status < 0)
{
// error
std::cerr << " Write failed. " << std::endl;
}
H5Dclose(dsetID);
H5Sclose(fileSpace);
H5Sclose(memSpace);
H5Pclose(plistID);
}
//
//
std::shared_ptr<HDF5NativeWriter> h5writer;
// HDF5NativeWriter* h5writer;
IO::IO(const Settings &s, MPI_Comm comm)
{
m_outputfilename = s.outputfile + ".h5";
h5writer = std::make_shared<HDF5NativeWriter>(m_outputfilename);
if (h5writer == nullptr)
throw std::ios_base::failure("ERROR: failed to open ADIOS h5writer\n");
}
IO::~IO()
{
h5writer->Close();
// delete h5writer;
}
void IO::write(int step, const HeatTransfer &ht, const Settings &s,
MPI_Comm comm)
{
std::vector<hsize_t> dims = {s.gndx, s.gndy};
std::vector<hsize_t> offset = {s.offsx, s.offsy};
std::vector<hsize_t> count = {s.ndx, s.ndy};
h5writer->WriteSimple("T", 2, ht.data_noghost().data(), H5T_NATIVE_DOUBLE,
dims.data(), offset.data(), count.data());
h5writer->WriteScalar("gndy", &(s.gndy), H5T_NATIVE_UINT);
h5writer->Advance();
}
<commit_msg>minor change<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* IO_ADIOS2.cpp
*
* Created on: Feb 2017
* Author: Norbert Podhorszki
*/
#include "IO.h"
#include <string>
#include <stdexcept>
#include <hdf5.h>
#include <memory>
#include <ios>
#include <iostream>
class HDF5NativeWriter
{
public:
HDF5NativeWriter(const std::string &fileName);
~HDF5NativeWriter();
bool Advance();
void Close();
void CheckWriteGroup();
void WriteScalar(const std::string &varName, const void *data,
hid_t h5Type);
void WriteSimple(const std::string &varName, int dimSize, const void *data,
hid_t h5Type, const hsize_t *shape, const hsize_t *offset,
const hsize_t *count);
int m_CurrentTimeStep;
unsigned int m_TotalTimeSteps;
private:
hid_t m_FilePropertyListId;
hid_t m_FileId;
hid_t m_GroupId;
};
HDF5NativeWriter::HDF5NativeWriter(const std::string &fileName)
: m_CurrentTimeStep(0), m_TotalTimeSteps(0)
{
m_FilePropertyListId = H5Pcreate(H5P_FILE_ACCESS);
// read a file collectively
H5Pset_fapl_mpio(m_FilePropertyListId, MPI_COMM_WORLD, MPI_INFO_NULL);
m_FileId = H5Fcreate(fileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT,
m_FilePropertyListId);
if (m_FileId < 0)
{
throw std::runtime_error("Unable to open " + fileName + " for reading");
}
std::string ts0 = "/TimeStep0";
m_GroupId = H5Gcreate2(m_FileId, ts0.c_str(), H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
if (m_GroupId < 0)
{
throw std::runtime_error("HDF5: Unable to create group " + ts0);
}
}
HDF5NativeWriter::~HDF5NativeWriter() { Close(); }
void HDF5NativeWriter::Close()
{
if (m_FileId < 0)
return;
hid_t s = H5Screate(H5S_SCALAR);
hid_t attr = H5Acreate(m_FileId, "NumTimeSteps", H5T_NATIVE_UINT, s,
H5P_DEFAULT, H5P_DEFAULT);
uint totalTimeSteps = m_CurrentTimeStep + 1;
if (m_GroupId < 0)
{
totalTimeSteps = m_CurrentTimeStep;
}
H5Awrite(attr, H5T_NATIVE_UINT, &totalTimeSteps);
H5Sclose(s);
H5Aclose(attr);
if (m_GroupId >= 0)
{
H5Gclose(m_GroupId);
m_GroupId = -1;
}
H5Fclose(m_FileId);
m_FileId = -1;
H5Pclose(m_FilePropertyListId);
}
bool HDF5NativeWriter::Advance()
{
if (m_GroupId >= 0)
{
H5Gclose(m_GroupId);
m_GroupId = -1;
}
++m_CurrentTimeStep;
return true;
}
void HDF5NativeWriter::CheckWriteGroup()
{
if (m_GroupId >= 0)
{
return;
}
std::string timeStepName = "/TimeStep" + std::to_string(m_CurrentTimeStep);
m_GroupId = H5Gcreate2(m_FileId, timeStepName.c_str(), H5P_DEFAULT,
H5P_DEFAULT, H5P_DEFAULT);
if (m_GroupId < 0)
{
throw std::runtime_error("HDF5: Unable to create group " +
timeStepName);
}
}
void HDF5NativeWriter::WriteScalar(const std::string &varName, const void *data,
hid_t h5Type)
{
CheckWriteGroup();
// scalar
hid_t filespaceID = H5Screate(H5S_SCALAR);
hid_t dsetID = H5Dcreate(m_GroupId, varName.c_str(), h5Type, filespaceID,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
herr_t status =
H5Dwrite(dsetID, h5Type, H5S_ALL, H5S_ALL, H5P_DEFAULT, data);
H5Sclose(filespaceID);
H5Dclose(dsetID);
}
void HDF5NativeWriter::WriteSimple(const std::string &varName, int dimSize,
const void *data, hid_t h5Type,
const hsize_t *shape, const hsize_t *offset,
const hsize_t *count)
{
CheckWriteGroup();
hid_t fileSpace = H5Screate_simple(dimSize, shape, NULL);
hid_t dsetID = H5Dcreate(m_GroupId, varName.c_str(), h5Type, fileSpace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
hid_t memSpace = H5Screate_simple(dimSize, count, NULL);
// Select hyperslab
fileSpace = H5Dget_space(dsetID);
H5Sselect_hyperslab(fileSpace, H5S_SELECT_SET, offset, NULL, count, NULL);
// Create property list for collective dataset write.
hid_t plistID = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(plistID, H5FD_MPIO_COLLECTIVE);
herr_t status;
status = H5Dwrite(dsetID, h5Type, memSpace, fileSpace, plistID, data);
if (status < 0)
{
// error
std::cerr << " Write failed. " << std::endl;
}
H5Dclose(dsetID);
H5Sclose(fileSpace);
H5Sclose(memSpace);
H5Pclose(plistID);
}
//
//
std::shared_ptr<HDF5NativeWriter> h5writer;
// HDF5NativeWriter* h5writer;
IO::IO(const Settings &s, MPI_Comm comm)
{
m_outputfilename = s.outputfile + ".h5";
if (s.outputfile[0]=='0') {
std::cout<<" no writer. "<<std::endl;
h5writer = nullptr;
return;
}
h5writer = std::make_shared<HDF5NativeWriter>(m_outputfilename);
if (h5writer == nullptr)
throw std::ios_base::failure("ERROR: failed to open ADIOS h5writer\n");
}
IO::~IO()
{
if (h5writer != nullptr) {
h5writer->Close();
}
// delete h5writer;
}
void IO::write(int step, const HeatTransfer &ht, const Settings &s,
MPI_Comm comm)
{
if (h5writer == nullptr) {
return;
}
std::vector<hsize_t> dims = {s.gndx, s.gndy};
std::vector<hsize_t> offset = {s.offsx, s.offsy};
std::vector<hsize_t> count = {s.ndx, s.ndy};
h5writer->WriteSimple("T", 2, ht.data_noghost().data(), H5T_NATIVE_DOUBLE,
dims.data(), offset.data(), count.data());
h5writer->WriteScalar("gndy", &(s.gndy), H5T_NATIVE_UINT);
h5writer->WriteScalar("gndx", &(s.gndx), H5T_NATIVE_UINT);
h5writer->Advance();
}
<|endoftext|>
|
<commit_before>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* wxparaver *
* Paraver Trace Visualization and Analysis Tool *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL 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 *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
| @file: $HeadURL$
| @last_commit: $Date$
| @version: $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <string>
#include "helpcontents.h"
//#include "wx/html/htmlfilt.h"
#include "paravermain.h"
////@begin XPM images
////@end XPM images
/*!
* HelpContents type definition
*/
IMPLEMENT_DYNAMIC_CLASS( HelpContents, wxDialog )
/*!
* HelpContents event table definition
*/
BEGIN_EVENT_TABLE( HelpContents, wxDialog )
////@begin HelpContents event table entries
EVT_HTML_LINK_CLICKED( ID_HTMLWINDOW, HelpContents::OnHtmlwindowLinkClicked )
EVT_BUTTON( ID_BUTTON_INDEX, HelpContents::OnButtonIndexClick )
EVT_BUTTON( ID_BUTTON_CLOSE, HelpContents::OnButtonCloseClick )
////@end HelpContents event table entries
END_EVENT_TABLE()
/*!
* HelpContents constructors
*/
HelpContents::HelpContents()
{
Init();
}
HelpContents::HelpContents( wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style )
{
Init();
Create(parent, id, caption, pos, size, style);
}
/*!
* HelpContents creator
*/
bool HelpContents::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin HelpContents creation
SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
wxDialog::Create( parent, id, caption, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end HelpContents creation
return true;
}
/*!
* HelpContents destructor
*/
HelpContents::~HelpContents()
{
}
/*!
* Member initialisation
*/
void HelpContents::Init()
{
currentTutorialDir = _("");
}
const wxString HelpContents::getHtmlIndex( const wxString& path )
{
wxString htmlIndex;
wxFileName index( path + wxFileName::GetPathSeparator() + _("index.html") );
if ( index.FileExists() )
{
htmlIndex = index.GetFullPath();
}
return htmlIndex;
}
const wxString HelpContents::getTitle( int numTutorial, const wxString& path )
{
wxString tutorialTitle;
wxHtmlWindow auxHtml( this );
auxHtml.LoadPage( path + wxFileName::GetPathSeparator() + _("index.html") );
tutorialTitle = auxHtml.GetOpenedPageTitle();
if ( tutorialTitle.empty() || tutorialTitle == _("index.html") ) // never is empty !?!
{
string auxStrTitleFileName( path + wxFileName::GetPathSeparator() + _("tutorial_title") );
string auxLine;
ifstream titleFile;
titleFile.open( auxStrTitleFileName.c_str() );
if ( titleFile.good() )
{
std::getline( titleFile, auxLine );
if ( auxLine.size() > 0 )
{
tutorialTitle = wxString::FromAscii( auxLine.c_str() );
}
else
{
tutorialTitle = _("Tutorial ");
tutorialTitle << numTutorial;
}
}
else
{
tutorialTitle = _("Tutorial ");
tutorialTitle << numTutorial;
}
titleFile.close();
}
return tutorialTitle;
}
void HelpContents::appendTutorial( const wxString& title,
const wxString& path,
wxString& htmlDoc )
{
htmlDoc += _("<LI><P><A HREF=\"") + path + _("\">") + title + _("</A></P></LI>");
}
void HelpContents::htmlMessage( wxString& htmlDoc )
{
htmlDoc += _("<P><H3>No tutorial found!</H3></P>");
/*
htmlDoc += _("<P>Before going on, please have in mind that:</P>");
htmlDoc += _("<UL>");
htmlDoc += _("<LI>A single <B>tutorials root directory</B> must contain all ");
htmlDoc += _("the <B>tutorials directories</B> that you want <B>visible</B> for wxparaver.</LI>");
htmlDoc += _("<LI>In their own directories, every tutorial has a <B>first page</B> called <TT>index.html</TT>, and also related content (like traces, cfgs, etc.).</LI>");
htmlDoc += _("<LI>You <B>don't</B> need to <B>write</B> any global tutorials page; we walk through the included tutorials ");
htmlDoc += _("in the given root directory and build it for you.</LI>");
htmlDoc += _("<LI>The tutorial title showed in this automatically built main index is read from:</LI>");
htmlDoc += _("<OL type=\"1\">");
htmlDoc += _("<LI>The <TT>TITLE</TT> tag in the<TT>index.html</TT> file.</LI>");
htmlDoc += _("<LI>If this tag is missing or empty, from a single line file named <TT>tutorial_title</TT>");
htmlDoc += _(", also local to this tutorial.</LI>");
htmlDoc += _("<LI>If no <TT>tutorial_title</TT> file is found, we give a numbered 'Tutorial #'.</LI>");
htmlDoc += _("</OL>");
htmlDoc += _("</UL>");
*/
htmlDoc += _("<P>Please check that <B>root directory</B> to tutorials is properly defined:</P>");
htmlDoc += _("<OL type=\"1\">");
htmlDoc += _("<LI>Open <A HREF=\"init_preferences\"><I>Preferences Window</I></A>.</LI>");
htmlDoc += _("<LI>Select <I>Global</I> tab.</LI>");
htmlDoc += _("<LI>In the <I>Default directories</I> box, change the <I>Tutorials root</I> directory");
htmlDoc += _("<LI>The tutorials list will be immediately rebuilt after you save your ");
htmlDoc += _("new settings clicking the <I>Ok</I> button in the <A HREF=\"init_preferences\"><I>Preferences Window</I></A>.</LI>");
htmlDoc += _("</OL>");
htmlDoc += _("<P>If you still get this help, check these steps again, or please contact us at paraver@bsc.es.</P>");
}
void HelpContents::buildIndex()
{
// get tutorials directory
string auxStrPath = paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath();
wxString auxPath = wxString::FromAscii( auxStrPath.c_str() );
wxFileName tutorialsGlobalPath( auxPath );
// open html index
wxString tutorialsHtmlIndex, tutorialsList;
tutorialsHtmlIndex += _("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
tutorialsHtmlIndex += _("<HTML><HEAD><TITLE>Tutorials</TITLE></HEAD><BODY>");
// look for tutorials directories, and for index.html inside them
if ( wxDirExists( auxPath ) )
{
tutorialsList += _("<UL>");
int numTutorials = 0;
wxString currentDir = wxFindFirstFile(
tutorialsGlobalPath.GetLongPath() + wxFileName::GetPathSeparator() + _("*"),
wxDIR );
while( !currentDir.empty() )
{
wxString currentTutorialHtmlIndex( getHtmlIndex( currentDir ) );
if ( currentTutorialHtmlIndex != _("") )
{
// index.html found! => we consider this is a tutorial
numTutorials++;
appendTutorial( getTitle( numTutorials, currentDir ), currentTutorialHtmlIndex, tutorialsList );
}
currentDir = wxFindNextFile();
}
tutorialsList += _("</UL>");
if ( numTutorials == 0 )
{
htmlMessage( tutorialsHtmlIndex );
}
else
{
tutorialsHtmlIndex += _("<P><H3><B>Index</B></H3></P>");
tutorialsHtmlIndex += tutorialsList;
}
}
else
{
htmlMessage( tutorialsHtmlIndex );
}
// close html index
tutorialsHtmlIndex += _("</BODY></HTML>");
htmlWindow->SetPage( tutorialsHtmlIndex.ToUTF8() );
}
/*!
* Control creation for HelpContents
*/
void HelpContents::CreateControls()
{
////@begin HelpContents content construction
HelpContents* itemDialog1 = this;
wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
itemDialog1->SetSizer(itemBoxSizer2);
htmlWindow = new wxHtmlWindow( itemDialog1, ID_HTMLWINDOW, wxDefaultPosition, wxSize(600, 400), wxHW_SCROLLBAR_AUTO|wxSUNKEN_BORDER|wxHSCROLL|wxVSCROLL );
itemBoxSizer2->Add(htmlWindow, 1, wxGROW|wxALL, 5);
wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer2->Add(itemBoxSizer4, 0, wxGROW|wxALL, 5);
wxButton* itemButton5 = new wxButton( itemDialog1, ID_BUTTON_INDEX, _("Index"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer4->Add(itemButton5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer4->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* itemButton7 = new wxButton( itemDialog1, ID_BUTTON_CLOSE, _("Close"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer4->Add(itemButton7, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
////@end HelpContents content construction
buildIndex();
}
/*!
* Should we show tooltips?
*/
bool HelpContents::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap HelpContents::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin HelpContents bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end HelpContents bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon HelpContents::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin HelpContents icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end HelpContents icon retrieval
}
std::string HelpContents::getHrefFullPath( wxHtmlLinkEvent &event )
{
string hrefFullPath = paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath();
hrefFullPath += wxString( wxFileName::GetPathSeparator() ).mb_str();
hrefFullPath += currentTutorialDir.mb_str();
hrefFullPath += wxString( wxFileName::GetPathSeparator() ).mb_str();
hrefFullPath += std::string( event.GetLinkInfo().GetHref().mb_str() );
return hrefFullPath;
}
bool HelpContents::matchHrefExtension( wxHtmlLinkEvent &event, const wxString extension )
{
return ( event.GetLinkInfo().GetHref().Right( extension.Len() ).Cmp( extension ) == 0 );
}
/*!
* wxEVT_COMMAND_HTML_LINK_CLICKED event handler for ID_HTMLWINDOW
*/
void HelpContents::OnHtmlwindowLinkClicked( wxHtmlLinkEvent& event )
{
if ( matchHrefExtension( event, _(".prv") ) || matchHrefExtension( event, _(".prv.gz")))
{
paraverMain::myParaverMain->DoLoadTrace( getHrefFullPath( event ) );
}
else if ( matchHrefExtension( event, _(".cfg")))
{
if ( paraverMain::myParaverMain->GetLoadedTraces().size() > 0 )
{
paraverMain::myParaverMain->DoLoadCFG( getHrefFullPath( event ) );
}
else
{
wxMessageDialog message( this, _("No trace loaded."), _( "Warning" ), wxOK );
message.ShowModal();
}
}
else if ( event.GetLinkInfo().GetHref().Cmp( _("init_preferences") ) == 0 )
{
paraverMain::myParaverMain->ShowPreferences();
// we rebuild it anyway
buildIndex();
}
else
{
// If current clicked link points to a tutorial index.html file, keep its
// tutorial directory name to allow relative references.
// Idea to detect tutorial:
// /home/user/root-tutorials/ => dir depth tutorials = 3
// vs.
// /home/user/root-tutorials/tutorial1/index.html => dir depth current = 4
// /home/user/root-tutorials/tutorial1/html/.../anyotherpage.html => dir depth current > 4
wxString anyTutorialPath =
wxString( paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath().c_str() );
if ( anyTutorialPath[ anyTutorialPath.Len() - 1 ] != wxString( wxFileName::GetPathSeparator() ))
{
// last separator needed to count properly
anyTutorialPath += wxString( wxFileName::GetPathSeparator() );
}
wxFileName anyTutorialDir( anyTutorialPath );
size_t dirsDepthTutorials = anyTutorialDir.GetDirCount();
wxFileName currentLink( event.GetLinkInfo().GetHref() );
size_t dirsDepthCurrentLink = currentLink.GetDirCount();
if (( dirsDepthCurrentLink == dirsDepthTutorials + 1 ) &&
( currentLink.GetFullName().Cmp( _("index.html") ) == 0 ))
{
wxArrayString dirs = currentLink.GetDirs();
currentTutorialDir = dirs[ dirsDepthCurrentLink - 1 ];
}
// and let the html window browse it.
event.Skip();
}
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON_CLOSE
*/
void HelpContents::OnButtonCloseClick( wxCommandEvent& event )
{
Close();
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON_INDEX
*/
void HelpContents::OnButtonIndexClick( wxCommandEvent& event )
{
buildIndex();
}
<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* wxparaver *
* Paraver Trace Visualization and Analysis Tool *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL 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 *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
| @file: $HeadURL$
| @last_commit: $Date$
| @version: $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <string>
#include "helpcontents.h"
//#include "wx/html/htmlfilt.h"
#include "paravermain.h"
////@begin XPM images
////@end XPM images
/*!
* HelpContents type definition
*/
IMPLEMENT_DYNAMIC_CLASS( HelpContents, wxDialog )
/*!
* HelpContents event table definition
*/
BEGIN_EVENT_TABLE( HelpContents, wxDialog )
////@begin HelpContents event table entries
EVT_HTML_LINK_CLICKED( ID_HTMLWINDOW, HelpContents::OnHtmlwindowLinkClicked )
EVT_BUTTON( ID_BUTTON_INDEX, HelpContents::OnButtonIndexClick )
EVT_BUTTON( ID_BUTTON_CLOSE, HelpContents::OnButtonCloseClick )
////@end HelpContents event table entries
END_EVENT_TABLE()
/*!
* HelpContents constructors
*/
HelpContents::HelpContents()
{
Init();
}
HelpContents::HelpContents( wxWindow* parent,
wxWindowID id,
const wxString& caption,
const wxPoint& pos,
const wxSize& size,
long style )
{
Init();
Create(parent, id, caption, pos, size, style);
}
/*!
* HelpContents creator
*/
bool HelpContents::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin HelpContents creation
SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
wxDialog::Create( parent, id, caption, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end HelpContents creation
return true;
}
/*!
* HelpContents destructor
*/
HelpContents::~HelpContents()
{
}
/*!
* Member initialisation
*/
void HelpContents::Init()
{
currentTutorialDir = _("");
}
const wxString HelpContents::getHtmlIndex( const wxString& path )
{
wxString htmlIndex;
wxFileName index( path + wxFileName::GetPathSeparator() + _("index.html") );
if ( index.FileExists() )
{
htmlIndex = index.GetFullPath();
}
return htmlIndex;
}
const wxString HelpContents::getTitle( int numTutorial, const wxString& path )
{
wxString tutorialTitle;
wxHtmlWindow auxHtml( this );
auxHtml.LoadPage( path + wxFileName::GetPathSeparator() + _("index.html") );
tutorialTitle = auxHtml.GetOpenedPageTitle();
if ( tutorialTitle.empty() || tutorialTitle == _("index.html") ) // never is empty !?!
{
string auxStrTitleFileName( path + wxFileName::GetPathSeparator() + _("tutorial_title") );
string auxLine;
ifstream titleFile;
titleFile.open( auxStrTitleFileName.c_str() );
if ( titleFile.good() )
{
std::getline( titleFile, auxLine );
if ( auxLine.size() > 0 )
{
tutorialTitle = wxString::FromAscii( auxLine.c_str() );
}
else
{
tutorialTitle = _("Tutorial ");
tutorialTitle << numTutorial;
}
}
else
{
tutorialTitle = _("Tutorial ");
tutorialTitle << numTutorial;
}
titleFile.close();
}
return tutorialTitle;
}
void HelpContents::appendTutorial( const wxString& title,
const wxString& path,
wxString& htmlDoc )
{
htmlDoc += _("<LI><P><A HREF=\"") + path + _("\">") + title + _("</A></P></LI>");
}
void HelpContents::htmlMessage( wxString& htmlDoc )
{
htmlDoc += _("<P><H3>No tutorial found!</H3></P>");
/*
htmlDoc += _("<P>Before going on, please have in mind that:</P>");
htmlDoc += _("<UL>");
htmlDoc += _("<LI>A single <B>tutorials root directory</B> must contain all ");
htmlDoc += _("the <B>tutorials directories</B> that you want <B>visible</B> for wxparaver.</LI>");
htmlDoc += _("<LI>In their own directories, every tutorial has a <B>first page</B> called <TT>index.html</TT>, and also related content (like traces, cfgs, etc.).</LI>");
htmlDoc += _("<LI>You <B>don't</B> need to <B>write</B> any global tutorials page; we walk through the included tutorials ");
htmlDoc += _("in the given root directory and build it for you.</LI>");
htmlDoc += _("<LI>The tutorial title showed in this automatically built main index is read from:</LI>");
htmlDoc += _("<OL type=\"1\">");
htmlDoc += _("<LI>The <TT>TITLE</TT> tag in the<TT>index.html</TT> file.</LI>");
htmlDoc += _("<LI>If this tag is missing or empty, from a single line file named <TT>tutorial_title</TT>");
htmlDoc += _(", also local to this tutorial.</LI>");
htmlDoc += _("<LI>If no <TT>tutorial_title</TT> file is found, we give a numbered 'Tutorial #'.</LI>");
htmlDoc += _("</OL>");
htmlDoc += _("</UL>");
*/
htmlDoc += _("<P>Please check that <B>root directory</B> to tutorials is properly defined:</P>");
htmlDoc += _("<OL type=\"1\">");
htmlDoc += _("<LI>Open <A HREF=\"init_preferences\"><I>Preferences Window</I></A>.</LI>");
htmlDoc += _("<LI>Select <I>Global</I> tab.</LI>");
htmlDoc += _("<LI>In the <I>Default directories</I> box, change the <I>Tutorials root</I> directory");
htmlDoc += _("<LI>The tutorials list will be immediately rebuilt after you save your ");
htmlDoc += _("new settings clicking the <I>Ok</I> button in the <I>Preferences Window</I>.</LI>");
htmlDoc += _("</OL>");
htmlDoc += _("<P>If you still get this help, check these steps again, or please contact us at paraver@bsc.es.</P>");
}
void HelpContents::buildIndex()
{
// get tutorials directory
string auxStrPath = paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath();
wxString auxPath = wxString::FromAscii( auxStrPath.c_str() );
wxFileName tutorialsGlobalPath( auxPath );
// open html index
wxString tutorialsHtmlIndex, tutorialsList;
tutorialsHtmlIndex += _("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
tutorialsHtmlIndex += _("<HTML><HEAD><TITLE>Tutorials</TITLE></HEAD><BODY>");
// look for tutorials directories, and for index.html inside them
if ( wxDirExists( auxPath ) )
{
tutorialsList += _("<UL>");
int numTutorials = 0;
wxString currentDir = wxFindFirstFile(
tutorialsGlobalPath.GetLongPath() + wxFileName::GetPathSeparator() + _("*"),
wxDIR );
while( !currentDir.empty() )
{
wxString currentTutorialHtmlIndex( getHtmlIndex( currentDir ) );
if ( currentTutorialHtmlIndex != _("") )
{
// index.html found! => we consider this is a tutorial
numTutorials++;
appendTutorial( getTitle( numTutorials, currentDir ), currentTutorialHtmlIndex, tutorialsList );
}
currentDir = wxFindNextFile();
}
tutorialsList += _("</UL>");
if ( numTutorials == 0 )
{
htmlMessage( tutorialsHtmlIndex );
}
else
{
tutorialsHtmlIndex += _("<P><H3><B>Index</B></H3></P>");
tutorialsHtmlIndex += tutorialsList;
}
}
else
{
htmlMessage( tutorialsHtmlIndex );
}
// close html index
tutorialsHtmlIndex += _("</BODY></HTML>");
htmlWindow->SetPage( tutorialsHtmlIndex.ToUTF8() );
}
/*!
* Control creation for HelpContents
*/
void HelpContents::CreateControls()
{
////@begin HelpContents content construction
HelpContents* itemDialog1 = this;
wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
itemDialog1->SetSizer(itemBoxSizer2);
htmlWindow = new wxHtmlWindow( itemDialog1, ID_HTMLWINDOW, wxDefaultPosition, wxSize(600, 400), wxHW_SCROLLBAR_AUTO|wxSUNKEN_BORDER|wxHSCROLL|wxVSCROLL );
itemBoxSizer2->Add(htmlWindow, 1, wxGROW|wxALL, 5);
wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxHORIZONTAL);
itemBoxSizer2->Add(itemBoxSizer4, 0, wxGROW|wxALL, 5);
wxButton* itemButton5 = new wxButton( itemDialog1, ID_BUTTON_INDEX, _("Index"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer4->Add(itemButton5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
itemBoxSizer4->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* itemButton7 = new wxButton( itemDialog1, ID_BUTTON_CLOSE, _("Close"), wxDefaultPosition, wxDefaultSize, 0 );
itemBoxSizer4->Add(itemButton7, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
////@end HelpContents content construction
buildIndex();
}
/*!
* Should we show tooltips?
*/
bool HelpContents::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap HelpContents::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin HelpContents bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end HelpContents bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon HelpContents::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin HelpContents icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end HelpContents icon retrieval
}
std::string HelpContents::getHrefFullPath( wxHtmlLinkEvent &event )
{
string hrefFullPath = paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath();
hrefFullPath += wxString( wxFileName::GetPathSeparator() ).mb_str();
hrefFullPath += currentTutorialDir.mb_str();
hrefFullPath += wxString( wxFileName::GetPathSeparator() ).mb_str();
hrefFullPath += std::string( event.GetLinkInfo().GetHref().mb_str() );
return hrefFullPath;
}
bool HelpContents::matchHrefExtension( wxHtmlLinkEvent &event, const wxString extension )
{
return ( event.GetLinkInfo().GetHref().Right( extension.Len() ).Cmp( extension ) == 0 );
}
/*!
* wxEVT_COMMAND_HTML_LINK_CLICKED event handler for ID_HTMLWINDOW
*/
void HelpContents::OnHtmlwindowLinkClicked( wxHtmlLinkEvent& event )
{
if ( matchHrefExtension( event, _(".prv") ) || matchHrefExtension( event, _(".prv.gz")))
{
paraverMain::myParaverMain->DoLoadTrace( getHrefFullPath( event ) );
}
else if ( matchHrefExtension( event, _(".cfg")))
{
if ( paraverMain::myParaverMain->GetLoadedTraces().size() > 0 )
{
paraverMain::myParaverMain->DoLoadCFG( getHrefFullPath( event ) );
}
else
{
wxMessageDialog message( this, _("No trace loaded."), _( "Warning" ), wxOK );
message.ShowModal();
}
}
else if ( event.GetLinkInfo().GetHref().Cmp( _("init_preferences") ) == 0 )
{
paraverMain::myParaverMain->ShowPreferences();
// we rebuild it anyway
buildIndex();
}
else
{
// If current clicked link points to a tutorial index.html file, keep its
// tutorial directory name to allow relative references.
// Idea to detect tutorial:
// /home/user/root-tutorials/ => dir depth tutorials = 3
// vs.
// /home/user/root-tutorials/tutorial1/index.html => dir depth current = 4
// /home/user/root-tutorials/tutorial1/html/.../anyotherpage.html => dir depth current > 4
wxString anyTutorialPath =
wxString( paraverMain::myParaverMain->GetParaverConfig()->getGlobalTutorialsPath().c_str() );
if ( anyTutorialPath[ anyTutorialPath.Len() - 1 ] != wxString( wxFileName::GetPathSeparator() ))
{
// last separator needed to count properly
anyTutorialPath += wxString( wxFileName::GetPathSeparator() );
}
wxFileName anyTutorialDir( anyTutorialPath );
size_t dirsDepthTutorials = anyTutorialDir.GetDirCount();
wxFileName currentLink( event.GetLinkInfo().GetHref() );
size_t dirsDepthCurrentLink = currentLink.GetDirCount();
if (( dirsDepthCurrentLink == dirsDepthTutorials + 1 ) &&
( currentLink.GetFullName().Cmp( _("index.html") ) == 0 ))
{
wxArrayString dirs = currentLink.GetDirs();
currentTutorialDir = dirs[ dirsDepthCurrentLink - 1 ];
}
// and let the html window browse it.
event.Skip();
}
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON_CLOSE
*/
void HelpContents::OnButtonCloseClick( wxCommandEvent& event )
{
Close();
}
/*!
* wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_BUTTON_INDEX
*/
void HelpContents::OnButtonIndexClick( wxCommandEvent& event )
{
buildIndex();
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2014 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "EaseInOutAnim.h"
#include "../player/Player.h"
#include "../base/MathHelper.h"
#include <math.h>
using namespace boost::python;
using namespace std;
namespace avg {
EaseInOutAnim::EaseInOutAnim(const object& node, const string& sAttrName,
long long duration, const object& startValue, const object& endValue,
long long easeInDuration, long long easeOutDuration, bool bUseInt,
const object& startCallback, const object& stopCallback)
: SimpleAnim(node, sAttrName, duration, startValue, endValue, bUseInt, startCallback,
stopCallback),
m_EaseInDuration(float(easeInDuration)/duration),
m_EaseOutDuration(float(easeOutDuration)/duration)
{
}
EaseInOutAnim::~EaseInOutAnim()
{
}
float EaseInOutAnim::interpolate(float t)
{
float accelDist = m_EaseInDuration*2/M_PI;
float decelDist = m_EaseOutDuration*2/M_PI;
float dist;
if (t<m_EaseInDuration) {
// Acceleration stage
float nt = t/m_EaseInDuration;
float s = sin(-M_PI/2+nt*M_PI/2)+1;
dist = s*accelDist;
} else if (t > 1-m_EaseOutDuration) {
// Deceleration stage
float nt = (t-(1-m_EaseOutDuration))/m_EaseOutDuration;
float s = sin(nt*M_PI/2);
dist = accelDist+(1-m_EaseInDuration-m_EaseOutDuration)+s*decelDist;
} else {
// Linear stage
dist = accelDist+t-m_EaseInDuration;
}
return dist/(accelDist+(1-m_EaseInDuration-m_EaseOutDuration)+decelDist);
}
}
<commit_msg>Windows warning fix.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2014 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "EaseInOutAnim.h"
#include "../player/Player.h"
#include "../base/MathHelper.h"
#include <math.h>
using namespace boost::python;
using namespace std;
namespace avg {
EaseInOutAnim::EaseInOutAnim(const object& node, const string& sAttrName,
long long duration, const object& startValue, const object& endValue,
long long easeInDuration, long long easeOutDuration, bool bUseInt,
const object& startCallback, const object& stopCallback)
: SimpleAnim(node, sAttrName, duration, startValue, endValue, bUseInt, startCallback,
stopCallback),
m_EaseInDuration(float(easeInDuration)/duration),
m_EaseOutDuration(float(easeOutDuration)/duration)
{
}
EaseInOutAnim::~EaseInOutAnim()
{
}
float EaseInOutAnim::interpolate(float t)
{
float accelDist = m_EaseInDuration*2/float(M_PI);
float decelDist = m_EaseOutDuration*2/float(M_PI);
float dist;
if (t<m_EaseInDuration) {
// Acceleration stage
float nt = t/m_EaseInDuration;
float s = float(sin(-M_PI/2+nt*M_PI/2)+1);
dist = s*accelDist;
} else if (t > 1-m_EaseOutDuration) {
// Deceleration stage
float nt = (t-(1-m_EaseOutDuration))/m_EaseOutDuration;
float s = sin(nt*float(M_PI)/2);
dist = accelDist+(1-m_EaseInDuration-m_EaseOutDuration)+s*decelDist;
} else {
// Linear stage
dist = accelDist+t-m_EaseInDuration;
}
return dist/(accelDist+(1-m_EaseInDuration-m_EaseOutDuration)+decelDist);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The clvk 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 "device.hpp"
#include "memory.hpp"
#include "utils.hpp"
cvk_device* cvk_device::create(VkPhysicalDevice pdev) {
cvk_device* device = new cvk_device(pdev);
if (!device->init()) {
delete device;
return nullptr;
}
return device;
}
bool cvk_device::init_queues(uint32_t* num_queues, uint32_t* queue_family) {
// Get number of queue families
uint32_t num_families;
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families, nullptr);
cvk_info_fn(
"physical device (%s) has %u queue families:",
vulkan_physical_device_type_string(m_properties.deviceType).c_str(),
num_families);
// Get their properties
std::vector<VkQueueFamilyProperties> families(num_families);
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families,
families.data());
// Look for suitable queues
bool found_queues = false;
*num_queues = 0;
for (uint32_t i = 0; i < num_families; i++) {
cvk_info_fn("queue family %u: %2u queues | %s", i,
families[i].queueCount,
vulkan_queue_flags_string(families[i].queueFlags).c_str());
if (!found_queues && (families[i].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
*queue_family = i;
*num_queues = families[i].queueCount;
found_queues = true;
}
}
if (!found_queues) {
cvk_error("Could not find a suitable queue family for this device");
return false;
}
// Initialise the queue allocator
m_vulkan_queue_alloc_index = 0;
return true;
}
bool cvk_device::init_extensions() {
uint32_t numext;
VkResult res =
vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext, nullptr);
CVK_VK_CHECK_ERROR_RET(
res, false, "Failed to get the number of device extension properties");
cvk_info("%u device extension properties reported.", numext);
std::vector<VkExtensionProperties> extensions(numext);
res = vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext,
extensions.data());
CVK_VK_CHECK_ERROR_RET(res, false,
"Could not enumerate device extension properties");
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 1, 0)) {
m_vulkan_device_extensions.push_back(
VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME);
m_vulkan_device_extensions.push_back(
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
}
const std::vector<const char*> desired_extensions = {
VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME,
VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME,
};
for (size_t i = 0; i < numext; i++) {
cvk_info("Found extension %s, spec version %u",
extensions[i].extensionName, extensions[i].specVersion);
for (auto de : desired_extensions) {
if (!strcmp(de, extensions[i].extensionName)) {
m_vulkan_device_extensions.push_back(de);
cvk_info_fn("found extension %s, enabling", de);
}
}
}
return true;
}
void cvk_device::init_features() {
// Query supported features.
m_features_ubo_stdlayout.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR;
m_features_ubo_stdlayout.pNext = nullptr;
m_features_float16_int8.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR;
m_features_float16_int8.pNext = &m_features_ubo_stdlayout;
m_features_variable_pointer.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES;
m_features_variable_pointer.pNext = &m_features_float16_int8;
VkPhysicalDeviceFeatures2 supported_features;
supported_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
supported_features.pNext = &m_features_variable_pointer;
vkGetPhysicalDeviceFeatures2(m_pdev, &supported_features);
// Selectively enable core features.
memset(&m_features, 0, sizeof(m_features));
if (supported_features.features.shaderInt16) {
m_features.features.shaderInt16 = VK_TRUE;
}
if (supported_features.features.shaderInt64) {
m_features.features.shaderInt64 = VK_TRUE;
}
if (supported_features.features.shaderFloat64) {
m_features.features.shaderFloat64 = VK_TRUE;
}
if (supported_features.features.shaderStorageImageWriteWithoutFormat) {
m_features.features.shaderStorageImageWriteWithoutFormat = VK_TRUE;
}
// All queried extended features are enabled when supported.
m_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
m_features.pNext = &m_features_variable_pointer;
}
void cvk_device::construct_extension_string() {
// Start with required extensions
m_extensions = "cl_khr_global_int32_base_atomics "
"cl_khr_global_int32_extended_atomics "
"cl_khr_local_int32_base_atomics "
"cl_khr_local_int32_extended_atomics "
"cl_khr_byte_addressable_store ";
// Add always supported extension
#ifndef CLSPV_ONLINE_COMPILER
m_extensions += "cl_khr_il_program ";
#endif
}
bool cvk_device::create_vulkan_queues_and_device(uint32_t num_queues,
uint32_t queue_family) {
// Give all queues the same priority
std::vector<float> queuePriorities(num_queues, 1.0f);
VkDeviceQueueCreateInfo queueCreateInfo = {
VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr,
0, // flags
queue_family,
num_queues, // queueCount
queuePriorities.data()};
// Create logical device
const VkDeviceCreateInfo createInfo = {
VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType
&m_features, // pNext
0, // flags
1, // queueCreateInfoCount
&queueCreateInfo, // pQueueCreateInfos,
0, // enabledLayerCount
nullptr, // ppEnabledLayerNames
static_cast<uint32_t>(
m_vulkan_device_extensions.size()), // enabledExtensionCount
m_vulkan_device_extensions.data(), // ppEnabledExtensionNames
nullptr, // pEnabledFeatures
};
VkResult res = vkCreateDevice(m_pdev, &createInfo, nullptr, &m_dev);
CVK_VK_CHECK_ERROR_RET(res, false, "Failed to create a device");
// Construct the queue wrappers now that our queues exist
for (auto i = 0U; i < num_queues; i++) {
VkQueue queue;
vkGetDeviceQueue(m_dev, queue_family, i, &queue);
m_vulkan_queues.emplace_back(
cvk_vulkan_queue_wrapper(queue, queue_family));
}
return true;
}
bool cvk_device::compute_buffer_alignement_requirements() {
// Work out the required alignment for buffers
const VkBufferCreateInfo bufferCreateInfo = {
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
1, // size
cvk_buffer::USAGE_FLAGS, // usage
VK_SHARING_MODE_EXCLUSIVE,
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
};
VkBuffer buffer;
auto res = vkCreateBuffer(m_dev, &bufferCreateInfo, nullptr, &buffer);
CVK_VK_CHECK_ERROR_RET(res, false, "Failed to create a buffer");
VkMemoryRequirements memreqs;
vkGetBufferMemoryRequirements(m_dev, buffer, &memreqs);
uint32_t alignment_bits = memreqs.alignment * 8;
// The OpenCL spec requires at least 1024 bits (long16's alignment)
m_mem_base_addr_align = std::max(alignment_bits, 1024u);
vkDestroyBuffer(m_dev, buffer, nullptr);
return true;
}
void cvk_device::log_limits_and_memory_information() {
// Print relevant device limits
const VkPhysicalDeviceLimits& limits = vulkan_limits();
cvk_info_fn("device's resources per stage limits:");
cvk_info_fn(" total = %u", limits.maxPerStageResources);
cvk_info_fn(" uniform buffers = %u",
limits.maxPerStageDescriptorUniformBuffers);
cvk_info_fn(" storage buffers = %u",
limits.maxPerStageDescriptorStorageBuffers);
cvk_info_fn("device's max buffer size = %s",
pretty_size(limits.maxStorageBufferRange).c_str());
// Print memoy information
cvk_info_fn("device has %u memory types:",
m_mem_properties.memoryTypeCount);
for (uint32_t i = 0; i < m_mem_properties.memoryTypeCount; i++) {
VkMemoryType memtype = m_mem_properties.memoryTypes[i];
auto heapsize = m_mem_properties.memoryHeaps[memtype.heapIndex].size;
cvk_info_fn(
" %u: heap = %u, %s | %s", i, memtype.heapIndex,
pretty_size(heapsize).c_str(),
vulkan_memory_property_flags_string(memtype.propertyFlags).c_str());
}
cvk_info_fn("device has %u memory heaps:",
m_mem_properties.memoryHeapCount);
for (uint32_t i = 0; i < m_mem_properties.memoryHeapCount; i++) {
VkMemoryHeap memheap = m_mem_properties.memoryHeaps[i];
cvk_info_fn(" %u: %s | %s", i, pretty_size(memheap.size).c_str(),
vulkan_memory_property_flags_string(memheap.flags).c_str());
}
}
bool cvk_device::init() {
cvk_info_fn("Initialising device %s", m_properties.deviceName);
uint32_t num_queues, queue_family;
if (!init_queues(&num_queues, &queue_family)) {
return false;
}
if (!init_extensions()) {
return false;
}
init_features();
construct_extension_string();
if (!create_vulkan_queues_and_device(num_queues, queue_family)) {
return false;
}
if (!compute_buffer_alignement_requirements()) {
return false;
}
log_limits_and_memory_information();
return true;
}
bool cvk_device::supports_capability(spv::Capability capability) const {
switch (capability) {
// Capabilities required by all Vulkan implementations:
case spv::CapabilityShader:
case spv::CapabilitySampled1D:
case spv::CapabilityImage1D:
case spv::CapabilityImageQuery:
return true;
// Optional capabilities:
case spv::CapabilityFloat16:
return m_features_float16_int8.shaderFloat16;
case spv::CapabilityFloat64:
return m_features.features.shaderFloat64;
case spv::CapabilityInt8:
return m_features_float16_int8.shaderInt8;
case spv::CapabilityInt16:
return m_features.features.shaderInt16;
case spv::CapabilityInt64:
return m_features.features.shaderInt64;
case spv::CapabilityStorageImageWriteWithoutFormat:
return m_features.features.shaderStorageImageWriteWithoutFormat;
case spv::CapabilityVariablePointers:
return m_features_variable_pointer.variablePointers;
case spv::CapabilityVariablePointersStorageBuffer:
return m_features_variable_pointer.variablePointersStorageBuffer;
// Capabilities that have not yet been mapped to Vulkan features:
default:
cvk_warn_fn("Capability %d not yet mapped to a feature.", capability);
return false;
}
}
<commit_msg>Don't request physical device properties2 as device extension (#150)<commit_after>// Copyright 2018 The clvk 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 "device.hpp"
#include "memory.hpp"
#include "utils.hpp"
cvk_device* cvk_device::create(VkPhysicalDevice pdev) {
cvk_device* device = new cvk_device(pdev);
if (!device->init()) {
delete device;
return nullptr;
}
return device;
}
bool cvk_device::init_queues(uint32_t* num_queues, uint32_t* queue_family) {
// Get number of queue families
uint32_t num_families;
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families, nullptr);
cvk_info_fn(
"physical device (%s) has %u queue families:",
vulkan_physical_device_type_string(m_properties.deviceType).c_str(),
num_families);
// Get their properties
std::vector<VkQueueFamilyProperties> families(num_families);
vkGetPhysicalDeviceQueueFamilyProperties(m_pdev, &num_families,
families.data());
// Look for suitable queues
bool found_queues = false;
*num_queues = 0;
for (uint32_t i = 0; i < num_families; i++) {
cvk_info_fn("queue family %u: %2u queues | %s", i,
families[i].queueCount,
vulkan_queue_flags_string(families[i].queueFlags).c_str());
if (!found_queues && (families[i].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
*queue_family = i;
*num_queues = families[i].queueCount;
found_queues = true;
}
}
if (!found_queues) {
cvk_error("Could not find a suitable queue family for this device");
return false;
}
// Initialise the queue allocator
m_vulkan_queue_alloc_index = 0;
return true;
}
bool cvk_device::init_extensions() {
uint32_t numext;
VkResult res =
vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext, nullptr);
CVK_VK_CHECK_ERROR_RET(
res, false, "Failed to get the number of device extension properties");
cvk_info("%u device extension properties reported.", numext);
std::vector<VkExtensionProperties> extensions(numext);
res = vkEnumerateDeviceExtensionProperties(m_pdev, nullptr, &numext,
extensions.data());
CVK_VK_CHECK_ERROR_RET(res, false,
"Could not enumerate device extension properties");
if (m_properties.apiVersion < VK_MAKE_VERSION(1, 1, 0)) {
m_vulkan_device_extensions.push_back(
VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME);
}
const std::vector<const char*> desired_extensions = {
VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME,
VK_KHR_UNIFORM_BUFFER_STANDARD_LAYOUT_EXTENSION_NAME,
};
for (size_t i = 0; i < numext; i++) {
cvk_info("Found extension %s, spec version %u",
extensions[i].extensionName, extensions[i].specVersion);
for (auto de : desired_extensions) {
if (!strcmp(de, extensions[i].extensionName)) {
m_vulkan_device_extensions.push_back(de);
cvk_info_fn("found extension %s, enabling", de);
}
}
}
return true;
}
void cvk_device::init_features() {
// Query supported features.
m_features_ubo_stdlayout.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR;
m_features_ubo_stdlayout.pNext = nullptr;
m_features_float16_int8.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR;
m_features_float16_int8.pNext = &m_features_ubo_stdlayout;
m_features_variable_pointer.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES;
m_features_variable_pointer.pNext = &m_features_float16_int8;
VkPhysicalDeviceFeatures2 supported_features;
supported_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
supported_features.pNext = &m_features_variable_pointer;
vkGetPhysicalDeviceFeatures2(m_pdev, &supported_features);
// Selectively enable core features.
memset(&m_features, 0, sizeof(m_features));
if (supported_features.features.shaderInt16) {
m_features.features.shaderInt16 = VK_TRUE;
}
if (supported_features.features.shaderInt64) {
m_features.features.shaderInt64 = VK_TRUE;
}
if (supported_features.features.shaderFloat64) {
m_features.features.shaderFloat64 = VK_TRUE;
}
if (supported_features.features.shaderStorageImageWriteWithoutFormat) {
m_features.features.shaderStorageImageWriteWithoutFormat = VK_TRUE;
}
// All queried extended features are enabled when supported.
m_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
m_features.pNext = &m_features_variable_pointer;
}
void cvk_device::construct_extension_string() {
// Start with required extensions
m_extensions = "cl_khr_global_int32_base_atomics "
"cl_khr_global_int32_extended_atomics "
"cl_khr_local_int32_base_atomics "
"cl_khr_local_int32_extended_atomics "
"cl_khr_byte_addressable_store ";
// Add always supported extension
#ifndef CLSPV_ONLINE_COMPILER
m_extensions += "cl_khr_il_program ";
#endif
}
bool cvk_device::create_vulkan_queues_and_device(uint32_t num_queues,
uint32_t queue_family) {
// Give all queues the same priority
std::vector<float> queuePriorities(num_queues, 1.0f);
VkDeviceQueueCreateInfo queueCreateInfo = {
VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
nullptr,
0, // flags
queue_family,
num_queues, // queueCount
queuePriorities.data()};
// Create logical device
const VkDeviceCreateInfo createInfo = {
VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType
&m_features, // pNext
0, // flags
1, // queueCreateInfoCount
&queueCreateInfo, // pQueueCreateInfos,
0, // enabledLayerCount
nullptr, // ppEnabledLayerNames
static_cast<uint32_t>(
m_vulkan_device_extensions.size()), // enabledExtensionCount
m_vulkan_device_extensions.data(), // ppEnabledExtensionNames
nullptr, // pEnabledFeatures
};
VkResult res = vkCreateDevice(m_pdev, &createInfo, nullptr, &m_dev);
CVK_VK_CHECK_ERROR_RET(res, false, "Failed to create a device");
// Construct the queue wrappers now that our queues exist
for (auto i = 0U; i < num_queues; i++) {
VkQueue queue;
vkGetDeviceQueue(m_dev, queue_family, i, &queue);
m_vulkan_queues.emplace_back(
cvk_vulkan_queue_wrapper(queue, queue_family));
}
return true;
}
bool cvk_device::compute_buffer_alignement_requirements() {
// Work out the required alignment for buffers
const VkBufferCreateInfo bufferCreateInfo = {
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
1, // size
cvk_buffer::USAGE_FLAGS, // usage
VK_SHARING_MODE_EXCLUSIVE,
0, // queueFamilyIndexCount
nullptr, // pQueueFamilyIndices
};
VkBuffer buffer;
auto res = vkCreateBuffer(m_dev, &bufferCreateInfo, nullptr, &buffer);
CVK_VK_CHECK_ERROR_RET(res, false, "Failed to create a buffer");
VkMemoryRequirements memreqs;
vkGetBufferMemoryRequirements(m_dev, buffer, &memreqs);
uint32_t alignment_bits = memreqs.alignment * 8;
// The OpenCL spec requires at least 1024 bits (long16's alignment)
m_mem_base_addr_align = std::max(alignment_bits, 1024u);
vkDestroyBuffer(m_dev, buffer, nullptr);
return true;
}
void cvk_device::log_limits_and_memory_information() {
// Print relevant device limits
const VkPhysicalDeviceLimits& limits = vulkan_limits();
cvk_info_fn("device's resources per stage limits:");
cvk_info_fn(" total = %u", limits.maxPerStageResources);
cvk_info_fn(" uniform buffers = %u",
limits.maxPerStageDescriptorUniformBuffers);
cvk_info_fn(" storage buffers = %u",
limits.maxPerStageDescriptorStorageBuffers);
cvk_info_fn("device's max buffer size = %s",
pretty_size(limits.maxStorageBufferRange).c_str());
// Print memoy information
cvk_info_fn("device has %u memory types:",
m_mem_properties.memoryTypeCount);
for (uint32_t i = 0; i < m_mem_properties.memoryTypeCount; i++) {
VkMemoryType memtype = m_mem_properties.memoryTypes[i];
auto heapsize = m_mem_properties.memoryHeaps[memtype.heapIndex].size;
cvk_info_fn(
" %u: heap = %u, %s | %s", i, memtype.heapIndex,
pretty_size(heapsize).c_str(),
vulkan_memory_property_flags_string(memtype.propertyFlags).c_str());
}
cvk_info_fn("device has %u memory heaps:",
m_mem_properties.memoryHeapCount);
for (uint32_t i = 0; i < m_mem_properties.memoryHeapCount; i++) {
VkMemoryHeap memheap = m_mem_properties.memoryHeaps[i];
cvk_info_fn(" %u: %s | %s", i, pretty_size(memheap.size).c_str(),
vulkan_memory_property_flags_string(memheap.flags).c_str());
}
}
bool cvk_device::init() {
cvk_info_fn("Initialising device %s", m_properties.deviceName);
uint32_t num_queues, queue_family;
if (!init_queues(&num_queues, &queue_family)) {
return false;
}
if (!init_extensions()) {
return false;
}
init_features();
construct_extension_string();
if (!create_vulkan_queues_and_device(num_queues, queue_family)) {
return false;
}
if (!compute_buffer_alignement_requirements()) {
return false;
}
log_limits_and_memory_information();
return true;
}
bool cvk_device::supports_capability(spv::Capability capability) const {
switch (capability) {
// Capabilities required by all Vulkan implementations:
case spv::CapabilityShader:
case spv::CapabilitySampled1D:
case spv::CapabilityImage1D:
case spv::CapabilityImageQuery:
return true;
// Optional capabilities:
case spv::CapabilityFloat16:
return m_features_float16_int8.shaderFloat16;
case spv::CapabilityFloat64:
return m_features.features.shaderFloat64;
case spv::CapabilityInt8:
return m_features_float16_int8.shaderInt8;
case spv::CapabilityInt16:
return m_features.features.shaderInt16;
case spv::CapabilityInt64:
return m_features.features.shaderInt64;
case spv::CapabilityStorageImageWriteWithoutFormat:
return m_features.features.shaderStorageImageWriteWithoutFormat;
case spv::CapabilityVariablePointers:
return m_features_variable_pointer.variablePointers;
case spv::CapabilityVariablePointersStorageBuffer:
return m_features_variable_pointer.variablePointersStorageBuffer;
// Capabilities that have not yet been mapped to Vulkan features:
default:
cvk_warn_fn("Capability %d not yet mapped to a feature.", capability);
return false;
}
}
<|endoftext|>
|
<commit_before>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Vec3>
#include <osg/Matrix>
#include <iostream>
void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
osg::Matrix f;
f.makeFrustum(left,right,bottom,top,zNear,zFar);
double c_left=0;
double c_right=0;
double c_top=0;
double c_bottom=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testFrustum"<<f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar)<<std::endl;
std::cout << " left = "<<left<<" compute "<<c_left<<std::endl;
std::cout << " right = "<<right<<" compute "<<c_right<<std::endl;
std::cout << " bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
std::cout << " top = "<<top<<" compute "<<c_top<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
osg::Matrix f;
f.makeOrtho(left,right,bottom,top,zNear,zFar);
double c_left=0;
double c_right=0;
double c_top=0;
double c_bottom=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testOrtho "<< f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar) << std::endl;
std::cout << " left = "<<left<<" compute "<<c_left<<std::endl;
std::cout << " right = "<<right<<" compute "<<c_right<<std::endl;
std::cout << " bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
std::cout << " top = "<<top<<" compute "<<c_top<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testPerspective(double fovy,double aspect,double zNear,double zFar)
{
osg::Matrix f;
f.makePerspective(fovy,aspect,zNear,zFar);
double c_fovy=0;
double c_aspect=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testPerspective "<< f.getPerspective(c_fovy,c_aspect,c_zNear,c_zFar) << std::endl;
std::cout << " fovy = "<<fovy<<" compute "<<c_fovy<<std::endl;
std::cout << " aspect = "<<aspect<<" compute "<<c_aspect<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
osg::Matrix mv;
mv.makeLookAt(eye,center,up);
osg::Vec3 c_eye,c_center,c_up;
mv.getLookAt(c_eye,c_center,c_up);
std::cout << "testLookAt"<<std::endl;
std::cout << " eye "<<eye<< " compute "<<c_eye<<std::endl;
std::cout << " eye "<<center<< " compute "<<c_center<<std::endl;
std::cout << " eye "<<up<< " compute "<<c_up<<std::endl;
std::cout << std::endl;
}
void sizeOfTest()
{
std::cout<<"sizeof(bool)=="<<sizeof(bool)<<std::endl;
std::cout<<"sizeof(char)=="<<sizeof(char)<<std::endl;
std::cout<<"sizeof(short)=="<<sizeof(short)<<std::endl;
std::cout<<"sizeof(int)=="<<sizeof(int)<<std::endl;
std::cout<<"sizeof(long)=="<<sizeof(long)<<std::endl;
std::cout<<"sizeof(long int)=="<<sizeof(long int)<<std::endl;
#if defined(_MSC_VER)
// long long isn't supported on VS6.0...
std::cout<<"sizeof(__int64)=="<<sizeof(__int64)<<std::endl;
#else
std::cout<<"sizeof(long long)=="<<sizeof(long long)<<std::endl;
#endif
std::cout<<"sizeof(float)=="<<sizeof(float)<<std::endl;
std::cout<<"sizeof(double)=="<<sizeof(double)<<std::endl;
}
int main( int argc, char** argv )
{
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
bool printQualifiedTest = false;
while (arguments.read("qt")) printQualifiedTest = true;
bool printMatrixTest = false;
while (arguments.read("matrix")) printMatrixTest = true;
bool printSizeOfTest = false;
while (arguments.read("sizeof")) printSizeOfTest = true;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (printMatrixTest)
{
std::cout<<"****** Running matrix tests ******"<<std::endl;
testFrustum(-1,1,-1,1,1,1000);
testFrustum(0,1,1,2,2.5,100000);
testOrtho(0,1,1,2,2.1,1000);
testOrtho(-1,10,1,20,2.5,100000);
testPerspective(20,1,1,1000);
testPerspective(90,2,1,1000);
testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
}
if (printSizeOfTest)
{
std::cout<<"**** sizeof() tests ******"<<std::endl;
sizeOfTest();
std::cout<<std::endl;
}
if (printQualifiedTest)
{
std::cout<<"***** Qualified Tests ******"<<std::endl;
osgUtx::QualifiedTestPrinter printer;
osgUtx::TestGraph::instance().root()->accept( printer );
std::cout<<std::endl;
}
std::cout<<"****** Running tests ******"<<std::endl;
// Global Data or Context
osgUtx::TestContext ctx;
osgUtx::TestRunner runner( ctx );
runner.specify("root");
osgUtx::TestGraph::instance().root()->accept( runner );
return 0;
}
<commit_msg>Added test for quat multiplication ordering.<commit_after>#include <osg/UnitTestFramework>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Vec3>
#include <osg/Matrix>
#include <iostream>
void testFrustum(double left,double right,double bottom,double top,double zNear,double zFar)
{
osg::Matrix f;
f.makeFrustum(left,right,bottom,top,zNear,zFar);
double c_left=0;
double c_right=0;
double c_top=0;
double c_bottom=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testFrustum"<<f.getFrustum(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar)<<std::endl;
std::cout << " left = "<<left<<" compute "<<c_left<<std::endl;
std::cout << " right = "<<right<<" compute "<<c_right<<std::endl;
std::cout << " bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
std::cout << " top = "<<top<<" compute "<<c_top<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testOrtho(double left,double right,double bottom,double top,double zNear,double zFar)
{
osg::Matrix f;
f.makeOrtho(left,right,bottom,top,zNear,zFar);
double c_left=0;
double c_right=0;
double c_top=0;
double c_bottom=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testOrtho "<< f.getOrtho(c_left,c_right,c_bottom,c_top,c_zNear,c_zFar) << std::endl;
std::cout << " left = "<<left<<" compute "<<c_left<<std::endl;
std::cout << " right = "<<right<<" compute "<<c_right<<std::endl;
std::cout << " bottom = "<<bottom<<" compute "<<c_bottom<<std::endl;
std::cout << " top = "<<top<<" compute "<<c_top<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testPerspective(double fovy,double aspect,double zNear,double zFar)
{
osg::Matrix f;
f.makePerspective(fovy,aspect,zNear,zFar);
double c_fovy=0;
double c_aspect=0;
double c_zNear=0;
double c_zFar=0;
std::cout << "testPerspective "<< f.getPerspective(c_fovy,c_aspect,c_zNear,c_zFar) << std::endl;
std::cout << " fovy = "<<fovy<<" compute "<<c_fovy<<std::endl;
std::cout << " aspect = "<<aspect<<" compute "<<c_aspect<<std::endl;
std::cout << " zNear = "<<zNear<<" compute "<<c_zNear<<std::endl;
std::cout << " zFar = "<<zFar<<" compute "<<c_zFar<<std::endl;
std::cout << std::endl;
}
void testLookAt(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up)
{
osg::Matrix mv;
mv.makeLookAt(eye,center,up);
osg::Vec3 c_eye,c_center,c_up;
mv.getLookAt(c_eye,c_center,c_up);
std::cout << "testLookAt"<<std::endl;
std::cout << " eye "<<eye<< " compute "<<c_eye<<std::endl;
std::cout << " eye "<<center<< " compute "<<c_center<<std::endl;
std::cout << " eye "<<up<< " compute "<<c_up<<std::endl;
std::cout << std::endl;
}
void sizeOfTest()
{
std::cout<<"sizeof(bool)=="<<sizeof(bool)<<std::endl;
std::cout<<"sizeof(char)=="<<sizeof(char)<<std::endl;
std::cout<<"sizeof(short)=="<<sizeof(short)<<std::endl;
std::cout<<"sizeof(int)=="<<sizeof(int)<<std::endl;
std::cout<<"sizeof(long)=="<<sizeof(long)<<std::endl;
std::cout<<"sizeof(long int)=="<<sizeof(long int)<<std::endl;
#if defined(_MSC_VER)
// long long isn't supported on VS6.0...
std::cout<<"sizeof(__int64)=="<<sizeof(__int64)<<std::endl;
#else
std::cout<<"sizeof(long long)=="<<sizeof(long long)<<std::endl;
#endif
std::cout<<"sizeof(float)=="<<sizeof(float)<<std::endl;
std::cout<<"sizeof(double)=="<<sizeof(double)<<std::endl;
}
void testQuat()
{
osg::Quat q1;
q1.makeRotate(osg::DegreesToRadians(30.0),0.0f,0.0f,1.0f);
osg::Quat q2;
q2.makeRotate(osg::DegreesToRadians(133.0),0.0f,1.0f,1.0f);
osg::Quat q1_2 = q1*q2;
osg::Quat q2_1 = q2*q1;
osg::Matrix m1 = osg::Matrix::rotate(q1);
osg::Matrix m2 = osg::Matrix::rotate(q2);
osg::Matrix m1_2 = m1*m2;
osg::Matrix m2_1 = m2*m1;
osg::Quat qm1_2;
qm1_2.set(m1_2);
osg::Quat qm2_1;
qm2_1.set(m2_1);
std::cout<<"q1*q2 = "<<q1_2<<std::endl;
std::cout<<"q2*q1 = "<<q2_1<<std::endl;
std::cout<<"m1*m2 = "<<qm1_2<<std::endl;
std::cout<<"m2*m1 = "<<qm2_1<<std::endl;
}
int main( int argc, char** argv )
{
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
bool printQualifiedTest = false;
while (arguments.read("qt")) printQualifiedTest = true;
bool printMatrixTest = false;
while (arguments.read("matrix")) printMatrixTest = true;
bool printSizeOfTest = false;
while (arguments.read("sizeof")) printSizeOfTest = true;
bool printQuatTest = false;
while (arguments.read("quat")) printQuatTest = true;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (printQuatTest)
{
testQuat();
}
if (printMatrixTest)
{
std::cout<<"****** Running matrix tests ******"<<std::endl;
testFrustum(-1,1,-1,1,1,1000);
testFrustum(0,1,1,2,2.5,100000);
testOrtho(0,1,1,2,2.1,1000);
testOrtho(-1,10,1,20,2.5,100000);
testPerspective(20,1,1,1000);
testPerspective(90,2,1,1000);
testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
}
if (printSizeOfTest)
{
std::cout<<"**** sizeof() tests ******"<<std::endl;
sizeOfTest();
std::cout<<std::endl;
}
if (printQualifiedTest)
{
std::cout<<"***** Qualified Tests ******"<<std::endl;
osgUtx::QualifiedTestPrinter printer;
osgUtx::TestGraph::instance().root()->accept( printer );
std::cout<<std::endl;
}
std::cout<<"****** Running tests ******"<<std::endl;
// Global Data or Context
osgUtx::TestContext ctx;
osgUtx::TestRunner runner( ctx );
runner.specify("root");
osgUtx::TestGraph::instance().root()->accept( runner );
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 Google
// 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.
//
// This model implements a simple jobshop problem with
// earlyness-tardiness costs.
//
// A earlyness-tardinessjobshop is a standard scheduling problem where
// you must schedule a set of jobs on a set of machines. Each job is
// a sequence of tasks (a task can only start when the preceding task
// finished), each of which occupies a single specific machine during
// a specific duration. Therefore, a job is a sequence of pairs
// (machine id, duration), along with a release data (minimum start
// date of the first task of the job, and due data (end time of the
// last job) with a tardiness linear penalty.
// The objective is to minimize the sum of early-tardy penalties for each job.
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "linear_solver/linear_solver.h"
#include "util/string_array.h"
#include "cpp/jobshop_earlytardy.h"
DEFINE_string(
jet_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jet format:\n"
" - the first line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\", ended by due_date, early_cost,"
"late_cost\n"
"note: jobs with one task are not supported");
DEFINE_int32(machine_count, 10, "Machine count");
DEFINE_int32(job_count, 10, "Job count");
DEFINE_int32(max_release_date, 0, "Max release date");
DEFINE_int32(max_early_cost, 0, "Max earlyness weight");
DEFINE_int32(max_tardy_cost, 3, "Max tardiness weight");
DEFINE_int32(max_duration, 10, "Max duration of a task");
DEFINE_int32(scale_factor, 130, "Scale factor (in percent)");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
DEFINE_bool(time_placement, false, "Use MIP based time placement");
DECLARE_bool(log_prefix);
namespace operations_research {
class TimePlacement : public DecisionBuilder {
public:
TimePlacement(const EtJobShopData& data,
const std::vector<SequenceVar*>& all_sequences,
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks)
: data_(data),
all_sequences_(all_sequences),
jobs_to_tasks_(jobs_to_tasks),
horizon_(data_.horizon()),
mp_solver_("TimePlacement", MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING),
num_tasks_(0) {
for (int i = 0; i < jobs_to_tasks_.size(); ++i) {
num_tasks_ += jobs_to_tasks_[i].size();
}
}
virtual ~TimePlacement() {}
virtual Decision* Next(Solver* const solver) {
mp_solver_.Clear();
std::vector<std::vector<MPVariable*> > all_vars;
hash_map<IntervalVar*, MPVariable*> mapping;
const double infinity = mp_solver_.infinity();
all_vars.resize(all_sequences_.size());
// Creates the MP Variables.
for (int s = 0; s < jobs_to_tasks_.size(); ++s) {
for (int t = 0; t < jobs_to_tasks_[s].size(); ++t) {
IntervalVar* const task = jobs_to_tasks_[s][t];
const string name = StringPrintf("J%dT%d", s, t);
MPVariable* const var =
mp_solver_.MakeIntVar(task->StartMin(), task->StartMax(), name);
mapping[task] = var;
}
}
// Adds the jobs precedence constraints.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size() - 1; ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
const int duration = first_task->DurationMax();
IntervalVar* const second_task = jobs_to_tasks_[j][t + 1];
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Adds the ranked machines constraints.
for (int s = 0; s < all_sequences_.size(); ++s) {
SequenceVar* const sequence = all_sequences_[s];
std::vector<int> rank_firsts;
std::vector<int> rank_lasts;
std::vector<int> unperformed;
sequence->FillSequence(&rank_firsts, &rank_lasts, &unperformed);
CHECK_EQ(0, rank_lasts.size());
CHECK_EQ(0, unperformed.size());
for (int i = 0; i < rank_firsts.size() - 1; ++i) {
IntervalVar* const first_task = sequence->Interval(rank_firsts[i]);
const int duration = first_task->DurationMax();
IntervalVar* const second_task = sequence->Interval(rank_firsts[i + 1]);
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Creates penalty terms and objective.
std::vector<MPVariable*> terms;
mp_solver_.MakeIntVarArray(jobs_to_tasks_.size(),
0,
infinity,
"terms",
&terms);
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
mp_solver_.MutableObjective()->SetCoefficient(terms[j], 1.0);
}
mp_solver_.MutableObjective()->SetMinimization();
// Forces penalty terms to be above late and early costs.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
IntervalVar* const last_task = jobs_to_tasks_[j].back();
const int duration = last_task->DurationMin();
MPVariable* const mp_start = mapping[last_task];
const Job& job = data_.GetJob(j);
const int ideal_start = job.due_date - duration;
const int early_offset = job.early_cost * ideal_start;
MPConstraint* const early_ct =
mp_solver_.MakeRowConstraint(early_offset, infinity);
early_ct->SetCoefficient(terms[j], 1);
early_ct->SetCoefficient(mp_start, job.early_cost);
const int tardy_offset = job.tardy_cost * ideal_start;
MPConstraint* const tardy_ct =
mp_solver_.MakeRowConstraint(-tardy_offset, infinity);
tardy_ct->SetCoefficient(terms[j], 1);
tardy_ct->SetCoefficient(mp_start, -job.tardy_cost);
}
// Solve.
CHECK_EQ(MPSolver::OPTIMAL, mp_solver_.Solve());
// Inject MIP solution into the CP part.
LOG(INFO) << "MP cost = " << mp_solver_.objective_value();
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size(); ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
MPVariable* const first_var = mapping[first_task];
const int date = first_var->solution_value();
first_task->SetStartRange(date, date);
}
}
return NULL;
}
virtual string DebugString() const {
return "TimePlacement";
}
private:
const EtJobShopData& data_;
const std::vector<SequenceVar*>& all_sequences_;
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks_;
const int horizon_;
MPSolver mp_solver_;
int num_tasks_;
};
void EtJobShop(const EtJobShopData& data) {
Solver solver("et_jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
const std::vector<Task>& tasks = job.all_tasks;
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Add release date.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][0];
Constraint* const prec =
solver.MakeIntervalVarRelation(t,
Solver::STARTS_AFTER,
job.release_date);
solver.AddConstraint(prec);
}
std::vector<IntVar*> penalties;
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][machine_count - 1];
IntVar* const penalty =
solver.MakeConvexPiecewiseExpr(t->EndExpr(),
job.early_cost,
job.due_date,
job.due_date,
job.tardy_cost)->Var();
penalties.push_back(penalty);
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Objective: minimize the weighted penalties.
IntVar* const objective_var = solver.MakeSum(penalties)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
FLAGS_time_placement ?
solver.RevAlloc(new TimePlacement(data, all_sequences, jobs_to_tasks)) :
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
FLAGS_log_prefix = false;
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
operations_research::EtJobShopData data;
if (!FLAGS_jet_file.empty()) {
data.LoadJetFile(FLAGS_jet_file);
} else {
data.GenerateRandomData(FLAGS_machine_count,
FLAGS_job_count,
FLAGS_max_release_date,
FLAGS_max_early_cost,
FLAGS_max_tardy_cost,
FLAGS_max_duration,
FLAGS_scale_factor,
FLAGS_seed);
}
operations_research::EtJobShop(data);
return 0;
}
<commit_msg>implement time placement code for early tardy<commit_after>// Copyright 2010-2012 Google
// 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.
//
// This model implements a simple jobshop problem with
// earlyness-tardiness costs.
//
// A earlyness-tardinessjobshop is a standard scheduling problem where
// you must schedule a set of jobs on a set of machines. Each job is
// a sequence of tasks (a task can only start when the preceding task
// finished), each of which occupies a single specific machine during
// a specific duration. Therefore, a job is a sequence of pairs
// (machine id, duration), along with a release data (minimum start
// date of the first task of the job, and due data (end time of the
// last job) with a tardiness linear penalty.
// The objective is to minimize the sum of early-tardy penalties for each job.
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "linear_solver/linear_solver.h"
#include "util/string_array.h"
#include "cpp/jobshop_earlytardy.h"
DEFINE_string(
jet_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jet format:\n"
" - the first line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\", ended by due_date, early_cost,"
"late_cost\n"
"note: jobs with one task are not supported");
DEFINE_int32(machine_count, 10, "Machine count");
DEFINE_int32(job_count, 10, "Job count");
DEFINE_int32(max_release_date, 0, "Max release date");
DEFINE_int32(max_early_cost, 0, "Max earlyness weight");
DEFINE_int32(max_tardy_cost, 3, "Max tardiness weight");
DEFINE_int32(max_duration, 10, "Max duration of a task");
DEFINE_int32(scale_factor, 130, "Scale factor (in percent)");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
DEFINE_bool(time_placement, false, "Use MIP based time placement");
DECLARE_bool(log_prefix);
namespace operations_research {
class TimePlacement : public DecisionBuilder {
public:
TimePlacement(const EtJobShopData& data,
const std::vector<SequenceVar*>& all_sequences,
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks)
: data_(data),
all_sequences_(all_sequences),
jobs_to_tasks_(jobs_to_tasks),
mp_solver_("TimePlacement", MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING),
num_tasks_(0) {
for (int i = 0; i < jobs_to_tasks_.size(); ++i) {
num_tasks_ += jobs_to_tasks_[i].size();
}
}
virtual ~TimePlacement() {}
virtual Decision* Next(Solver* const solver) {
mp_solver_.Clear();
std::vector<std::vector<MPVariable*> > all_vars;
hash_map<IntervalVar*, MPVariable*> mapping;
const double infinity = mp_solver_.infinity();
all_vars.resize(all_sequences_.size());
// Creates the MP Variables.
for (int s = 0; s < jobs_to_tasks_.size(); ++s) {
for (int t = 0; t < jobs_to_tasks_[s].size(); ++t) {
IntervalVar* const task = jobs_to_tasks_[s][t];
const string name = StringPrintf("J%dT%d", s, t);
MPVariable* const var =
mp_solver_.MakeIntVar(task->StartMin(), task->StartMax(), name);
mapping[task] = var;
}
}
// Adds the jobs precedence constraints.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size() - 1; ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
const int duration = first_task->DurationMax();
IntervalVar* const second_task = jobs_to_tasks_[j][t + 1];
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Adds the ranked machines constraints.
for (int s = 0; s < all_sequences_.size(); ++s) {
SequenceVar* const sequence = all_sequences_[s];
std::vector<int> rank_firsts;
std::vector<int> rank_lasts;
std::vector<int> unperformed;
sequence->FillSequence(&rank_firsts, &rank_lasts, &unperformed);
CHECK_EQ(0, rank_lasts.size());
CHECK_EQ(0, unperformed.size());
for (int i = 0; i < rank_firsts.size() - 1; ++i) {
IntervalVar* const first_task = sequence->Interval(rank_firsts[i]);
const int duration = first_task->DurationMax();
IntervalVar* const second_task = sequence->Interval(rank_firsts[i + 1]);
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Creates penalty terms and objective.
std::vector<MPVariable*> terms;
mp_solver_.MakeIntVarArray(jobs_to_tasks_.size(),
0,
infinity,
"terms",
&terms);
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
mp_solver_.MutableObjective()->SetCoefficient(terms[j], 1.0);
}
mp_solver_.MutableObjective()->SetMinimization();
// Forces penalty terms to be above late and early costs.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
IntervalVar* const last_task = jobs_to_tasks_[j].back();
const int duration = last_task->DurationMin();
MPVariable* const mp_start = mapping[last_task];
const Job& job = data_.GetJob(j);
const int ideal_start = job.due_date - duration;
const int early_offset = job.early_cost * ideal_start;
MPConstraint* const early_ct =
mp_solver_.MakeRowConstraint(early_offset, infinity);
early_ct->SetCoefficient(terms[j], 1);
early_ct->SetCoefficient(mp_start, job.early_cost);
const int tardy_offset = job.tardy_cost * ideal_start;
MPConstraint* const tardy_ct =
mp_solver_.MakeRowConstraint(-tardy_offset, infinity);
tardy_ct->SetCoefficient(terms[j], 1);
tardy_ct->SetCoefficient(mp_start, -job.tardy_cost);
}
// Solve.
CHECK_EQ(MPSolver::OPTIMAL, mp_solver_.Solve());
// Inject MIP solution into the CP part.
LOG(INFO) << "MP cost = " << mp_solver_.objective_value();
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size(); ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
MPVariable* const first_var = mapping[first_task];
const int date = first_var->solution_value();
first_task->SetStartRange(date, date);
}
}
return NULL;
}
virtual string DebugString() const {
return "TimePlacement";
}
private:
const EtJobShopData& data_;
const std::vector<SequenceVar*>& all_sequences_;
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks_;
MPSolver mp_solver_;
int num_tasks_;
};
void EtJobShop(const EtJobShopData& data) {
Solver solver("et_jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
const std::vector<Task>& tasks = job.all_tasks;
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Add release date.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][0];
Constraint* const prec =
solver.MakeIntervalVarRelation(t,
Solver::STARTS_AFTER,
job.release_date);
solver.AddConstraint(prec);
}
std::vector<IntVar*> penalties;
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][machine_count - 1];
IntVar* const penalty =
solver.MakeConvexPiecewiseExpr(t->EndExpr(),
job.early_cost,
job.due_date,
job.due_date,
job.tardy_cost)->Var();
penalties.push_back(penalty);
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Objective: minimize the weighted penalties.
IntVar* const objective_var = solver.MakeSum(penalties)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
FLAGS_time_placement ?
solver.RevAlloc(new TimePlacement(data, all_sequences, jobs_to_tasks)) :
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
FLAGS_log_prefix = false;
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
operations_research::EtJobShopData data;
if (!FLAGS_jet_file.empty()) {
data.LoadJetFile(FLAGS_jet_file);
} else {
data.GenerateRandomData(FLAGS_machine_count,
FLAGS_job_count,
FLAGS_max_release_date,
FLAGS_max_early_cost,
FLAGS_max_tardy_cost,
FLAGS_max_duration,
FLAGS_scale_factor,
FLAGS_seed);
}
operations_research::EtJobShop(data);
return 0;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
extern "C" {
#include <lirc/lirc_client.h>
}
namespace {
const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;
// Configuration (this should be in a configuration file)
const char* server_socket_path = "/tmp/asgard_socket";
const char* client_socket_path = "/tmp/asgard_ir_socket";
//Buffers
char write_buffer[buffer_size + 1];
char receive_buffer[buffer_size + 1];
// The socket file descriptor
int socket_fd;
// The socket addresses
struct sockaddr_un client_address;
struct sockaddr_un server_address;
// The remote IDs
int source_id = -1;
int button_actuator_id = -1;
void stop(){
std::cout << "asgard:ir: stop the driver" << std::endl;
//Closes LIRC
lirc_deinit();
// Unregister the button actuator, if necessary
if(button_actuator_id >= 0){
auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id);
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
// Unregister the source, if necessary
if(source_id >= 0){
auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
// Unlink the client socket
unlink(client_socket_path);
// Close the socket
close(socket_fd);
}
void terminate(int){
stop();
std::exit(0);
}
void ir_received(char* raw_code){
std::string full_code(raw_code);
auto code_end = full_code.find(' ');
std::string code(full_code.begin(), full_code.begin() + code_end);
auto repeat_end = full_code.find(' ', code_end + 1);
std::string repeat(full_code.begin() + code_end + 1, full_code.begin() + repeat_end);
auto key_end = full_code.find(' ', repeat_end + 1);
std::string key(full_code.begin() + repeat_end + 1, full_code.begin() + key_end);
std::cout << "asgard:ir: Received: " << code << ":" << repeat << ":" << key << std::endl;
//Send the event to the server
auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %s", source_id, button_actuator_id, key.c_str());
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
} //End of anonymous namespace
int main(){
//Initiate LIRC. Exit on failure
char lirc_name[] = "lirc";
if(lirc_init(lirc_name, 1) == -1){
std::cout << "asgard:ir: Failed to init LIRC" << std::endl;
return 1;
}
// Open the socket
socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(socket_fd < 0){
std::cerr << "asgard:ir: socket() failed" << std::endl;
return 1;
}
// Init the client address
memset(&client_address, 0, sizeof(struct sockaddr_un));
client_address.sun_family = AF_UNIX;
snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path);
// Unlink the client socket
unlink(client_socket_path);
// Bind to client socket
if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){
std::cerr << "asgard:ir: bind() failed" << std::endl;
return 1;
}
//Register signals for "proper" shutdown
signal(SIGTERM, terminate);
signal(SIGINT, terminate);
// Init the server address
memset(&server_address, 0, sizeof(struct sockaddr_un));
server_address.sun_family = AF_UNIX;
snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path);
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the source
auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE ir");
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length);
receive_buffer[bytes_received] = '\0';
source_id = atoi(receive_buffer);
std::cout << "asgard:ir: remote source: " << source_id << std::endl;
// Register the button actuator
nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "ir_button_1");
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length);
receive_buffer[bytes_received] = '\0';
button_actuator_id = atoi(receive_buffer);
std::cout << "asgard:ir: remote button actuator: " << button_actuator_id << std::endl;
//Read the default LIRC config
struct lirc_config* config;
if(lirc_readconfig(NULL,&config,NULL)==0){
char* code;
//Do stuff while LIRC socket is open 0=open -1=closed.
while(lirc_nextcode(&code)==0){
//If code = NULL, nothing was returned from LIRC socket
if(code){
//Send code further
ir_received(code);
//Need to free up code before the next loop
free(code);
}
}
//Frees the data structures associated with config.
lirc_freeconfig(config);
} else {
std::cout << "asgard:ir: Failed to read LIRC config" << std::endl;
}
stop();
return 0;
}
<commit_msg>Update copyright<commit_after>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
extern "C" {
#include <lirc/lirc_client.h>
}
namespace {
const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;
// Configuration (this should be in a configuration file)
const char* server_socket_path = "/tmp/asgard_socket";
const char* client_socket_path = "/tmp/asgard_ir_socket";
//Buffers
char write_buffer[buffer_size + 1];
char receive_buffer[buffer_size + 1];
// The socket file descriptor
int socket_fd;
// The socket addresses
struct sockaddr_un client_address;
struct sockaddr_un server_address;
// The remote IDs
int source_id = -1;
int button_actuator_id = -1;
void stop(){
std::cout << "asgard:ir: stop the driver" << std::endl;
//Closes LIRC
lirc_deinit();
// Unregister the button actuator, if necessary
if(button_actuator_id >= 0){
auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_ACTUATOR %d %d", source_id, button_actuator_id);
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
// Unregister the source, if necessary
if(source_id >= 0){
auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
// Unlink the client socket
unlink(client_socket_path);
// Close the socket
close(socket_fd);
}
void terminate(int){
stop();
std::exit(0);
}
void ir_received(char* raw_code){
std::string full_code(raw_code);
auto code_end = full_code.find(' ');
std::string code(full_code.begin(), full_code.begin() + code_end);
auto repeat_end = full_code.find(' ', code_end + 1);
std::string repeat(full_code.begin() + code_end + 1, full_code.begin() + repeat_end);
auto key_end = full_code.find(' ', repeat_end + 1);
std::string key(full_code.begin() + repeat_end + 1, full_code.begin() + key_end);
std::cout << "asgard:ir: Received: " << code << ":" << repeat << ":" << key << std::endl;
//Send the event to the server
auto nbytes = snprintf(write_buffer, buffer_size, "EVENT %d %d %s", source_id, button_actuator_id, key.c_str());
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
}
} //End of anonymous namespace
int main(){
//Initiate LIRC. Exit on failure
char lirc_name[] = "lirc";
if(lirc_init(lirc_name, 1) == -1){
std::cout << "asgard:ir: Failed to init LIRC" << std::endl;
return 1;
}
// Open the socket
socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(socket_fd < 0){
std::cerr << "asgard:ir: socket() failed" << std::endl;
return 1;
}
// Init the client address
memset(&client_address, 0, sizeof(struct sockaddr_un));
client_address.sun_family = AF_UNIX;
snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path);
// Unlink the client socket
unlink(client_socket_path);
// Bind to client socket
if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){
std::cerr << "asgard:ir: bind() failed" << std::endl;
return 1;
}
//Register signals for "proper" shutdown
signal(SIGTERM, terminate);
signal(SIGINT, terminate);
// Init the server address
memset(&server_address, 0, sizeof(struct sockaddr_un));
server_address.sun_family = AF_UNIX;
snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path);
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the source
auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE ir");
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length);
receive_buffer[bytes_received] = '\0';
source_id = atoi(receive_buffer);
std::cout << "asgard:ir: remote source: " << source_id << std::endl;
// Register the button actuator
nbytes = snprintf(write_buffer, buffer_size, "REG_ACTUATOR %d %s", source_id, "ir_button_1");
sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un));
bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length);
receive_buffer[bytes_received] = '\0';
button_actuator_id = atoi(receive_buffer);
std::cout << "asgard:ir: remote button actuator: " << button_actuator_id << std::endl;
//Read the default LIRC config
struct lirc_config* config;
if(lirc_readconfig(NULL,&config,NULL)==0){
char* code;
//Do stuff while LIRC socket is open 0=open -1=closed.
while(lirc_nextcode(&code)==0){
//If code = NULL, nothing was returned from LIRC socket
if(code){
//Send code further
ir_received(code);
//Need to free up code before the next loop
free(code);
}
}
//Frees the data structures associated with config.
lirc_freeconfig(config);
} else {
std::cout << "asgard:ir: Failed to read LIRC config" << std::endl;
}
stop();
return 0;
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
ll ans{0};
for (auto s{0LL}; s < W - 1; ++s)
{
for (auto y{0LL}; y < H - 1; ++y)
{
ll tmp{calc(s, y)};
if (s == 0)
{
ans += tmp;
}
else
{
ans += 2 * tmp;
}
}
}
return ans;
}
private:
ll rhs(ll s, ll y)
{
return 2 * K - s * (H - y) + gcd(s, H) - 2;
}
ll rhs_bound(ll s, ll y)
{
return 2 * K - s * (H - y) + H - 2;
}
ll lhs(ll x, ll s, ll y)
{
return H * x - gcd(H - y, x) - gcd(y, x + s);
}
ll calc(ll s, ll y)
{
ll R{rhs(s, y)};
if (R < 0)
{
return 0;
}
ll ans{min(W - s - 1, R / H)};
ll x{R / H + 1};
if (x + s < W && lhs(x, s, y) <= R)
{
++ans;
}
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * solve.answer() + 2 * solve2.answer()};
cout << ans << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
ll ans{0};
for (auto s{0LL}; s < W - 1; ++s)
{
for (auto y{0LL}; rhs_bound(s, y) >= 0 && y < H - 1; ++y)
{
ll tmp{calc(s, y)};
if (s == 0)
{
ans += tmp;
}
else
{
ans += 2 * tmp;
}
}
}
return ans;
}
private:
ll rhs(ll s, ll y)
{
return 2 * K - s * (H - y) + gcd(s, H) - 2;
}
ll rhs_bound(ll s, ll y)
{
return 2 * K - s * (H - y) + H - 2;
}
ll lhs(ll x, ll s, ll y)
{
return H * x - gcd(H - y, x) - gcd(y, x + s);
}
ll calc(ll s, ll y)
{
ll R{rhs(s, y)};
if (R < 0)
{
return 0;
}
ll ans{min(W - s - 1, R / H)};
ll x{R / H + 1};
if (x + s < W && lhs(x, s, y) <= R)
{
++ans;
}
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * solve.answer() + 2 * solve2.answer()};
cout << ans << endl;
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "image.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace nda;
template <typename Input, typename Filter, typename Output>
void conv2d(const Input& input, const Filter& filter, const Output& output) {
for (index_t y : output.y()) {
for (index_t x : output.x()) {
for (index_t c : output.c()) {
output(x, y, c) = 0;
}
for (index_t dy : filter.y()) {
for (index_t dx : filter.x()) {
for (index_t c : output.c()) {
output(x, y, c) += input(x + dx, y + dy, c) * filter(dx, dy, c);
}
}
}
}
}
}
// TODO: This is slow, fix it. The C version below is fast :(
template <typename Input, typename Filter, typename Output>
void conv2d_tiled(const Input& input, const Filter& filter, const Output& output) {
using T = typename Output::value_type;
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(T);
// The strategy used here is:
// - vectorize the channel dimension (assume it has stride 1)
// - tile x and y to get some re-use of the stencil, and to
// get ILP for the accumulators.
constexpr index_t unroll_x = 2;
constexpr index_t unroll_y = 4;
for (auto yo : split<unroll_y>(output.y())) {
for (auto xo : split<unroll_x>(output.x())) {
for (auto co : split<vector_size>(output.c())) {
auto output_tile = output(xo, yo, co);
T buffer[unroll_x * unroll_y * vector_size] = { static_cast<T>(0) };
auto accumulator = make_array_ref(buffer, make_compact(output_tile.shape()));
for (index_t dy : filter.y()) {
for (index_t dx : filter.x()) {
for (index_t y : accumulator.y()) {
for (index_t x : accumulator.x()) {
for (index_t c : accumulator.c()) {
accumulator(x, y, c) += input(x + dx, y + dy, c) * filter(dx, dy, c);
}
}
}
}
}
for (index_t y : output_tile.y()) {
for (index_t x : output_tile.x()) {
for (index_t c : output_tile.c()) {
output_tile(x, y, c) = accumulator(x, y, c);
}
}
}
}
}
}
}
// This generates the following inner loop:
// LBB12_6:
// vmovups -256(%r8,%r14), %ymm9
// vfmadd231ps -384(%rdi,%r15), %ymm9, %ymm1
// vmovups -256(%rdi,%r15), %ymm10
// vfmadd231ps %ymm10, %ymm9, %ymm2
// vfmadd231ps -384(%r12,%r15), %ymm9, %ymm3
// vmovups -256(%r12,%r15), %ymm11
// vfmadd231ps -384(%r10,%r15), %ymm9, %ymm5
// vfmadd231ps %ymm11, %ymm9, %ymm4
// vmovups -256(%r10,%r15), %ymm12
// vfmadd231ps %ymm12, %ymm9, %ymm6
// vfmadd231ps -384(%r13,%r15), %ymm9, %ymm7
// vmovups -256(%r13,%r15), %ymm13
// vfmadd213ps %ymm8, %ymm13, %ymm9
// vmovups -128(%r8,%r14), %ymm8
// vfmadd231ps %ymm10, %ymm8, %ymm1
// vmovups -128(%rdi,%r15), %ymm10
// vfmadd231ps %ymm11, %ymm8, %ymm3
// vmovups -128(%r12,%r15), %ymm11
// vfmadd231ps %ymm12, %ymm8, %ymm5
// vmovups -128(%r10,%r15), %ymm12
// vfmadd231ps %ymm13, %ymm8, %ymm7
// vmovups -128(%r13,%r15), %ymm13
// vfmadd231ps %ymm10, %ymm8, %ymm2
// vfmadd231ps %ymm11, %ymm8, %ymm4
// vfmadd231ps %ymm12, %ymm8, %ymm6
// vfmadd213ps %ymm9, %ymm13, %ymm8
// vmovups (%r8,%r14), %ymm9
// vfmadd231ps %ymm10, %ymm9, %ymm1
// vfmadd231ps %ymm11, %ymm9, %ymm3
// vfmadd231ps %ymm12, %ymm9, %ymm5
// vfmadd231ps (%rdi,%r15), %ymm9, %ymm2
// vfmadd231ps (%r12,%r15), %ymm9, %ymm4
// vfmadd231ps (%r10,%r15), %ymm9, %ymm6
// vfmadd231ps %ymm13, %ymm9, %ymm7
// vfmadd231ps (%r13,%r15), %ymm9, %ymm8
// addq $384, %r14
// addq %rsi, %r15
// cmpq $1408, %r14
// jne LBB12_6
template <index_t Channels, index_t DX, index_t DY>
void conv2d_tiled_c(
const float* input, const float* filter, float* output,
index_t width, index_t height, index_t input_stride, index_t output_stride) {
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(float);
// The strategy used here is:
// - vectorize the channel dimension (assume it has stride 1)
// - tile x and y to get some re-use of the stencil, and to
// get ILP for the accumulators.
constexpr index_t unroll_x = 2;
constexpr index_t unroll_y = 4;
for (index_t yo = 0; yo < height; yo += unroll_y) {
for (index_t xo = 0; xo < width; xo += unroll_x) {
for (index_t co = 0; co < Channels; co += vector_size) {
float buffer[unroll_x * unroll_y * vector_size] = { 0.0f };
for (index_t dy = 0; dy < DY; dy++) {
for (index_t dx = 0; dx < DX; dx++) {
#pragma unroll
for (index_t yi = 0; yi < unroll_y; yi++) {
#pragma unroll
for (index_t xi = 0; xi < unroll_x; xi++) {
for (index_t ci = 0; ci < vector_size; ci++) {
index_t x = xo + xi;
index_t y = yo + yi;
index_t c = co + ci;
buffer[xi * vector_size + yi * vector_size * unroll_x + ci] +=
input[(x + dx) * Channels + (y + dy) * input_stride + c] * filter[dy * DX * Channels + dx * Channels + c];
}
}
}
}
}
for (index_t yi = 0; yi < unroll_y; yi++) {
for (index_t xi = 0; xi < unroll_x; xi++) {
for (index_t ci = 0; ci < vector_size; ci++) {
index_t x = xo + xi;
index_t y = yo + yi;
index_t c = co + ci;
output[x * Channels + y * output_stride + c] = buffer[xi * vector_size + yi * vector_size * unroll_x + ci];
}
}
}
}
}
}
}
int main(int, const char**) {
constexpr int C = 32;
constexpr int W = 100;
constexpr int H = 80;
constexpr int DX = 3;
constexpr int DY = 3;
auto input = make_array<float>(chunky_image_shape<C, nda::dynamic>(W + DX, H + DY, {}));
auto filter = make_array<float>(shape<dim<0, DX, C>, dim<0, DY, C*DX>, dense_dim<0, C>>());
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices with random values.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
generate(input, [&]() { return uniform(rng); });
generate(filter, [&]() { return uniform(rng); });
auto naive_output = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double naive_time = benchmark([&]() {
conv2d(input.cref(), filter.cref(), naive_output.ref());
});
std::cout << "naive time: " << naive_time * 1e3 << " ms" << std::endl;
auto tiled_output = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double tiled_time = benchmark([&]() {
conv2d_tiled(input.cref(), filter.cref(), tiled_output.ref());
});
std::cout << "tiled time: " << tiled_time * 1e3 << " ms" << std::endl;
auto tiled_output_c = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double tiled_time_c = benchmark([&]() {
conv2d_tiled_c<C, DX, DY>(
input.data(), filter.data(), tiled_output_c.data(),
tiled_output_c.width(), tiled_output_c.height(),
input.y().stride(), tiled_output_c.y().stride());
});
std::cout << "tiled time (C): " << tiled_time_c * 1e3 << " ms" << std::endl;
const float epsilon = 1e-4f;
for_each_index(naive_output.shape(), [&](const index_of_rank<3>& i) {
if (std::abs(naive_output(i) - tiled_output(i)) > epsilon) {
std::cout
<< "naive_output(i) = " << naive_output(i)
<< " != tiled_output(i) = " << tiled_output(i) << std::endl;
}
if (std::abs(naive_output(i) - tiled_output_c(i)) > epsilon) {
std::cout
<< "naive_output(i) = " << naive_output(i)
<< " != tiled_output_c(i) = " << tiled_output_c(i) << std::endl;
}
});
return 0;
}
<commit_msg>The naive one wasn't actually fully naive.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "image.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace nda;
template <typename Input, typename Filter, typename Output>
void conv2d(const Input& input, const Filter& filter, const Output& output) {
for (index_t y : output.y()) {
for (index_t x : output.x()) {
for (index_t c : output.c()) {
output(x, y, c) = 0;
for (index_t dy : filter.y()) {
for (index_t dx : filter.x()) {
output(x, y, c) += input(x + dx, y + dy, c) * filter(dx, dy, c);
}
}
}
}
}
}
// TODO: This is slow, fix it. The C version below is fast :(
template <typename Input, typename Filter, typename Output>
void conv2d_tiled(const Input& input, const Filter& filter, const Output& output) {
using T = typename Output::value_type;
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(T);
// The strategy used here is:
// - vectorize the channel dimension (assume it has stride 1)
// - tile x and y to get some re-use of the stencil, and to
// get ILP for the accumulators.
constexpr index_t unroll_x = 2;
constexpr index_t unroll_y = 4;
for (auto yo : split<unroll_y>(output.y())) {
for (auto xo : split<unroll_x>(output.x())) {
for (auto co : split<vector_size>(output.c())) {
auto output_tile = output(xo, yo, co);
T buffer[unroll_x * unroll_y * vector_size] = { static_cast<T>(0) };
auto accumulator = make_array_ref(buffer, make_compact(output_tile.shape()));
for (index_t dy : filter.y()) {
for (index_t dx : filter.x()) {
#pragma unroll
for (index_t y : accumulator.y()) {
#pragma unroll
for (index_t x : accumulator.x()) {
for (index_t c : accumulator.c()) {
accumulator(x, y, c) += input(x + dx, y + dy, c) * filter(dx, dy, c);
}
}
}
}
}
for (index_t y : output_tile.y()) {
for (index_t x : output_tile.x()) {
for (index_t c : output_tile.c()) {
output_tile(x, y, c) = accumulator(x, y, c);
}
}
}
}
}
}
}
// This generates the following inner loop:
// LBB12_6:
// vmovups -256(%r8,%r14), %ymm9
// vfmadd231ps -384(%rdi,%r15), %ymm9, %ymm1
// vmovups -256(%rdi,%r15), %ymm10
// vfmadd231ps %ymm10, %ymm9, %ymm2
// vfmadd231ps -384(%r12,%r15), %ymm9, %ymm3
// vmovups -256(%r12,%r15), %ymm11
// vfmadd231ps -384(%r10,%r15), %ymm9, %ymm5
// vfmadd231ps %ymm11, %ymm9, %ymm4
// vmovups -256(%r10,%r15), %ymm12
// vfmadd231ps %ymm12, %ymm9, %ymm6
// vfmadd231ps -384(%r13,%r15), %ymm9, %ymm7
// vmovups -256(%r13,%r15), %ymm13
// vfmadd213ps %ymm8, %ymm13, %ymm9
// vmovups -128(%r8,%r14), %ymm8
// vfmadd231ps %ymm10, %ymm8, %ymm1
// vmovups -128(%rdi,%r15), %ymm10
// vfmadd231ps %ymm11, %ymm8, %ymm3
// vmovups -128(%r12,%r15), %ymm11
// vfmadd231ps %ymm12, %ymm8, %ymm5
// vmovups -128(%r10,%r15), %ymm12
// vfmadd231ps %ymm13, %ymm8, %ymm7
// vmovups -128(%r13,%r15), %ymm13
// vfmadd231ps %ymm10, %ymm8, %ymm2
// vfmadd231ps %ymm11, %ymm8, %ymm4
// vfmadd231ps %ymm12, %ymm8, %ymm6
// vfmadd213ps %ymm9, %ymm13, %ymm8
// vmovups (%r8,%r14), %ymm9
// vfmadd231ps %ymm10, %ymm9, %ymm1
// vfmadd231ps %ymm11, %ymm9, %ymm3
// vfmadd231ps %ymm12, %ymm9, %ymm5
// vfmadd231ps (%rdi,%r15), %ymm9, %ymm2
// vfmadd231ps (%r12,%r15), %ymm9, %ymm4
// vfmadd231ps (%r10,%r15), %ymm9, %ymm6
// vfmadd231ps %ymm13, %ymm9, %ymm7
// vfmadd231ps (%r13,%r15), %ymm9, %ymm8
// addq $384, %r14
// addq %rsi, %r15
// cmpq $1408, %r14
// jne LBB12_6
template <index_t Channels, index_t DX, index_t DY>
void conv2d_tiled_c(
const float* input, const float* filter, float* output,
index_t width, index_t height, index_t input_stride, index_t output_stride) {
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(float);
// The strategy used here is:
// - vectorize the channel dimension (assume it has stride 1)
// - tile x and y to get some re-use of the stencil, and to
// get ILP for the accumulators.
constexpr index_t unroll_x = 2;
constexpr index_t unroll_y = 4;
for (index_t yo = 0; yo < height; yo += unroll_y) {
for (index_t xo = 0; xo < width; xo += unroll_x) {
for (index_t co = 0; co < Channels; co += vector_size) {
float buffer[unroll_x * unroll_y * vector_size] = { 0.0f };
for (index_t dy = 0; dy < DY; dy++) {
for (index_t dx = 0; dx < DX; dx++) {
#pragma unroll
for (index_t yi = 0; yi < unroll_y; yi++) {
#pragma unroll
for (index_t xi = 0; xi < unroll_x; xi++) {
for (index_t ci = 0; ci < vector_size; ci++) {
index_t x = xo + xi;
index_t y = yo + yi;
index_t c = co + ci;
buffer[xi * vector_size + yi * vector_size * unroll_x + ci] +=
input[(x + dx) * Channels + (y + dy) * input_stride + c] * filter[dy * DX * Channels + dx * Channels + c];
}
}
}
}
}
for (index_t yi = 0; yi < unroll_y; yi++) {
for (index_t xi = 0; xi < unroll_x; xi++) {
for (index_t ci = 0; ci < vector_size; ci++) {
index_t x = xo + xi;
index_t y = yo + yi;
index_t c = co + ci;
output[x * Channels + y * output_stride + c] = buffer[xi * vector_size + yi * vector_size * unroll_x + ci];
}
}
}
}
}
}
}
int main(int, const char**) {
constexpr int C = 32;
constexpr int W = 100;
constexpr int H = 80;
constexpr int DX = 3;
constexpr int DY = 3;
auto input = make_array<float>(chunky_image_shape<C, nda::dynamic>(W + DX, H + DY, {}));
auto filter = make_array<float>(shape<dim<0, DX, C>, dim<0, DY, C*DX>, dense_dim<0, C>>());
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices with random values.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
generate(input, [&]() { return uniform(rng); });
generate(filter, [&]() { return uniform(rng); });
auto naive_output = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double naive_time = benchmark([&]() {
conv2d(input.cref(), filter.cref(), naive_output.ref());
});
std::cout << "naive time: " << naive_time * 1e3 << " ms" << std::endl;
auto tiled_output = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double tiled_time = benchmark([&]() {
conv2d_tiled(input.cref(), filter.cref(), tiled_output.ref());
});
std::cout << "tiled time: " << tiled_time * 1e3 << " ms" << std::endl;
auto tiled_output_c = make_array<float>(chunky_image_shape<C, nda::dynamic>(W, H, {}));
double tiled_time_c = benchmark([&]() {
conv2d_tiled_c<C, DX, DY>(
input.data(), filter.data(), tiled_output_c.data(),
tiled_output_c.width(), tiled_output_c.height(),
input.y().stride(), tiled_output_c.y().stride());
});
std::cout << "tiled time (C): " << tiled_time_c * 1e3 << " ms" << std::endl;
const float epsilon = 1e-4f;
for_each_index(naive_output.shape(), [&](const index_of_rank<3>& i) {
if (std::abs(naive_output(i) - tiled_output(i)) > epsilon) {
std::cout
<< "naive_output(i) = " << naive_output(i)
<< " != tiled_output(i) = " << tiled_output(i) << std::endl;
}
if (std::abs(naive_output(i) - tiled_output_c(i)) > epsilon) {
std::cout
<< "naive_output(i) = " << naive_output(i)
<< " != tiled_output_c(i) = " << tiled_output_c(i) << std::endl;
}
});
return 0;
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
#if DEBUG == 1
cerr << "W = " << W << ", H = " << H << endl;
#endif
ll ans{0};
for (auto s{0LL}; s < W - 1; ++s)
{
for (auto y{1LL}; (H - y) * s <= 2 * K + H - 2 && y < H; ++y)
{
ll tmp{calc(s, y)};
if (s == 0)
{
ans += tmp;
}
else
{
ans += 2 * tmp;
}
}
}
return ans;
}
private:
ll calc(ll s, ll y)
{
ll R{2 * K - (H - y) * s + gcd(H, s) - 2};
if (R < 0)
{
return 0;
}
ll ans{min(W - s - 1, R / H)};
ll x{R / H + 1};
#if DEBUG == 1
if (H < 10)
{
cerr << "ans = " << ans << endl;
cerr << "x = " << x << endl;
}
#endif
if (x + s < W && H * x - gcd(H - y, x) + gcd(y, x + s) <= R)
{
++ans;
}
#if DEBUG == 1
if (H < 10)
{
cerr << "calc(" << s << ", " << y << ") = " << ans << endl;
}
#endif
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * solve.answer() + 2 * solve2.answer()};
cout << ans << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 6/14/2020, 3:53:32 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- Solve -----
class Solve
{
ll W, H, K;
public:
Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {}
ll answer()
{
#if DEBUG == 1
cerr << "W = " << W << ", H = " << H << endl;
#endif
ll ans{0};
for (auto s{0LL}; s < W - 1; ++s)
{
for (auto y{1LL}; (H - y) * s <= 2 * K + H - 2 && y < H; ++y)
{
ll tmp{calc(s, y)};
if (s == 0)
{
ans += tmp;
}
else
{
ans += 2 * tmp;
}
}
}
return ans;
}
private:
ll calc(ll s, ll y)
{
ll R{2 * K - (H - y) * s + gcd(H, s) - 2};
if (R < 0)
{
return 0;
}
ll ans{min(W - s - 1, R / H)};
ll x{R / H + 1};
#if DEBUG == 1
if (H < 10)
{
cerr << "ans = " << ans << endl;
cerr << "x = " << x << endl;
cerr << "R = " << R << endl;
}
#endif
if (x + s < W && H * x - gcd(H - y, x) + gcd(y, x + s) <= R)
{
++ans;
}
#if DEBUG == 1
if (H < 10)
{
cerr << "calc(" << s << ", " << y << ") = " << ans << endl;
}
#endif
return ans;
}
};
// ----- main() -----
int main()
{
ll W, H, K;
cin >> W >> H >> K;
Solve solve(W, H, K), solve2(H, W, K);
ll ans{2 * solve.answer() + 2 * solve2.answer()};
cout << ans << endl;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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
*/
#include "arch/x86/predecoder.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/host.hh"
namespace X86ISA
{
void Predecoder::process()
{
//This function drives the predecoder state machine.
//Some sanity checks. You shouldn't try to process more bytes if
//there aren't any, and you shouldn't overwrite an already
//predecoder ExtMachInst.
assert(!outOfBytes);
assert(!emiIsReady);
//While there's still something to do...
while(!emiIsReady && !outOfBytes)
{
uint8_t nextByte = getNextByte();
switch(state)
{
case PrefixState:
state = doPrefixState(nextByte);
break;
case OpcodeState:
state = doOpcodeState(nextByte);
break;
case ModRMState:
state = doModRMState(nextByte);
break;
case SIBState:
state = doSIBState(nextByte);
break;
case DisplacementState:
state = doDisplacementState();
break;
case ImmediateState:
state = doImmediateState();
break;
case ErrorState:
panic("Went to the error state in the predecoder.\n");
default:
panic("Unrecognized state! %d\n", state);
}
}
}
//Either get a prefix and record it in the ExtMachInst, or send the
//state machine on to get the opcode(s).
Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)
{
uint8_t prefix = Prefixes[nextByte];
State nextState = PrefixState;
if(prefix)
consumeByte();
switch(prefix)
{
//Operand size override prefixes
case OperandSizeOverride:
DPRINTF(Predecoder, "Found operand size override prefix.\n");
break;
case AddressSizeOverride:
DPRINTF(Predecoder, "Found address size override prefix.\n");
break;
//Segment override prefixes
case CSOverride:
DPRINTF(Predecoder, "Found cs segment override.\n");
break;
case DSOverride:
DPRINTF(Predecoder, "Found ds segment override.\n");
break;
case ESOverride:
DPRINTF(Predecoder, "Found es segment override.\n");
break;
case FSOverride:
DPRINTF(Predecoder, "Found fs segment override.\n");
break;
case GSOverride:
DPRINTF(Predecoder, "Found gs segment override.\n");
break;
case SSOverride:
DPRINTF(Predecoder, "Found ss segment override.\n");
break;
case Lock:
DPRINTF(Predecoder, "Found lock prefix.\n");
break;
case Rep:
DPRINTF(Predecoder, "Found rep prefix.\n");
break;
case Repne:
DPRINTF(Predecoder, "Found repne prefix.\n");
break;
case RexPrefix:
DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte);
emi.rex = nextByte;
break;
case 0:
emi.opcode.num = 0;
nextState = OpcodeState;
break;
default:
panic("Unrecognized prefix %#x\n", nextByte);
}
return nextState;
}
//Load all the opcodes (currently up to 2) and then figure out
//what immediate and/or ModRM is needed.
Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.opcode.num++;
//We can't handle 3+ byte opcodes right now
assert(emi.opcode.num < 3);
consumeByte();
if(emi.opcode.num == 1 && nextByte == 0x0f)
{
nextState = OpcodeState;
DPRINTF(Predecoder, "Found two byte opcode.\n");
emi.opcode.prefixA = nextByte;
}
else if(emi.opcode.num == 2 &&
(nextByte == 0x0f ||
(nextByte & 0xf8) == 0x38))
{
panic("Three byte opcodes aren't yet supported!\n");
nextState = OpcodeState;
DPRINTF(Predecoder, "Found three byte opcode.\n");
emi.opcode.prefixB = nextByte;
}
else
{
DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte);
emi.opcode.op = nextByte;
//Prepare for any immediate/displacement we might need
immediateCollected = 0;
emi.immediate = 0;
displacementCollected = 0;
emi.displacement = 0;
//Figure out how big of an immediate we'll retreive based
//on the opcode.
int immType = ImmediateType[
emi.opcode.num - 1][nextByte];
if(0) //16 bit mode
immediateSize = ImmediateTypeToSize[0][immType];
else if(!(emi.rex & 0x4)) //32 bit mode
immediateSize = ImmediateTypeToSize[1][immType];
else //64 bit mode
immediateSize = ImmediateTypeToSize[2][immType];
//Determine what to expect next
if (UsesModRM[emi.opcode.num - 1][nextByte]) {
nextState = ModRMState;
} else if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
}
return nextState;
}
//Get the ModRM byte and determine what displacement, if any, there is.
//Also determine whether or not to get the SIB byte, displacement, or
//immediate next.
Predecoder::State Predecoder::doModRMState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.modRM = nextByte;
DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte);
if (0) {//FIXME in 16 bit mode
//figure out 16 bit displacement size
if(nextByte & 0xC7 == 0x06 ||
nextByte & 0xC0 == 0x80)
displacementSize = 2;
else if(nextByte & 0xC0 == 0x40)
displacementSize = 1;
else
displacementSize = 0;
} else {
//figure out 32/64 bit displacement size
if(nextByte & 0xC7 == 0x05 ||
nextByte & 0xC0 == 0x80)
displacementSize = 4;
else if(nextByte & 0xC0 == 0x40)
displacementSize = 2;
else
displacementSize = 0;
}
//If there's an SIB, get that next.
//There is no SIB in 16 bit mode.
if(nextByte & 0x7 == 4 &&
nextByte & 0xC0 != 0xC0) {
// && in 32/64 bit mode)
nextState = SIBState;
} else if(displacementSize) {
nextState = DisplacementState;
} else if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
//The ModRM byte is consumed no matter what
consumeByte();
return nextState;
}
//Get the SIB byte. We don't do anything with it at this point, other
//than storing it in the ExtMachInst. Determine if we need to get a
//displacement or immediate next.
Predecoder::State Predecoder::doSIBState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.sib = nextByte;
DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte);
consumeByte();
if(displacementSize) {
nextState = DisplacementState;
} else if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
return nextState;
}
//Gather up the displacement, or at least as much of it
//as we can get.
Predecoder::State Predecoder::doDisplacementState()
{
State nextState = ErrorState;
getImmediate(displacementCollected,
emi.displacement,
displacementSize);
DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n",
displacementSize, displacementCollected);
if(displacementSize == displacementCollected) {
//Sign extend the displacement
switch(displacementSize)
{
case 1:
emi.displacement = sext<8>(emi.displacement);
break;
case 2:
emi.displacement = sext<16>(emi.displacement);
break;
case 4:
emi.displacement = sext<32>(emi.displacement);
break;
default:
panic("Undefined displacement size!\n");
}
DPRINTF(Predecoder, "Collected displacement %#x.\n",
emi.displacement);
if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
}
else
nextState = DisplacementState;
return nextState;
}
//Gather up the immediate, or at least as much of it
//as we can get
Predecoder::State Predecoder::doImmediateState()
{
State nextState = ErrorState;
getImmediate(immediateCollected,
emi.immediate,
immediateSize);
DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n",
immediateSize, immediateCollected);
if(immediateSize == immediateCollected)
{
DPRINTF(Predecoder, "Collected immediate %#x.\n",
emi.immediate);
emiIsReady = true;
nextState = PrefixState;
}
else
nextState = ImmediateState;
return nextState;
}
}
<commit_msg>Zero out ModRM if the byte isn't there, and fix some displacement size stuff.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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
*/
#include "arch/x86/predecoder.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/host.hh"
namespace X86ISA
{
void Predecoder::process()
{
//This function drives the predecoder state machine.
//Some sanity checks. You shouldn't try to process more bytes if
//there aren't any, and you shouldn't overwrite an already
//predecoder ExtMachInst.
assert(!outOfBytes);
assert(!emiIsReady);
//While there's still something to do...
while(!emiIsReady && !outOfBytes)
{
uint8_t nextByte = getNextByte();
switch(state)
{
case PrefixState:
state = doPrefixState(nextByte);
break;
case OpcodeState:
state = doOpcodeState(nextByte);
break;
case ModRMState:
state = doModRMState(nextByte);
break;
case SIBState:
state = doSIBState(nextByte);
break;
case DisplacementState:
state = doDisplacementState();
break;
case ImmediateState:
state = doImmediateState();
break;
case ErrorState:
panic("Went to the error state in the predecoder.\n");
default:
panic("Unrecognized state! %d\n", state);
}
}
}
//Either get a prefix and record it in the ExtMachInst, or send the
//state machine on to get the opcode(s).
Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)
{
uint8_t prefix = Prefixes[nextByte];
State nextState = PrefixState;
if(prefix)
consumeByte();
switch(prefix)
{
//Operand size override prefixes
case OperandSizeOverride:
DPRINTF(Predecoder, "Found operand size override prefix.\n");
break;
case AddressSizeOverride:
DPRINTF(Predecoder, "Found address size override prefix.\n");
break;
//Segment override prefixes
case CSOverride:
DPRINTF(Predecoder, "Found cs segment override.\n");
break;
case DSOverride:
DPRINTF(Predecoder, "Found ds segment override.\n");
break;
case ESOverride:
DPRINTF(Predecoder, "Found es segment override.\n");
break;
case FSOverride:
DPRINTF(Predecoder, "Found fs segment override.\n");
break;
case GSOverride:
DPRINTF(Predecoder, "Found gs segment override.\n");
break;
case SSOverride:
DPRINTF(Predecoder, "Found ss segment override.\n");
break;
case Lock:
DPRINTF(Predecoder, "Found lock prefix.\n");
break;
case Rep:
DPRINTF(Predecoder, "Found rep prefix.\n");
break;
case Repne:
DPRINTF(Predecoder, "Found repne prefix.\n");
break;
case RexPrefix:
DPRINTF(Predecoder, "Found Rex prefix %#x.\n", nextByte);
emi.rex = nextByte;
break;
case 0:
emi.opcode.num = 0;
nextState = OpcodeState;
break;
default:
panic("Unrecognized prefix %#x\n", nextByte);
}
return nextState;
}
//Load all the opcodes (currently up to 2) and then figure out
//what immediate and/or ModRM is needed.
Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.opcode.num++;
//We can't handle 3+ byte opcodes right now
assert(emi.opcode.num < 3);
consumeByte();
if(emi.opcode.num == 1 && nextByte == 0x0f)
{
nextState = OpcodeState;
DPRINTF(Predecoder, "Found two byte opcode.\n");
emi.opcode.prefixA = nextByte;
}
else if(emi.opcode.num == 2 &&
(nextByte == 0x0f ||
(nextByte & 0xf8) == 0x38))
{
panic("Three byte opcodes aren't yet supported!\n");
nextState = OpcodeState;
DPRINTF(Predecoder, "Found three byte opcode.\n");
emi.opcode.prefixB = nextByte;
}
else
{
DPRINTF(Predecoder, "Found opcode %#x.\n", nextByte);
emi.opcode.op = nextByte;
//Prepare for any immediate/displacement we might need
immediateCollected = 0;
emi.immediate = 0;
displacementCollected = 0;
emi.displacement = 0;
//Figure out how big of an immediate we'll retreive based
//on the opcode.
int immType = ImmediateType[
emi.opcode.num - 1][nextByte];
if(0) //16 bit mode
immediateSize = ImmediateTypeToSize[0][immType];
else if(!(emi.rex & 0x4)) //32 bit mode
immediateSize = ImmediateTypeToSize[1][immType];
else //64 bit mode
immediateSize = ImmediateTypeToSize[2][immType];
//Determine what to expect next
if (UsesModRM[emi.opcode.num - 1][nextByte]) {
nextState = ModRMState;
} else {
//If there's no modRM byte, set it to 0 so we can detect
//that later.
emi.modRM = 0;
if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
}
}
return nextState;
}
//Get the ModRM byte and determine what displacement, if any, there is.
//Also determine whether or not to get the SIB byte, displacement, or
//immediate next.
Predecoder::State Predecoder::doModRMState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.modRM = nextByte;
DPRINTF(Predecoder, "Found modrm byte %#x.\n", nextByte);
if (0) {//FIXME in 16 bit mode
//figure out 16 bit displacement size
if(nextByte & 0xC7 == 0x06 ||
nextByte & 0xC0 == 0x80)
displacementSize = 2;
else if(nextByte & 0xC0 == 0x40)
displacementSize = 1;
else
displacementSize = 0;
} else {
//figure out 32/64 bit displacement size
if(nextByte & 0xC6 == 0x04 ||
nextByte & 0xC0 == 0x80)
displacementSize = 4;
else if(nextByte & 0xC0 == 0x40)
displacementSize = 1;
else
displacementSize = 0;
}
//If there's an SIB, get that next.
//There is no SIB in 16 bit mode.
if(nextByte & 0x7 == 4 &&
nextByte & 0xC0 != 0xC0) {
// && in 32/64 bit mode)
nextState = SIBState;
} else if(displacementSize) {
nextState = DisplacementState;
} else if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
//The ModRM byte is consumed no matter what
consumeByte();
return nextState;
}
//Get the SIB byte. We don't do anything with it at this point, other
//than storing it in the ExtMachInst. Determine if we need to get a
//displacement or immediate next.
Predecoder::State Predecoder::doSIBState(uint8_t nextByte)
{
State nextState = ErrorState;
emi.sib = nextByte;
DPRINTF(Predecoder, "Found SIB byte %#x.\n", nextByte);
consumeByte();
if(displacementSize) {
nextState = DisplacementState;
} else if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
return nextState;
}
//Gather up the displacement, or at least as much of it
//as we can get.
Predecoder::State Predecoder::doDisplacementState()
{
State nextState = ErrorState;
getImmediate(displacementCollected,
emi.displacement,
displacementSize);
DPRINTF(Predecoder, "Collecting %d byte displacement, got %d bytes.\n",
displacementSize, displacementCollected);
if(displacementSize == displacementCollected) {
//Sign extend the displacement
switch(displacementSize)
{
case 1:
emi.displacement = sext<8>(emi.displacement);
break;
case 2:
emi.displacement = sext<16>(emi.displacement);
break;
case 4:
emi.displacement = sext<32>(emi.displacement);
break;
default:
panic("Undefined displacement size!\n");
}
DPRINTF(Predecoder, "Collected displacement %#x.\n",
emi.displacement);
if(immediateSize) {
nextState = ImmediateState;
} else {
emiIsReady = true;
nextState = PrefixState;
}
}
else
nextState = DisplacementState;
return nextState;
}
//Gather up the immediate, or at least as much of it
//as we can get
Predecoder::State Predecoder::doImmediateState()
{
State nextState = ErrorState;
getImmediate(immediateCollected,
emi.immediate,
immediateSize);
DPRINTF(Predecoder, "Collecting %d byte immediate, got %d bytes.\n",
immediateSize, immediateCollected);
if(immediateSize == immediateCollected)
{
DPRINTF(Predecoder, "Collected immediate %#x.\n",
emi.immediate);
emiIsReady = true;
nextState = PrefixState;
}
else
nextState = ImmediateState;
return nextState;
}
}
<|endoftext|>
|
<commit_before>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
typedef unsigned char * BytePtr;
template <class T>
inline void swapBytes( T &s )
{
if( sizeof( T ) == 1 ) return;
T d = s;
BytePtr sptr = (BytePtr)&s;
BytePtr dptr = &(((BytePtr)&d)[sizeof(T)-1]);
for( unsigned int i = 0; i < sizeof(T); i++ )
*(sptr++) = *(dptr--);
}
class PackedEvent
{
public:
PackedEvent():
_eventType(osgProducer::EventAdapter::NONE),
_key(0),
_button(0),
_Xmin(0),_Xmax(0),
_Ymin(0),_Ymax(0),
_mx(0),
_my(0),
_buttonMask(0),
_modKeyMask(0),
_time(0.0) {}
void set(const osgProducer::EventAdapter& event)
{
_eventType = event._eventType;
_key = event._key;
_button = event._button;
_Xmin = event._Xmin;
_Xmax = event._Xmax;
_Ymin = event._Ymin;
_Ymax = event._Ymax;
_mx = event._mx;
_my = event._my;
_buttonMask = event._buttonMask;
_modKeyMask = event._modKeyMask;
_time = event._time;
}
void get(osgProducer::EventAdapter& event)
{
event._eventType = _eventType;
event._key = _key;
event._button = _button;
event._Xmin = _Xmin;
event._Xmax = _Xmax;
event._Ymin = _Ymin;
event._Ymax = _Ymax;
event._mx = _mx;
event._my = _my;
event._buttonMask = _buttonMask;
event._modKeyMask = _modKeyMask;
event._time = _time;
}
void swapBytes()
{
}
protected:
osgProducer::EventAdapter::EventType _eventType;
int _key;
int _button;
float _Xmin,_Xmax;
float _Ymin,_Ymax;
float _mx;
float _my;
unsigned int _buttonMask;
unsigned int _modKeyMask;
double _time;
};
const unsigned int MAX_NUM_EVENTS = 10;
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = 0x12345678;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void readEventQueue(osgProducer::Viewer& viewer);
void writeEventQueue(osgProducer::Viewer& viewer);
void checkByteOrder( void )
{
if( _byte_order == 0x78563412 ) // We're backwards
{
swapBytes( _byte_order );
swapBytes( _masterKilled );
for( int i = 0; i < 16; i++ )
swapBytes( _matrix.ptr()[i] );
// umm.. we should byte swap _frameStamp too...
for(unsigned int ei=0; ei<_numEvents; ++ei)
{
_events[ei].swapBytes();
}
}
}
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned int _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
unsigned int _numEvents;
PackedEvent _events[MAX_NUM_EVENTS];
};
void CameraPacket::readEventQueue(osgProducer::Viewer& viewer)
{
osgProducer::KeyboardMouseCallback::EventQueue queue;
viewer.getKeyboardMouseCallback()->copyEventQueue(queue);
_numEvents = 0;
for(osgProducer::KeyboardMouseCallback::EventQueue::iterator itr =queue.begin();
itr != queue.end() && _numEvents<MAX_NUM_EVENTS;
++itr, ++_numEvents)
{
osgProducer::EventAdapter* event = itr->get();
_events[_numEvents].set(*event);
}
osg::notify(osg::INFO)<<"written events = "<<_numEvents<<std::endl;
}
void CameraPacket::writeEventQueue(osgProducer::Viewer& viewer)
{
osg::notify(osg::INFO)<<"recieved events = "<<_numEvents<<std::endl;
// copy the packed events to osgProducer style events.
osgProducer::KeyboardMouseCallback::EventQueue queue;
for(unsigned int ei=0; ei<_numEvents; ++ei)
{
osgProducer::EventAdapter* event = new osgProducer::EventAdapter;
_events[ei].get(*event);
queue.push_back(event);
}
// pass them to the viewer.
viewer.getKeyboardMouseCallback()->appendEventQueue(queue);
}
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
osg::notify(osg::INFO)<<"FrameStamp "<<sizeof(osg::FrameStamp)<<std::endl;
osg::notify(osg::INFO)<<"osg::Matrix "<<sizeof(osg::Matrix)<<std::endl;
osg::notify(osg::INFO)<<"PackedEvent "<<sizeof(PackedEvent)<<std::endl;
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov))
{
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
if (camera_fov>0.0f)
{
float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
CameraPacket *cp = new CameraPacket;
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
osg::Timer_t startTick = osg::Timer::instance()->tick();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp->setPacket(modelview,viewer.getFrameStamp());
cp->readEventQueue(viewer);
bc.setBuffer(cp, sizeof( CameraPacket ));
std::cout << "bc.sync()"<<sizeof( CameraPacket )<<std::endl;
bc.sync();
}
break;
case(SLAVE):
{
rc.setBuffer(cp, sizeof( CameraPacket ));
osg::notify(osg::INFO) << "rc.sync()"<<sizeof( CameraPacket )<<std::endl;
rc.sync();
cp->checkByteOrder();
cp->writeEventQueue(viewer);
if (cp->getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
osg::Timer_t endTick = osg::Timer::instance()->tick();
osg::notify(osg::INFO)<<"Time to do cluster sync "<<osg::Timer::instance()->delta_m(startTick,endTick)<<std::endl;
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
if (viewerMode==SLAVE)
{
osg::Matrix modelview;
cp->getModelView(modelview,camera_offset);
viewer.setView(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp->setMasterKilled(true);
bc.setBuffer(cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "Broadcasting death."<<std::endl;
}
return 0;
}
<commit_msg>Implement a scratch pad for writing and read data to, to solve issue between running a master and slave on a mix of 32bit and 64bit.<commit_after>#ifdef USE_MEM_CHECK
#include <mcheck.h>
#endif
#include <osg/Group>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgProducer/Viewer>
#include <osg/Quat>
#if defined (WIN32) && !defined(__CYGWIN__)
#include <winsock.h>
#endif
#include "receiver.h"
#include "broadcaster.h"
const unsigned int MAX_NUM_EVENTS = 10;
const unsigned int SWAP_BYTES_COMPARE = 0x12345678;
class CameraPacket {
public:
CameraPacket():_masterKilled(false)
{
_byte_order = SWAP_BYTES_COMPARE;
}
void setPacket(const osg::Matrix& matrix,const osg::FrameStamp* frameStamp)
{
_matrix = matrix;
if (frameStamp)
{
_frameStamp = *frameStamp;
}
}
void getModelView(osg::Matrix& matrix,float angle_offset=0.0f)
{
matrix = _matrix * osg::Matrix::rotate(osg::DegreesToRadians(angle_offset),0.0f,1.0f,0.0f);
}
void readEventQueue(osgProducer::Viewer& viewer);
void writeEventQueue(osgProducer::Viewer& viewer);
void setMasterKilled(const bool flag) { _masterKilled = flag; }
const bool getMasterKilled() const { return _masterKilled; }
unsigned int _byte_order;
bool _masterKilled;
osg::Matrix _matrix;
// note don't use a ref_ptr as used elsewhere for FrameStamp
// since we don't want to copy the pointer - but the memory.
// FrameStamp doesn't have a private destructor to allow
// us to do this, even though its a reference counted object.
osg::FrameStamp _frameStamp;
osgProducer::KeyboardMouseCallback::EventQueue _events;
};
class DataConverter
{
public:
DataConverter(unsigned int numBytes):
_startPtr(0),
_endPtr(0),
_swapBytes(false),
_currentPtr(0)
{
_currentPtr = _startPtr = new char[numBytes];
_endPtr = _startPtr+numBytes;
_numBytes = numBytes;
}
char* _startPtr;
char* _endPtr;
unsigned int _numBytes;
bool _swapBytes;
char* _currentPtr;
inline void write1(char* ptr)
{
if (_currentPtr+1>=_endPtr) return;
*(_currentPtr++) = *(ptr);
}
inline void read1(char* ptr)
{
if (_currentPtr+1>=_endPtr) return;
*(ptr) = *(_currentPtr++);
}
inline void write2(char* ptr)
{
if (_currentPtr+2>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read2(char* ptr)
{
if (_currentPtr+2>=_endPtr) return;
if (_swapBytes)
{
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void write4(char* ptr)
{
if (_currentPtr+4>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read4(char* ptr)
{
if (_currentPtr+4>=_endPtr) return;
if (_swapBytes)
{
*(ptr+3) = *(_currentPtr++);
*(ptr+2) = *(_currentPtr++);
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void write8(char* ptr)
{
if (_currentPtr+8>=_endPtr) return;
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr++);
*(_currentPtr++) = *(ptr);
}
inline void read8(char* ptr)
{
char* endPtr = _currentPtr+8;
if (endPtr>=_endPtr) return;
if (_swapBytes)
{
*(ptr+7) = *(_currentPtr++);
*(ptr+6) = *(_currentPtr++);
*(ptr+5) = *(_currentPtr++);
*(ptr+4) = *(_currentPtr++);
*(ptr+3) = *(_currentPtr++);
*(ptr+2) = *(_currentPtr++);
*(ptr+1) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
else
{
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr++) = *(_currentPtr++);
*(ptr) = *(_currentPtr++);
}
}
inline void writeChar(char c) { write1(&c); }
inline void writeUChar(unsigned char c) { write1((char*)&c); }
inline void writeShort(short c) { write2((char*)&c); }
inline void writeUShort(unsigned short c) { write2((char*)&c); }
inline void writeInt(int c) { write4((char*)&c); }
inline void writeUInt(unsigned int c) { write4((char*)&c); }
inline void writeFloat(float c) { write4((char*)&c); }
inline void writeDouble(double c) { write8((char*)&c); }
inline char readChar() { char c; read1(&c); return c; }
inline unsigned char readUChar() { unsigned char c; read1((char*)&c); return c; }
inline short readShort() { short c; read2((char*)&c); return c; }
inline unsigned short readUShort() { unsigned short c; read2((char*)&c); return c; }
inline int readInt() { int c; read4((char*)&c); return c; }
inline unsigned int readUInt() { unsigned int c; read4((char*)&c); return c; }
inline float readFloat() { float c; read4((char*)&c); return c; }
inline double readDouble() { double c; read8((char*)&c); return c; }
void write(const osg::FrameStamp& fs)
{
writeUInt(fs.getFrameNumber());
return writeDouble(fs.getReferenceTime());
}
void read(osg::FrameStamp& fs)
{
fs.setFrameNumber(readUInt());
fs.setReferenceTime(readDouble());
}
void write(const osg::Matrix& matrix)
{
writeDouble(matrix(0,0));
writeDouble(matrix(0,1));
writeDouble(matrix(0,2));
writeDouble(matrix(0,3));
writeDouble(matrix(1,0));
writeDouble(matrix(1,1));
writeDouble(matrix(1,2));
writeDouble(matrix(1,3));
writeDouble(matrix(2,0));
writeDouble(matrix(2,1));
writeDouble(matrix(2,2));
writeDouble(matrix(2,3));
writeDouble(matrix(3,0));
writeDouble(matrix(3,1));
writeDouble(matrix(3,2));
writeDouble(matrix(3,3));
}
void read(osg::Matrix& matrix)
{
matrix(0,0) = readDouble();
matrix(0,1) = readDouble();
matrix(0,2) = readDouble();
matrix(0,3) = readDouble();
matrix(1,0) = readDouble();
matrix(1,1) = readDouble();
matrix(1,2) = readDouble();
matrix(1,3) = readDouble();
matrix(2,0) = readDouble();
matrix(2,1) = readDouble();
matrix(2,2) = readDouble();
matrix(2,3) = readDouble();
matrix(3,0) = readDouble();
matrix(3,1) = readDouble();
matrix(3,2) = readDouble();
matrix(3,3) = readDouble();
}
void write(const osgProducer::EventAdapter& event)
{
writeUInt(event._eventType);
writeUInt(event._key);
writeUInt(event._button);
writeFloat(event._Xmin);
writeFloat(event._Xmax);
writeFloat(event._Ymin);
writeFloat(event._Ymax);
writeFloat(event._mx);
writeFloat(event._my);
writeUInt(event._buttonMask);
writeUInt(event._modKeyMask);
writeDouble(event._time);
}
void read(osgProducer::EventAdapter& event)
{
event._eventType = (osgGA::GUIEventAdapter::EventType)readUInt();
event._key = readUInt();
event._button = readUInt();
event._Xmin = readFloat();
event._Xmax = readFloat();
event._Ymin = readFloat();
event._Ymax = readFloat();
event._mx = readFloat();
event._my = readFloat();
event._buttonMask = readUInt();
event._modKeyMask = readUInt();
event._time = readDouble();
}
void write(CameraPacket& cameraPacket)
{
writeUInt(cameraPacket._byte_order);
writeUInt(cameraPacket._masterKilled);
write(cameraPacket._matrix);
write(cameraPacket._frameStamp);
writeUInt(cameraPacket._events.size());
for(unsigned int i=0;i<cameraPacket._events.size();++i)
{
write(*(cameraPacket._events[i]));
}
}
void read(CameraPacket& cameraPacket)
{
cameraPacket._byte_order = readUInt();
if (cameraPacket._byte_order != SWAP_BYTES_COMPARE) _swapBytes = !_swapBytes;
cameraPacket._masterKilled = readUInt();
read(cameraPacket._matrix);
read(cameraPacket._frameStamp);
cameraPacket._events.clear();
unsigned int numEvents = readUInt();
for(unsigned int i=0;i<numEvents;++i)
{
osgProducer::EventAdapter* event = new osgProducer::EventAdapter;
read(*(event));
cameraPacket._events.push_back(event);
}
}
};
void CameraPacket::readEventQueue(osgProducer::Viewer& viewer)
{
viewer.getKeyboardMouseCallback()->copyEventQueue(_events);
osg::notify(osg::INFO)<<"written events = "<<_events.size()<<std::endl;
}
void CameraPacket::writeEventQueue(osgProducer::Viewer& viewer)
{
osg::notify(osg::INFO)<<"recieved events = "<<_events.size()<<std::endl;
// copy the events to osgProducer style events.
viewer.getKeyboardMouseCallback()->appendEventQueue(_events);
}
enum ViewerMode
{
STAND_ALONE,
SLAVE,
MASTER
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering. Note, cluster support will soon be encompassed in Producer itself.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, reciving view via packets.");
arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// read up the osgcluster specific arguments.
ViewerMode viewerMode = STAND_ALONE;
while (arguments.read("-m")) viewerMode = MASTER;
while (arguments.read("-s")) viewerMode = SLAVE;
int socketNumber=8100;
while (arguments.read("-n",socketNumber)) ;
float camera_fov=-1.0f;
while (arguments.read("-f",camera_fov))
{
}
float camera_offset=45.0f;
while (arguments.read("-o",camera_offset)) ;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// load model.
osg::ref_ptr<osg::Node> rootnode = osgDB::readNodeFiles(arguments);
// set the scene to render
viewer.setSceneData(rootnode.get());
// create the windows and run the threads.
viewer.realize();
// set up the lens after realize as the Producer lens is not set up properly before this.... will need to inveestigate this at a later date.
if (camera_fov>0.0f)
{
float aspectRatio = tan( osg::DegreesToRadians(viewer.getLensVerticalFov()*0.5)) / tan(osg::DegreesToRadians(viewer.getLensHorizontalFov()*0.5));
float new_fovy = osg::RadiansToDegrees(atan( aspectRatio * tan( osg::DegreesToRadians(camera_fov*0.5))))*2.0f;
std::cout << "setting lens perspective : original "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
viewer.setLensPerspective(camera_fov,new_fovy,1.0f,1000.0f);
std::cout << "setting lens perspective : new "<<viewer.getLensHorizontalFov()<<" "<<viewer.getLensVerticalFov()<<std::endl;
}
CameraPacket *cp = new CameraPacket;
// objects for managing the broadcasting and recieving of camera packets.
Broadcaster bc;
Receiver rc;
bc.setPort(static_cast<short int>(socketNumber));
rc.setPort(static_cast<short int>(socketNumber));
bool masterKilled = false;
DataConverter scratchPad(1024);
while( !viewer.done() && !masterKilled )
{
// wait for all cull and draw threads to complete.
viewer.sync();
osg::Timer_t startTick = osg::Timer::instance()->tick();
// special handling for working as a cluster.
switch (viewerMode)
{
case(MASTER):
{
// take camera zero as the guide.
osg::Matrix modelview(viewer.getCameraConfig()->getCamera(0)->getViewMatrix());
cp->setPacket(modelview,viewer.getFrameStamp());
cp->readEventQueue(viewer);
scratchPad.write(*cp);
bc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
std::cout << "bc.sync()"<<scratchPad._numBytes<<std::endl;
bc.sync();
}
break;
case(SLAVE):
{
rc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
osg::notify(osg::INFO) << "rc.sync()"<<scratchPad._numBytes<<std::endl;
rc.sync();
scratchPad.read(*cp);
cp->writeEventQueue(viewer);
if (cp->getMasterKilled())
{
std::cout << "Received master killed."<<std::endl;
// break out of while (!done) loop since we've now want to shut down.
masterKilled = true;
}
}
break;
default:
// no need to anything here, just a normal interactive viewer.
break;
}
osg::Timer_t endTick = osg::Timer::instance()->tick();
osg::notify(osg::INFO)<<"Time to do cluster sync "<<osg::Timer::instance()->delta_m(startTick,endTick)<<std::endl;
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
if (viewerMode==SLAVE)
{
osg::Matrix modelview;
cp->getModelView(modelview,camera_offset);
viewer.setView(modelview);
}
// fire off the cull and draw traversals of the scene.
if(!masterKilled)
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
// if we are master clean up by telling all slaves that we're going down.
if (viewerMode==MASTER)
{
// need to broadcast my death.
cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
cp->setMasterKilled(true);
bc.setBuffer(cp, sizeof( CameraPacket ));
bc.sync();
std::cout << "Broadcasting death."<<std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2020 ANON authors, see AUTHORS file.
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 "sync_teflon_app.h"
#include "log.h"
#include "sproc_mgr.h"
#include "nlohmann/json.hpp"
#include <sys/stat.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/QueryRequest.h>
using namespace nlohmann;
using namespace Aws::DynamoDB::Model;
namespace
{
struct tef_app
{
tef_app(const Aws::String &id,
const Aws::Vector<Aws::String> &filesv,
Aws::Map<Aws::String, const std::shared_ptr<AttributeValue>> &fids)
: id(id)
{
for (auto &f : filesv)
{
files[fids[f]->GetS()] = f;
}
}
Aws::String id;
std::map<Aws::String, Aws::String> files;
};
void exe_cmd(const std::string &str)
{
std::string cmd = "bash -c '" + str + "'";
auto f = popen(cmd.c_str(), "r");
if (f)
{
auto exit_code = pclose(f);
if (exit_code != 0)
anon_throw(std::runtime_error, "command: " << str << " exited non-zero: " << error_string(exit_code));
}
else
{
anon_throw(std::runtime_error, "popen failed: " << errno_string());
}
}
void create_empty_directory(const ec2_info &ec2i, const Aws::String &id)
{
auto dir = ec2i.root_dir;
if (id.size() != 0)
{
dir += "/";
dir += id.c_str();
}
std::ostringstream oss;
oss << "rm -rf " << dir << " && mkdir " << dir;
exe_cmd(oss.str());
}
void remove_directory(const ec2_info &ec2i, const Aws::String &id)
{
auto dir = ec2i.root_dir;
if (id.size() != 0)
{
dir += "/";
dir += id.c_str();
}
std::ostringstream oss;
oss << "rm -rf " << id;
exe_cmd(oss.str());
}
bool validate_user_data_string(const json& ud, const char* key)
{
if (ud.find(key) == ud.end() || !ud[key].is_string()) {
anon_log_error("no " << key << " in user data");
return false;
}
return true;
}
bool validate_all_user_data_strings(const json& ud)
{
return validate_user_data_string(ud, "artifacts_ddb_table_name")
&& validate_user_data_string(ud, "artifacts_ddb_table_region")
&& validate_user_data_string(ud, "artifacts_ddb_table_primary_key")
&& validate_user_data_string(ud, "artifacts_s3_bucket")
&& validate_user_data_string(ud, "artifacts_s3_key");
}
std::shared_ptr<tef_app> curr_app;
} // namespace
teflon_state sync_teflon_app(const ec2_info &ec2i)
{
auto &ud = ec2i.user_data_js;
if (!validate_all_user_data_strings(ud))
return teflon_server_failed;
Aws::Client::ClientConfiguration ddb_config;
std::string region = ud["artifacts_ddb_table_region"];
ddb_config.region = region.c_str();
Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);
if (!curr_app)
create_empty_directory(ec2i, "");
std::string table_name = ud["artifacts_ddb_table_name"];
std::string p_key_name = ud["artifacts_ddb_table_primary_key_name"];
std::string p_key_value = ud["artifacts_ddb_table_primary_key_value"];
std::string s_key_name = ud["artifacts_ddb_table_secondary_key_name"];
std::string s_key_value = ud["artifacts_ddb_table_secondary_key_value"];
QueryRequest q_req;
q_req.WithTableName(table_name)
.WithKeyConditionExpression("#P = :p AND #S = :s")
.WithScanIndexForward(false)
.AddExpressionAttributeNames("#P", p_key_name)
.AddExpressionAttributeValues(":p", AttributeValue(p_key_value))
.AddExpressionAttributeNames("#S", s_key_name)
.AddExpressionAttributeValues(":s", AttributeValue(s_key_value));
auto outcome = ddbc.Query(q_req);
if (!outcome.IsSuccess())
anon_throw(std::runtime_error, "Query failed: " << outcome.GetError());
auto &result = outcome.GetResult();
auto &items = result.GetItems();
if (items.size() == 0)
anon_throw(std::runtime_error, "no item for " << p_key_value << "/" << s_key_value << " in ddb table " << table_name);
auto &cur_def = items[0];
auto end = cur_def.end();
auto uid_it = cur_def.find("uid");
if (uid_it == end)
anon_throw(std::runtime_error, "item missing \"uid\" entry");
auto uid = uid_it->second.GetS();
if (curr_app && uid == curr_app->id)
{
anon_log("current server definition matches running server, no-op");
return teflon_server_still_running;
}
auto files_it = cur_def.find("files");
auto exe_it = cur_def.find("entry");
auto ids_it = cur_def.find("fids");
if (files_it == end || exe_it == end || ids_it == end)
anon_throw(std::runtime_error, "current_server record missing required \"files\", \"entry\", and/or \"fids\" field(s)");
auto files_needed = files_it->second.GetSS();
auto file_to_execute = exe_it->second.GetS();
auto ids = ids_it->second.GetM();
std::string bucket = ud["artifacts_s3_bucket"];
std::string key = ud["artifacts_s3_key"];
std::ostringstream files_cmd;
for (const auto &f : files_needed)
{
if (ids.find(f) == ids.end())
anon_throw(std::runtime_error, "file: \"" << f << "\" missing in fids");
if (curr_app && curr_app->files.find(f) != curr_app->files.end())
{
// f matches a file we have already downloaded, so just hard link it
// to the new directory
auto existing_file = curr_app->files[f];
files_cmd << "ln " << ec2i.root_dir << "/" << curr_app->id << "/" << curr_app->files[f]
<< " " << ec2i.root_dir << "/" << uid << "/" << f << " || exit 1 &\n";
}
else
{
// does not match an existing file, so download it from s3
files_cmd << "aws s3 cp s3://" << bucket << "/" << key
<< "/" << ids[f]->GetS() << "/" << f << " "
<< ec2i.root_dir << "/" << uid << "/" << f << " --quiet || exit 1 &\n";
}
}
create_empty_directory(ec2i, uid);
files_cmd << "wait < <(jobs -p)\n";
exe_cmd(files_cmd.str());
std::ostringstream ef;
ef << ec2i.root_dir << "/" << uid << "/" << file_to_execute;
auto efs = ef.str();
chmod(efs.c_str(), ACCESSPERMS);
try
{
auto new_app = std::make_shared<tef_app>(uid, files_needed, ids);
start_server(efs.c_str(), false /*do_tls*/, std::vector<std::string>());
if (curr_app)
remove_directory(ec2i, curr_app->id);
curr_app = new_app;
}
catch (const std::exception &exc)
{
anon_log_error("start_server failed: " << exc.what());
remove_directory(ec2i, uid);
return teflon_server_failed;
}
catch (...)
{
anon_log_error("start_server");
remove_directory(ec2i, uid);
return teflon_server_failed;
}
return teflon_server_running;
}
<commit_msg>bug fix<commit_after>/*
Copyright (c) 2020 ANON authors, see AUTHORS file.
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 "sync_teflon_app.h"
#include "log.h"
#include "sproc_mgr.h"
#include "nlohmann/json.hpp"
#include <sys/stat.h>
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/QueryRequest.h>
using namespace nlohmann;
using namespace Aws::DynamoDB::Model;
namespace
{
struct tef_app
{
tef_app(const Aws::String &id,
const Aws::Vector<Aws::String> &filesv,
Aws::Map<Aws::String, const std::shared_ptr<AttributeValue>> &fids)
: id(id)
{
for (auto &f : filesv)
{
files[fids[f]->GetS()] = f;
}
}
Aws::String id;
std::map<Aws::String, Aws::String> files;
};
void exe_cmd(const std::string &str)
{
std::string cmd = "bash -c '" + str + "'";
auto f = popen(cmd.c_str(), "r");
if (f)
{
auto exit_code = pclose(f);
if (exit_code != 0)
anon_throw(std::runtime_error, "command: " << str << " exited non-zero: " << error_string(exit_code));
}
else
{
anon_throw(std::runtime_error, "popen failed: " << errno_string());
}
}
void create_empty_directory(const ec2_info &ec2i, const Aws::String &id)
{
auto dir = ec2i.root_dir;
if (id.size() != 0)
{
dir += "/";
dir += id.c_str();
}
std::ostringstream oss;
oss << "rm -rf " << dir << " && mkdir " << dir;
exe_cmd(oss.str());
}
void remove_directory(const ec2_info &ec2i, const Aws::String &id)
{
auto dir = ec2i.root_dir;
if (id.size() != 0)
{
dir += "/";
dir += id.c_str();
}
std::ostringstream oss;
oss << "rm -rf " << id;
exe_cmd(oss.str());
}
bool validate_user_data_string(const json& ud, const char* key)
{
if (ud.find(key) == ud.end() || !ud[key].is_string()) {
anon_log_error("no " << key << " in user data");
return false;
}
return true;
}
bool validate_all_user_data_strings(const json& ud)
{
return validate_user_data_string(ud, "artifacts_ddb_table_region")
&& validate_user_data_string(ud, "artifacts_ddb_table_name")
&& validate_user_data_string(ud, "artifacts_ddb_table_primary_key_name")
&& validate_user_data_string(ud, "artifacts_ddb_table_primary_key_value")
&& validate_user_data_string(ud, "artifacts_ddb_table_secondary_key_name")
&& validate_user_data_string(ud, "artifacts_ddb_table_secondary_key_value")
&& validate_user_data_string(ud, "artifacts_s3_bucket")
&& validate_user_data_string(ud, "artifacts_s3_key");
}
std::shared_ptr<tef_app> curr_app;
} // namespace
teflon_state sync_teflon_app(const ec2_info &ec2i)
{
auto &ud = ec2i.user_data_js;
if (!validate_all_user_data_strings(ud))
return teflon_server_failed;
Aws::Client::ClientConfiguration ddb_config;
std::string region = ud["artifacts_ddb_table_region"];
ddb_config.region = region.c_str();
Aws::DynamoDB::DynamoDBClient ddbc(ddb_config);
if (!curr_app)
create_empty_directory(ec2i, "");
std::string table_name = ud["artifacts_ddb_table_name"];
std::string p_key_name = ud["artifacts_ddb_table_primary_key_name"];
std::string p_key_value = ud["artifacts_ddb_table_primary_key_value"];
std::string s_key_name = ud["artifacts_ddb_table_secondary_key_name"];
std::string s_key_value = ud["artifacts_ddb_table_secondary_key_value"];
QueryRequest q_req;
q_req.WithTableName(table_name)
.WithKeyConditionExpression("#P = :p AND #S = :s")
.WithScanIndexForward(false)
.AddExpressionAttributeNames("#P", p_key_name)
.AddExpressionAttributeValues(":p", AttributeValue(p_key_value))
.AddExpressionAttributeNames("#S", s_key_name)
.AddExpressionAttributeValues(":s", AttributeValue(s_key_value));
auto outcome = ddbc.Query(q_req);
if (!outcome.IsSuccess())
anon_throw(std::runtime_error, "Query failed: " << outcome.GetError());
auto &result = outcome.GetResult();
auto &items = result.GetItems();
if (items.size() == 0)
anon_throw(std::runtime_error, "no item for " << p_key_value << "/" << s_key_value << " in ddb table " << table_name);
auto &cur_def = items[0];
auto end = cur_def.end();
auto uid_it = cur_def.find("uid");
if (uid_it == end)
anon_throw(std::runtime_error, "item missing \"uid\" entry");
auto uid = uid_it->second.GetS();
if (curr_app && uid == curr_app->id)
{
anon_log("current server definition matches running server, no-op");
return teflon_server_still_running;
}
auto files_it = cur_def.find("files");
auto exe_it = cur_def.find("entry");
auto ids_it = cur_def.find("fids");
if (files_it == end || exe_it == end || ids_it == end)
anon_throw(std::runtime_error, "current_server record missing required \"files\", \"entry\", and/or \"fids\" field(s)");
auto files_needed = files_it->second.GetSS();
auto file_to_execute = exe_it->second.GetS();
auto ids = ids_it->second.GetM();
std::string bucket = ud["artifacts_s3_bucket"];
std::string key = ud["artifacts_s3_key"];
std::ostringstream files_cmd;
for (const auto &f : files_needed)
{
if (ids.find(f) == ids.end())
anon_throw(std::runtime_error, "file: \"" << f << "\" missing in fids");
if (curr_app && curr_app->files.find(f) != curr_app->files.end())
{
// f matches a file we have already downloaded, so just hard link it
// to the new directory
auto existing_file = curr_app->files[f];
files_cmd << "ln " << ec2i.root_dir << "/" << curr_app->id << "/" << curr_app->files[f]
<< " " << ec2i.root_dir << "/" << uid << "/" << f << " || exit 1 &\n";
}
else
{
// does not match an existing file, so download it from s3
files_cmd << "aws s3 cp s3://" << bucket << "/" << key
<< "/" << ids[f]->GetS() << "/" << f << " "
<< ec2i.root_dir << "/" << uid << "/" << f << " --quiet || exit 1 &\n";
}
}
create_empty_directory(ec2i, uid);
files_cmd << "wait < <(jobs -p)\n";
exe_cmd(files_cmd.str());
std::ostringstream ef;
ef << ec2i.root_dir << "/" << uid << "/" << file_to_execute;
auto efs = ef.str();
chmod(efs.c_str(), ACCESSPERMS);
try
{
auto new_app = std::make_shared<tef_app>(uid, files_needed, ids);
start_server(efs.c_str(), false /*do_tls*/, std::vector<std::string>());
if (curr_app)
remove_directory(ec2i, curr_app->id);
curr_app = new_app;
}
catch (const std::exception &exc)
{
anon_log_error("start_server failed: " << exc.what());
remove_directory(ec2i, uid);
return teflon_server_failed;
}
catch (...)
{
anon_log_error("start_server");
remove_directory(ec2i, uid);
return teflon_server_failed;
}
return teflon_server_running;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2015 Jonathan Hale <squareys@googlemail.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.
*/
#include <Corrade/PluginManager/PluginManager.h>
#include <Magnum/Audio/AbstractImporter.h>
#include <Magnum/Audio/Buffer.h>
#include <Magnum/Audio/Context.h>
#include <Magnum/Audio/Renderer.h>
#include <Magnum/Audio/Source.h>
#include <Magnum/Buffer.h>
#include <Magnum/DefaultFramebuffer.h>
#include <Magnum/Math/Range.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/MeshTools/CompressIndices.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Renderer.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Object.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/Shaders/Flat.h>
#include <Magnum/Texture.h>
#include <Magnum/TextureFormat.h>
#include <Magnum/Trade/AbstractImporter.h>
#include <Magnum/Trade/ImageData.h>
#include "configure.h"
#include "TexturedDrawable2D.h"
#include "Types.h"
namespace Magnum {namespace Examples {
class AudioExample: public Platform::Application {
public:
explicit AudioExample(const Arguments& arguments);
private:
void drawEvent() override;
void mousePressEvent(MouseEvent& event) override;
void mouseMoveEvent(MouseMoveEvent& event) override;
void updateSourceTranslation(const Vector2i& mousePos);
Buffer _vertexBuffer;
Mesh _mesh;
Shaders::Flat2D _shader;
/* Scene objects */
Scene2D _scene;
SceneGraph::Camera2D _camera;
Object2D _sourceTopObject;
Object2D _sourceFrontObject;
/* Drawable groups, separated per viewport */
SceneGraph::DrawableGroup2D _drawablesFront;
SceneGraph::DrawableGroup2D _drawablesTop;
/* Drawables */
std::unique_ptr<TexturedDrawable2D> _listenerFront;
std::unique_ptr<TexturedDrawable2D> _listenerTop;
std::unique_ptr<TexturedDrawable2D> _sourceFront;
std::unique_ptr<TexturedDrawable2D> _sourceTop;
/* Textures */
Texture2D _textureListenerTop;
Texture2D _textureListenerFront;
Texture2D _textureSource;
/* Viewports ranges */
Range2Di _leftViewport;
Range2Di _rightViewport;
/* Audio related members */
Audio::Context _context;
Audio::Buffer _testBuffer;
Audio::Source _source;
Corrade::Containers::Array<char> _bufferData;
};
AudioExample::AudioExample(const Arguments& arguments):
Platform::Application{arguments, Configuration{}.setTitle("Magnum Audio Example")},
_shader(Shaders::Flat2D::Flag::Textured),
_scene(),
_camera(_scene),
_sourceTopObject(&_scene),
_sourceFrontObject(&_scene),
_leftViewport(),
_rightViewport(),
_context(), /* Create the audio context. Without this, sound will not be initialized. */
_testBuffer(),
_source()
{
/* Create a 2D plane for rendering all the sprites. */
_vertexBuffer.setData(MeshTools::interleave(std::vector<Vector2>{
{1.0f, -1.0f},
{1.0f, 1.0f},
{-1.0f, -1.0f},
{-1.0f, 1.0f}
}, std::vector<Vector2>{
{1.0f, 0.0f},
{1.0f, 1.0f},
{0.0f, 0.0f},
{0.0f, 1.0f}
}), BufferUsage::StaticDraw);
_mesh.setPrimitive(MeshPrimitive::TriangleStrip)
.setCount(4)
.addVertexBuffer(_vertexBuffer, 0, Shaders::Flat2D::Position{}, Shaders::Flat2D::TextureCoordinates{});
/* Prepare viewports for top view (on the right) and front view (on the left) */
const Vector2i halfViewport = defaultFramebuffer.viewport().size()*Vector2::xScale(0.5f);
_leftViewport = Range2Di::fromSize({}, halfViewport);
_rightViewport = Range2Di::fromSize({halfViewport.x(), 0}, halfViewport);
/* Setup camera to scale down pixel measure to -1.0;1.0 on x and y according to aspect ratio for both viewports */
_camera.setProjectionMatrix(Matrix3::projection({1.0f, 1.f/Vector2{halfViewport}.aspectRatio()}));
/* Load TGA importer plugin */
PluginManager::Manager<Trade::AbstractImporter> imageManager{MAGNUM_PLUGINS_IMPORTER_DIR};
PluginManager::Manager<Audio::AbstractImporter> audioManager{MAGNUM_PLUGINS_AUDIOIMPORTER_DIR};
if(!(imageManager.load("TgaImporter") & PluginManager::LoadState::Loaded))
std::exit(1);
std::unique_ptr<Trade::AbstractImporter> importer = imageManager.instance("TgaImporter");
if(!(audioManager.load("WavAudioImporter") & PluginManager::LoadState::Loaded))
std::exit(1);
std::unique_ptr<Audio::AbstractImporter> wavImporter = audioManager.instance("WavAudioImporter");
/* Load the textures from compiled resources */
const Utility::Resource rs{"audio-data"};
if(!importer->openData(rs.getRaw("source.tga")))
std::exit(2);
std::optional<Trade::ImageData2D> image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureSource.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
if(!importer->openData(rs.getRaw("listener_top.tga")))
std::exit(2);
image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureListenerTop.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
if(!importer->openData(rs.getRaw("listener_front.tga")))
std::exit(2);
image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureListenerFront.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
/* Load wav file */
if(!wavImporter->openData(rs.getRaw("test.wav")))
std::exit(2);
_bufferData = wavImporter->data(); /* Get the data from importer */
/* Add the sample data to the buffer */
_testBuffer.setData(wavImporter->format(), _bufferData, wavImporter->frequency());
/* Make our sound source play the buffer again and again... */
_source.setBuffer(&_testBuffer);
_source.setLooping(true);
_source.play();
/* Create and add drawables to scene */
_listenerFront.reset(new TexturedDrawable2D(_mesh, _shader, _textureListenerFront, _scene, _drawablesFront));
_listenerTop.reset(new TexturedDrawable2D(_mesh, _shader, _textureListenerTop, _scene, _drawablesTop));
_sourceFront.reset(new TexturedDrawable2D(_mesh, _shader, _textureSource, _sourceFrontObject, _drawablesFront));
_sourceTop.reset(new TexturedDrawable2D(_mesh, _shader, _textureSource, _sourceTopObject, _drawablesTop));
/* We do not need depth test, drawing order is fine. */
Renderer::disable(Renderer::Feature::DepthTest);
/* Enable blending for alpha channel in textures. */
Renderer::enable(Renderer::Feature::Blending);
Renderer::setBlendFunction(Renderer::BlendFunction::SourceAlpha, Renderer::BlendFunction::OneMinusSourceAlpha);
Renderer::setClearColor({0.6, 0.6, 0.6, 1.0});
/* setup image scaling since the plane is currently larger than the screen. */
_sourceFront->scale({0.1, 0.1});
_sourceTop->scale({0.1, 0.1});
_listenerFront->scale({0.1, 0.1});
_listenerTop->scale({0.1, 0.05});
/* initial positioning of sound source */
_sourceTopObject.translate({0.5, 0.3});
_sourceFrontObject.translate({0.5, 0.3});
/* set initial sound source position to match the visualization */
_source.setPosition(Vector3i{5, 3, 3});
}
void AudioExample::updateSourceTranslation(const Vector2i& mousePos) {
const Vector2 normalized = Vector2{mousePos}/Vector2{_leftViewport.size()} - Vector2{0.5f};
const Vector2 position = normalized*Vector2::yScale(-1.0f)*_camera.projectionSize();
Vector2 newTop = {position.x(), _sourceTopObject.transformation().translation().y()};
Vector2 newFront = {position.x(), _sourceFrontObject.transformation().translation().y()};
if (normalized.x() > 0.5f) {
/* clicked on the right viewport/"top view" */
newTop.y() = position.y();
newFront.x() -= 1.0f;
newTop.x() -= 1.0f;
} else {
/* clicked on the left viewport/"front view" */
newFront.y() = position.y();
}
_sourceTopObject.setTransformation(Matrix3::translation(newTop));
_sourceFrontObject.setTransformation(Matrix3::translation(newFront));
/* Update sound source position to new input */
_source.setPosition(Vector3i{Int(newTop.x()*10), Int(newFront.y()*10), Int(newTop.y()*10)});
}
void AudioExample::drawEvent() {
defaultFramebuffer.clear(FramebufferClear::Color);
defaultFramebuffer.setViewport(_leftViewport);
_camera.draw(_drawablesFront);
defaultFramebuffer.setViewport(_rightViewport);
_camera.draw(_drawablesTop);
swapBuffers();
}
void AudioExample::mousePressEvent(MouseEvent& event) {
if(event.button() != MouseEvent::Button::Left) return;
updateSourceTranslation(event.position());
event.setAccepted();
redraw();
}
void AudioExample::mouseMoveEvent(MouseMoveEvent& event) {
if(!(event.buttons() & MouseMoveEvent::Button::Left)) return;
updateSourceTranslation(event.position());
event.setAccepted();
redraw();
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::AudioExample)
<commit_msg>audio: Remove custom clear color<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2015 Jonathan Hale <squareys@googlemail.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.
*/
#include <Corrade/PluginManager/PluginManager.h>
#include <Magnum/Audio/AbstractImporter.h>
#include <Magnum/Audio/Buffer.h>
#include <Magnum/Audio/Context.h>
#include <Magnum/Audio/Renderer.h>
#include <Magnum/Audio/Source.h>
#include <Magnum/Buffer.h>
#include <Magnum/DefaultFramebuffer.h>
#include <Magnum/Math/Range.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/MeshTools/CompressIndices.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Renderer.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Object.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/Shaders/Flat.h>
#include <Magnum/Texture.h>
#include <Magnum/TextureFormat.h>
#include <Magnum/Trade/AbstractImporter.h>
#include <Magnum/Trade/ImageData.h>
#include "configure.h"
#include "TexturedDrawable2D.h"
#include "Types.h"
namespace Magnum {namespace Examples {
class AudioExample: public Platform::Application {
public:
explicit AudioExample(const Arguments& arguments);
private:
void drawEvent() override;
void mousePressEvent(MouseEvent& event) override;
void mouseMoveEvent(MouseMoveEvent& event) override;
void updateSourceTranslation(const Vector2i& mousePos);
Buffer _vertexBuffer;
Mesh _mesh;
Shaders::Flat2D _shader;
/* Scene objects */
Scene2D _scene;
SceneGraph::Camera2D _camera;
Object2D _sourceTopObject;
Object2D _sourceFrontObject;
/* Drawable groups, separated per viewport */
SceneGraph::DrawableGroup2D _drawablesFront;
SceneGraph::DrawableGroup2D _drawablesTop;
/* Drawables */
std::unique_ptr<TexturedDrawable2D> _listenerFront;
std::unique_ptr<TexturedDrawable2D> _listenerTop;
std::unique_ptr<TexturedDrawable2D> _sourceFront;
std::unique_ptr<TexturedDrawable2D> _sourceTop;
/* Textures */
Texture2D _textureListenerTop;
Texture2D _textureListenerFront;
Texture2D _textureSource;
/* Viewports ranges */
Range2Di _leftViewport;
Range2Di _rightViewport;
/* Audio related members */
Audio::Context _context;
Audio::Buffer _testBuffer;
Audio::Source _source;
Corrade::Containers::Array<char> _bufferData;
};
AudioExample::AudioExample(const Arguments& arguments):
Platform::Application{arguments, Configuration{}.setTitle("Magnum Audio Example")},
_shader(Shaders::Flat2D::Flag::Textured),
_scene(),
_camera(_scene),
_sourceTopObject(&_scene),
_sourceFrontObject(&_scene),
_leftViewport(),
_rightViewport(),
_context(), /* Create the audio context. Without this, sound will not be initialized. */
_testBuffer(),
_source()
{
/* Create a 2D plane for rendering all the sprites. */
_vertexBuffer.setData(MeshTools::interleave(std::vector<Vector2>{
{1.0f, -1.0f},
{1.0f, 1.0f},
{-1.0f, -1.0f},
{-1.0f, 1.0f}
}, std::vector<Vector2>{
{1.0f, 0.0f},
{1.0f, 1.0f},
{0.0f, 0.0f},
{0.0f, 1.0f}
}), BufferUsage::StaticDraw);
_mesh.setPrimitive(MeshPrimitive::TriangleStrip)
.setCount(4)
.addVertexBuffer(_vertexBuffer, 0, Shaders::Flat2D::Position{}, Shaders::Flat2D::TextureCoordinates{});
/* Prepare viewports for top view (on the right) and front view (on the left) */
const Vector2i halfViewport = defaultFramebuffer.viewport().size()*Vector2::xScale(0.5f);
_leftViewport = Range2Di::fromSize({}, halfViewport);
_rightViewport = Range2Di::fromSize({halfViewport.x(), 0}, halfViewport);
/* Setup camera to scale down pixel measure to -1.0;1.0 on x and y according to aspect ratio for both viewports */
_camera.setProjectionMatrix(Matrix3::projection({1.0f, 1.f/Vector2{halfViewport}.aspectRatio()}));
/* Load TGA importer plugin */
PluginManager::Manager<Trade::AbstractImporter> imageManager{MAGNUM_PLUGINS_IMPORTER_DIR};
PluginManager::Manager<Audio::AbstractImporter> audioManager{MAGNUM_PLUGINS_AUDIOIMPORTER_DIR};
if(!(imageManager.load("TgaImporter") & PluginManager::LoadState::Loaded))
std::exit(1);
std::unique_ptr<Trade::AbstractImporter> importer = imageManager.instance("TgaImporter");
if(!(audioManager.load("WavAudioImporter") & PluginManager::LoadState::Loaded))
std::exit(1);
std::unique_ptr<Audio::AbstractImporter> wavImporter = audioManager.instance("WavAudioImporter");
/* Load the textures from compiled resources */
const Utility::Resource rs{"audio-data"};
if(!importer->openData(rs.getRaw("source.tga")))
std::exit(2);
std::optional<Trade::ImageData2D> image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureSource.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
if(!importer->openData(rs.getRaw("listener_top.tga")))
std::exit(2);
image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureListenerTop.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
if(!importer->openData(rs.getRaw("listener_front.tga")))
std::exit(2);
image = importer->image2D(0);
CORRADE_INTERNAL_ASSERT(image);
_textureListenerFront.setWrapping(Sampler::Wrapping::ClampToEdge)
.setMagnificationFilter(Sampler::Filter::Linear)
.setMinificationFilter(Sampler::Filter::Linear)
.setStorage(1, TextureFormat::RGBA8, image->size())
.setSubImage(0, {}, *image);
/* Load wav file */
if(!wavImporter->openData(rs.getRaw("test.wav")))
std::exit(2);
_bufferData = wavImporter->data(); /* Get the data from importer */
/* Add the sample data to the buffer */
_testBuffer.setData(wavImporter->format(), _bufferData, wavImporter->frequency());
/* Make our sound source play the buffer again and again... */
_source.setBuffer(&_testBuffer);
_source.setLooping(true);
_source.play();
/* Create and add drawables to scene */
_listenerFront.reset(new TexturedDrawable2D(_mesh, _shader, _textureListenerFront, _scene, _drawablesFront));
_listenerTop.reset(new TexturedDrawable2D(_mesh, _shader, _textureListenerTop, _scene, _drawablesTop));
_sourceFront.reset(new TexturedDrawable2D(_mesh, _shader, _textureSource, _sourceFrontObject, _drawablesFront));
_sourceTop.reset(new TexturedDrawable2D(_mesh, _shader, _textureSource, _sourceTopObject, _drawablesTop));
/* We do not need depth test, drawing order is fine. */
Renderer::disable(Renderer::Feature::DepthTest);
/* Enable blending for alpha channel in textures. */
Renderer::enable(Renderer::Feature::Blending);
Renderer::setBlendFunction(Renderer::BlendFunction::SourceAlpha, Renderer::BlendFunction::OneMinusSourceAlpha);
/* setup image scaling since the plane is currently larger than the screen. */
_sourceFront->scale({0.1, 0.1});
_sourceTop->scale({0.1, 0.1});
_listenerFront->scale({0.1, 0.1});
_listenerTop->scale({0.1, 0.05});
/* initial positioning of sound source */
_sourceTopObject.translate({0.5, 0.3});
_sourceFrontObject.translate({0.5, 0.3});
/* set initial sound source position to match the visualization */
_source.setPosition(Vector3i{5, 3, 3});
}
void AudioExample::updateSourceTranslation(const Vector2i& mousePos) {
const Vector2 normalized = Vector2{mousePos}/Vector2{_leftViewport.size()} - Vector2{0.5f};
const Vector2 position = normalized*Vector2::yScale(-1.0f)*_camera.projectionSize();
Vector2 newTop = {position.x(), _sourceTopObject.transformation().translation().y()};
Vector2 newFront = {position.x(), _sourceFrontObject.transformation().translation().y()};
if (normalized.x() > 0.5f) {
/* clicked on the right viewport/"top view" */
newTop.y() = position.y();
newFront.x() -= 1.0f;
newTop.x() -= 1.0f;
} else {
/* clicked on the left viewport/"front view" */
newFront.y() = position.y();
}
_sourceTopObject.setTransformation(Matrix3::translation(newTop));
_sourceFrontObject.setTransformation(Matrix3::translation(newFront));
/* Update sound source position to new input */
_source.setPosition(Vector3i{Int(newTop.x()*10), Int(newFront.y()*10), Int(newTop.y()*10)});
}
void AudioExample::drawEvent() {
defaultFramebuffer.clear(FramebufferClear::Color);
defaultFramebuffer.setViewport(_leftViewport);
_camera.draw(_drawablesFront);
defaultFramebuffer.setViewport(_rightViewport);
_camera.draw(_drawablesTop);
swapBuffers();
}
void AudioExample::mousePressEvent(MouseEvent& event) {
if(event.button() != MouseEvent::Button::Left) return;
updateSourceTranslation(event.position());
event.setAccepted();
redraw();
}
void AudioExample::mouseMoveEvent(MouseMoveEvent& event) {
if(!(event.buttons() & MouseMoveEvent::Button::Left)) return;
updateSourceTranslation(event.position());
event.setAccepted();
redraw();
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::AudioExample)
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/installer/setup/setup_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class SetupUtilTest : public testing::Test {
protected:
virtual void SetUp() {
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_));
data_dir_ = data_dir_.AppendASCII("installer");
ASSERT_TRUE(file_util::PathExists(data_dir_));
// Name a subdirectory of the user temp directory.
ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_));
test_dir_ = test_dir_.AppendASCII("SetupUtilTest");
// Create a fresh, empty copy of this test directory.
file_util::Delete(test_dir_, true);
file_util::CreateDirectory(test_dir_);
ASSERT_TRUE(file_util::PathExists(test_dir_));
}
virtual void TearDown() {
// Clean up test directory
ASSERT_TRUE(file_util::Delete(test_dir_, false));
ASSERT_FALSE(file_util::PathExists(test_dir_));
}
// the path to temporary directory used to contain the test operations
FilePath test_dir_;
// The path to input data used in tests.
FilePath data_dir_;
};
};
// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, ApplyDiffPatchTest) {
FilePath work_dir(test_dir_);
work_dir = work_dir.AppendASCII("ApplyDiffPatchTest");
ASSERT_FALSE(file_util::PathExists(work_dir));
EXPECT_TRUE(file_util::CreateDirectory(work_dir));
ASSERT_TRUE(file_util::PathExists(work_dir));
FilePath src = data_dir_.AppendASCII("archive1.7z");
FilePath patch = data_dir_.AppendASCII("archive.diff");
FilePath dest = work_dir.AppendASCII("archive2.7z");
EXPECT_EQ(setup_util::ApplyDiffPatch(src, patch, dest), 0);
FilePath base = data_dir_.AppendASCII("archive2.7z");
EXPECT_TRUE(file_util::ContentsEqual(dest, base));
EXPECT_EQ(setup_util::ApplyDiffPatch(FilePath(), FilePath(), FilePath()), 6);
}
// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, GetVersionFromDirTest) {
// Create a version dir
FilePath chrome_dir = test_dir_.AppendASCII("1.0.0.0");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
scoped_ptr<installer::Version> version(
setup_util::GetVersionFromDir(test_dir_));
ASSERT_TRUE(version->GetString() == L"1.0.0.0");
file_util::Delete(chrome_dir, true);
ASSERT_FALSE(file_util::PathExists(chrome_dir));
ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_) == NULL);
chrome_dir = test_dir_.AppendASCII("ABC");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_) == NULL);
chrome_dir = test_dir_.AppendASCII("2.3.4.5");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
version.reset(setup_util::GetVersionFromDir(test_dir_));
ASSERT_TRUE(version->GetString() == L"2.3.4.5");
}
<commit_msg>Fix setup_unittest.exe so it, you know, can ever possibly pass.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/installer/setup/setup_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class SetupUtilTest : public testing::Test {
protected:
virtual void SetUp() {
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_));
data_dir_ = data_dir_.AppendASCII("installer");
ASSERT_TRUE(file_util::PathExists(data_dir_));
// Create a temp directory for testing.
ASSERT_TRUE(test_dir_.CreateUniqueTempDir());
}
virtual void TearDown() {
// Clean up test directory manually so we can fail if it leaks.
ASSERT_TRUE(test_dir_.Delete());
}
// The temporary directory used to contain the test operations.
ScopedTempDir test_dir_;
// The path to input data used in tests.
FilePath data_dir_;
};
}
// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, ApplyDiffPatchTest) {
FilePath work_dir(test_dir_.path());
work_dir = work_dir.AppendASCII("ApplyDiffPatchTest");
ASSERT_FALSE(file_util::PathExists(work_dir));
EXPECT_TRUE(file_util::CreateDirectory(work_dir));
ASSERT_TRUE(file_util::PathExists(work_dir));
FilePath src = data_dir_.AppendASCII("archive1.7z");
FilePath patch = data_dir_.AppendASCII("archive.diff");
FilePath dest = work_dir.AppendASCII("archive2.7z");
EXPECT_EQ(setup_util::ApplyDiffPatch(src, patch, dest), 0);
FilePath base = data_dir_.AppendASCII("archive2.7z");
EXPECT_TRUE(file_util::ContentsEqual(dest, base));
EXPECT_EQ(setup_util::ApplyDiffPatch(FilePath(), FilePath(), FilePath()), 6);
}
// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, GetVersionFromDirTest) {
// Create a version dir
FilePath chrome_dir = test_dir_.path().AppendASCII("1.0.0.0");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
scoped_ptr<installer::Version> version(
setup_util::GetVersionFromDir(test_dir_.path()));
ASSERT_TRUE(version->GetString() == L"1.0.0.0");
file_util::Delete(chrome_dir, true);
ASSERT_FALSE(file_util::PathExists(chrome_dir));
ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_.path()) == NULL);
chrome_dir = test_dir_.path().AppendASCII("ABC");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_.path()) == NULL);
chrome_dir = test_dir_.path().AppendASCII("2.3.4.5");
file_util::CreateDirectory(chrome_dir);
ASSERT_TRUE(file_util::PathExists(chrome_dir));
version.reset(setup_util::GetVersionFromDir(test_dir_.path()));
ASSERT_TRUE(version->GetString() == L"2.3.4.5");
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright 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: Ali Saidi
* Andreas Hansson
*/
#ifndef __BASE_ADDR_RANGE_MAP_HH__
#define __BASE_ADDR_RANGE_MAP_HH__
#include <map>
#include <utility>
#include "base/addr_range.hh"
/**
* The AddrRangeMap uses an STL map to implement an interval tree for
* address decoding. The value stored is a template type and can be
* e.g. a port identifier, or a pointer.
*/
template <typename V, int max_cache_size=0>
class AddrRangeMap
{
private:
typedef std::map<AddrRange, V> RangeMap;
public:
typedef typename RangeMap::iterator iterator;
typedef typename RangeMap::const_iterator const_iterator;
/**
* Find entry that contains the given address range
*
* Searches through the ranges in the address map and returns an
* iterator to the entry which range is a superset of the input
* address range. Returns end() if none found.
*
* @param r An input address range
* @return An iterator that contains the input address range
*/
const_iterator
contains(const AddrRange &r) const
{
return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });
}
/**
* Find entry that contains the given address
*
* Searches through the ranges in the address map and returns an
* iterator to the entry which range is a superset of the input
* address. Returns end() if none found.
*
* @param r An input address
* @return An iterator that contains the input address
*/
const_iterator
contains(Addr r) const
{
return contains(RangeSize(r, 1));
}
/**
* Find entry that intersects with the given address range
*
* Searches through the ranges in the address map and returns an
* iterator to the first entry which range intersects with the
* input address.
*
* @param r An input address
* @return An iterator that intersects with the input address range
*/
const_iterator
intersects(const AddrRange &r) const
{
return find(r, [r](const AddrRange r1) { return r.intersects(r1); });
}
const_iterator
insert(const AddrRange &r, const V& d)
{
if (intersects(r) != end())
return tree.end();
return tree.insert(std::make_pair(r, d)).first;
}
void
erase(iterator p)
{
cache.remove(p);
tree.erase(p);
}
void
erase(iterator p, iterator q)
{
for (auto it = p; it != q; it++) {
cache.remove(p);
}
tree.erase(p,q);
}
void
clear()
{
cache.erase(cache.begin(), cache.end());
tree.erase(tree.begin(), tree.end());
}
const_iterator
begin() const
{
return tree.begin();
}
iterator
begin()
{
return tree.begin();
}
const_iterator
end() const
{
return tree.end();
}
iterator
end()
{
return tree.end();
}
std::size_t
size() const
{
return tree.size();
}
bool
empty() const
{
return tree.empty();
}
private:
/**
* Add an address range map entry to the cache.
*
* @param it Iterator to the entry in the address range map
*/
void
addNewEntryToCache(const_iterator it) const
{
if (max_cache_size != 0) {
// If there's a cache, add this element to it.
if (cache.size() >= max_cache_size) {
// If the cache is full, move the last element to the
// front and overwrite it with the new value. This
// avoids creating or destroying elements of the list.
auto last = cache.end();
last--;
*last = it;
if (max_cache_size > 1)
cache.splice(cache.begin(), cache, last);
} else {
cache.push_front(it);
}
}
}
/**
* Find entry that satisfies a condition on an address range
*
* Searches through the ranges in the address map and returns an
* iterator to the entry that satisfies the input conidition on
* the input address range. Returns end() if none found.
*
* @param r An input address range
* @param f A condition on an address range
* @return An iterator that contains the input address range
*/
const_iterator
find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const
{
// Check the cache first
for (auto c = cache.begin(); c != cache.end(); c++) {
auto it = *c;
if (cond(it->first)) {
// If this entry matches, promote it to the front
// of the cache and return it.
cache.splice(cache.begin(), cache, c);
return it;
}
}
const_iterator next = tree.upper_bound(r);
if (next != end() && cond(next->first)) {
addNewEntryToCache(next);
return next;
}
if (next == begin())
return end();
next--;
const_iterator i;
do {
i = next;
if (cond(i->first)) {
addNewEntryToCache(i);
return i;
}
// Keep looking if the next range merges with the current one.
} while (next != begin() &&
(--next)->first.mergesWith(i->first));
return end();
}
RangeMap tree;
/**
* A list of iterator that correspond to the max_cache_size most
* recently used entries in the address range map. This mainly
* used to optimize lookups. The elements in the list should
* always be valid iterators of the tree.
*/
mutable std::list<const_iterator> cache;
};
#endif //__BASE_ADDR_RANGE_MAP_HH__
<commit_msg>base: Fix includes in AddrRangeMap header file<commit_after>/*
* Copyright (c) 2012, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright 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: Ali Saidi
* Andreas Hansson
*/
#ifndef __BASE_ADDR_RANGE_MAP_HH__
#define __BASE_ADDR_RANGE_MAP_HH__
#include <cstddef>
#include <functional>
#include <list>
#include <map>
#include <utility>
#include "base/addr_range.hh"
#include "base/types.hh"
/**
* The AddrRangeMap uses an STL map to implement an interval tree for
* address decoding. The value stored is a template type and can be
* e.g. a port identifier, or a pointer.
*/
template <typename V, int max_cache_size=0>
class AddrRangeMap
{
private:
typedef std::map<AddrRange, V> RangeMap;
public:
typedef typename RangeMap::iterator iterator;
typedef typename RangeMap::const_iterator const_iterator;
/**
* Find entry that contains the given address range
*
* Searches through the ranges in the address map and returns an
* iterator to the entry which range is a superset of the input
* address range. Returns end() if none found.
*
* @param r An input address range
* @return An iterator that contains the input address range
*/
const_iterator
contains(const AddrRange &r) const
{
return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });
}
/**
* Find entry that contains the given address
*
* Searches through the ranges in the address map and returns an
* iterator to the entry which range is a superset of the input
* address. Returns end() if none found.
*
* @param r An input address
* @return An iterator that contains the input address
*/
const_iterator
contains(Addr r) const
{
return contains(RangeSize(r, 1));
}
/**
* Find entry that intersects with the given address range
*
* Searches through the ranges in the address map and returns an
* iterator to the first entry which range intersects with the
* input address.
*
* @param r An input address
* @return An iterator that intersects with the input address range
*/
const_iterator
intersects(const AddrRange &r) const
{
return find(r, [r](const AddrRange r1) { return r.intersects(r1); });
}
const_iterator
insert(const AddrRange &r, const V& d)
{
if (intersects(r) != end())
return tree.end();
return tree.insert(std::make_pair(r, d)).first;
}
void
erase(iterator p)
{
cache.remove(p);
tree.erase(p);
}
void
erase(iterator p, iterator q)
{
for (auto it = p; it != q; it++) {
cache.remove(p);
}
tree.erase(p,q);
}
void
clear()
{
cache.erase(cache.begin(), cache.end());
tree.erase(tree.begin(), tree.end());
}
const_iterator
begin() const
{
return tree.begin();
}
iterator
begin()
{
return tree.begin();
}
const_iterator
end() const
{
return tree.end();
}
iterator
end()
{
return tree.end();
}
std::size_t
size() const
{
return tree.size();
}
bool
empty() const
{
return tree.empty();
}
private:
/**
* Add an address range map entry to the cache.
*
* @param it Iterator to the entry in the address range map
*/
void
addNewEntryToCache(const_iterator it) const
{
if (max_cache_size != 0) {
// If there's a cache, add this element to it.
if (cache.size() >= max_cache_size) {
// If the cache is full, move the last element to the
// front and overwrite it with the new value. This
// avoids creating or destroying elements of the list.
auto last = cache.end();
last--;
*last = it;
if (max_cache_size > 1)
cache.splice(cache.begin(), cache, last);
} else {
cache.push_front(it);
}
}
}
/**
* Find entry that satisfies a condition on an address range
*
* Searches through the ranges in the address map and returns an
* iterator to the entry that satisfies the input conidition on
* the input address range. Returns end() if none found.
*
* @param r An input address range
* @param f A condition on an address range
* @return An iterator that contains the input address range
*/
const_iterator
find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const
{
// Check the cache first
for (auto c = cache.begin(); c != cache.end(); c++) {
auto it = *c;
if (cond(it->first)) {
// If this entry matches, promote it to the front
// of the cache and return it.
cache.splice(cache.begin(), cache, c);
return it;
}
}
const_iterator next = tree.upper_bound(r);
if (next != end() && cond(next->first)) {
addNewEntryToCache(next);
return next;
}
if (next == begin())
return end();
next--;
const_iterator i;
do {
i = next;
if (cond(i->first)) {
addNewEntryToCache(i);
return i;
}
// Keep looking if the next range merges with the current one.
} while (next != begin() &&
(--next)->first.mergesWith(i->first));
return end();
}
RangeMap tree;
/**
* A list of iterator that correspond to the max_cache_size most
* recently used entries in the address range map. This mainly
* used to optimize lookups. The elements in the list should
* always be valid iterators of the tree.
*/
mutable std::list<const_iterator> cache;
};
#endif //__BASE_ADDR_RANGE_MAP_HH__
<|endoftext|>
|
<commit_before>// Day24.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct Node;
typedef std::pair<size_t, size_t> Vector2D;
typedef std::shared_ptr<Node> NodePtr;
typedef std::vector<NodePtr> NodeVector;
typedef std::pair<NodePtr, size_t> NodeDistance;
typedef std::vector<NodeDistance> NodeDistanceVector;
struct Node
{
size_t Number;
NodeDistanceVector Neighbors;
};
NodeVector GetNodes(const std::string & InputFile);
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map);
uint64_t GetShortestRoute(const NodeVector & Nodes);
int main()
{
NodeVector Nodes = GetNodes("Input.txt");
/*
for (auto & Node : Nodes)
{
std::cout << Node->Number << ": ";
for (auto & Neighbor : Node->Neighbors)
{
std::cout << Neighbor.first->Number << "->" << std::setw(5) << Neighbor.second << " ";
}
std::cout << std::endl;
}
*/
std::cout << "Steps: " << GetShortestRoute(Nodes) << std::endl;
system("pause");
return 0;
}
NodeVector GetNodes(const std::string & InputFile)
{
const StringVector Lines = GetFileLines(InputFile);
std::map<size_t, Vector2D> Points;
for (size_t Y = 0; Y < Lines.size(); Y++)
{
const std::string & Line = Lines[Y];
for (size_t X = 0; X < Line.size(); X++)
{
if (Line[X] == '.' || Line[X] == '#')
continue;
Points.insert({ static_cast<size_t>(Line[X] - '0'), { X, Y } });
}
}
NodeVector Nodes(Points.size());
std::generate(Nodes.begin(), Nodes.end(), std::make_shared<Node>);
for (auto Point : Points)
{
Nodes[Point.first]->Number = Point.first;
FloodFill(Point.second, Nodes[Point.first], Nodes, Lines);
}
return Nodes;
}
void Add(Vector2D Position, std::set<Vector2D> & VisitedPosition, std::list<Vector2D> & NewPositions, NodePtr & Node, NodeVector & Nodes, const StringVector & Map, size_t Distance)
{
char Tile = Map[Position.second][Position.first];
if (Tile == '#')
return;
auto Result = VisitedPosition.insert(Position);
if (!Result.second)
return;
NewPositions.push_back(Position);
if (Tile != '.')
{
size_t NodeId = Tile - '0';
NodePtr OtherNode = Nodes[NodeId];
for (auto Neighbor : Node->Neighbors)
{
if (Neighbor.first == OtherNode)
return;
}
Node->Neighbors.emplace_back(OtherNode, Distance);
OtherNode->Neighbors.emplace_back(Node, Distance);
}
}
void DebugPrint(const std::set<Vector2D> & VisitedPositions, const std::list<Vector2D> & New, const std::list<Vector2D> & Open, const StringVector & Map)
{
constexpr char Visited = '0';
constexpr char NewChar = '.';
constexpr char OpenChar = 'X';
system("cls");
for (size_t Y = 0; Y < Map.size(); ++Y)
{
for (size_t X = 0; X < Map[Y].size(); ++X)
{
Vector2D Position = { X ,Y };
if (std::find(New.begin(), New.end(), Position) != New.end())
{
std::cout << NewChar;
continue;
}
if (std::find(Open.begin(), Open.end(), Position) != Open.end())
{
std::cout << OpenChar;
continue;
}
if (VisitedPositions.find(Position) != VisitedPositions.end())
{
std::cout << Visited;
continue;
}
switch(Map[Y][X])
{
case '#':
std::cout << '+';
break;
case '.':
std::cout << ' ';
break;
default:
std::cout << Map[Y][X];
}
}
std::cout << std::endl;
}
system("pause");
}
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map)
{
std::list<Vector2D> NewPositions({ Start });
std::list<Vector2D> OpenPositions;
std::set<Vector2D> VisitedPosition({ Start });
size_t Distance = 0;
do {
//DebugPrint(VisitedPosition, NewPositions, OpenPositions, Map);
std::swap(NewPositions, OpenPositions);
Distance++;
while (!OpenPositions.empty())
{
Vector2D Pos = OpenPositions.front();
OpenPositions.pop_front();
if (Pos.first > 0)
Add({ Pos.first - 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.first < Map[0].size())
Add({ Pos.first + 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.second > 0)
Add({ Pos.first, Pos.second - 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.second < Map.size())
Add({ Pos.first, Pos.second + 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
}
} while (!NewPositions.empty());
}
uint64_t GetShortestRouteRec(const NodePtr Node, std::vector<NodePtr> VisitedNodes,const uint64_t RouteDistance, uint64_t ShortestRouteSoFar, const size_t NodeCount)
{
if (RouteDistance > ShortestRouteSoFar)
return ShortestRouteSoFar;
VisitedNodes.push_back(Node);
if (VisitedNodes.size() == NodeCount)
{
/*
for (auto & PathNode : VisitedNodes)
{
std::cout << PathNode->Number << " -> ";
}
std::cout << std::endl;
*/
return RouteDistance;
}
for (const NodeDistance & OtherNode : Node->Neighbors)
{
if (std::find(VisitedNodes.begin(), VisitedNodes.end(), OtherNode.first) != VisitedNodes.end())
continue;
ShortestRouteSoFar = std::min(ShortestRouteSoFar, GetShortestRouteRec(OtherNode.first, VisitedNodes, RouteDistance + OtherNode.second, ShortestRouteSoFar, NodeCount));
}
return ShortestRouteSoFar;
}
uint64_t GetShortestRoute(const NodeVector & Nodes)
{
uint64_t ShortestRouteDistance = UINT64_MAX;
ShortestRouteDistance = GetShortestRouteRec(Nodes[0], {}, 0, ShortestRouteDistance, Nodes.size());
return ShortestRouteDistance;
}<commit_msg>Day 24 part two<commit_after>// Day24.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct Node;
typedef std::pair<size_t, size_t> Vector2D;
typedef std::shared_ptr<Node> NodePtr;
typedef std::vector<NodePtr> NodeVector;
typedef std::pair<NodePtr, size_t> NodeDistance;
typedef std::vector<NodeDistance> NodeDistanceVector;
struct Node
{
size_t Number;
NodeDistanceVector Neighbors;
};
NodeVector GetNodes(const std::string & InputFile);
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map);
uint64_t GetShortestRoute(const NodeVector & Nodes, NodePtr EndNode);
int main()
{
NodeVector Nodes = GetNodes("Input.txt");
/*
for (auto & Node : Nodes)
{
std::cout << Node->Number << ": ";
for (auto & Neighbor : Node->Neighbors)
{
std::cout << Neighbor.first->Number << "->" << std::setw(5) << Neighbor.second << " ";
}
std::cout << std::endl;
}
*/
std::cout << "Part One: " << GetShortestRoute(Nodes, nullptr) << std::endl;
std::cout << "Part Two: " << GetShortestRoute(Nodes, Nodes[0]) << std::endl;
system("pause");
return 0;
}
NodeVector GetNodes(const std::string & InputFile)
{
const StringVector Lines = GetFileLines(InputFile);
std::map<size_t, Vector2D> Points;
for (size_t Y = 0; Y < Lines.size(); Y++)
{
const std::string & Line = Lines[Y];
for (size_t X = 0; X < Line.size(); X++)
{
if (Line[X] == '.' || Line[X] == '#')
continue;
Points.insert({ static_cast<size_t>(Line[X] - '0'), { X, Y } });
}
}
NodeVector Nodes(Points.size());
std::generate(Nodes.begin(), Nodes.end(), std::make_shared<Node>);
for (auto Point : Points)
{
Nodes[Point.first]->Number = Point.first;
FloodFill(Point.second, Nodes[Point.first], Nodes, Lines);
}
return Nodes;
}
void Add(Vector2D Position, std::set<Vector2D> & VisitedPosition, std::list<Vector2D> & NewPositions, NodePtr & Node, NodeVector & Nodes, const StringVector & Map, size_t Distance)
{
char Tile = Map[Position.second][Position.first];
if (Tile == '#')
return;
auto Result = VisitedPosition.insert(Position);
if (!Result.second)
return;
NewPositions.push_back(Position);
if (Tile != '.')
{
size_t NodeId = Tile - '0';
NodePtr OtherNode = Nodes[NodeId];
for (auto Neighbor : Node->Neighbors)
{
if (Neighbor.first == OtherNode)
return;
}
Node->Neighbors.emplace_back(OtherNode, Distance);
OtherNode->Neighbors.emplace_back(Node, Distance);
}
}
void DebugPrint(const std::set<Vector2D> & VisitedPositions, const std::list<Vector2D> & New, const std::list<Vector2D> & Open, const StringVector & Map)
{
constexpr char Visited = '0';
constexpr char NewChar = '.';
constexpr char OpenChar = 'X';
system("cls");
for (size_t Y = 0; Y < Map.size(); ++Y)
{
for (size_t X = 0; X < Map[Y].size(); ++X)
{
Vector2D Position = { X ,Y };
if (std::find(New.begin(), New.end(), Position) != New.end())
{
std::cout << NewChar;
continue;
}
if (std::find(Open.begin(), Open.end(), Position) != Open.end())
{
std::cout << OpenChar;
continue;
}
if (VisitedPositions.find(Position) != VisitedPositions.end())
{
std::cout << Visited;
continue;
}
switch(Map[Y][X])
{
case '#':
std::cout << '+';
break;
case '.':
std::cout << ' ';
break;
default:
std::cout << Map[Y][X];
}
}
std::cout << std::endl;
}
system("pause");
}
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map)
{
std::list<Vector2D> NewPositions({ Start });
std::list<Vector2D> OpenPositions;
std::set<Vector2D> VisitedPosition({ Start });
size_t Distance = 0;
do {
//DebugPrint(VisitedPosition, NewPositions, OpenPositions, Map);
std::swap(NewPositions, OpenPositions);
Distance++;
while (!OpenPositions.empty())
{
Vector2D Pos = OpenPositions.front();
OpenPositions.pop_front();
if (Pos.first > 0)
Add({ Pos.first - 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.first < Map[0].size())
Add({ Pos.first + 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.second > 0)
Add({ Pos.first, Pos.second - 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
if (Pos.second < Map.size())
Add({ Pos.first, Pos.second + 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);
}
} while (!NewPositions.empty());
}
uint64_t GetShortestRouteRec(const NodePtr Node, std::vector<NodePtr> VisitedNodes,const uint64_t RouteDistance, uint64_t ShortestRouteSoFar, const size_t NodeCount, NodePtr EndNode)
{
if (RouteDistance > ShortestRouteSoFar)
return ShortestRouteSoFar;
VisitedNodes.push_back(Node);
if (VisitedNodes.size() == NodeCount)
{
/*
for (auto & PathNode : VisitedNodes)
{
std::cout << PathNode->Number << " -> ";
}
std::cout << std::endl;
*/
if (!EndNode)
{
return RouteDistance;
}
else
{
auto Result = std::find_if(Node->Neighbors.begin(), Node->Neighbors.end(), [EndNode](const NodeDistance & Other)->bool { return Other.first == EndNode; });
if (Result != Node->Neighbors.end())
return RouteDistance + Result->second;
else
return ShortestRouteSoFar;
}
}
for (const NodeDistance & OtherNode : Node->Neighbors)
{
if (std::find(VisitedNodes.begin(), VisitedNodes.end(), OtherNode.first) != VisitedNodes.end())
continue;
ShortestRouteSoFar = std::min(ShortestRouteSoFar, GetShortestRouteRec(OtherNode.first, VisitedNodes, RouteDistance + OtherNode.second, ShortestRouteSoFar, NodeCount, EndNode));
}
return ShortestRouteSoFar;
}
uint64_t GetShortestRoute(const NodeVector & Nodes, NodePtr EndNode)
{
uint64_t ShortestRouteDistance = UINT64_MAX;
ShortestRouteDistance = GetShortestRouteRec(Nodes[0], {}, 0, ShortestRouteDistance, Nodes.size(), EndNode);
return ShortestRouteDistance;
}<|endoftext|>
|
<commit_before><commit_msg>option to enable/disable PMT shields and OldAD<commit_after><|endoftext|>
|
<commit_before>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#include <array>
#include <cstdint>
#include "AES_SBox.hpp"
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm Key Length Block Size Number of Rounds
// (Nk words) (Nb words) (Nr)
//
// AES-128 4 4 10
// AES-192 6 4 12
// AES-256 8 4 14
//
////////////////////////////////////////////////////////////////////////////////
// 5.2 Key Expansion
//
template <typename VAR, typename T, typename U, typename BITWISE>
class AES_KeyExpansion
{
public:
typedef VAR VarType;
typedef std::array<VAR, 16> Key128Type;
typedef std::array<VAR, 24> Key192Type;
typedef std::array<VAR, 32> Key256Type;
typedef std::array<VAR, 176> Schedule128Type;
typedef std::array<VAR, 208> Schedule192Type;
typedef std::array<VAR, 240> Schedule256Type;
AES_KeyExpansion() = default;
// AES-128
void operator() (const std::array<VAR, 16>& key,
std::array<VAR, 176>& w) const {
expand(key, w);
}
// AES-192
void operator() (const std::array<VAR, 24>& key,
std::array<VAR, 208>& w) const {
expand(key, w);
}
// AES-256
void operator() (const std::array<VAR, 32>& key,
std::array<VAR, 240>& w) const {
expand(key, w);
}
private:
// AES-128 max (4(Nr + 1) - 1)/Nk - 1 is 10 - 1 = 9
// AES-192 max (4(Nr + 1) - 1)/Nk - 1 is 8 - 1 = 7
// AES-256 max (4(Nr + 1) - 1)/Nk - 1 is 7 - 1 = 6
std::uint8_t rcon(const std::size_t i) const {
if (i < 8) {
// i = 0 is x^0 = 0x01 = 1 << 0
// i = 1 is x^1 = 0x02 = 1 << 1
// i = 2 is x^2 = 0x04 = 1 << 2
// i = 3 is x^3 = 0x08 = 1 << 3
// i = 4 is x^4 = 0x10 = 1 << 4
// i = 5 is x^5 = 0x20 = 1 << 5
// i = 6 is x^6 = 0x40 = 1 << 6
// i = 7 is x^7 = 0x80 = 1 << 7
return 1 << i;
} else if (8 == i) {
// i = 8 is x^4 + x^3 + x + 1 = 0x1b
return 0x1b;
} else if (9 == i) {
// i = 9 is x^5 + x^4 + x^2 + x = 0x36
return 0x36;
} else {
return 0; // should never happen
}
}
// AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)
// AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)
// AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)
template <std::size_t KSZ, std::size_t WSZ>
void expand(const std::array<VAR, KSZ>& key, // 4 * Nk octets
std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets
{
const std::size_t
Nk = key.size() / 4,
Nr = w.size() / 16 - 1;
for (std::size_t i = 0; i < Nk; ++i) {
w[4*i] = key[4*i];
w[4*i + 1] = key[4*i + 1];
w[4*i + 2] = key[4*i + 2];
w[4*i + 3] = key[4*i + 3];
}
for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {
std::array<VAR, 4> temp = { w[4*(i - 1)],
w[4*(i - 1) + 1],
w[4*(i - 1) + 2],
w[4*(i - 1) + 3] };
if (0 == i % Nk) {
const VAR tmp = temp[0];
temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i/Nk - 1)));
temp[1] = m_sbox(temp[2]);
temp[2] = m_sbox(temp[3]);
temp[3] = m_sbox(tmp);
} else if (Nk > 6 && 4 == i % Nk) {
temp[0] = m_sbox(temp[0]);
temp[1] = m_sbox(temp[1]);
temp[2] = m_sbox(temp[2]);
temp[3] = m_sbox(temp[3]);
}
w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);
w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);
w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);
w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);
}
}
const AES_SBox<T, U, BITWISE> m_sbox;
};
} // namespace snarkfront
#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#include <array>
#include <cstdint>
#include <snarkfront/AES_SBox.hpp>
namespace snarkfront {
////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm Key Length Block Size Number of Rounds
// (Nk words) (Nb words) (Nr)
//
// AES-128 4 4 10
// AES-192 6 4 12
// AES-256 8 4 14
//
////////////////////////////////////////////////////////////////////////////////
// 5.2 Key Expansion
//
template <typename VAR, typename T, typename U, typename BITWISE>
class AES_KeyExpansion
{
public:
typedef VAR VarType;
typedef std::array<VAR, 16> Key128Type;
typedef std::array<VAR, 24> Key192Type;
typedef std::array<VAR, 32> Key256Type;
typedef std::array<VAR, 176> Schedule128Type;
typedef std::array<VAR, 208> Schedule192Type;
typedef std::array<VAR, 240> Schedule256Type;
AES_KeyExpansion() = default;
// AES-128
void operator() (const std::array<VAR, 16>& key,
std::array<VAR, 176>& w) const {
expand(key, w);
}
// AES-192
void operator() (const std::array<VAR, 24>& key,
std::array<VAR, 208>& w) const {
expand(key, w);
}
// AES-256
void operator() (const std::array<VAR, 32>& key,
std::array<VAR, 240>& w) const {
expand(key, w);
}
private:
// AES-128 max (4(Nr + 1) - 1)/Nk - 1 is 10 - 1 = 9
// AES-192 max (4(Nr + 1) - 1)/Nk - 1 is 8 - 1 = 7
// AES-256 max (4(Nr + 1) - 1)/Nk - 1 is 7 - 1 = 6
std::uint8_t rcon(const std::size_t i) const {
if (i < 8) {
// i = 0 is x^0 = 0x01 = 1 << 0
// i = 1 is x^1 = 0x02 = 1 << 1
// i = 2 is x^2 = 0x04 = 1 << 2
// i = 3 is x^3 = 0x08 = 1 << 3
// i = 4 is x^4 = 0x10 = 1 << 4
// i = 5 is x^5 = 0x20 = 1 << 5
// i = 6 is x^6 = 0x40 = 1 << 6
// i = 7 is x^7 = 0x80 = 1 << 7
return 1 << i;
} else if (8 == i) {
// i = 8 is x^4 + x^3 + x + 1 = 0x1b
return 0x1b;
} else if (9 == i) {
// i = 9 is x^5 + x^4 + x^2 + x = 0x36
return 0x36;
} else {
return 0; // should never happen
}
}
// AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)
// AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)
// AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)
template <std::size_t KSZ, std::size_t WSZ>
void expand(const std::array<VAR, KSZ>& key, // 4 * Nk octets
std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets
{
const std::size_t
Nk = key.size() / 4,
Nr = w.size() / 16 - 1;
for (std::size_t i = 0; i < Nk; ++i) {
w[4*i] = key[4*i];
w[4*i + 1] = key[4*i + 1];
w[4*i + 2] = key[4*i + 2];
w[4*i + 3] = key[4*i + 3];
}
for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {
std::array<VAR, 4> temp = { w[4*(i - 1)],
w[4*(i - 1) + 1],
w[4*(i - 1) + 2],
w[4*(i - 1) + 3] };
if (0 == i % Nk) {
const VAR tmp = temp[0];
temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i/Nk - 1)));
temp[1] = m_sbox(temp[2]);
temp[2] = m_sbox(temp[3]);
temp[3] = m_sbox(tmp);
} else if (Nk > 6 && 4 == i % Nk) {
temp[0] = m_sbox(temp[0]);
temp[1] = m_sbox(temp[1]);
temp[2] = m_sbox(temp[2]);
temp[3] = m_sbox(temp[3]);
}
w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);
w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);
w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);
w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);
}
}
const AES_SBox<T, U, BITWISE> m_sbox;
};
} // namespace snarkfront
#endif
<|endoftext|>
|
<commit_before>#include "factor.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
bool fact(std::vector <std::string> *out, int input, const char *otherFacts, int level, int iter = 0) {
if (level == 0)
return false;
if (input < 0) input *=-1;
for (int d = input - 1; d > 1; --d) {
if (input % d == 0) {
char tmp1[256], tmp2[256];
sprintf(tmp1, "%d * %d%s%s", d, input / d, strlen(otherFacts) > 0 ? " * " : "", otherFacts);
sprintf(tmp2, "%s%s%d", otherFacts, strlen(otherFacts) > 0 ? " * " : "", input / d);
out->push_back(tmp1);
fact(out, d, tmp2, level - 1, iter + 1);
return true;
}
}
return false;
}
std::string factHelper(int input, int iterations) {
std::vector <std::string> out;
std::ostringstream s;
std::string equals;
s << input << "\n";
if (input >= 0)
equals = " = ";
else
equals = " = -";
if (!fact(&out, input, "", 20)) {
s << equals << input;
} else {
for (int i = 0; i < iterations && i < static_cast<int>(out.size()); ++i)
s << equals << out[i] << "\n";
}
return s.str();
}
Factorizer::Factorizer() {}
QString Factorizer::factorize(int in, int iterations) const {
qDebug() << "factorize called" << in << iterations;
return factHelper(in, iterations).c_str();
}
<commit_msg>Substitute Unicode '×' for the ASCII '*' in user-visible output.<commit_after>#include "factor.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
bool fact(std::vector <std::string> *out, int input, const char *otherFacts, int level, int iter = 0) {
if (level == 0)
return false;
if (input < 0) input *=-1;
for (int d = input - 1; d > 1; --d) {
if (input % d == 0) {
char tmp1[256], tmp2[256];
sprintf(tmp1, "%d * %d%s%s", d, input / d, strlen(otherFacts) > 0 ? " * " : "", otherFacts);
sprintf(tmp2, "%s%s%d", otherFacts, strlen(otherFacts) > 0 ? " * " : "", input / d);
out->push_back(tmp1);
fact(out, d, tmp2, level - 1, iter + 1);
return true;
}
}
return false;
}
std::string factHelper(int input, int iterations) {
std::vector <std::string> out;
std::ostringstream s;
std::string equals;
s << input << "\n";
if (input >= 0)
equals = " = ";
else
equals = " = -";
if (!fact(&out, input, "", 20)) {
s << equals << input;
} else {
for (int i = 0; i < iterations && i < static_cast<int>(out.size()); ++i)
s << equals << out[i] << "\n";
}
return s.str();
}
Factorizer::Factorizer() {}
QString Factorizer::factorize(int in, int iterations) const {
qDebug() << "factorize called" << in << iterations;
QString result = factHelper(in, iterations).c_str();
result.replace("*", "×");
return result;
}
<|endoftext|>
|
<commit_before>/*
* FDOmenu - Menu code generator for icewm
* Copyright (C) 2015 Eduard Bloch
*
* Inspired by icewm-menu-gnome2 and Freedesktop.org specifications
* Using pure glib/gio code and a built-in menu structure instead
* the XML based external definition (as suggested by FD.o specs)
*
* Release under terms of the GNU Library General Public License
* (version 2.0)
*
* 2015/02/05: Eduard Bloch <edi@gmx.de>
* - initial version
*/
#include "config.h"
#include "base.h"
#include "sysdep.h"
#include "intl.h"
#include <glib.h>
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include <gio/gdesktopappinfo.h>
template<class T>
struct auto_gfree
{
T *p;
auto_gfree(T *xp) : p(xp) {};
~auto_gfree() { g_free(p); }
};
bool find_in_zArray(const char * const *arrToScan, const char *keyword)
{
for(const gchar * const * p=arrToScan;*p;++p)
if(!strcmp(keyword, *p))
return true;
return false;
}
typedef GList* pglist;
pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
//#warning needing a dupe filter for filename, maybe use GHashTable for that
void proc_dir(const char *path, int depth=7)
{
if(!--depth)
return;
//printf("dir: %s\n", path);
GDir *pdir = g_dir_open (path, 0, NULL);
if(!pdir)
return;
const gchar *szFilename(NULL);
while(NULL != (szFilename = g_dir_read_name (pdir)))
{
if(!szFilename)
continue;
gchar *szFullName = g_strjoin("/", path, szFilename, 0);
auto_gfree<gchar> xxfree(szFullName);
static GStatBuf buf;
if(g_stat(szFullName, &buf))
return;
if(S_ISDIR(buf.st_mode))
proc_dir(szFullName, depth);
if(!S_ISREG(buf.st_mode))
return;
//printf("got: %s\n", szFullName);
GDesktopAppInfo *pInfo = g_desktop_app_info_new_from_filename (szFullName);
if(!pInfo)
continue;
if(!g_app_info_should_show((GAppInfo*) pInfo))
continue;
const char *cmdraw = g_app_info_get_commandline ((GAppInfo*) pInfo);
if(!cmdraw || !*cmdraw)
continue;
// let's whitespace all special fields that we don't support
gchar * cmd = g_strdup(cmdraw);
auto_gfree<gchar> cmdfree(cmd);
bool bDelChars=false;
for(gchar *p=cmd; *p; ++p)
{
if('%' == *p)
bDelChars=true;
if(bDelChars)
*p = ' ';
if(bDelChars && !isprint((unsigned)*p))
bDelChars=false;
}
const char *pName=g_app_info_get_name( (GAppInfo*) pInfo);
if(!pName)
continue;
const char *pCats=g_desktop_app_info_get_categories(pInfo);
if(!pCats)
pCats="Other";
//printf("icon: %s -> %s\n", pName, pCats);
const char *sicon = "-";
GIcon *pIcon=g_app_info_get_icon( (GAppInfo*) pInfo);
if (pIcon)
sicon = g_icon_to_string(pIcon);
char *menuLine = g_strdup_printf("# %s -> %s\n"
"prog \"%s\" %s %s\n",
szFullName, pCats,
pName, sicon, cmd);
//printf("%s", menuLine);
// pidgeonholing roughly by guessed menu structure
gchar **ppCats = g_strsplit(pCats, ";", -1);
if (find_in_zArray(ppCats, "Screensaver"))
mscreensavers = g_list_append(mscreensavers, menuLine);
else if (find_in_zArray(ppCats, "Settings"))
msettings = g_list_append(msettings, menuLine);
else if (find_in_zArray(ppCats, "Accessories"))
maccessories = g_list_append(maccessories, menuLine);
else if (find_in_zArray(ppCats, "Development"))
mdevelopment = g_list_append(mdevelopment, menuLine);
else if (find_in_zArray(ppCats, "Education"))
meducation = g_list_append(meducation, menuLine);
else if (find_in_zArray(ppCats, "Game"))
mgames = g_list_append(mgames, menuLine);
else if (find_in_zArray(ppCats, "Graphics"))
mgraphics = g_list_append(mgraphics, menuLine);
else if (find_in_zArray(ppCats, "Audio") || find_in_zArray(ppCats, "Video")
|| find_in_zArray(ppCats, "AudioVideo"))
{
mmultimedia = g_list_append(mmultimedia, menuLine);
}
else if (find_in_zArray(ppCats, "Network"))
mnetwork = g_list_append(mnetwork, menuLine);
else if (find_in_zArray(ppCats, "Office"))
moffice = g_list_append(moffice, menuLine);
else if (find_in_zArray(ppCats, "System") || find_in_zArray(ppCats, "Emulator"))
{
msystem = g_list_append(msystem, menuLine);
}
else
mother = g_list_append(mother, menuLine);
//fprintf(stderr, "jo, %s", menuLine);
}
g_dir_close(pdir);
}
void dump_menu()
{
/*
for (pglist l = msettings; l != NULL; l = l->next)
{
puts((char*) l->data);
}
*/
/*
pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
*/
struct tMenuHead {
char *title;
pglist pEntries;
tMenuHead(char *xt, pglist p) : title(xt), pEntries(p){};
};
pglist xmenu = 0;
// XXX: convert to g_list_insert_sorted using a locale based gcomp function
xmenu = g_list_append(xmenu, new tMenuHead(_("Settings"), msettings));
xmenu = g_list_append(xmenu, new tMenuHead(_("Screensavers"), mscreensavers));
xmenu = g_list_append(xmenu, new tMenuHead(_("Accessories"), maccessories));
xmenu = g_list_append(xmenu, new tMenuHead(_("Development"), mdevelopment));
xmenu = g_list_append(xmenu, new tMenuHead(_("Education"), meducation));
xmenu = g_list_append(xmenu, new tMenuHead(_("Games"), mgames));
xmenu = g_list_append(xmenu, new tMenuHead(_("Graphics"), mgraphics));
xmenu = g_list_append(xmenu, new tMenuHead(_("Multimedia"), mmultimedia));
xmenu = g_list_append(xmenu, new tMenuHead(_("Network"), mnetwork));
xmenu = g_list_append(xmenu, new tMenuHead(_("Office"), moffice));
xmenu = g_list_append(xmenu, new tMenuHead(_("System"), msystem));
xmenu = g_list_append(xmenu, new tMenuHead(_("Other"), mother));
for (pglist l = xmenu; l != NULL; l = l->next)
{
printf("menu \"%s\" folder {\n", ((tMenuHead*) l->data)->title);
for (pglist m = ((tMenuHead*) l->data)->pEntries; m != NULL; m = m->next)
{
puts((char*) m->data);
}
puts("}\n");
}
}
int main(int argc, char **) {
setlocale (LC_ALL, "");
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
const char * usershare=getenv("XDG_DATA_HOME"),
*sysshare=getenv("XDG_DATA_DIRS");
if(!usershare || !*usershare)
usershare=g_strjoin(NULL, getenv("HOME"), "/.local/share", NULL);
if(!sysshare || !*sysshare)
sysshare="/usr/local/share/:/usr/share/";
if(argc>1)
{
g_fprintf(stderr, "This program doesn't use command line options. It only listens to\n"
"environment variables defined by XDG Base Directory Specification.\n"
"XDG_DATA_HOME=%s\nXDG_DATA_DIRS=%s\n"
,usershare, sysshare);
return EXIT_FAILURE;
}
proc_dir(usershare);
gchar **ppDirs = g_strsplit (sysshare, ":", -1);
for(const gchar * const * p=ppDirs;*p;++p)
proc_dir(g_strjoin(0, *p, "/applications", 0));
dump_menu();
return EXIT_SUCCESS;
}
<commit_msg>Better recursion control<commit_after>/*
* FDOmenu - Menu code generator for icewm
* Copyright (C) 2015 Eduard Bloch
*
* Inspired by icewm-menu-gnome2 and Freedesktop.org specifications
* Using pure glib/gio code and a built-in menu structure instead
* the XML based external definition (as suggested by FD.o specs)
*
* Release under terms of the GNU Library General Public License
* (version 2.0)
*
* 2015/02/05: Eduard Bloch <edi@gmx.de>
* - initial version
*/
#include "config.h"
#include "base.h"
#include "sysdep.h"
#include "intl.h"
#include <glib.h>
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include <gio/gdesktopappinfo.h>
template<class T>
struct auto_gfree
{
T *p;
auto_gfree(T *xp) : p(xp) {};
~auto_gfree() { g_free(p); }
};
bool find_in_zArray(const char * const *arrToScan, const char *keyword)
{
for(const gchar * const * p=arrToScan;*p;++p)
if(!strcmp(keyword, *p))
return true;
return false;
}
typedef GList* pglist;
pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
//#warning needing a dupe filter for filename, maybe use GHashTable for that
void proc_dir(const char *path, unsigned depth=0)
{
//printf("dir: %s\n", path);
GDir *pdir = g_dir_open (path, 0, NULL);
if(!pdir)
return;
const gchar *szFilename(NULL);
while(NULL != (szFilename = g_dir_read_name (pdir)))
{
if(!szFilename)
continue;
gchar *szFullName = g_strjoin("/", path, szFilename, 0);
auto_gfree<gchar> xxfree(szFullName);
static GStatBuf buf;
if(g_stat(szFullName, &buf))
return;
if(S_ISDIR(buf.st_mode))
{
static ino_t reclog[6];
for(unsigned i=0; i<depth; ++i)
{
if(reclog[i] == buf.st_ino)
goto dir_visited_before;
}
if(depth<ACOUNT(reclog))
{
reclog[++depth] = buf.st_ino;
proc_dir(szFullName, depth);
--depth;
}
dir_visited_before:;
}
if(!S_ISREG(buf.st_mode))
return;
//printf("got: %s\n", szFullName);
GDesktopAppInfo *pInfo = g_desktop_app_info_new_from_filename (szFullName);
if(!pInfo)
continue;
if(!g_app_info_should_show((GAppInfo*) pInfo))
continue;
const char *cmdraw = g_app_info_get_commandline ((GAppInfo*) pInfo);
if(!cmdraw || !*cmdraw)
continue;
// let's whitespace all special fields that we don't support
gchar * cmd = g_strdup(cmdraw);
auto_gfree<gchar> cmdfree(cmd);
bool bDelChars=false;
for(gchar *p=cmd; *p; ++p)
{
if('%' == *p)
bDelChars=true;
if(bDelChars)
*p = ' ';
if(bDelChars && !isprint((unsigned)*p))
bDelChars=false;
}
const char *pName=g_app_info_get_name( (GAppInfo*) pInfo);
if(!pName)
continue;
const char *pCats=g_desktop_app_info_get_categories(pInfo);
if(!pCats)
pCats="Other";
//printf("icon: %s -> %s\n", pName, pCats);
const char *sicon = "-";
GIcon *pIcon=g_app_info_get_icon( (GAppInfo*) pInfo);
if (pIcon)
sicon = g_icon_to_string(pIcon);
char *menuLine = g_strdup_printf("# %s -> %s\n"
"prog \"%s\" %s %s\n",
szFullName, pCats,
pName, sicon, cmd);
//printf("%s", menuLine);
// pidgeonholing roughly by guessed menu structure
gchar **ppCats = g_strsplit(pCats, ";", -1);
if (find_in_zArray(ppCats, "Screensaver"))
mscreensavers = g_list_append(mscreensavers, menuLine);
else if (find_in_zArray(ppCats, "Settings"))
msettings = g_list_append(msettings, menuLine);
else if (find_in_zArray(ppCats, "Accessories"))
maccessories = g_list_append(maccessories, menuLine);
else if (find_in_zArray(ppCats, "Development"))
mdevelopment = g_list_append(mdevelopment, menuLine);
else if (find_in_zArray(ppCats, "Education"))
meducation = g_list_append(meducation, menuLine);
else if (find_in_zArray(ppCats, "Game"))
mgames = g_list_append(mgames, menuLine);
else if (find_in_zArray(ppCats, "Graphics"))
mgraphics = g_list_append(mgraphics, menuLine);
else if (find_in_zArray(ppCats, "Audio") || find_in_zArray(ppCats, "Video")
|| find_in_zArray(ppCats, "AudioVideo"))
{
mmultimedia = g_list_append(mmultimedia, menuLine);
}
else if (find_in_zArray(ppCats, "Network"))
mnetwork = g_list_append(mnetwork, menuLine);
else if (find_in_zArray(ppCats, "Office"))
moffice = g_list_append(moffice, menuLine);
else if (find_in_zArray(ppCats, "System") || find_in_zArray(ppCats, "Emulator"))
{
msystem = g_list_append(msystem, menuLine);
}
else
mother = g_list_append(mother, menuLine);
//fprintf(stderr, "jo, %s", menuLine);
}
g_dir_close(pdir);
}
void dump_menu()
{
/*
for (pglist l = msettings; l != NULL; l = l->next)
{
puts((char*) l->data);
}
*/
/*
pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
*/
struct tMenuHead {
char *title;
pglist pEntries;
tMenuHead(char *xt, pglist p) : title(xt), pEntries(p){};
};
pglist xmenu = 0;
// XXX: convert to g_list_insert_sorted using a locale based gcomp function
xmenu = g_list_append(xmenu, new tMenuHead(_("Settings"), msettings));
xmenu = g_list_append(xmenu, new tMenuHead(_("Screensavers"), mscreensavers));
xmenu = g_list_append(xmenu, new tMenuHead(_("Accessories"), maccessories));
xmenu = g_list_append(xmenu, new tMenuHead(_("Development"), mdevelopment));
xmenu = g_list_append(xmenu, new tMenuHead(_("Education"), meducation));
xmenu = g_list_append(xmenu, new tMenuHead(_("Games"), mgames));
xmenu = g_list_append(xmenu, new tMenuHead(_("Graphics"), mgraphics));
xmenu = g_list_append(xmenu, new tMenuHead(_("Multimedia"), mmultimedia));
xmenu = g_list_append(xmenu, new tMenuHead(_("Network"), mnetwork));
xmenu = g_list_append(xmenu, new tMenuHead(_("Office"), moffice));
xmenu = g_list_append(xmenu, new tMenuHead(_("System"), msystem));
xmenu = g_list_append(xmenu, new tMenuHead(_("Other"), mother));
for (pglist l = xmenu; l != NULL; l = l->next)
{
printf("menu \"%s\" folder {\n", ((tMenuHead*) l->data)->title);
for (pglist m = ((tMenuHead*) l->data)->pEntries; m != NULL; m = m->next)
{
puts((char*) m->data);
}
puts("}\n");
}
}
int main(int argc, char **) {
setlocale (LC_ALL, "");
#ifdef ENABLE_NLS
bindtextdomain(PACKAGE, LOCDIR);
textdomain(PACKAGE);
#endif
const char * usershare=getenv("XDG_DATA_HOME"),
*sysshare=getenv("XDG_DATA_DIRS");
if(!usershare || !*usershare)
usershare=g_strjoin(NULL, getenv("HOME"), "/.local/share", NULL);
if(!sysshare || !*sysshare)
sysshare="/usr/local/share/:/usr/share/";
if(argc>1)
{
g_fprintf(stderr, "This program doesn't use command line options. It only listens to\n"
"environment variables defined by XDG Base Directory Specification.\n"
"XDG_DATA_HOME=%s\n"
"XDG_DATA_DIRS=%s\n"
,usershare, sysshare);
return EXIT_FAILURE;
}
proc_dir(usershare);
gchar **ppDirs = g_strsplit (sysshare, ":", -1);
for(const gchar * const * p=ppDirs;*p;++p)
proc_dir(g_strjoin(0, *p, "/applications", 0));
dump_menu();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <signal.h>
#include "global.hpp"
#include "helper.hpp"
#include "database.hpp"
#include "message.hpp"
#include "judge.hpp"
#include "webserver.hpp"
#include "contest.hpp"
#include "attempt.hpp"
using namespace std;
static bool quit = false;
class pjudge {
public:
pjudge() : sudden(sudden_shutdown()) {
key_t key = msq.key();
FILE* fp = fopen("pjudge.bin", "wb");
fwrite(&key,sizeof key,1,fp);
fclose(fp);
}
~pjudge() {
if (!sudden) remove("pjudge.bin");
}
void update() {
msq.update();
}
static bool sudden_shutdown() {
FILE* fp = fopen("pjudge.bin","rb");
if (!fp) return false;
fclose(fp);
return true;
}
static key_t alive() {
FILE* fp = fopen("pjudge.bin", "rb");
if (!fp) return 0;
key_t key;
fread(&key,sizeof key,1,fp);
fclose(fp);
MessageQueue msq;
PingMessage(msq.key()).send(key);
if (msq.receive(3).mtype != IMALIVE) return 0;
return key;
}
private:
bool sudden;
MessageQueue msq;
};
static void term(int) {
Global::shutdown();
}
static key_t online() {
key_t key = pjudge::alive();
if (!key) {
printf("pjudge is not running: online operations can't be done.\n");
_exit(0);
}
return key;
}
static void offline() {
if (pjudge::alive()) {
printf("pjudge is running: offline operations can't be done.\n");
_exit(0);
}
}
namespace Global {
void install(const string& path) {
FILE* fp = fopen(path.c_str(),"r");
if (fp) {
fclose(fp);
printf("pjudge install failed: file already exists.\n");
return;
}
system("mkdir -p %s",path.c_str());
system("cp -rf /usr/local/share/pjudge/* %s",path.c_str());
printf("pjudge installed at %s.\n",path.c_str());
}
void start() {
offline();
bool sudden = pjudge::sudden_shutdown();
if (sudden) printf(
"WARNING: last pjudge[%s] execution stopped suddenly.\n"
"this execution will not make database backups.\n"
"YOU MUST: 1) check your data; 2) stop pjudge; 3) manually rollback the\n"
"database if necessary; and 4) remove file 'pjudge.bin'.\n"
"next execution will be fine.\n",
getcwd().c_str()
);
printf("pjudge[%s] started.\n",getcwd().c_str());
if (daemon(1,1) < 0) { // fork and redirect IO to /dev/null
perror(stringf(
"pjudge[%s] could not start in background",
getcwd().c_str()
).c_str());
_exit(-1);
}
freopen("stdout.txt","w",stdout);
freopen("stderr.txt","w",stderr);
pjudge pj; // RAII
signal(SIGTERM,term); // Global::shutdown();
signal(SIGPIPE,SIG_IGN); // ignore broken pipes (tcp shit)
Database::init(!sudden);
Contest::fix();
Attempt::fix();
Judge::init();
WebServer::init();
while (!quit) {
pj.update();
usleep(25000);
}
WebServer::close();
Judge::close();
Database::close();
}
void stop() {
key_t key = online();
Message(STOP).send(key);
MessageQueue msq;
PingMessage ping(msq.key());
do {
ping.send(key);
} while (msq.receive(1).mtype == IMALIVE);
printf("pjudge[%s] stopped.\n",getcwd().c_str());
}
void rerun_attempt(int id) {
RerunAttMessage(id).send(online());
printf(
"pjudge[%s] pushed attempt id=%d to queue.\n",
getcwd().c_str(),
id
);
}
void shutdown() {
quit = true;
}
} // namespace Global
<commit_msg>Closing stdin<commit_after>#include <unistd.h>
#include <signal.h>
#include "global.hpp"
#include "helper.hpp"
#include "database.hpp"
#include "message.hpp"
#include "judge.hpp"
#include "webserver.hpp"
#include "contest.hpp"
#include "attempt.hpp"
using namespace std;
static bool quit = false;
class pjudge {
public:
pjudge() : sudden(sudden_shutdown()) {
key_t key = msq.key();
FILE* fp = fopen("pjudge.bin", "wb");
fwrite(&key,sizeof key,1,fp);
fclose(fp);
}
~pjudge() {
if (!sudden) remove("pjudge.bin");
}
void update() {
msq.update();
}
static bool sudden_shutdown() {
FILE* fp = fopen("pjudge.bin","rb");
if (!fp) return false;
fclose(fp);
return true;
}
static key_t alive() {
FILE* fp = fopen("pjudge.bin", "rb");
if (!fp) return 0;
key_t key;
fread(&key,sizeof key,1,fp);
fclose(fp);
MessageQueue msq;
PingMessage(msq.key()).send(key);
if (msq.receive(3).mtype != IMALIVE) return 0;
return key;
}
private:
bool sudden;
MessageQueue msq;
};
static void term(int) {
Global::shutdown();
}
static key_t online() {
key_t key = pjudge::alive();
if (!key) {
printf("pjudge is not running: online operations can't be done.\n");
_exit(0);
}
return key;
}
static void offline() {
if (pjudge::alive()) {
printf("pjudge is running: offline operations can't be done.\n");
_exit(0);
}
}
namespace Global {
void install(const string& path) {
FILE* fp = fopen(path.c_str(),"r");
if (fp) {
fclose(fp);
printf("pjudge install failed: file already exists.\n");
return;
}
system("mkdir -p %s",path.c_str());
system("cp -rf /usr/local/share/pjudge/* %s",path.c_str());
printf("pjudge installed at %s.\n",path.c_str());
}
void start() {
offline();
bool sudden = pjudge::sudden_shutdown();
if (sudden) printf(
"WARNING: last pjudge[%s] execution stopped suddenly.\n"
"this execution will not make database backups.\n"
"YOU MUST: 1) check your data; 2) stop pjudge; 3) manually rollback the\n"
"database if necessary; and 4) remove file 'pjudge.bin'.\n"
"next execution will be fine.\n",
getcwd().c_str()
);
printf("pjudge[%s] started.\n",getcwd().c_str());
if (daemon(1,1) < 0) { // fork and redirect IO to /dev/null
perror(stringf(
"pjudge[%s] could not start in background",
getcwd().c_str()
).c_str());
_exit(-1);
}
freopen("/dev/null","r",stdin);
freopen("stdout.txt","w",stdout);
freopen("stderr.txt","w",stderr);
pjudge pj; // RAII
signal(SIGTERM,term); // Global::shutdown();
signal(SIGPIPE,SIG_IGN); // ignore broken pipes (tcp shit)
Database::init(!sudden);
Contest::fix();
Attempt::fix();
Judge::init();
WebServer::init();
while (!quit) {
pj.update();
usleep(25000);
}
WebServer::close();
Judge::close();
Database::close();
}
void stop() {
key_t key = online();
Message(STOP).send(key);
MessageQueue msq;
PingMessage ping(msq.key());
do {
ping.send(key);
} while (msq.receive(1).mtype == IMALIVE);
printf("pjudge[%s] stopped.\n",getcwd().c_str());
}
void rerun_attempt(int id) {
RerunAttMessage(id).send(online());
printf(
"pjudge[%s] pushed attempt id=%d to queue.\n",
getcwd().c_str(),
id
);
}
void shutdown() {
quit = true;
}
} // namespace Global
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediadescriptor.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-05-08 14:54: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
*
************************************************************************/
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_
//_______________________________________________
// includes
#ifndef __COM_SUN_STAR_IO_XINPUTSTREAM_HPP__
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
struct.
@descr It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
represent the MediaDescriptor item.
Further this helper defines often used functions (as e.g. open of the required streams,
consistent checks etcpp.) and it defines all useable property names.
@attention This class isnt threadsafe and must be guarded from outside!
*/
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
//-------------------------------------------
// const
public:
//---------------------------------------
/** @short these methods can be used to get the different property names
as static const OUString values.
@descr Because definition and declaration of static const class members
does not work as expected under windows (under unix it works as well)
these way must be used :-(
*/
static const ::rtl::OUString& PROP_ASTEMPLATE();
static const ::rtl::OUString& PROP_CHARACTERSET();
static const ::rtl::OUString& PROP_DEEPDETECTION();
static const ::rtl::OUString& PROP_DETECTSERVICE();
static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
static const ::rtl::OUString& PROP_EXTENSION();
static const ::rtl::OUString& PROP_FILENAME();
static const ::rtl::OUString& PROP_FILTERNAME();
static const ::rtl::OUString& PROP_FILTEROPTIONS();
static const ::rtl::OUString& PROP_FORMAT();
static const ::rtl::OUString& PROP_FRAMENAME();
static const ::rtl::OUString& PROP_HIDDEN();
static const ::rtl::OUString& PROP_INPUTSTREAM();
static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
static const ::rtl::OUString& PROP_JUMPMARK();
static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
static const ::rtl::OUString& PROP_MEDIATYPE();
static const ::rtl::OUString& PROP_MINIMIZED();
static const ::rtl::OUString& PROP_NOAUTOSAVE();
static const ::rtl::OUString& PROP_OPENNEWVIEW();
static const ::rtl::OUString& PROP_OUTPUTSTREAM();
static const ::rtl::OUString& PROP_PASSWORD();
static const ::rtl::OUString& PROP_PATTERN();
static const ::rtl::OUString& PROP_POSSIZE();
static const ::rtl::OUString& PROP_POSTDATA();
static const ::rtl::OUString& PROP_POSTSTRING();
static const ::rtl::OUString& PROP_PREVIEW();
static const ::rtl::OUString& PROP_READONLY();
static const ::rtl::OUString& PROP_REFERRER();
static const ::rtl::OUString& PROP_SALVAGEDFILE();
static const ::rtl::OUString& PROP_SILENT();
static const ::rtl::OUString& PROP_STATUSINDICATOR();
static const ::rtl::OUString& PROP_STREAM();
static const ::rtl::OUString& PROP_TEMPLATENAME();
static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
static const ::rtl::OUString& PROP_TITLE();
static const ::rtl::OUString& PROP_TYPENAME();
static const ::rtl::OUString& PROP_UCBCONTENT();
static const ::rtl::OUString& PROP_UPDATEDOCMODE();
static const ::rtl::OUString& PROP_URL();
static const ::rtl::OUString& PROP_VERSION();
static const ::rtl::OUString& PROP_VIEWID();
static const ::rtl::OUString& PROP_REPAIRPACKAGE();
static const ::rtl::OUString& PROP_DOCUMENTTITLE();
static const ::rtl::OUString& PROP_MODEL();
static const ::rtl::OUString& PROP_VIEWONLY();
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short these ctors do nothing - excepting that they forward
the given parameters to the base class ctors.
@descr The ctros must be overwritten to resolve conflicts with
the default ctors of the compiler :-(.
*/
MediaDescriptor();
MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short it checks if the descriptor already has a valid
InputStream item and creates a new one, if not.
@descr This method uses the current items of this MediaDescriptor,
to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
It creates a seekable stream and put it into the descriptor.
A might existing InteractionHandler will be used automaticly,
to solve problems!
@return TRUE, if the stream was already part of the descriptor or could
be created as new item. FALSE otherwhise.
*/
sal_Bool addInputStream();
//---------------------------------------
/** @short it checks if the descriptor describes a readonly stream.
@descr The descriptor itself isnt changed doing so.
It's only checked if the stream seems to be based
of a real readonly file.
@Attention
We dont check the property "ReadOnly" here. Because
this property can be set from outside and overwrites
the readonly state of the stream.
If e.g. the stream could be opened read/write ...
but "ReadOnly" property is set to TRUE, this means:
show a readonly UI on top of this read/write stream.
@return TRUE, if the stream must be interpreted as readonly ...
FALSE otherwhise.
*/
sal_Bool isStreamReadOnly() const;
//-------------------------------------------
// helper
private:
//---------------------------------------
/** @short tries to open a stream by using the given PostData stream.
@descr The stream is used directly ...
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param xPostData
the PostData stream.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xPostData)
throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short tries to open a stream by using the given URL.
@descr First it tries to open the content in r/w mode (if its
allowed to do so). Only in case its not allowed or it failed
the stream will be tried to open in readonly mode.
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param sURL
the URL for open.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(const ::rtl::OUString& sURL)
throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short some URL parts can make trouble for opening streams (e.g. jumpmarks.)
An URL should be "normalized" before its used.
@param sURL
the original URL (e.g. including a jumpmark)
@return [string]
the "normalized" URL (e.g. without jumpmark)
*/
COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};
} // namespace comphelper
#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.7.40); FILE MERGED 2006/05/23 22:36:05 sb 1.7.40.3: RESYNC: (1.8-1.9); FILE MERGED 2005/09/23 03:04:45 sb 1.7.40.2: RESYNC: (1.7-1.8); FILE MERGED 2005/09/08 13:16:47 sb 1.7.40.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediadescriptor.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-19 22:43: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
*
************************************************************************/
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_
//_______________________________________________
// includes
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
struct.
@descr It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
represent the MediaDescriptor item.
Further this helper defines often used functions (as e.g. open of the required streams,
consistent checks etcpp.) and it defines all useable property names.
@attention This class isnt threadsafe and must be guarded from outside!
*/
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
//-------------------------------------------
// const
public:
//---------------------------------------
/** @short these methods can be used to get the different property names
as static const OUString values.
@descr Because definition and declaration of static const class members
does not work as expected under windows (under unix it works as well)
these way must be used :-(
*/
static const ::rtl::OUString& PROP_ASTEMPLATE();
static const ::rtl::OUString& PROP_CHARACTERSET();
static const ::rtl::OUString& PROP_DEEPDETECTION();
static const ::rtl::OUString& PROP_DETECTSERVICE();
static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
static const ::rtl::OUString& PROP_EXTENSION();
static const ::rtl::OUString& PROP_FILENAME();
static const ::rtl::OUString& PROP_FILTERNAME();
static const ::rtl::OUString& PROP_FILTEROPTIONS();
static const ::rtl::OUString& PROP_FORMAT();
static const ::rtl::OUString& PROP_FRAMENAME();
static const ::rtl::OUString& PROP_HIDDEN();
static const ::rtl::OUString& PROP_INPUTSTREAM();
static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
static const ::rtl::OUString& PROP_JUMPMARK();
static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
static const ::rtl::OUString& PROP_MEDIATYPE();
static const ::rtl::OUString& PROP_MINIMIZED();
static const ::rtl::OUString& PROP_NOAUTOSAVE();
static const ::rtl::OUString& PROP_OPENNEWVIEW();
static const ::rtl::OUString& PROP_OUTPUTSTREAM();
static const ::rtl::OUString& PROP_PASSWORD();
static const ::rtl::OUString& PROP_PATTERN();
static const ::rtl::OUString& PROP_POSSIZE();
static const ::rtl::OUString& PROP_POSTDATA();
static const ::rtl::OUString& PROP_POSTSTRING();
static const ::rtl::OUString& PROP_PREVIEW();
static const ::rtl::OUString& PROP_READONLY();
static const ::rtl::OUString& PROP_REFERRER();
static const ::rtl::OUString& PROP_SALVAGEDFILE();
static const ::rtl::OUString& PROP_SILENT();
static const ::rtl::OUString& PROP_STATUSINDICATOR();
static const ::rtl::OUString& PROP_STREAM();
static const ::rtl::OUString& PROP_TEMPLATENAME();
static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
static const ::rtl::OUString& PROP_TITLE();
static const ::rtl::OUString& PROP_TYPENAME();
static const ::rtl::OUString& PROP_UCBCONTENT();
static const ::rtl::OUString& PROP_UPDATEDOCMODE();
static const ::rtl::OUString& PROP_URL();
static const ::rtl::OUString& PROP_VERSION();
static const ::rtl::OUString& PROP_VIEWID();
static const ::rtl::OUString& PROP_REPAIRPACKAGE();
static const ::rtl::OUString& PROP_DOCUMENTTITLE();
static const ::rtl::OUString& PROP_MODEL();
static const ::rtl::OUString& PROP_VIEWONLY();
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short these ctors do nothing - excepting that they forward
the given parameters to the base class ctors.
@descr The ctros must be overwritten to resolve conflicts with
the default ctors of the compiler :-(.
*/
MediaDescriptor();
MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short it checks if the descriptor already has a valid
InputStream item and creates a new one, if not.
@descr This method uses the current items of this MediaDescriptor,
to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
It creates a seekable stream and put it into the descriptor.
A might existing InteractionHandler will be used automaticly,
to solve problems!
@return TRUE, if the stream was already part of the descriptor or could
be created as new item. FALSE otherwhise.
*/
sal_Bool addInputStream();
//---------------------------------------
/** @short it checks if the descriptor describes a readonly stream.
@descr The descriptor itself isnt changed doing so.
It's only checked if the stream seems to be based
of a real readonly file.
@Attention
We dont check the property "ReadOnly" here. Because
this property can be set from outside and overwrites
the readonly state of the stream.
If e.g. the stream could be opened read/write ...
but "ReadOnly" property is set to TRUE, this means:
show a readonly UI on top of this read/write stream.
@return TRUE, if the stream must be interpreted as readonly ...
FALSE otherwhise.
*/
sal_Bool isStreamReadOnly() const;
//-------------------------------------------
// helper
private:
//---------------------------------------
/** @short tries to open a stream by using the given PostData stream.
@descr The stream is used directly ...
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param xPostData
the PostData stream.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData()
throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short tries to open a stream by using the given URL.
@descr First it tries to open the content in r/w mode (if its
allowed to do so). Only in case its not allowed or it failed
the stream will be tried to open in readonly mode.
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param sURL
the URL for open.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(const ::rtl::OUString& sURL)
throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short some URL parts can make trouble for opening streams (e.g. jumpmarks.)
An URL should be "normalized" before its used.
@param sURL
the original URL (e.g. including a jumpmark)
@return [string]
the "normalized" URL (e.g. without jumpmark)
*/
COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};
} // namespace comphelper
#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<|endoftext|>
|
<commit_before>
#include <string.h>
#include "boxed.h"
#include "closure.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::FunctionCallbackInfo;
using Nan::WeakCallbackType;
namespace GNodeJS {
// Our base template for all GObjects
static Nan::Persistent<FunctionTemplate> baseTemplate;
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data);
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info);
static bool InitGParameterFromProperty(GParameter *parameter,
void *klass,
Local<String> name,
Local<Value> value) {
Nan::Utf8String name_utf8 (name);
GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_utf8);
// Ignore additionnal keys in options, thus return true
if (pspec == NULL)
return true;
GType value_type = G_PARAM_SPEC_VALUE_TYPE (pspec);
parameter->name = pspec->name;
g_value_init (¶meter->value, value_type);
if (!CanConvertV8ToGValue(¶meter->value, value)) {
char* message = g_strdup_printf("Cannot convert value for property \"%s\", expected type %s",
*name_utf8, g_type_name(value_type));
Nan::ThrowTypeError(message);
free(message);
return false;
}
if (!V8ToGValue (¶meter->value, value)) {
char* message = g_strdup_printf("Couldn't convert value for property \"%s\", expected type %s",
*name_utf8, g_type_name(value_type));
Nan::ThrowTypeError(message);
free(message);
return false;
}
return true;
}
static bool InitGParametersFromProperty(GParameter **parameters_p,
int *n_parameters_p,
void *klass,
Local<Object> property_hash) {
Local<Array> properties = property_hash->GetOwnPropertyNames ();
int n_parameters = properties->Length ();
GParameter *parameters = g_new0 (GParameter, n_parameters);
for (int i = 0; i < n_parameters; i++) {
Local<String> name = properties->Get(i)->ToString();
Local<Value> value = property_hash->Get (name);
if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))
return false;
}
*parameters_p = parameters;
*n_parameters_p = n_parameters;
return true;
}
static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
g_assert (data != NULL);
auto *persistent = (Persistent<Object> *) data;
if (toggle_down) {
/* We're dropping from 2 refs to 1 ref. We are the last holder. Make
* sure that that our weak ref is installed. */
persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter);
} else {
/* We're going from 1 ref to 2 refs. We can't let our wrapper be
* collected, so make sure that our reference is persistent */
persistent->ClearWeak ();
}
}
static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) {
object->SetAlignedPointerInInternalField (0, gobject);
g_object_ref_sink (gobject);
g_object_add_toggle_ref (gobject, ToggleNotify, NULL);
Persistent<Object> *persistent = new Persistent<Object>(isolate, object);
g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent);
}
static void GObjectConstructor(const FunctionCallbackInfo<Value> &info) {
Isolate *isolate = info.GetIsolate ();
/* The flow of this function is a bit twisty.
* There's two cases for when this code is called:
* user code doing `new Gtk.Widget({ ... })`, and
* internal code as part of WrapperFromGObject, where
* the constructor is called with one external. */
if (!info.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call.");
return;
}
Local<Object> self = info.This ();
if (info[0]->IsExternal ()) {
/* The External case. This is how WrapperFromGObject is called. */
void *data = External::Cast (*info[0])->Value ();
GObject *gobject = G_OBJECT (data);
AssociateGObject (isolate, self, gobject);
Nan::DefineOwnProperty(self,
Nan::New<String>("__gtype__").ToLocalChecked(),
Nan::New<Number>(G_OBJECT_TYPE(gobject)),
(v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
);
} else {
/* User code calling `new Gtk.Widget({ ... })` */
GObject *gobject;
GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value ();
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info);
void *klass = g_type_class_ref (gtype);
GParameter *parameters = NULL;
int n_parameters = 0;
if (info[0]->IsObject ()) {
Local<Object> property_hash = info[0]->ToObject ();
if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {
// Error will already be thrown from InitGParametersFromProperty
goto out;
}
}
gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);
AssociateGObject (isolate, self, gobject);
Nan::DefineOwnProperty(self,
UTF8("__gtype__"),
Nan::New<Number>(g_registered_type_info_get_g_type(gi_info)),
(v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
);
out:
g_free (parameters);
g_type_class_unref (klass);
}
}
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) {
GObject *gobject = data.GetParameter ();
void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark());
Persistent<Object> *persistent = (Persistent<Object> *) type_data;
delete persistent;
/* We're destroying the wrapper object, so make sure to clear out
* the qdata that points back to us. */
g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL);
g_object_unref (gobject);
}
static GISignalInfo* FindSignalInfo(GIObjectInfo *info, const char *signal_detail) {
char* signal_name = Util::GetSignalName(signal_detail);
GISignalInfo *signal_info = NULL;
GIBaseInfo *parent = g_base_info_ref(info);
while (parent) {
// Find on GObject
signal_info = g_object_info_find_signal (parent, signal_name);
if (signal_info)
break;
// Find on Interfaces
int n_interfaces = g_object_info_get_n_interfaces (info);
for (int i = 0; i < n_interfaces; i++) {
GIBaseInfo* interface_info = g_object_info_get_interface (info, i);
signal_info = g_interface_info_find_signal (interface_info, signal_name);
g_base_info_unref (interface_info);
if (signal_info)
goto out;
}
GIBaseInfo* next_parent = g_object_info_get_parent(parent);
g_base_info_unref(parent);
parent = next_parent;
}
out:
if (parent)
g_base_info_unref(parent);
g_free(signal_name);
return signal_info;
}
static void ThrowSignalNotFound(GIBaseInfo *object_info, const char* signal_name) {
char *message = g_strdup_printf("Signal \"%s\" not found for instance of %s",
signal_name, GetInfoName(object_info));
Nan::ThrowError(message);
g_free(message);
}
static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info, bool after) {
GObject *gobject = GObjectFromWrapper (info.This ());
if (!gobject) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
if (!info[0]->IsString()) {
Nan::ThrowTypeError("Signal ID invalid");
return;
}
if (!info[1]->IsFunction()) {
Nan::ThrowTypeError("Signal callback is not a function");
return;
}
const char *signal_name = *Nan::Utf8String (info[0]->ToString());
Local<Function> callback = info[1].As<Function>();
GType gtype = (GType) Nan::Get(info.This(), UTF8("__gtype__")).ToLocalChecked()->NumberValue();
GIBaseInfo *object_info = g_irepository_find_by_gtype (NULL, gtype);
GISignalInfo *signal_info = FindSignalInfo (object_info, signal_name);
if (signal_info == NULL) {
ThrowSignalNotFound(object_info, signal_name);
}
else {
GClosure *gclosure = MakeClosure (callback, signal_info);
ulong handler_id = g_signal_connect_closure (gobject, signal_name, gclosure, after);
info.GetReturnValue().Set((double)handler_id);
}
g_base_info_unref(object_info);
}
static void SignalDisconnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info) {
GObject *gobject = GObjectFromWrapper (info.This ());
if (!gobject) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError("Signal ID should be a number");
return;
}
gpointer instance = static_cast<gpointer>(gobject);
ulong handler_id = info[0]->NumberValue();
g_signal_handler_disconnect (instance, handler_id);
info.GetReturnValue().Set((double)handler_id);
}
NAN_METHOD(SignalConnect) {
SignalConnectInternal(info, false);
}
NAN_METHOD(SignalDisconnect) {
SignalDisconnectInternal(info);
}
NAN_METHOD(GObjectToString) {
Local<Object> self = info.This();
if (!ValueHasInternalField(self)) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
GObject* g_object = GObjectFromWrapper(self);
GType type = G_OBJECT_TYPE (g_object);
const char* typeName = g_type_name(type);
char *className = *Nan::Utf8String(self->GetConstructorName());
void *address = self->GetAlignedPointerFromInternalField(0);
char *str = g_strdup_printf("[%s:%s %#zx]", typeName, className, (unsigned long)address);
info.GetReturnValue().Set(UTF8(str));
g_free(str);
}
Local<FunctionTemplate> GetBaseClassTemplate() {
static bool isBaseClassCreated = false;
if (!isBaseClassCreated) {
isBaseClassCreated = true;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>();
Nan::SetPrototypeMethod(tpl, "connect", SignalConnect);
Nan::SetPrototypeMethod(tpl, "disconnect", SignalDisconnect);
Nan::SetPrototypeMethod(tpl, "toString", GObjectToString);
baseTemplate.Reset(tpl);
}
// get FunctionTemplate from persistent object
Local<FunctionTemplate> tpl = Nan::New(baseTemplate);
return tpl;
}
static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) {
const GType gtype = g_registered_type_info_get_g_type (info);
g_assert(gtype != G_TYPE_NONE);
const char *class_name = g_type_name (gtype);
auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info));
tpl->SetClassName (UTF8(class_name));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
GIObjectInfo *parent_info = g_object_info_get_parent (info);
if (parent_info) {
auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info);
tpl->Inherit(parent_tpl);
} else {
tpl->Inherit(GetBaseClassTemplate());
}
return tpl;
}
static Local<FunctionTemplate> GetClassTemplate(GType gtype) {
void *data = g_type_get_qdata (gtype, GNodeJS::template_quark());
if (data) {
auto *persistent = (Persistent<FunctionTemplate> *) data;
auto tpl = New<FunctionTemplate> (*persistent);
return tpl;
} else {
GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype);
auto tpl = NewClassTemplate(gi_info);
auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl);
persistent->SetWeak (
g_base_info_ref (gi_info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
}
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
return GetClassTemplate(gtype);
}
Local<Function> MakeClass(GIBaseInfo *info) {
auto tpl = GetClassTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromGObject(GObject *gobject) {
if (gobject == NULL)
return Nan::Null();
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
if (data) {
/* Easy case: we already have an object. */
auto *persistent = (Persistent<Object> *) data;
auto obj = New<Object> (*persistent);
return obj;
} else {
GType gtype = G_OBJECT_TYPE(gobject);
g_type_ensure(gtype); //void *klass = g_type_class_ref (type);
auto tpl = GetClassTemplate(gtype);
Local<Function> constructor = tpl->GetFunction ();
Local<Value> gobject_external = New<External> (gobject);
Local<Value> args[] = { gobject_external };
Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked();
return obj;
}
}
GObject * GObjectFromWrapper(Local<Value> value) {
if (!ValueHasInternalField(value))
return nullptr;
Local<Object> object = value->ToObject ();
void *ptr = object->GetAlignedPointerFromInternalField (0);
GObject *gobject = G_OBJECT (ptr);
return gobject;
}
};
<commit_msg>gobject: reuse gtype<commit_after>
#include <string.h>
#include "boxed.h"
#include "closure.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Persistent;
using Nan::New;
using Nan::FunctionCallbackInfo;
using Nan::WeakCallbackType;
namespace GNodeJS {
// Our base template for all GObjects
static Nan::Persistent<FunctionTemplate> baseTemplate;
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data);
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info);
static bool InitGParameterFromProperty(GParameter *parameter,
void *klass,
Local<String> name,
Local<Value> value) {
Nan::Utf8String name_utf8 (name);
GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_utf8);
// Ignore additionnal keys in options, thus return true
if (pspec == NULL)
return true;
GType value_type = G_PARAM_SPEC_VALUE_TYPE (pspec);
parameter->name = pspec->name;
g_value_init (¶meter->value, value_type);
if (!CanConvertV8ToGValue(¶meter->value, value)) {
char* message = g_strdup_printf("Cannot convert value for property \"%s\", expected type %s",
*name_utf8, g_type_name(value_type));
Nan::ThrowTypeError(message);
free(message);
return false;
}
if (!V8ToGValue (¶meter->value, value)) {
char* message = g_strdup_printf("Couldn't convert value for property \"%s\", expected type %s",
*name_utf8, g_type_name(value_type));
Nan::ThrowTypeError(message);
free(message);
return false;
}
return true;
}
static bool InitGParametersFromProperty(GParameter **parameters_p,
int *n_parameters_p,
void *klass,
Local<Object> property_hash) {
Local<Array> properties = property_hash->GetOwnPropertyNames ();
int n_parameters = properties->Length ();
GParameter *parameters = g_new0 (GParameter, n_parameters);
for (int i = 0; i < n_parameters; i++) {
Local<String> name = properties->Get(i)->ToString();
Local<Value> value = property_hash->Get (name);
if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))
return false;
}
*parameters_p = parameters;
*n_parameters_p = n_parameters;
return true;
}
static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
g_assert (data != NULL);
auto *persistent = (Persistent<Object> *) data;
if (toggle_down) {
/* We're dropping from 2 refs to 1 ref. We are the last holder. Make
* sure that that our weak ref is installed. */
persistent->SetWeak (gobject, GObjectDestroyed, v8::WeakCallbackType::kParameter);
} else {
/* We're going from 1 ref to 2 refs. We can't let our wrapper be
* collected, so make sure that our reference is persistent */
persistent->ClearWeak ();
}
}
static void AssociateGObject(Isolate *isolate, Local<Object> object, GObject *gobject) {
object->SetAlignedPointerInInternalField (0, gobject);
g_object_ref_sink (gobject);
g_object_add_toggle_ref (gobject, ToggleNotify, NULL);
Persistent<Object> *persistent = new Persistent<Object>(isolate, object);
g_object_set_qdata (gobject, GNodeJS::object_quark(), persistent);
}
static void GObjectConstructor(const FunctionCallbackInfo<Value> &info) {
Isolate *isolate = info.GetIsolate ();
/* The flow of this function is a bit twisty.
* There's two cases for when this code is called:
* user code doing `new Gtk.Widget({ ... })`, and
* internal code as part of WrapperFromGObject, where
* the constructor is called with one external. */
if (!info.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call.");
return;
}
Local<Object> self = info.This ();
if (info[0]->IsExternal ()) {
/* The External case. This is how WrapperFromGObject is called. */
void *data = External::Cast (*info[0])->Value ();
GObject *gobject = G_OBJECT (data);
AssociateGObject (isolate, self, gobject);
Nan::DefineOwnProperty(self,
Nan::New<String>("__gtype__").ToLocalChecked(),
Nan::New<Number>(G_OBJECT_TYPE(gobject)),
(v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
);
} else {
/* User code calling `new Gtk.Widget({ ... })` */
GObject *gobject;
GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*info.Data ())->Value ();
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info);
void *klass = g_type_class_ref (gtype);
GParameter *parameters = NULL;
int n_parameters = 0;
if (info[0]->IsObject ()) {
Local<Object> property_hash = info[0]->ToObject ();
if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {
// Error will already be thrown from InitGParametersFromProperty
goto out;
}
}
gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);
AssociateGObject (isolate, self, gobject);
Nan::DefineOwnProperty(self,
UTF8("__gtype__"),
Nan::New<Number>(gtype),
(v8::PropertyAttribute)(v8::PropertyAttribute::ReadOnly | v8::PropertyAttribute::DontEnum)
);
out:
g_free (parameters);
g_type_class_unref (klass);
}
}
static void GObjectDestroyed(const v8::WeakCallbackInfo<GObject> &data) {
GObject *gobject = data.GetParameter ();
void *type_data = g_object_get_qdata (gobject, GNodeJS::object_quark());
Persistent<Object> *persistent = (Persistent<Object> *) type_data;
delete persistent;
/* We're destroying the wrapper object, so make sure to clear out
* the qdata that points back to us. */
g_object_set_qdata (gobject, GNodeJS::object_quark(), NULL);
g_object_unref (gobject);
}
static GISignalInfo* FindSignalInfo(GIObjectInfo *info, const char *signal_detail) {
char* signal_name = Util::GetSignalName(signal_detail);
GISignalInfo *signal_info = NULL;
GIBaseInfo *parent = g_base_info_ref(info);
while (parent) {
// Find on GObject
signal_info = g_object_info_find_signal (parent, signal_name);
if (signal_info)
break;
// Find on Interfaces
int n_interfaces = g_object_info_get_n_interfaces (info);
for (int i = 0; i < n_interfaces; i++) {
GIBaseInfo* interface_info = g_object_info_get_interface (info, i);
signal_info = g_interface_info_find_signal (interface_info, signal_name);
g_base_info_unref (interface_info);
if (signal_info)
goto out;
}
GIBaseInfo* next_parent = g_object_info_get_parent(parent);
g_base_info_unref(parent);
parent = next_parent;
}
out:
if (parent)
g_base_info_unref(parent);
g_free(signal_name);
return signal_info;
}
static void ThrowSignalNotFound(GIBaseInfo *object_info, const char* signal_name) {
char *message = g_strdup_printf("Signal \"%s\" not found for instance of %s",
signal_name, GetInfoName(object_info));
Nan::ThrowError(message);
g_free(message);
}
static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info, bool after) {
GObject *gobject = GObjectFromWrapper (info.This ());
if (!gobject) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
if (!info[0]->IsString()) {
Nan::ThrowTypeError("Signal ID invalid");
return;
}
if (!info[1]->IsFunction()) {
Nan::ThrowTypeError("Signal callback is not a function");
return;
}
const char *signal_name = *Nan::Utf8String (info[0]->ToString());
Local<Function> callback = info[1].As<Function>();
GType gtype = (GType) Nan::Get(info.This(), UTF8("__gtype__")).ToLocalChecked()->NumberValue();
GIBaseInfo *object_info = g_irepository_find_by_gtype (NULL, gtype);
GISignalInfo *signal_info = FindSignalInfo (object_info, signal_name);
if (signal_info == NULL) {
ThrowSignalNotFound(object_info, signal_name);
}
else {
GClosure *gclosure = MakeClosure (callback, signal_info);
ulong handler_id = g_signal_connect_closure (gobject, signal_name, gclosure, after);
info.GetReturnValue().Set((double)handler_id);
}
g_base_info_unref(object_info);
}
static void SignalDisconnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &info) {
GObject *gobject = GObjectFromWrapper (info.This ());
if (!gobject) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError("Signal ID should be a number");
return;
}
gpointer instance = static_cast<gpointer>(gobject);
ulong handler_id = info[0]->NumberValue();
g_signal_handler_disconnect (instance, handler_id);
info.GetReturnValue().Set((double)handler_id);
}
NAN_METHOD(SignalConnect) {
SignalConnectInternal(info, false);
}
NAN_METHOD(SignalDisconnect) {
SignalDisconnectInternal(info);
}
NAN_METHOD(GObjectToString) {
Local<Object> self = info.This();
if (!ValueHasInternalField(self)) {
Nan::ThrowTypeError("Object is not a GObject");
return;
}
GObject* g_object = GObjectFromWrapper(self);
GType type = G_OBJECT_TYPE (g_object);
const char* typeName = g_type_name(type);
char *className = *Nan::Utf8String(self->GetConstructorName());
void *address = self->GetAlignedPointerFromInternalField(0);
char *str = g_strdup_printf("[%s:%s %#zx]", typeName, className, (unsigned long)address);
info.GetReturnValue().Set(UTF8(str));
g_free(str);
}
Local<FunctionTemplate> GetBaseClassTemplate() {
static bool isBaseClassCreated = false;
if (!isBaseClassCreated) {
isBaseClassCreated = true;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>();
Nan::SetPrototypeMethod(tpl, "connect", SignalConnect);
Nan::SetPrototypeMethod(tpl, "disconnect", SignalDisconnect);
Nan::SetPrototypeMethod(tpl, "toString", GObjectToString);
baseTemplate.Reset(tpl);
}
// get FunctionTemplate from persistent object
Local<FunctionTemplate> tpl = Nan::New(baseTemplate);
return tpl;
}
static Local<FunctionTemplate> NewClassTemplate (GIBaseInfo *info) {
const GType gtype = g_registered_type_info_get_g_type (info);
g_assert(gtype != G_TYPE_NONE);
const char *class_name = g_type_name (gtype);
auto tpl = New<FunctionTemplate> (GObjectConstructor, New<External> (info));
tpl->SetClassName (UTF8(class_name));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
GIObjectInfo *parent_info = g_object_info_get_parent (info);
if (parent_info) {
auto parent_tpl = GetClassTemplateFromGI ((GIBaseInfo *) parent_info);
tpl->Inherit(parent_tpl);
} else {
tpl->Inherit(GetBaseClassTemplate());
}
return tpl;
}
static Local<FunctionTemplate> GetClassTemplate(GType gtype) {
void *data = g_type_get_qdata (gtype, GNodeJS::template_quark());
if (data) {
auto *persistent = (Persistent<FunctionTemplate> *) data;
auto tpl = New<FunctionTemplate> (*persistent);
return tpl;
} else {
GIBaseInfo *gi_info = g_irepository_find_by_gtype(NULL, gtype);
auto tpl = NewClassTemplate(gi_info);
auto *persistent = new Persistent<FunctionTemplate>(Isolate::GetCurrent(), tpl);
persistent->SetWeak (
g_base_info_ref (gi_info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
}
static Local<FunctionTemplate> GetClassTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
return GetClassTemplate(gtype);
}
Local<Function> MakeClass(GIBaseInfo *info) {
auto tpl = GetClassTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromGObject(GObject *gobject) {
if (gobject == NULL)
return Nan::Null();
void *data = g_object_get_qdata (gobject, GNodeJS::object_quark());
if (data) {
/* Easy case: we already have an object. */
auto *persistent = (Persistent<Object> *) data;
auto obj = New<Object> (*persistent);
return obj;
} else {
GType gtype = G_OBJECT_TYPE(gobject);
g_type_ensure(gtype); //void *klass = g_type_class_ref (type);
auto tpl = GetClassTemplate(gtype);
Local<Function> constructor = tpl->GetFunction ();
Local<Value> gobject_external = New<External> (gobject);
Local<Value> args[] = { gobject_external };
Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked();
return obj;
}
}
GObject * GObjectFromWrapper(Local<Value> value) {
if (!ValueHasInternalField(value))
return nullptr;
Local<Object> object = value->ToObject ();
void *ptr = object->GetAlignedPointerFromInternalField (0);
GObject *gobject = G_OBJECT (ptr);
return gobject;
}
};
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// 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.
#include "Utility.h"
#include "Container/VectorWrap.h"
#include "Container/SetWrap.h"
#include "Container/MapWrap.h"
#include "Property/Common.h"
#include "Container/Container.h"
#if defined(TULIP_DEBUG_MODE)
void tulip_debug_wrap(void) {
tulip::VectorWrap<int>::wrap("IVec");
tulip::SetWrap<int>::wrap("ISet");
tulip::MapWrap<int, std::string>::wrap("ISMap");
}
#else
# define tulip_debug_wrap() (void)0
#endif
BOOST_PYTHON_MODULE(Tulip) {
tulip_debug_wrap();
tulip::TulipDict::wrap();
}
<commit_msg>:construction: chore(tulip): updated the test for tulip<commit_after>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// 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.
#include "Utility.h"
#include "Container/VectorWrap.h"
#include "Container/SetWrap.h"
#include "Container/MapWrap.h"
// #include "Property/Common.h" // Not implementation
#include "Container/Container.h"
#include <iostream>
#if defined(TULIP_DEBUG_MODE)
static void tulip_run_callscript(const tulip::TulipDict& d) {
PyObject* k{};
PyObject* v{};
py::ssize_t pos{};
while (PyDict_Next(d.ptr(), &pos, &k, &v)) {
py::call_method<void>(v, "show");
}
}
void tulip_debug_wrap(void) {
tulip::VectorWrap<int>::wrap("IVec");
tulip::SetWrap<int>::wrap("ISet");
tulip::MapWrap<int, std::string>::wrap("ISMap");
py::def("tulip_run_callscript", tulip_run_callscript);
}
#else
# define tulip_debug_wrap() (void)0
#endif
BOOST_PYTHON_MODULE(Tulip) {
PyEval_InitThreads();
tulip_debug_wrap();
tulip::TulipList::wrap();
tulip::TulipDict::wrap();
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "GapValueAux.h"
#include "MooseSystem.h"
#include "mesh.h"
template<>
InputParameters validParams<GapValueAux>()
{
InputParameters params = validParams<AuxKernel>();
params.addRequiredParam<unsigned int>("paired_boundary", "The boundary on the other side of a gap.");
params.addRequiredCoupledVar("paired_variable", "The variable to get the value of.");
params.set<bool>("use_displaced_mesh") = true;
return params;
}
GapValueAux::GapValueAux(const std::string & name, InputParameters parameters)
:AuxKernel(name, parameters),
_penetration_locator(getPenetrationLocator(parameters.get<unsigned int>("paired_boundary"), getParam<std::vector<unsigned int> >("boundary")[0])),
_paired_variable(coupled("paired_variable"))
{
_moose_system.needSerializedSolution(true);
}
Real
GapValueAux::computeValue()
{
PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
Elem * slave_side = pinfo->_side;
std::vector<std::vector<Real> > & slave_side_phi = pinfo->_side_phi;
std::vector<unsigned int> slave_side_dof_indices;
_moose_system._dof_map->dof_indices(slave_side, slave_side_dof_indices ,_paired_variable);
Real gap_temp = 0.0;
for(unsigned int i=0; i<slave_side_dof_indices.size(); i++)
//The zero index is because we only have point that the phis are evaluated at
gap_temp += slave_side_phi[i][0] * _moose_system._serialized_solution(slave_side_dof_indices[i]);
std::cout<<gap_temp<<std::endl;
return gap_temp;
}
<commit_msg>change the way gap heat transfer is done such that the roughnesses are only considered when the gap gets below them... this provides a cutoff point while still _freezing_ the gap after it gets to a certain point<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "GapValueAux.h"
#include "MooseSystem.h"
#include "mesh.h"
template<>
InputParameters validParams<GapValueAux>()
{
InputParameters params = validParams<AuxKernel>();
params.addRequiredParam<unsigned int>("paired_boundary", "The boundary on the other side of a gap.");
params.addRequiredCoupledVar("paired_variable", "The variable to get the value of.");
params.set<bool>("use_displaced_mesh") = true;
return params;
}
GapValueAux::GapValueAux(const std::string & name, InputParameters parameters)
:AuxKernel(name, parameters),
_penetration_locator(getPenetrationLocator(parameters.get<unsigned int>("paired_boundary"), getParam<std::vector<unsigned int> >("boundary")[0])),
_paired_variable(coupled("paired_variable"))
{
_moose_system.needSerializedSolution(true);
}
Real
GapValueAux::computeValue()
{
PenetrationLocator::PenetrationInfo * pinfo = _penetration_locator._penetration_info[_current_node->id()];
Elem * slave_side = pinfo->_side;
std::vector<std::vector<Real> > & slave_side_phi = pinfo->_side_phi;
std::vector<unsigned int> slave_side_dof_indices;
_moose_system._dof_map->dof_indices(slave_side, slave_side_dof_indices ,_paired_variable);
Real gap_temp = 0.0;
for(unsigned int i=0; i<slave_side_dof_indices.size(); i++)
//The zero index is because we only have point that the phis are evaluated at
gap_temp += slave_side_phi[i][0] * _moose_system._serialized_solution(slave_side_dof_indices[i]);
return gap_temp;
}
<|endoftext|>
|
<commit_before>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "hstock.hxx"
#include "stock.hxx"
#include "hashmap.hxx"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
struct StockMap {
struct pool &pool;
const StockClass &cls;
void *class_ctx;
/**
* The maximum number of items in each stock.
*/
unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
unsigned max_idle;
struct hashmap &stocks;
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_linear(&_pool, "hstock", 4096)),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
stocks(*hashmap_new(&pool, 64)) {}
~StockMap() {
hashmap_rewind(&stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&stocks)) != nullptr) {
Stock *stock = (Stock *)pair->value;
stock_free(stock);
}
pool_unref(&pool);
}
void Destroy() {
DeleteFromPool(pool, this);
}
};
/*
* stock handler
*
*/
static void
hstock_stock_empty(Stock &stock, const char *uri, void *ctx)
{
StockMap *hstock = (StockMap *)ctx;
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)hstock, (const void *)&stock, uri);
hashmap_remove_existing(&hstock->stocks, uri, &stock);
stock_free(&stock);
}
static constexpr StockHandler hstock_stock_handler = {
.empty = hstock_stock_empty,
};
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(cls.item_size > sizeof(StockItem));
assert(cls.create != nullptr);
assert(cls.borrow != nullptr);
assert(cls.release != nullptr);
assert(cls.destroy != nullptr);
assert(max_idle > 0);
return NewFromPool<StockMap>(pool, pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
hstock->Destroy();
}
void
hstock_fade_all(StockMap &hstock)
{
hashmap_rewind(&hstock.stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&hstock.stocks)) != nullptr) {
Stock &stock = *(Stock *)pair->value;
stock_fade_all(stock);
}
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
struct hashmap *h = &stock.stocks;
hashmap_rewind(h);
const struct hashmap_pair *p;
while ((p = hashmap_next(h)) != nullptr) {
const Stock &s = *(const Stock *)p->value;
stock_add_stats(s, data);
}
}
static Stock &
hstock_get_stock(StockMap &hstock, const char *uri)
{
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
if (stock == nullptr) {
stock = stock_new(hstock.pool, hstock.cls, hstock.class_ctx,
uri, hstock.limit, hstock.max_idle,
hstock_stock_handler, &hstock);
hashmap_set(&hstock.stocks, stock_get_uri(*stock), stock);
}
return *stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
const StockGetHandler &handler, void *handler_ctx,
struct async_operation_ref &async_ref)
{
auto &stock = hstock_get_stock(hstock, uri);
stock_get(stock, pool, info, handler, handler_ctx, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
Stock &stock = hstock_get_stock(hstock, uri);
return stock_get_now(stock, pool, info, error_r);
}
void
hstock_put(gcc_unused StockMap &hstock, gcc_unused const char *uri,
StockItem &object, bool destroy)
{
#ifndef NDEBUG
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
assert(stock != nullptr);
assert(stock == object.stock);
#endif
stock_put(object, destroy);
}
<commit_msg>hstock: make attributes "const"<commit_after>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "hstock.hxx"
#include "stock.hxx"
#include "hashmap.hxx"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
struct StockMap {
struct pool &pool;
const StockClass &cls;
void *const class_ctx;
/**
* The maximum number of items in each stock.
*/
const unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
const unsigned max_idle;
struct hashmap &stocks;
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_linear(&_pool, "hstock", 4096)),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
stocks(*hashmap_new(&pool, 64)) {}
~StockMap() {
hashmap_rewind(&stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&stocks)) != nullptr) {
Stock *stock = (Stock *)pair->value;
stock_free(stock);
}
pool_unref(&pool);
}
void Destroy() {
DeleteFromPool(pool, this);
}
};
/*
* stock handler
*
*/
static void
hstock_stock_empty(Stock &stock, const char *uri, void *ctx)
{
StockMap *hstock = (StockMap *)ctx;
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)hstock, (const void *)&stock, uri);
hashmap_remove_existing(&hstock->stocks, uri, &stock);
stock_free(&stock);
}
static constexpr StockHandler hstock_stock_handler = {
.empty = hstock_stock_empty,
};
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(cls.item_size > sizeof(StockItem));
assert(cls.create != nullptr);
assert(cls.borrow != nullptr);
assert(cls.release != nullptr);
assert(cls.destroy != nullptr);
assert(max_idle > 0);
return NewFromPool<StockMap>(pool, pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
hstock->Destroy();
}
void
hstock_fade_all(StockMap &hstock)
{
hashmap_rewind(&hstock.stocks);
const struct hashmap_pair *pair;
while ((pair = hashmap_next(&hstock.stocks)) != nullptr) {
Stock &stock = *(Stock *)pair->value;
stock_fade_all(stock);
}
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
struct hashmap *h = &stock.stocks;
hashmap_rewind(h);
const struct hashmap_pair *p;
while ((p = hashmap_next(h)) != nullptr) {
const Stock &s = *(const Stock *)p->value;
stock_add_stats(s, data);
}
}
static Stock &
hstock_get_stock(StockMap &hstock, const char *uri)
{
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
if (stock == nullptr) {
stock = stock_new(hstock.pool, hstock.cls, hstock.class_ctx,
uri, hstock.limit, hstock.max_idle,
hstock_stock_handler, &hstock);
hashmap_set(&hstock.stocks, stock_get_uri(*stock), stock);
}
return *stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
const StockGetHandler &handler, void *handler_ctx,
struct async_operation_ref &async_ref)
{
auto &stock = hstock_get_stock(hstock, uri);
stock_get(stock, pool, info, handler, handler_ctx, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
Stock &stock = hstock_get_stock(hstock, uri);
return stock_get_now(stock, pool, info, error_r);
}
void
hstock_put(gcc_unused StockMap &hstock, gcc_unused const char *uri,
StockItem &object, bool destroy)
{
#ifndef NDEBUG
Stock *stock = (Stock *)hashmap_get(&hstock.stocks, uri);
assert(stock != nullptr);
assert(stock == object.stock);
#endif
stock_put(object, destroy);
}
<|endoftext|>
|
<commit_before>#include "stepper_motor.h"
#include "jenny5_types.h"
#include "utils.h"
//-------------------------------------------------------------------------------
t_stepper_motor_controller::t_stepper_motor_controller(void)
{
// dir_pin = 2;
// step_pin = 3;
enable_pin = 4;
sensors_count = 0;
sensors = NULL;
motor_running = 0;
stepper = NULL;
going_to_position = false;
sensor_stop_position = NULL;
}
//-------------------------------------------------------------------------------
t_stepper_motor_controller::~t_stepper_motor_controller(void)
{
if (stepper)
delete stepper;
if (sensors)
delete[] sensors;
if (sensor_stop_position)
delete[] sensor_stop_position;
sensors_count = 0;
motor_running = 0;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::create_init(byte _dir, byte _step, byte _enable, float default_motor_speed, float default_motor_acceleration)
{
enable_pin = _enable;
if (stepper)
delete stepper;
if (sensors)
delete[] sensors;
if (sensor_stop_position)
delete[] sensor_stop_position;
sensors_count = 0;
motor_running = 0;
going_to_position = false;
stepper = new AccelStepper(AccelStepper::DRIVER, _step, _dir);
stepper->setMaxSpeed(default_motor_speed);
stepper->setSpeed(default_motor_speed);
stepper->setAcceleration(default_motor_acceleration);
digitalWrite(_step, LOW);
digitalWrite(_dir, LOW);
pinMode(enable_pin, OUTPUT);
digitalWrite(enable_pin, HIGH); // all motors are disabled now
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::move_motor(int num_steps)
{
digitalWrite(enable_pin, LOW); // turn motor on
stepper->move(num_steps); //move num_steps
motor_running = 1;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::move_motor_to(int _position)
{
digitalWrite(enable_pin, LOW); // turn motor on
stepper->moveTo(_position); //move num_steps
motor_running = 1;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_speed(float _motor_speed)
{
stepper->setMaxSpeed(_motor_speed);
stepper->setSpeed(_motor_speed);
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_acceleration(float _motor_acceleration)
{
stepper->setAcceleration(_motor_acceleration);
// motor_acceleration = _motor_acceleration;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_speed_and_acceleration(float _motor_speed, float _motor_acceleration)
{
stepper->setMaxSpeed(_motor_speed);
stepper->setSpeed(_motor_speed);
stepper->setAcceleration(_motor_acceleration);
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::disable_motor(void)
{
digitalWrite(enable_pin, HIGH); // disable motor
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::lock_motor(void)
{
digitalWrite(enable_pin, LOW); // enable motor
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::add_sensor(byte sensor_type, byte sensor_index, int _min_pos, int _max_pos, int _home_pos, int8_t __direction)
{
sensors[sensors_count].type = sensor_type;
sensors[sensors_count].index = sensor_index;
sensors[sensors_count].min_pos = _min_pos;
sensors[sensors_count].max_pos = _max_pos;
sensors[sensors_count].home_pos = _home_pos;
sensors[sensors_count]._direction = __direction;
sensors_count++;
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::get_num_attached_sensors(void)
{
return sensors_count;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_num_attached_sensors(byte num_sensors)
{
if (sensors_count != num_sensors) {
// clear memory if the array has a different size
if (sensors) {
delete[] sensors;
sensors = NULL;
}
if (sensor_stop_position) {
delete[] sensor_stop_position;
sensor_stop_position = NULL;
}
if (num_sensors > 0) {
sensors = new t_sensor_info[num_sensors]; // allocate memory for them
sensor_stop_position = new int[num_sensors];
}
}
sensors_count = 0; // actual number of sensors
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_running(byte is_running)
{
motor_running = is_running;
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::is_motor_running(void)
{
return motor_running;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::get_sensor(byte sensor_index_in_motor_list, byte *sensor_type, byte *sensor_index, int *_min_pos, int *_max_pos, int *_home_pos, int8_t *__direction)
{
*sensor_type = sensors[sensor_index_in_motor_list].type;
*sensor_index = sensors[sensor_index_in_motor_list].index;
*_min_pos = sensors[sensor_index_in_motor_list].min_pos;
*_max_pos = sensors[sensor_index_in_motor_list].max_pos;
*_home_pos = sensors[sensor_index_in_motor_list].home_pos;
*__direction = sensors[sensor_index_in_motor_list]._direction;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::get_motor_speed_and_acceleration(float *_motor_speed, float *_motor_acceleration)
{
if (stepper) {
*_motor_acceleration = stepper->getAcceleration();
*_motor_speed = stepper->maxSpeed();
}
else {
*_motor_speed = 0;
*_motor_acceleration = 0;
}
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::run_motor(t_potentiometers_controller *potentiometers_control, t_buttons_controller *buttons_controller, int& dist_left_to_go)
{
// returns 1 if is still running
// returns 2 if it does nothing
// returns 0 if it has just stopped; in dist_to_go we have what is left to run (or 0)
bool limit_reached = false;
int distance_to_go = stepper->distanceToGo();
if (distance_to_go) {
for (byte j = 0; j < sensors_count; j++){
byte sensor_index = sensors[j].index;
byte type = sensors[j].type;
if (POTENTIOMETER == type) {
int potentiometer_direction = sensors[j]._direction;
int val = potentiometers_control->get_position(sensor_index);
if (sensors[j].min_pos > val){
if (distance_to_go * potentiometer_direction < 0) {
limit_reached = true;
}
}
if (sensors[j].max_pos < val){
if (distance_to_go * potentiometer_direction > 0) {
limit_reached = true;
}
}
if (going_to_position) {
// must stop to home
int pot_position = potentiometers_control->get_position(sensor_index);
int pot_stop_position = sensor_stop_position[j]; // sensors[j].home_pos;// potentiometers_control->get_home_position(sensor_index);
int8_t pot_direction = sensors[j]._direction;// potentiometers_control->get_direction(sensor_index);
if (pot_direction == 1) {
if (distance_to_go > 0) {
if (pot_position >= pot_stop_position)
limit_reached = true;
}
else { // distance to go is negative
if (pot_position <= pot_stop_position)
limit_reached = true;
}
}
else {// pot direction == -1
if (distance_to_go > 0) {
if (pot_position <= pot_stop_position)
limit_reached = true;
}
else { // distance to go is negative
if (pot_position >= pot_stop_position)
limit_reached = true;
}
}
}
}
else
if (BUTTON == type) {
int button_direction = sensors[j]._direction;
int button_state = buttons_controller->get_state(sensor_index);
if (button_state == 1) // limit reached
if (distance_to_go * button_direction > 0)
limit_reached = true;
}
}
if (!limit_reached){
stepper->run();
return MOTOR_STILL_RUNNING; // still running
}
else {
if (is_motor_running()) {
int to_go = stepper->distanceToGo();
stepper->setCurrentPosition(0);
stepper->move(0);
dist_left_to_go = to_go;
going_to_position = false;
//Serial.println("left to go > 0");
set_motor_running(0);
return MOTOR_JUST_STOPPED;
}
else
return MOTOR_DOES_NOTHING;
}
}
else {
// the motor has just finished the move, so we output that event
going_to_position = false;
if (is_motor_running()) {
set_motor_running(0);
dist_left_to_go = 0;
//Serial.println("left to go == 0");
return MOTOR_JUST_STOPPED; // distance to go
}
else
return MOTOR_DOES_NOTHING;
}
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::go_home(t_potentiometers_controller *potentiometers_control, t_buttons_controller* buttons_controller)
{
if (sensors_count > 0) {
int sensor_index = sensors[0].index;
byte sensor_type = sensors[0].type;
if (sensor_type == POTENTIOMETER) {
//calculate the remaining distance from the current position to home position, relative to the direction and position of the potentiometer
int pot_dir = sensors[0]._direction; // potentiometers_control->get_direction(sensor_index);
int pot_home = sensors[0].home_pos; // potentiometers_control->get_home_position(sensor_index);
int pot_pos = potentiometers_control->get_position(sensor_index);
int max_steps_to_home = pot_dir * sign(pot_home - pot_pos) * 32000;
going_to_position = true;
sensor_stop_position[0] = pot_home;
move_motor(max_steps_to_home);
}
else if (sensor_type == BUTTON) {
int b_direction = sensors[0]._direction;//buttons_controller->get_direction(sensor_index);
int max_steps_to_home;
if (b_direction > 0)
max_steps_to_home = 32000; // this depends on microstepping, gear redunction etc
else
max_steps_to_home = -32000;
going_to_position = true;
move_motor(max_steps_to_home);
}
}
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::go_to_sensor_position(int pot_stop_position)
{
if (sensors_count > 0) {
byte sensor_type = sensors[0].type;
if (sensor_type == POTENTIOMETER) {
//calculate the remaining distance from the current position to home position, relative to the direction and position of the potentiometer
int pot_dir = sensors[0]._direction; // potentiometers_control->get_direction(sensor_index);
int pot_home = sensors[0].home_pos; // potentiometers_control->get_home_position(sensor_index);
int max_steps_to_home = pot_dir * sign(-pot_home + pot_stop_position) * 32000;
//Serial.println(pot_dir);
//Serial.println(pot_home);
//Serial.println(pot_stop_position);
// Serial.println(distance_to_home);
going_to_position = true;
sensor_stop_position[0] = pot_stop_position;
//Serial.println(max_steps_to_home);
move_motor(max_steps_to_home);
}
else if (sensor_type == BUTTON) {
int b_direction = sensors[0]._direction;//buttons_controller->get_direction(sensor_index);
int max_steps_to_home;
if (b_direction > 0)
max_steps_to_home = 32000; // this depends on microstepping, gear redunction etc
else
max_steps_to_home = -32000;
going_to_position = true;
move_motor(max_steps_to_home);
}
}
}
//-------------------------------------------------------------------------------
<commit_msg>removed button from go_to_sensor_position method<commit_after>#include "stepper_motor.h"
#include "jenny5_types.h"
#include "utils.h"
//-------------------------------------------------------------------------------
t_stepper_motor_controller::t_stepper_motor_controller(void)
{
// dir_pin = 2;
// step_pin = 3;
enable_pin = 4;
sensors_count = 0;
sensors = NULL;
motor_running = 0;
stepper = NULL;
going_to_position = false;
sensor_stop_position = NULL;
}
//-------------------------------------------------------------------------------
t_stepper_motor_controller::~t_stepper_motor_controller(void)
{
if (stepper)
delete stepper;
if (sensors)
delete[] sensors;
if (sensor_stop_position)
delete[] sensor_stop_position;
sensors_count = 0;
motor_running = 0;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::create_init(byte _dir, byte _step, byte _enable, float default_motor_speed, float default_motor_acceleration)
{
enable_pin = _enable;
if (stepper)
delete stepper;
if (sensors)
delete[] sensors;
if (sensor_stop_position)
delete[] sensor_stop_position;
sensors_count = 0;
motor_running = 0;
going_to_position = false;
stepper = new AccelStepper(AccelStepper::DRIVER, _step, _dir);
stepper->setMaxSpeed(default_motor_speed);
stepper->setSpeed(default_motor_speed);
stepper->setAcceleration(default_motor_acceleration);
digitalWrite(_step, LOW);
digitalWrite(_dir, LOW);
pinMode(enable_pin, OUTPUT);
digitalWrite(enable_pin, HIGH); // all motors are disabled now
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::move_motor(int num_steps)
{
digitalWrite(enable_pin, LOW); // turn motor on
stepper->move(num_steps); //move num_steps
motor_running = 1;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::move_motor_to(int _position)
{
digitalWrite(enable_pin, LOW); // turn motor on
stepper->moveTo(_position); //move num_steps
motor_running = 1;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_speed(float _motor_speed)
{
stepper->setMaxSpeed(_motor_speed);
stepper->setSpeed(_motor_speed);
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_acceleration(float _motor_acceleration)
{
stepper->setAcceleration(_motor_acceleration);
// motor_acceleration = _motor_acceleration;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_speed_and_acceleration(float _motor_speed, float _motor_acceleration)
{
stepper->setMaxSpeed(_motor_speed);
stepper->setSpeed(_motor_speed);
stepper->setAcceleration(_motor_acceleration);
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::disable_motor(void)
{
digitalWrite(enable_pin, HIGH); // disable motor
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::lock_motor(void)
{
digitalWrite(enable_pin, LOW); // enable motor
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::add_sensor(byte sensor_type, byte sensor_index, int _min_pos, int _max_pos, int _home_pos, int8_t __direction)
{
sensors[sensors_count].type = sensor_type;
sensors[sensors_count].index = sensor_index;
sensors[sensors_count].min_pos = _min_pos;
sensors[sensors_count].max_pos = _max_pos;
sensors[sensors_count].home_pos = _home_pos;
sensors[sensors_count]._direction = __direction;
sensors_count++;
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::get_num_attached_sensors(void)
{
return sensors_count;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_num_attached_sensors(byte num_sensors)
{
if (sensors_count != num_sensors) {
// clear memory if the array has a different size
if (sensors) {
delete[] sensors;
sensors = NULL;
}
if (sensor_stop_position) {
delete[] sensor_stop_position;
sensor_stop_position = NULL;
}
if (num_sensors > 0) {
sensors = new t_sensor_info[num_sensors]; // allocate memory for them
sensor_stop_position = new int[num_sensors];
}
}
sensors_count = 0; // actual number of sensors
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::set_motor_running(byte is_running)
{
motor_running = is_running;
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::is_motor_running(void)
{
return motor_running;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::get_sensor(byte sensor_index_in_motor_list, byte *sensor_type, byte *sensor_index, int *_min_pos, int *_max_pos, int *_home_pos, int8_t *__direction)
{
*sensor_type = sensors[sensor_index_in_motor_list].type;
*sensor_index = sensors[sensor_index_in_motor_list].index;
*_min_pos = sensors[sensor_index_in_motor_list].min_pos;
*_max_pos = sensors[sensor_index_in_motor_list].max_pos;
*_home_pos = sensors[sensor_index_in_motor_list].home_pos;
*__direction = sensors[sensor_index_in_motor_list]._direction;
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::get_motor_speed_and_acceleration(float *_motor_speed, float *_motor_acceleration)
{
if (stepper) {
*_motor_acceleration = stepper->getAcceleration();
*_motor_speed = stepper->maxSpeed();
}
else {
*_motor_speed = 0;
*_motor_acceleration = 0;
}
}
//-------------------------------------------------------------------------------
byte t_stepper_motor_controller::run_motor(t_potentiometers_controller *potentiometers_control, t_buttons_controller *buttons_controller, int& dist_left_to_go)
{
// returns 1 if is still running
// returns 2 if it does nothing
// returns 0 if it has just stopped; in dist_to_go we have what is left to run (or 0)
bool limit_reached = false;
int distance_to_go = stepper->distanceToGo();
if (distance_to_go) {
for (byte j = 0; j < sensors_count; j++){
byte sensor_index = sensors[j].index;
byte sensor_type = sensors[j].type;
if (sensor_type == POTENTIOMETER) {
int potentiometer_direction = sensors[j]._direction;
int val = potentiometers_control->get_position(sensor_index);
if (sensors[j].min_pos > val){
if (distance_to_go * potentiometer_direction < 0) {
limit_reached = true;
}
}
if (sensors[j].max_pos < val){
if (distance_to_go * potentiometer_direction > 0) {
limit_reached = true;
}
}
if (going_to_position) {
// must stop to home
int pot_position = potentiometers_control->get_position(sensor_index);
int pot_stop_position = sensor_stop_position[j]; // sensors[j].home_pos;// potentiometers_control->get_home_position(sensor_index);
int8_t pot_direction = sensors[j]._direction;// potentiometers_control->get_direction(sensor_index);
if (pot_direction == 1) {
if (distance_to_go > 0) {
if (pot_position >= pot_stop_position)
limit_reached = true;
}
else { // distance to go is negative
if (pot_position <= pot_stop_position)
limit_reached = true;
}
}
else {// pot direction == -1
if (distance_to_go > 0) {
if (pot_position <= pot_stop_position)
limit_reached = true;
}
else { // distance to go is negative
if (pot_position >= pot_stop_position)
limit_reached = true;
}
}
}
}
else
if (sensor_type == BUTTON) {
int button_direction = sensors[j]._direction;
int button_state = buttons_controller->get_state(sensor_index);
if (button_state == 1) // limit reached
if (distance_to_go * button_direction > 0)
limit_reached = true;
}
}
if (!limit_reached){
stepper->run();
return MOTOR_STILL_RUNNING; // still running
}
else {
if (is_motor_running()) {
int to_go = stepper->distanceToGo();
stepper->setCurrentPosition(0);
stepper->move(0);
dist_left_to_go = to_go;
going_to_position = false;
//Serial.println("left to go > 0");
set_motor_running(0);
return MOTOR_JUST_STOPPED;
}
else
return MOTOR_DOES_NOTHING;
}
}
else {
// the motor has just finished the move, so we output that event
going_to_position = false;
if (is_motor_running()) {
set_motor_running(0);
dist_left_to_go = 0;
//Serial.println("left to go == 0");
return MOTOR_JUST_STOPPED; // distance to go
}
else
return MOTOR_DOES_NOTHING;
}
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::go_home(t_potentiometers_controller *potentiometers_control, t_buttons_controller* buttons_controller)
{
if (sensors_count > 0) {
int sensor_index = sensors[0].index;
byte sensor_type = sensors[0].type;
if (sensor_type == POTENTIOMETER) {
//calculate the remaining distance from the current position to home position, relative to the direction and position of the potentiometer
int pot_dir = sensors[0]._direction; // potentiometers_control->get_direction(sensor_index);
int pot_home = sensors[0].home_pos; // potentiometers_control->get_home_position(sensor_index);
int pot_pos = potentiometers_control->get_position(sensor_index);
int max_steps_to_home = pot_dir * sign(pot_home - pot_pos) * 32000;
going_to_position = true;
sensor_stop_position[0] = pot_home;
move_motor(max_steps_to_home);
}
else if (sensor_type == BUTTON) {
int b_direction = sensors[0]._direction;//buttons_controller->get_direction(sensor_index);
int max_steps_to_home;
if (b_direction > 0)
max_steps_to_home = 32000; // this depends on microstepping, gear redunction etc
else
max_steps_to_home = -32000;
going_to_position = true;
move_motor(max_steps_to_home);
}
}
}
//-------------------------------------------------------------------------------
void t_stepper_motor_controller::go_to_sensor_position(int pot_stop_position)
{
if (sensors_count > 0) {
byte sensor_type = sensors[0].type;
if (sensor_type == POTENTIOMETER) {
//calculate the remaining distance from the current position to home position, relative to the direction and position of the potentiometer
int pot_dir = sensors[0]._direction; // potentiometers_control->get_direction(sensor_index);
int pot_home = sensors[0].home_pos; // potentiometers_control->get_home_position(sensor_index);
int max_steps_to_home = pot_dir * sign(-pot_home + pot_stop_position) * 32000;
//Serial.println(pot_dir);
//Serial.println(pot_home);
//Serial.println(pot_stop_position);
// Serial.println(distance_to_home);
going_to_position = true;
sensor_stop_position[0] = pot_stop_position;
//Serial.println(max_steps_to_home);
move_motor(max_steps_to_home);
}
}
}
//-------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "Transient.h"
//Moose includes
#include "Kernel.h"
#include "Factory.h"
#include "SubProblem.h"
#include "ProblemFactory.h"
#include "TimePeriod.h"
#include "TimeScheme.h"
//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"
#include "o_string_stream.h"
// C++ Includes
#include <iomanip>
#include <iostream>
#include <fstream>
template<>
InputParameters validParams<Transient>()
{
InputParameters params = validParams<Executioner>();
std::vector<Real> sync_times(1);
sync_times[0] = -1;
params.addParam<Real>("start_time", 0.0, "The start time of the simulation");
params.addParam<Real>("end_time", 1.0e30, "The end time of the simulation");
params.addRequiredParam<Real>("dt", "The timestep size between solves");
params.addParam<Real>("dtmin", 0.0, "The minimum timestep size in an adaptive run");
params.addParam<Real>("dtmax", 1.0e30, "The maximum timestep size in an adaptive run");
params.addParam<Real>("num_steps", std::numeric_limits<Real>::max(), "The number of timesteps in a transient run");
params.addParam<int> ("n_startup_steps", 0, "The number of timesteps during startup");
params.addParam<bool>("trans_ss_check", false, "Whether or not to check for steady state conditions");
params.addParam<Real>("ss_check_tol", 1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
params.addParam<Real>("ss_tmin", 0.0, "Minimum number of timesteps to take before checking for steady state conditions.");
params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");
params.addParam<std::vector<Real> >("time_t", "The values of t");
params.addParam<std::vector<Real> >("time_dt", "The values of dt");
params.addParam<Real>("growth_factor", 2, "Maximum ratio of new to previous timestep sizes following a step that required the time step to be cut due to a failed solve. For use with 'time_t' and 'time_dt'.");
params.addParam<Real>("predictor_scale", 0.0, "The scale factor for the predictor (can range from 0 to 1)");
params.addParam<std::vector<std::string> >("time_periods", "The names of periods");
params.addParam<std::vector<Real> >("time_period_starts", "The start times of time periods");
params.addParam<std::vector<Real> >("time_period_ends", "The end times of time periods");
params.addParam<bool>("use_AB2", false, "Whether to use the Adams-Bashforth 2 predictor");
params.addParam<bool>("use_littlef", false, "if a function evaluation should be used or time deriv's in predictors");
params.addParam<bool>("abort_on_solve_fail", false, "abort if solve not converged rather than cut timestep");
return params;
}
Transient::Transient(const std::string & name, InputParameters parameters) :
Executioner(name, parameters),
_problem(*ProblemFactory::instance()->createFEProblem(_mesh)),
_t_step(_problem.timeStep()),
_time(_problem.time()),
_time_old(_problem.timeOld()),
_input_dt(getParam<Real>("dt")),
_dt(_problem.dt()),
_dt_old(_problem.dtOld()),
_prev_dt(-1),
_reset_dt(false),
_end_time(getParam<Real>("end_time")),
_dtmin(getParam<Real>("dtmin")),
_dtmax(getParam<Real>("dtmax")),
_num_steps(getParam<Real>("num_steps")),
_n_startup_steps(getParam<int>("n_startup_steps")),
_trans_ss_check(getParam<bool>("trans_ss_check")),
_ss_check_tol(getParam<Real>("ss_check_tol")),
_ss_tmin(getParam<Real>("ss_tmin")),
_converged(true),
_sync_times(getParam<std::vector<Real> >("sync_times")),
_remaining_sync_time(true),
_time_ipol(getParam<std::vector<Real> >("time_t"),
getParam<std::vector<Real> >("time_dt")),
_use_time_ipol(_time_ipol.getSampleSize() > 0),
_growth_factor(getParam<Real>("growth_factor")),
_cutback_occurred(false),
_abort(getParam<bool>("abort_on_solve_fail"))
{
_t_step = 0;
_dt = 0;
_time = _time_old = getParam<Real>("start_time");
_problem.transient(true);
if (parameters.wasSeenInInput("predictor_scale"))
{
Real predscale(getParam<Real>("predictor_scale"));
if (predscale >= 0.0 and predscale <= 1.0)
{
_problem.getNonlinearSystem().setPredictorScale(getParam<Real>("predictor_scale"));
}
else
{
mooseError("Input value for predictor_scale = "<< predscale << ", outside of permissible range (0 to 1)");
}
_problem.getTimeScheme()->_use_AB2 = getParam<bool>("use_AB2");
_problem.getTimeScheme()->_use_littlef = getParam<bool>("use_littlef");
}
if (!_restart_file_base.empty())
_problem.setRestartFile(_restart_file_base);
}
Transient::~Transient()
{
// This problem was built by the Factory and needs to be released by this destructor
delete &_problem;
}
void
Transient::execute()
{
_problem.initialSetup();
preExecute();
// Start time loop...
while(keepGoing())
{
takeStep();
if (lastSolveConverged())
endStep();
}
postExecute();
}
void
Transient::takeStep(Real input_dt)
{
if (_converged)
_problem.copyOldSolutions();
else
_problem.restoreSolutions();
_dt_old = _dt;
if (input_dt == -1.0)
_dt = computeConstrainedDT();
else
_dt = input_dt;
_problem.onTimestepBegin();
if (_converged)
{
// Update backward material data structures
_problem.updateMaterials();
}
// Increment time
_time = _time_old + _dt;
std::cout<<"DT: "<<_dt<<std::endl;
std::cout << " Solving time step ";
{
OStringStream out;
OSSInt(out,2,_t_step);
out << ", time=";
OSSRealzeroleft(out, 9, 6, _time);
out << "...";
std::cout << out.str() << std::endl;
}
preSolve();
_problem.timestepSetup();
// Compute Pre-Aux User Objects (Timestep begin)
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::PRE_AUX);
// Compute TimestepBegin AuxKernels
_problem.computeAuxiliaryKernels(EXEC_TIMESTEP_BEGIN);
// Compute Post-Aux User Objects (Timestep begin)
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::POST_AUX);
_problem.solve();
_converged = _problem.converged();
// Compute Pre-Aux User Objects
_problem.computeUserObjects(EXEC_TIMESTEP, UserObjectWarehouse::PRE_AUX);
postSolve();
_problem.onTimestepEnd();
// We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
bool last_solve_converged = lastSolveConverged();
// If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
if (last_solve_converged)
{
_problem.computeUserObjects(EXEC_TIMESTEP, UserObjectWarehouse::POST_AUX);
}
}
void
Transient::endStep()
{
// Compute the Error Indicators and Markers
_problem.computeIndicatorsAndMarkers();
// if _reset_dt is true, force the output no matter what
_problem.output(_reset_dt);
_problem.outputPostprocessors(_reset_dt);
#ifdef LIBMESH_ENABLE_AMR
if (_problem.adaptivity().isOn())
{
_problem.adaptMesh();
_problem.out().meshChanged();
}
#endif
_time_old = _time;
_t_step++;
}
Real
Transient::computeConstrainedDT()
{
// If this is the first step
if (_t_step == 0)
{
_t_step = 1;
_dt = _input_dt;
}
// // If start up steps are needed
// if(_t_step == 1 && _n_startup_steps > 1)
// _dt = _input_dt/(double)(_n_startup_steps);
// else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)
// _dt = _input_dt;
Real dt_cur = _dt;
//After startup steps, compute new dt
if (_t_step > _n_startup_steps)
dt_cur = computeDT();
// Don't let the time step size exceed maximum time step size
if (dt_cur > _dtmax)
dt_cur = _dtmax;
// Don't allow time step size to be smaller than minimum time step size
if (dt_cur < _dtmin)
dt_cur = _dtmin;
// Don't let time go beyond simulation end time
if (_time + dt_cur > _end_time)
dt_cur = _end_time - _time;
// Adjust to a sync time if supplied and skipped over
if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)
{
dt_cur = *_curr_sync_time_iter - _time;
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
_prev_dt = _dt;
_reset_dt = true;
}
else
{
if (_reset_dt)
{
if (_use_time_ipol)
dt_cur = _time_ipol.sample(_time);
else
dt_cur = _prev_dt;
_reset_dt = false;
}
}
return dt_cur;
}
Real
Transient::computeDT()
{
if (!lastSolveConverged())
{
_cutback_occurred = true;
//std::cout<<"Solve failed... cutting timestep"<<std::endl;
//return _dt / 2.0;
// Instead of blindly cutting timestep, respect dtmin.
if (_dt <= _dtmin)
mooseError("Solve failed and timestep already at or below dtmin, cannot continue!");
if (0.5 * _dt >= _dtmin)
return 0.5 * _dt;
else // (0.5 * _dt < _dtmin)
return _dtmin;
}
Real dt = _dt;
if (_use_time_ipol)
{
dt = _time_ipol.sample(_time);
if (_cutback_occurred &&
dt > _dt * _growth_factor)
{
dt = _dt * _growth_factor;
}
}
_cutback_occurred = false;
return dt;
}
bool
Transient::keepGoing()
{
// Check for stop condition based upon steady-state check flag:
if(_converged && _trans_ss_check == true && _time > _ss_tmin)
{
// Compute new time solution l2_norm
Real new_time_solution_norm = _problem.getNonlinearSystem().currentSolution()->l2_norm();
// Compute l2_norm relative error
Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;
// Check current solution relative error norm against steady-state tolerance
if(ss_relerr_norm < _ss_check_tol)
{
std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
return false;
}
else // Keep going
{
// Update solution norm for next time step
_old_time_solution_norm = new_time_solution_norm;
// Print steady-state relative error norm
std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
}
}
if(!_converged && _abort)
{
std::cout<<"Aborting as solve did not converge and input selected to abort"<<std::endl;
return false;
}
// Check for stop condition based upon number of simulation steps and/or solution end time:
if(_t_step>_num_steps)
return false;
if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
return false;
return true;
}
bool
Transient::lastSolveConverged()
{
return _converged;
}
void
Transient::preExecute()
{
// process time periods
const std::vector<TimePeriod *> _time_periods = _problem.getTimePeriods();
for (unsigned int i = 0; i < _time_periods.size(); ++i)
_sync_times.push_back(_time_periods[i]->start());
const std::vector<Real> & time = getParam<std::vector<Real> >("time_t");
if (_use_time_ipol)
_sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); // insert times as sync points except the very first one
sort(_sync_times.begin(), _sync_times.end());
_sync_times.erase(std::unique(_sync_times.begin(), _sync_times.end()), _sync_times.end()); // remove duplicates (needs sorted array)
// Advance to the first sync time if one is provided in sim time range
_curr_sync_time_iter = _sync_times.begin();
while (_remaining_sync_time && *_curr_sync_time_iter <= _time)
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
}
<commit_msg>Fixing uninitialized memory - refs #720<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "Transient.h"
//Moose includes
#include "Kernel.h"
#include "Factory.h"
#include "SubProblem.h"
#include "ProblemFactory.h"
#include "TimePeriod.h"
#include "TimeScheme.h"
//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"
#include "o_string_stream.h"
// C++ Includes
#include <iomanip>
#include <iostream>
#include <fstream>
template<>
InputParameters validParams<Transient>()
{
InputParameters params = validParams<Executioner>();
std::vector<Real> sync_times(1);
sync_times[0] = -1;
params.addParam<Real>("start_time", 0.0, "The start time of the simulation");
params.addParam<Real>("end_time", 1.0e30, "The end time of the simulation");
params.addRequiredParam<Real>("dt", "The timestep size between solves");
params.addParam<Real>("dtmin", 0.0, "The minimum timestep size in an adaptive run");
params.addParam<Real>("dtmax", 1.0e30, "The maximum timestep size in an adaptive run");
params.addParam<Real>("num_steps", std::numeric_limits<Real>::max(), "The number of timesteps in a transient run");
params.addParam<int> ("n_startup_steps", 0, "The number of timesteps during startup");
params.addParam<bool>("trans_ss_check", false, "Whether or not to check for steady state conditions");
params.addParam<Real>("ss_check_tol", 1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
params.addParam<Real>("ss_tmin", 0.0, "Minimum number of timesteps to take before checking for steady state conditions.");
params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");
params.addParam<std::vector<Real> >("time_t", "The values of t");
params.addParam<std::vector<Real> >("time_dt", "The values of dt");
params.addParam<Real>("growth_factor", 2, "Maximum ratio of new to previous timestep sizes following a step that required the time step to be cut due to a failed solve. For use with 'time_t' and 'time_dt'.");
params.addParam<Real>("predictor_scale", 0.0, "The scale factor for the predictor (can range from 0 to 1)");
params.addParam<std::vector<std::string> >("time_periods", "The names of periods");
params.addParam<std::vector<Real> >("time_period_starts", "The start times of time periods");
params.addParam<std::vector<Real> >("time_period_ends", "The end times of time periods");
params.addParam<bool>("use_AB2", false, "Whether to use the Adams-Bashforth 2 predictor");
params.addParam<bool>("use_littlef", false, "if a function evaluation should be used or time deriv's in predictors");
params.addParam<bool>("abort_on_solve_fail", false, "abort if solve not converged rather than cut timestep");
return params;
}
Transient::Transient(const std::string & name, InputParameters parameters) :
Executioner(name, parameters),
_problem(*ProblemFactory::instance()->createFEProblem(_mesh)),
_t_step(_problem.timeStep()),
_time(_problem.time()),
_time_old(_problem.timeOld()),
_input_dt(getParam<Real>("dt")),
_dt(_problem.dt()),
_dt_old(_problem.dtOld()),
_prev_dt(-1),
_reset_dt(false),
_end_time(getParam<Real>("end_time")),
_dtmin(getParam<Real>("dtmin")),
_dtmax(getParam<Real>("dtmax")),
_num_steps(getParam<Real>("num_steps")),
_n_startup_steps(getParam<int>("n_startup_steps")),
_trans_ss_check(getParam<bool>("trans_ss_check")),
_ss_check_tol(getParam<Real>("ss_check_tol")),
_ss_tmin(getParam<Real>("ss_tmin")),
_old_time_solution_norm(0.0),
_converged(true),
_sync_times(getParam<std::vector<Real> >("sync_times")),
_remaining_sync_time(true),
_time_ipol(getParam<std::vector<Real> >("time_t"),
getParam<std::vector<Real> >("time_dt")),
_use_time_ipol(_time_ipol.getSampleSize() > 0),
_growth_factor(getParam<Real>("growth_factor")),
_cutback_occurred(false),
_abort(getParam<bool>("abort_on_solve_fail"))
{
_t_step = 0;
_dt = 0;
_time = _time_old = getParam<Real>("start_time");
_problem.transient(true);
if (parameters.wasSeenInInput("predictor_scale"))
{
Real predscale(getParam<Real>("predictor_scale"));
if (predscale >= 0.0 and predscale <= 1.0)
{
_problem.getNonlinearSystem().setPredictorScale(getParam<Real>("predictor_scale"));
}
else
{
mooseError("Input value for predictor_scale = "<< predscale << ", outside of permissible range (0 to 1)");
}
_problem.getTimeScheme()->_use_AB2 = getParam<bool>("use_AB2");
_problem.getTimeScheme()->_use_littlef = getParam<bool>("use_littlef");
}
if (!_restart_file_base.empty())
_problem.setRestartFile(_restart_file_base);
}
Transient::~Transient()
{
// This problem was built by the Factory and needs to be released by this destructor
delete &_problem;
}
void
Transient::execute()
{
_problem.initialSetup();
preExecute();
// Start time loop...
while(keepGoing())
{
takeStep();
if (lastSolveConverged())
endStep();
}
postExecute();
}
void
Transient::takeStep(Real input_dt)
{
if (_converged)
_problem.copyOldSolutions();
else
_problem.restoreSolutions();
_dt_old = _dt;
if (input_dt == -1.0)
_dt = computeConstrainedDT();
else
_dt = input_dt;
_problem.onTimestepBegin();
if (_converged)
{
// Update backward material data structures
_problem.updateMaterials();
}
// Increment time
_time = _time_old + _dt;
std::cout<<"DT: "<<_dt<<std::endl;
std::cout << " Solving time step ";
{
OStringStream out;
OSSInt(out,2,_t_step);
out << ", time=";
OSSRealzeroleft(out, 9, 6, _time);
out << "...";
std::cout << out.str() << std::endl;
}
preSolve();
_problem.timestepSetup();
// Compute Pre-Aux User Objects (Timestep begin)
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::PRE_AUX);
// Compute TimestepBegin AuxKernels
_problem.computeAuxiliaryKernels(EXEC_TIMESTEP_BEGIN);
// Compute Post-Aux User Objects (Timestep begin)
_problem.computeUserObjects(EXEC_TIMESTEP_BEGIN, UserObjectWarehouse::POST_AUX);
_problem.solve();
_converged = _problem.converged();
// Compute Pre-Aux User Objects
_problem.computeUserObjects(EXEC_TIMESTEP, UserObjectWarehouse::PRE_AUX);
postSolve();
_problem.onTimestepEnd();
// We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
bool last_solve_converged = lastSolveConverged();
// If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
if (last_solve_converged)
{
_problem.computeUserObjects(EXEC_TIMESTEP, UserObjectWarehouse::POST_AUX);
}
}
void
Transient::endStep()
{
// Compute the Error Indicators and Markers
_problem.computeIndicatorsAndMarkers();
// if _reset_dt is true, force the output no matter what
_problem.output(_reset_dt);
_problem.outputPostprocessors(_reset_dt);
#ifdef LIBMESH_ENABLE_AMR
if (_problem.adaptivity().isOn())
{
_problem.adaptMesh();
_problem.out().meshChanged();
}
#endif
_time_old = _time;
_t_step++;
}
Real
Transient::computeConstrainedDT()
{
// If this is the first step
if (_t_step == 0)
{
_t_step = 1;
_dt = _input_dt;
}
// // If start up steps are needed
// if(_t_step == 1 && _n_startup_steps > 1)
// _dt = _input_dt/(double)(_n_startup_steps);
// else if (_t_step == 1+_n_startup_steps && _n_startup_steps > 1)
// _dt = _input_dt;
Real dt_cur = _dt;
//After startup steps, compute new dt
if (_t_step > _n_startup_steps)
dt_cur = computeDT();
// Don't let the time step size exceed maximum time step size
if (dt_cur > _dtmax)
dt_cur = _dtmax;
// Don't allow time step size to be smaller than minimum time step size
if (dt_cur < _dtmin)
dt_cur = _dtmin;
// Don't let time go beyond simulation end time
if (_time + dt_cur > _end_time)
dt_cur = _end_time - _time;
// Adjust to a sync time if supplied and skipped over
if (_remaining_sync_time && _time + dt_cur >= *_curr_sync_time_iter)
{
dt_cur = *_curr_sync_time_iter - _time;
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
_prev_dt = _dt;
_reset_dt = true;
}
else
{
if (_reset_dt)
{
if (_use_time_ipol)
dt_cur = _time_ipol.sample(_time);
else
dt_cur = _prev_dt;
_reset_dt = false;
}
}
return dt_cur;
}
Real
Transient::computeDT()
{
if (!lastSolveConverged())
{
_cutback_occurred = true;
//std::cout<<"Solve failed... cutting timestep"<<std::endl;
//return _dt / 2.0;
// Instead of blindly cutting timestep, respect dtmin.
if (_dt <= _dtmin)
mooseError("Solve failed and timestep already at or below dtmin, cannot continue!");
if (0.5 * _dt >= _dtmin)
return 0.5 * _dt;
else // (0.5 * _dt < _dtmin)
return _dtmin;
}
Real dt = _dt;
if (_use_time_ipol)
{
dt = _time_ipol.sample(_time);
if (_cutback_occurred &&
dt > _dt * _growth_factor)
{
dt = _dt * _growth_factor;
}
}
_cutback_occurred = false;
return dt;
}
bool
Transient::keepGoing()
{
// Check for stop condition based upon steady-state check flag:
if(_converged && _trans_ss_check == true && _time > _ss_tmin)
{
// Compute new time solution l2_norm
Real new_time_solution_norm = _problem.getNonlinearSystem().currentSolution()->l2_norm();
// Compute l2_norm relative error
Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;
// Check current solution relative error norm against steady-state tolerance
if(ss_relerr_norm < _ss_check_tol)
{
std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
return false;
}
else // Keep going
{
// Update solution norm for next time step
_old_time_solution_norm = new_time_solution_norm;
// Print steady-state relative error norm
std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
}
}
if(!_converged && _abort)
{
std::cout<<"Aborting as solve did not converge and input selected to abort"<<std::endl;
return false;
}
// Check for stop condition based upon number of simulation steps and/or solution end time:
if(_t_step>_num_steps)
return false;
if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
return false;
return true;
}
bool
Transient::lastSolveConverged()
{
return _converged;
}
void
Transient::preExecute()
{
// process time periods
const std::vector<TimePeriod *> _time_periods = _problem.getTimePeriods();
for (unsigned int i = 0; i < _time_periods.size(); ++i)
_sync_times.push_back(_time_periods[i]->start());
const std::vector<Real> & time = getParam<std::vector<Real> >("time_t");
if (_use_time_ipol)
_sync_times.insert(_sync_times.end(), time.begin()+1, time.end()); // insert times as sync points except the very first one
sort(_sync_times.begin(), _sync_times.end());
_sync_times.erase(std::unique(_sync_times.begin(), _sync_times.end()), _sync_times.end()); // remove duplicates (needs sorted array)
// Advance to the first sync time if one is provided in sim time range
_curr_sync_time_iter = _sync_times.begin();
while (_remaining_sync_time && *_curr_sync_time_iter <= _time)
if (++_curr_sync_time_iter == _sync_times.end())
_remaining_sync_time = false;
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MaterialData.h"
#include "Material.h"
MaterialData::MaterialData(MaterialPropertyStorage & storage) :
_storage(storage),
_n_qpoints(0),
_swapped(false)
{
}
MaterialData::~MaterialData()
{
release();
}
void
MaterialData::release()
{
_props.destroy();
_props_old.destroy();
_props_older.destroy();
}
void
MaterialData::size(unsigned int n_qpoints)
{
_props.resizeItems(n_qpoints);
// if there are stateful material properties in the system, also resize
// storage for old and older material properties
if (_storage.hasStatefulProperties())
{
_props_old.resizeItems(n_qpoints);
if (_storage.hasOlderProperties())
_props_older.resizeItems(n_qpoints);
}
_n_qpoints = n_qpoints;
}
unsigned int
MaterialData::nQPoints()
{
return _n_qpoints;
}
void
MaterialData::swap(const Elem & elem, unsigned int side/* = 0*/)
{
if (_storage.hasStatefulProperties())
{
_storage.swap(*this, elem, side);
_swapped = true;
}
}
void
MaterialData::reinit(std::vector<Material *> & mats)
{
for (std::vector<Material *>::iterator it = mats.begin(); it != mats.end(); ++it)
(*it)->computeProperties();
}
void
MaterialData::swapBack(const Elem & elem, unsigned int side/* = 0*/)
{
if (_storage.hasStatefulProperties())
{
_storage.swapBack(*this, elem, side);
_swapped = false;
}
}
bool
MaterialData::isSwapped()
{
return _swapped;
}
<commit_msg>Make MaterialData::swapBack() more robust.<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MaterialData.h"
#include "Material.h"
MaterialData::MaterialData(MaterialPropertyStorage & storage) :
_storage(storage),
_n_qpoints(0),
_swapped(false)
{
}
MaterialData::~MaterialData()
{
release();
}
void
MaterialData::release()
{
_props.destroy();
_props_old.destroy();
_props_older.destroy();
}
void
MaterialData::size(unsigned int n_qpoints)
{
_props.resizeItems(n_qpoints);
// if there are stateful material properties in the system, also resize
// storage for old and older material properties
if (_storage.hasStatefulProperties())
{
_props_old.resizeItems(n_qpoints);
if (_storage.hasOlderProperties())
_props_older.resizeItems(n_qpoints);
}
_n_qpoints = n_qpoints;
}
unsigned int
MaterialData::nQPoints()
{
return _n_qpoints;
}
void
MaterialData::swap(const Elem & elem, unsigned int side/* = 0*/)
{
if (_storage.hasStatefulProperties())
{
_storage.swap(*this, elem, side);
_swapped = true;
}
}
void
MaterialData::reinit(std::vector<Material *> & mats)
{
for (std::vector<Material *>::iterator it = mats.begin(); it != mats.end(); ++it)
(*it)->computeProperties();
}
void
MaterialData::swapBack(const Elem & elem, unsigned int side/* = 0*/)
{
if (_swapped && _storage.hasStatefulProperties())
{
_storage.swapBack(*this, elem, side);
_swapped = false;
}
}
bool
MaterialData::isSwapped()
{
return _swapped;
}
<|endoftext|>
|
<commit_before>// This file is intended to be included into an array of 'const char*'
#define STRING_CMP_FUNCS(op) \
"(define (string"op"? s1 s2)" \
" ("op" (%string-strcmp s1 s2) 0))"
STRING_CMP_FUNCS("="),
STRING_CMP_FUNCS("<"),
STRING_CMP_FUNCS(">"),
STRING_CMP_FUNCS("<="),
STRING_CMP_FUNCS(">="),
#undef STRING_CMP_FUNCS
#define STRING_CI_CMP_FUNCS(op) \
"(define (string-ci"op"? s1 s2)" \
" ("op" (%string-strcasecmp s1 s2) 0))"
STRING_CI_CMP_FUNCS("="),
STRING_CI_CMP_FUNCS("<"),
STRING_CI_CMP_FUNCS(">"),
STRING_CI_CMP_FUNCS("<="),
STRING_CI_CMP_FUNCS(">="),
#undef STRING_CI_CMP_FUNCS
"(define (substring str start end)"
" (let* ((size (- end start))"
" (str2 (make-string size)))"
" (do ((i 0 (+ i 1)))"
" ((= i size) str2)"
" (string-set! str2 i (string-ref str (+ i start))))))",
"(define (string-copy str)"
" (let* ((size (string-length str))"
" (str2 (make-string size)))"
" (do ((i 0 (+ i 1)))"
" ((= i size) str2)"
" (string-set! str2 i (string-ref str i)))))",
"(define (string-fill! str fill)"
" (let ((size (string-length str)))"
" (do ((i 0 (+ i 1)))"
" ((= i size) str)"
" (string-set! str i fill))))",
<commit_msg>cleanup string-copy<commit_after>// This file is intended to be included into an array of 'const char*'
#define STRING_CMP_FUNCS(op) \
"(define (string"op"? s1 s2)" \
" ("op" (%string-strcmp s1 s2) 0))"
STRING_CMP_FUNCS("="),
STRING_CMP_FUNCS("<"),
STRING_CMP_FUNCS(">"),
STRING_CMP_FUNCS("<="),
STRING_CMP_FUNCS(">="),
#undef STRING_CMP_FUNCS
#define STRING_CI_CMP_FUNCS(op) \
"(define (string-ci"op"? s1 s2)" \
" ("op" (%string-strcasecmp s1 s2) 0))"
STRING_CI_CMP_FUNCS("="),
STRING_CI_CMP_FUNCS("<"),
STRING_CI_CMP_FUNCS(">"),
STRING_CI_CMP_FUNCS("<="),
STRING_CI_CMP_FUNCS(">="),
#undef STRING_CI_CMP_FUNCS
"(define (substring str start end)"
" (let* ((size (- end start))"
" (str2 (make-string size)))"
" (do ((i 0 (+ i 1)))"
" ((= i size) str2)"
" (string-set! str2 i (string-ref str (+ i start))))))",
"(define (string-copy str)"
" (substring str 0 (string-length str)))",
"(define (string-fill! str fill)"
" (let ((size (string-length str)))"
" (do ((i 0 (+ i 1)))"
" ((= i size) str)"
" (string-set! str i fill))))",
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "CursesMenu.h"
#include "StateDatabase.h"
#include "TextUtils.h"
CursesMenuItem::CursesMenuItem(const std::string& str) : text(str) {
}
CursesMenuItem::~CursesMenuItem() {
}
void CursesMenuItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* just print the text of the item centered between col and col+width
if this item is selected, use reverse video */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < (width - text.size()) / 2; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
for (int i = (width - text.size()) /2 + text.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected)
wattroff(menuWin, A_REVERSE);
}
bool CursesMenuItem::handleKey(int, std::string&, CursesMenu&) {
return false;
}
void CursesMenuItem::deselect() {
}
SubmenuCMItem::SubmenuCMItem(const std::string& str, MenuCallback callback)
: CursesMenuItem(str), cb(callback) {
}
bool SubmenuCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
menu.setUpdateCallback(cb);
menu.forceUpdate();
}
return false;
}
CallbackCMItem::CallbackCMItem(const std::string& str, MenuCallback callback)
: CursesMenuItem(str), cb(callback) {
}
bool CallbackCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
cb(menu);
}
return false;
}
CommandCMItem::CommandCMItem(const std::string& str, const std::string& cmd,
bool update)
: CursesMenuItem(str), command(cmd), forceUpdate(update) {
}
bool CommandCMItem::handleKey(int c, std::string& str, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
str = command;
if (forceUpdate)
menu.forceUpdate();
return true;
}
return false;
}
BoolCMItem::BoolCMItem(std::string name, bool& variable, std::string trueText,
std::string falseText)
: CursesMenuItem(name), varRef(variable), trueTxt(trueText),
falseTxt(falseText) {
}
void BoolCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* print the name of the variable to the left of the center and the
value to the right, use reverse video if it is selected */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
wmove(menuWin, line, col + width / 2 + 1);
std::string& value = (varRef ? trueTxt : falseTxt);
waddstr(menuWin, value.c_str());
for (int i = width / 2 + 1 + value.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected)
wattroff(menuWin, A_REVERSE);
}
bool BoolCMItem::handleKey(int c, std::string&, CursesMenu&) {
if (c == ' ')
varRef = !varRef;
return false;
}
BZDBCMItem::BZDBCMItem(const std::string& variable)
: CursesMenuItem(variable), editing(false) {
}
void BZDBCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* print the name of the variable to the left of the center and the
value to the right, use reverse video if it is selected, but don't use
reverse video for the value if we're editing it */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
wmove(menuWin, line, col + width / 2 + 1);
std::string value = BZDB.get(text);
if (editing) {
wattroff(menuWin, A_REVERSE);
waddstr(menuWin, editString.c_str());
waddstr(menuWin, "_");
}
else
waddstr(menuWin, value.c_str());
for (int i = width / 2 + 1 + value.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected && !editing)
wattroff(menuWin, A_REVERSE);
}
bool BZDBCMItem::handleKey(int c, std::string& str, CursesMenu&) {
// if we're not editing, start if we get a return key
if (!editing && (c == '\n' || c == 13)) {
editing = true;
editString = BZDB.get(text);
return false;
}
// OK, we're editing
switch (c) {
// different codes for the return key - stop and send a /set command
case '\n':
case 13:
editing = false;
str = "/set ";
str += text + " \"" + editString + "\"";
return true;
// ESC - stop editing, don't touch the BZDB value
case 27:
editing = false;
break;
// backspace/delete - delete the last character
case KEY_BACKSPACE:
case KEY_DC:
case 127:
editString = (editString.size() > 0 ?
editString.substr(0, editString.size() - 1) : editString);
break;
// valid characters - edit the string
default:
if (c < 32 || c > 127 || editString.size() > 30)
return false;
editString += char(c);
break;
}
return false;
}
void BZDBCMItem::deselect() {
editing = false;
}
PlayerCMItem::PlayerCMItem(const PlayerIdMap& players, PlayerId playerId)
: CursesMenuItem(), playerMap(players), id(playerId) {
}
void PlayerCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
// score (wins-losses)[tks] callsign IP, reverse video if selected
std::string name, ip;
int wins, losses, tks;
PlayerIdMap::const_iterator iter = playerMap.find(id);
if (iter != playerMap.end()) {
name = iter->second.name;
ip = iter->second.ip;
wins = iter->second.wins;
losses = iter->second.losses;
tks = iter->second.tks;
std::ostringstream oss;
oss<<(wins - losses)<<" ("<<wins<<"-"<<losses<<")["<<tks<<"]";
unsigned int scoreLength = oss.str().size();
for (unsigned int i = 0; i < 21 - scoreLength; ++i)
oss<<' ';
oss<<name;
for (unsigned int i = 0; i < CallSignLen + 1 - name.size(); ++i)
oss<<' ';
oss<<ip;
for (unsigned int i = 0; i < 15 - ip.size(); ++i)
oss<<' ';
if (selected)
wattron(menuWin, A_REVERSE);
wmove(menuWin, line, col);
waddstr(menuWin, oss.str().substr(0, width).c_str());
if (selected)
wattroff(menuWin, A_REVERSE);
}
}
CursesMenu::CursesMenu(const PlayerIdMap& p)
: players(p), dirty(true) {
}
CursesMenu::~CursesMenu() {
clear();
}
void CursesMenu::setHeader(const std::string& newHeader) {
header = newHeader;
}
void CursesMenu::addItem(CursesMenuItem* item) {
items.push_back(item);
}
void CursesMenu::clear() {
for (unsigned int i = 0; i < items.size(); ++i)
delete items[i];
items.clear();
selection = 0;
}
void CursesMenu::showMenu() {
if (window == NULL)
return;
werase(window);
// update the menu if needed
rebuild();
// get the window size
int x1, x2, y1, y2, w, h;
getbegyx(window, y1, x1);
getmaxyx(window, y2, x2);
w = x2 - x1;
h = y2 - y1;
wmove(window, 0, w / 2 - header.size() / 2);
waddstr(window, header.c_str());
// this magic should scroll the menu so that the selected menu item
// always is visible
int start = selection - (h / 2 - 2);
start = (start + (h - 3) > (signed)items.size() ?
items.size() - (h - 3) : start);
start = (start < 0 ? 0 : start);
int end = start + (h - 3);
end = ((unsigned)end > items.size() ? items.size() : end);
// show the menu items
for (int i = start; i < end; ++i)
items[i]->showItem(window, 2 + (i - start), 10, w - 20, i == selection);
// draw a line at the bottom of the menu window
wmove(window, h - 1, 0);
wattron(window, A_UNDERLINE);
for (int i = 0; i < COLS; ++i)
waddstr(window, " ");
wattroff(window, A_UNDERLINE);
wrefresh(window);
}
bool CursesMenu::handleKey(int c, std::string& str) {
bool result = false;
str = "";
switch (c) {
case KEY_UP:
items[selection]->deselect();
selection = (selection == 0 ? items.size() - 1 : selection - 1);
break;
case KEY_DOWN:
items[selection]->deselect();
selection = ((unsigned)selection == items.size() - 1 ? 0 : selection + 1);
break;
default:
result = items[selection]->handleKey(c, str, *this);
}
showMenu();
return result;
}
void CursesMenu::setWindow(WINDOW* win) {
window = win;
}
void CursesMenu::setUpdateCallback(MenuCallback cb) {
rebuilder = cb;
}
void CursesMenu::forceUpdate() {
dirty = true;
}
void CursesMenu::rebuild() {
if (dirty) {
dirty = false;
rebuilder(*this);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Clean up the playerlist output in the curses menu<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "CursesMenu.h"
#include "StateDatabase.h"
#include "TextUtils.h"
CursesMenuItem::CursesMenuItem(const std::string& str) : text(str) {
}
CursesMenuItem::~CursesMenuItem() {
}
void CursesMenuItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* just print the text of the item centered between col and col+width
if this item is selected, use reverse video */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < (width - text.size()) / 2; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
for (int i = (width - text.size()) /2 + text.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected)
wattroff(menuWin, A_REVERSE);
}
bool CursesMenuItem::handleKey(int, std::string&, CursesMenu&) {
return false;
}
void CursesMenuItem::deselect() {
}
SubmenuCMItem::SubmenuCMItem(const std::string& str, MenuCallback callback)
: CursesMenuItem(str), cb(callback) {
}
bool SubmenuCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
menu.setUpdateCallback(cb);
menu.forceUpdate();
}
return false;
}
CallbackCMItem::CallbackCMItem(const std::string& str, MenuCallback callback)
: CursesMenuItem(str), cb(callback) {
}
bool CallbackCMItem::handleKey(int c, std::string&, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
cb(menu);
}
return false;
}
CommandCMItem::CommandCMItem(const std::string& str, const std::string& cmd,
bool update)
: CursesMenuItem(str), command(cmd), forceUpdate(update) {
}
bool CommandCMItem::handleKey(int c, std::string& str, CursesMenu& menu) {
// different key codes for the enter key
if (c == '\n' || c == 13) {
str = command;
if (forceUpdate)
menu.forceUpdate();
return true;
}
return false;
}
BoolCMItem::BoolCMItem(std::string name, bool& variable, std::string trueText,
std::string falseText)
: CursesMenuItem(name), varRef(variable), trueTxt(trueText),
falseTxt(falseText) {
}
void BoolCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* print the name of the variable to the left of the center and the
value to the right, use reverse video if it is selected */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
wmove(menuWin, line, col + width / 2 + 1);
std::string& value = (varRef ? trueTxt : falseTxt);
waddstr(menuWin, value.c_str());
for (int i = width / 2 + 1 + value.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected)
wattroff(menuWin, A_REVERSE);
}
bool BoolCMItem::handleKey(int c, std::string&, CursesMenu&) {
if (c == ' ')
varRef = !varRef;
return false;
}
BZDBCMItem::BZDBCMItem(const std::string& variable)
: CursesMenuItem(variable), editing(false) {
}
void BZDBCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
/* print the name of the variable to the left of the center and the
value to the right, use reverse video if it is selected, but don't use
reverse video for the value if we're editing it */
wmove(menuWin, line, col);
if (selected)
wattron(menuWin, A_REVERSE);
for (unsigned int i = 0; i < width / 2 - text.size() - 1; ++i)
waddstr(menuWin, " ");
waddstr(menuWin, text.c_str());
wmove(menuWin, line, col + width / 2 + 1);
std::string value = BZDB.get(text);
if (editing) {
wattroff(menuWin, A_REVERSE);
waddstr(menuWin, editString.c_str());
waddstr(menuWin, "_");
}
else
waddstr(menuWin, value.c_str());
for (int i = width / 2 + 1 + value.size(); i < width; ++i)
waddstr(menuWin, " ");
if (selected && !editing)
wattroff(menuWin, A_REVERSE);
}
bool BZDBCMItem::handleKey(int c, std::string& str, CursesMenu&) {
// if we're not editing, start if we get a return key
if (!editing && (c == '\n' || c == 13)) {
editing = true;
editString = BZDB.get(text);
return false;
}
// OK, we're editing
switch (c) {
// different codes for the return key - stop and send a /set command
case '\n':
case 13:
editing = false;
str = "/set ";
str += text + " \"" + editString + "\"";
return true;
// ESC - stop editing, don't touch the BZDB value
case 27:
editing = false;
break;
// backspace/delete - delete the last character
case KEY_BACKSPACE:
case KEY_DC:
case 127:
editString = (editString.size() > 0 ?
editString.substr(0, editString.size() - 1) : editString);
break;
// valid characters - edit the string
default:
if (c < 32 || c > 127 || editString.size() > 30)
return false;
editString += char(c);
break;
}
return false;
}
void BZDBCMItem::deselect() {
editing = false;
}
PlayerCMItem::PlayerCMItem(const PlayerIdMap& players, PlayerId playerId)
: CursesMenuItem(), playerMap(players), id(playerId) {
}
void PlayerCMItem::showItem(WINDOW* menuWin, int line, int col, int width,
bool selected) {
// score (wins-losses)[tks] callsign IP, reverse video if selected
std::string name, ip;
int wins, losses, tks;
int scorePad = 17;
int callsignPad = CallSignLen;
PlayerIdMap::const_iterator iter = playerMap.find(id);
if (iter != playerMap.end()) {
name = iter->second.name;
ip = iter->second.ip;
wins = iter->second.wins;
losses = iter->second.losses;
tks = iter->second.tks;
std::ostringstream oss;
oss<<(wins - losses)<<" ("<<wins<<"-"<<losses<<")["<<tks<<"]";
unsigned int streamLength = oss.str().size();
for (unsigned int i = 0; i < scorePad - streamLength; ++i)
oss<<' ';
oss<<' '<<name;
for (unsigned int i = 0; i < callsignPad - name.size(); ++i)
oss<<' ';
streamLength = oss.str().size();
if (selected)
wattron(menuWin, A_REVERSE);
wmove(menuWin, line, col);
waddstr(menuWin,
(oss.str().substr(0, width - ip.size() - 1) + " ").c_str());
waddstr(menuWin, ip.c_str());
if (selected)
wattroff(menuWin, A_REVERSE);
}
}
CursesMenu::CursesMenu(const PlayerIdMap& p)
: players(p), dirty(true) {
}
CursesMenu::~CursesMenu() {
clear();
}
void CursesMenu::setHeader(const std::string& newHeader) {
header = newHeader;
}
void CursesMenu::addItem(CursesMenuItem* item) {
items.push_back(item);
}
void CursesMenu::clear() {
for (unsigned int i = 0; i < items.size(); ++i)
delete items[i];
items.clear();
selection = 0;
}
void CursesMenu::showMenu() {
if (window == NULL)
return;
werase(window);
// update the menu if needed
rebuild();
// get the window size
int x1, x2, y1, y2, w, h;
getbegyx(window, y1, x1);
getmaxyx(window, y2, x2);
w = x2 - x1;
h = y2 - y1;
wmove(window, 0, w / 2 - header.size() / 2);
waddstr(window, header.c_str());
// this magic should scroll the menu so that the selected menu item
// always is visible
int start = selection - (h / 2 - 2);
start = (start + (h - 3) > (signed)items.size() ?
items.size() - (h - 3) : start);
start = (start < 0 ? 0 : start);
int end = start + (h - 3);
end = ((unsigned)end > items.size() ? items.size() : end);
// show the menu items
for (int i = start; i < end; ++i)
items[i]->showItem(window, 2 + (i - start), 10, w - 20, i == selection);
// draw a line at the bottom of the menu window
wmove(window, h - 1, 0);
wattron(window, A_UNDERLINE);
for (int i = 0; i < COLS; ++i)
waddstr(window, " ");
wattroff(window, A_UNDERLINE);
wrefresh(window);
}
bool CursesMenu::handleKey(int c, std::string& str) {
bool result = false;
str = "";
switch (c) {
case KEY_UP:
items[selection]->deselect();
selection = (selection == 0 ? items.size() - 1 : selection - 1);
break;
case KEY_DOWN:
items[selection]->deselect();
selection = ((unsigned)selection == items.size() - 1 ? 0 : selection + 1);
break;
default:
result = items[selection]->handleKey(c, str, *this);
}
showMenu();
return result;
}
void CursesMenu::setWindow(WINDOW* win) {
window = win;
}
void CursesMenu::setUpdateCallback(MenuCallback cb) {
rebuilder = cb;
}
void CursesMenu::forceUpdate() {
dirty = true;
}
void CursesMenu::rebuild() {
if (dirty) {
dirty = false;
rebuilder(*this);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/**************************************************************************/
/*!
@file Adafruit_MCP9808.cpp
@author K.Townsend (Adafruit Industries)
@license BSD (see license.txt)
I2C Driver for Microchip's MCP9808 I2C Temp sensor
This is a library for the Adafruit MCP9808 breakout
----> http://www.adafruit.com/products/1782
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#ifdef __AVR_ATtiny85__
#include "TinyWireM.h"
#define Wire TinyWireM
#else
#include <Wire.h>
#endif
#include "Adafruit_MCP9808.h"
/**************************************************************************/
/*!
@brief Instantiates a new MCP9808 class
*/
/**************************************************************************/
Adafruit_MCP9808::Adafruit_MCP9808() {
}
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
boolean Adafruit_MCP9808::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
if (read16(MCP9808_REG_MANUF_ID) != 0x0054) return false;
if (read16(MCP9808_REG_DEVICE_ID) != 0x0400) return false;
return true;
}
/**************************************************************************/
/*!
@brief Reads the 16-bit temperature register and returns the Centigrade
temperature as a float.
*/
/**************************************************************************/
float Adafruit_MCP9808::readTempC( void )
{
uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);
float temp = t & 0x0FFF;
temp /= 16.0;
if (t & 0x1000) temp -= 256;
return temp;
}
/**************************************************************************/
/*!
@brief Low level 16 bit read and write procedures!
*/
/**************************************************************************/
void Adafruit_MCP9808::write16(uint8_t reg, uint16_t value) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.write(value >> 8);
Wire.write(value & 0xFF);
Wire.endTransmission();
}
uint16_t Adafruit_MCP9808::read16(uint8_t reg) {
uint16_t val;
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission();
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
val = Wire.read();
val <<= 8;
val |= Wire.read();
return val;
}
<commit_msg>Added attribute to Adafruit_MCP9808 initializer list, added implementation for Adafruit_MCP9808::readTempF() method.<commit_after>/**************************************************************************/
/*!
@file Adafruit_MCP9808.cpp
@author K.Townsend (Adafruit Industries)
@license BSD (see license.txt)
I2C Driver for Microchip's MCP9808 I2C Temp sensor
This is a library for the Adafruit MCP9808 breakout
----> http://www.adafruit.com/products/1782
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#ifdef __AVR_ATtiny85__
#include "TinyWireM.h"
#define Wire TinyWireM
#else
#include <Wire.h>
#endif
#include "Adafruit_MCP9808.h"
/**************************************************************************/
/*!
@brief Instantiates a new MCP9808 class
*/
/**************************************************************************/
Adafruit_MCP9808::Adafruit_MCP9808()
: _i2caddr(0)
{ }
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
boolean Adafruit_MCP9808::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
if (read16(MCP9808_REG_MANUF_ID) != 0x0054) return false;
if (read16(MCP9808_REG_DEVICE_ID) != 0x0400) return false;
return true;
}
/**************************************************************************/
/*!
@brief Reads the 16-bit temperature register and returns the Fahrenheit
temperature as a float.
*/
/**************************************************************************/
float Adafruit_MCP9808::readTempF( void )
{
uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);
float temp = t & 0x0FFF;
temp /= 16.0;
if (t & 0x1000) temp -= 256;
temp = temp * 9.0 / 5.0 + 32;
return temp;
}
/**************************************************************************/
/*!
@brief Reads the 16-bit temperature register and returns the Centigrade
temperature as a float.
*/
/**************************************************************************/
float Adafruit_MCP9808::readTempC( void )
{
uint16_t t = read16(MCP9808_REG_AMBIENT_TEMP);
float temp = t & 0x0FFF;
temp /= 16.0;
if (t & 0x1000) temp -= 256;
return temp;
}
/**************************************************************************/
/*!
@brief Low level 16 bit read and write procedures!
*/
/**************************************************************************/
void Adafruit_MCP9808::write16(uint8_t reg, uint16_t value) {
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.write(value >> 8);
Wire.write(value & 0xFF);
Wire.endTransmission();
}
uint16_t Adafruit_MCP9808::read16(uint8_t reg) {
uint16_t val;
Wire.beginTransmission(_i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission();
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
val = Wire.read();
val <<= 8;
val |= Wire.read();
return val;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ListBox.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-04-02 10:54:31 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FORMS_LISTBOX_HXX_
#define _FORMS_LISTBOX_HXX_
#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_
#include <com/sun/star/form/binding/XListEntrySink.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_
#include <com/sun/star/form/binding/XListEntryListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif
//.........................................................................
namespace frm
{
//==================================================================
//= OListBoxModel
//==================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::util::XRefreshable
> OListBoxModel_BASE;
class OListBoxModel :public OBoundControlModel
,public OListBoxModel_BASE
,public OEntryListHelper
,public OErrorBroadcaster
,public ::comphelper::OAggregationArrayUsageHelper< OListBoxModel >
{
::com::sun::star::uno::Any m_aSaveValue;
// <properties>
::com::sun::star::form::ListSourceType m_eListSourceType; // type der list source
::com::sun::star::uno::Any m_aBoundColumn;
StringSequence m_aListSourceSeq; //
StringSequence m_aValueSeq; // alle Werte, readonly
::com::sun::star::uno::Sequence<sal_Int16> m_aDefaultSelectSeq; // DefaultSelected
// </properties>
::cppu::OInterfaceContainerHelper m_aRefreshListeners;
sal_Int16 m_nNULLPos; // position of the NULL value in our list
sal_Bool m_bBoundComponent : 1;
/** type how we should transfer our selection to external value bindings
*/
enum TransferSelection
{
tsIndexList, /// as list of indexes of selected entries
tsIndex, /// as index of the selected entry
tsEntryList, /// as list of string representations of selected entries
tsEntry /// as string representation of the selected entry
};
TransferSelection m_eTransferSelectionAs;
private:
// Helper functions
StringSequence GetCurValueSeq() const;
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
public:
DECLARE_DEFAULT_LEAF_XTOR( OListBoxModel );
// XServiceInfo
IMPLEMENTATION_NAME(OListBoxModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// UNO Anbindung
DECLARE_UNO3_AGG_DEFAULTS(OListBoxModel, OBoundControlModel);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing();
// OPropertySetHelper
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::uno::Exception);
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
protected:
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XPersistObject
virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XRefreshable
virtual void SAL_CALL refresh() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
// XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);
protected:
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual ::com::sun::star::uno::Any
translateExternalValueToControlValue( );
virtual ::com::sun::star::uno::Any
translateControlValueToExternalValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual void onConnectedExternalValue( );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
// OEntryListHelper overriables
virtual void stringItemListChanged( );
virtual void connectedExternalListSource( );
virtual void disconnectedExternalListSource( );
protected:
DECLARE_XCLONEABLE();
private:
void loadData();
/**
@precond we don't actually have an external list source
*/
void implRefreshListFromDbBinding( );
};
//==================================================================
//= OListBoxControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XItemListener,
::com::sun::star::form::XChangeBroadcaster > OListBoxControl_BASE;
class OListBoxControl :public OBoundControl
,public OListBoxControl_BASE
{
::cppu::OInterfaceContainerHelper m_aChangeListeners;
::com::sun::star::uno::Any m_aCurrentSelection;
Timer m_aChangeTimer;
protected:
// UNO Anbindung
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
public:
OListBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OListBoxControl();
// UNO Anbindung
DECLARE_UNO3_AGG_DEFAULTS(OListBoxControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
IMPLEMENTATION_NAME(OListBoxControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
// XFocusListener
virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
// XItemListener
virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing();
private:
DECL_LINK( OnTimeout, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_LISTBOX_HXX_
<commit_msg>INTEGRATION: CWS dba09 (1.7.44); FILE MERGED 2004/04/27 06:15:59 fs 1.7.44.2: RESYNC: (1.7-1.8); FILE MERGED 2004/04/05 12:05:47 fs 1.7.44.1: #i27024# +setPropertyValues<commit_after>/*************************************************************************
*
* $RCSfile: ListBox.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2004-05-10 12:46:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FORMS_LISTBOX_HXX_
#define _FORMS_LISTBOX_HXX_
#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLERRORBROADCASTER_HPP_
#include <com/sun/star/sdb/XSQLErrorBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_LISTSOURCETYPE_HPP_
#include <com/sun/star/form/ListSourceType.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XITEMLISTENER_HPP_
#include <com/sun/star/awt/XItemListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XCHANGEBROADCASTER_HPP_
#include <com/sun/star/form/XChangeBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_
#include <com/sun/star/form/binding/XListEntrySink.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_
#include <com/sun/star/form/binding/XListEntryListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef FORMS_ERRORBROADCASTER_HXX
#include "errorbroadcaster.hxx"
#endif
#ifndef FORMS_ENTRYLISTHELPER_HXX
#include "entrylisthelper.hxx"
#endif
//.........................................................................
namespace frm
{
//==================================================================
//= OListBoxModel
//==================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::util::XRefreshable
> OListBoxModel_BASE;
class OListBoxModel :public OBoundControlModel
,public OListBoxModel_BASE
,public OEntryListHelper
,public OErrorBroadcaster
,public ::comphelper::OAggregationArrayUsageHelper< OListBoxModel >
{
::com::sun::star::uno::Any m_aSaveValue;
// <properties>
::com::sun::star::form::ListSourceType m_eListSourceType; // type der list source
::com::sun::star::uno::Any m_aBoundColumn;
StringSequence m_aListSourceSeq; //
StringSequence m_aValueSeq; // alle Werte, readonly
::com::sun::star::uno::Sequence<sal_Int16> m_aDefaultSelectSeq; // DefaultSelected
// </properties>
::cppu::OInterfaceContainerHelper m_aRefreshListeners;
sal_Int16 m_nNULLPos; // position of the NULL value in our list
sal_Bool m_bBoundComponent : 1;
/** type how we should transfer our selection to external value bindings
*/
enum TransferSelection
{
tsIndexList, /// as list of indexes of selected entries
tsIndex, /// as index of the selected entry
tsEntryList, /// as list of string representations of selected entries
tsEntry /// as string representation of the selected entry
};
TransferSelection m_eTransferSelectionAs;
private:
// Helper functions
StringSequence GetCurValueSeq() const;
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
public:
DECLARE_DEFAULT_LEAF_XTOR( OListBoxModel );
// XServiceInfo
IMPLEMENTATION_NAME(OListBoxModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// UNO Anbindung
DECLARE_UNO3_AGG_DEFAULTS(OListBoxModel, OBoundControlModel);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing();
// OPropertySetHelper
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::uno::Exception);
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
protected:
// XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XMultiPropertySet
virtual void SAL_CALL setPropertyValues(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XPersistObject
virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// XRefreshable
virtual void SAL_CALL refresh() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeRefreshListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XRefreshListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
// XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);
protected:
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual ::com::sun::star::uno::Any
translateExternalValueToControlValue( );
virtual ::com::sun::star::uno::Any
translateControlValueToExternalValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual void onDisconnectedDbColumn();
virtual void onConnectedExternalValue( );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
// OEntryListHelper overriables
virtual void stringItemListChanged( );
virtual void connectedExternalListSource( );
virtual void disconnectedExternalListSource( );
protected:
DECLARE_XCLONEABLE();
private:
void loadData();
/**
@precond we don't actually have an external list source
*/
void implRefreshListFromDbBinding( );
};
//==================================================================
//= OListBoxControl
//==================================================================
typedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,
::com::sun::star::awt::XItemListener,
::com::sun::star::form::XChangeBroadcaster > OListBoxControl_BASE;
class OListBoxControl :public OBoundControl
,public OListBoxControl_BASE
{
::cppu::OInterfaceContainerHelper m_aChangeListeners;
::com::sun::star::uno::Any m_aCurrentSelection;
Timer m_aChangeTimer;
protected:
// UNO Anbindung
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();
public:
OListBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
virtual ~OListBoxControl();
// UNO Anbindung
DECLARE_UNO3_AGG_DEFAULTS(OListBoxControl, OBoundControl);
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
IMPLEMENTATION_NAME(OListBoxControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// XChangeBroadcaster
virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw(::com::sun::star::uno::RuntimeException);
// XFocusListener
virtual void SAL_CALL focusGained(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL focusLost(const ::com::sun::star::awt::FocusEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
// XItemListener
virtual void SAL_CALL itemStateChanged(const ::com::sun::star::awt::ItemEvent& _rEvent) throw(::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw (::com::sun::star::uno::RuntimeException);
// OComponentHelper
virtual void SAL_CALL disposing();
private:
DECL_LINK( OnTimeout, void* );
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_LISTBOX_HXX_
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include <string>
#include "SpawnPosition.h"
#include "DropGeometry.h"
#include "Obstacle.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
#include "GameKeeper.h"
#include "BZDBCache.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerId);
if (!playerData)
return;
team = playerData->player.getTeam();
azimuth = (float)(bzfrand() * 2.0 * M_PI);
if (playerData->player.shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
playerData->player.setRestartOnBase(false);
} else {
const float tankRadius = BZDBCache::tankRadius;
safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDBCache::tankRadius) * 1.5);
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDBCache::worldSize;
const float maxWorldHeight = world->getMaxWorldHeight();
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
const float waterLevel = world->getWaterLevel();
float minZ = 0.0f;
if (waterLevel > minZ) {
minZ = waterLevel;
}
float maxZ = maxWorldHeight;
if (onGroundOnly) {
maxZ = 0.0f;
}
if (DropGeometry::dropPlayer(testPos, minZ, maxZ)) {
foundspot = true;
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
bool dangerous = isImminentlyDangerous();
if (foundspot && !dangerous) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((float)(enemyAngle + M_PI), (float)(2.0 * M_PI));
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
} else if (dangerous) {
foundspot = false;
}
}
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// vector points from test to enemy
float dx = enemyPos[0] - testPos[0];
float dy = enemyPos[0] - testPos[1];
float angActual = atan2f (dy, dx);
float diff = fmodf(enemyAzimuth - angActual, (float)M_PI * 2.0f);
// now diff is between {-PI*2 and +PI*2}, and we're looking for values around
// -PI or +PI, because that's when the enemy is facing the source.
diff = fabsf (diff); // between {0 and +PI*2}
diff = fabsf ((float)(diff - M_PI));
if (diff < (deviation / 2.0f)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
GameKeeper::Player *playerData;
for (int i = 0; i < curMaxPlayers; i++) {
playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->player.isAlive()) {
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
if (playerData->player.getFlag() >= 0) {
// check for dangerous flags
const FlagInfo *finfo = FlagInfo::get(playerData->player.getFlag());
const FlagType *ftype = finfo->flag.type;
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
GameKeeper::Player *playerData;
float worstDist = 1e12f; // huge number
bool noEnemy = true;
for (int i = 0; i < curMaxPlayers; i++) {
playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->player.isAlive()
&& areFoes(playerData->player.getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
noEnemy = false;
}
}
}
}
if (noEnemy)
enemyAngle = (float)(bzfrand() * 2.0 * M_PI);
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make SpawnPosition use playerData->lastState rather than directly accessing the lastState[] array<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include <string>
#include "SpawnPosition.h"
#include "DropGeometry.h"
#include "Obstacle.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
#include "GameKeeper.h"
#include "BZDBCache.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
GameKeeper::Player *playerData
= GameKeeper::Player::getPlayerByIndex(playerId);
if (!playerData)
return;
team = playerData->player.getTeam();
azimuth = (float)(bzfrand() * 2.0 * M_PI);
if (playerData->player.shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
playerData->player.setRestartOnBase(false);
} else {
const float tankRadius = BZDBCache::tankRadius;
safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDBCache::tankRadius) * 1.5);
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDBCache::worldSize;
const float maxWorldHeight = world->getMaxWorldHeight();
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
const float waterLevel = world->getWaterLevel();
float minZ = 0.0f;
if (waterLevel > minZ) {
minZ = waterLevel;
}
float maxZ = maxWorldHeight;
if (onGroundOnly) {
maxZ = 0.0f;
}
if (DropGeometry::dropPlayer(testPos, minZ, maxZ)) {
foundspot = true;
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
bool dangerous = isImminentlyDangerous();
if (foundspot && !dangerous) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((float)(enemyAngle + M_PI), (float)(2.0 * M_PI));
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
} else if (dangerous) {
foundspot = false;
}
}
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// vector points from test to enemy
float dx = enemyPos[0] - testPos[0];
float dy = enemyPos[0] - testPos[1];
float angActual = atan2f (dy, dx);
float diff = fmodf(enemyAzimuth - angActual, (float)M_PI * 2.0f);
// now diff is between {-PI*2 and +PI*2}, and we're looking for values around
// -PI or +PI, because that's when the enemy is facing the source.
diff = fabsf (diff); // between {0 and +PI*2}
diff = fabsf ((float)(diff - M_PI));
if (diff < (deviation / 2.0f)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
GameKeeper::Player *playerData;
for (int i = 0; i < curMaxPlayers; i++) {
playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->player.isAlive()) {
float *enemyPos = playerData->lastState->pos;
float enemyAngle = playerData->lastState->azimuth;
if (playerData->player.getFlag() >= 0) {
// check for dangerous flags
const FlagInfo *finfo = FlagInfo::get(playerData->player.getFlag());
const FlagType *ftype = finfo->flag.type;
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, (float)(M_PI / 9.0))) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
GameKeeper::Player *playerData;
float worstDist = 1e12f; // huge number
bool noEnemy = true;
for (int i = 0; i < curMaxPlayers; i++) {
playerData = GameKeeper::Player::getPlayerByIndex(i);
if (!playerData)
continue;
if (playerData->player.isAlive()
&& areFoes(playerData->player.getTeam(), team)) {
float *enemyPos = playerData->lastState->pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = playerData->lastState->azimuth;
noEnemy = false;
}
}
}
}
if (noEnemy)
enemyAngle = (float)(bzfrand() * 2.0 * M_PI);
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<commit_msg>GTK uses a different controller for the bookmark bar view context menu than toolkit_views and this adds the same check for incognito pref that I added for views.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#include "cef/cef_app_handler.h"
#include "cosmetic_blocker.h"
namespace doogie {
CefAppHandler::CefAppHandler() {}
bool CefAppHandler::OnBeforeNavigation(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
CefRenderProcessHandler::NavigationType navigation_type,
bool is_redirect) {
if (before_nav_callback_) {
return before_nav_callback_(browser, frame, request,
navigation_type, is_redirect);
}
return false;
}
void CefAppHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
// Prevent document.webkitExitFullscreen from being mutated because
// we need to call it internally in Doogie.
// TODO(cretz): Find a better way, ref:
// http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=13642#p35988
frame->ExecuteJavaScript(
"Object.defineProperty(document, 'webkitExitFullscreen', { "
" value: document.webkitExitFullscreen, "
" writable: false "
"});",
"<doogie>",
0);
blocker_.OnFrameCreated(browser, frame, context);
}
void CefAppHandler::OnWebKitInitialized() {
}
} // namespace doogie
<commit_msg>Remove top level SharedArrayBuffer object. Fixes #68.<commit_after>#include "cef/cef_app_handler.h"
#include "cosmetic_blocker.h"
namespace doogie {
CefAppHandler::CefAppHandler() {}
bool CefAppHandler::OnBeforeNavigation(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefRequest> request,
CefRenderProcessHandler::NavigationType navigation_type,
bool is_redirect) {
if (before_nav_callback_) {
return before_nav_callback_(browser, frame, request,
navigation_type, is_redirect);
}
return false;
}
void CefAppHandler::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
// Prevent document.webkitExitFullscreen from being mutated because
// we need to call it internally in Doogie.
// TODO(cretz): Find a better way, ref:
// http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=13642#p35988
frame->ExecuteJavaScript(
"Object.defineProperty(document, 'webkitExitFullscreen', { "
" value: document.webkitExitFullscreen, "
" writable: false "
"});",
"<doogie>",
0);
// Temporarily disable SharedArrayBuffer, ref: https://github.com/cretz/doogie/issues/68
frame->ExecuteJavaScript("delete window.SharedArrayBuffer", "<doogie>", 0);
blocker_.OnFrameCreated(browser, frame, context);
}
void CefAppHandler::OnWebKitInitialized() {
}
} // namespace doogie
<|endoftext|>
|
<commit_before>//===-- IndirectCallPromotionAnalysis.cpp - Find promotion candidates ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Helper methods for identifying profitable indirect call promotion
// candidates for an instruction when the indirect-call value profile metadata
// is available.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/IndirectCallSiteVisitor.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/Debug.h"
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "pgo-icall-prom-analysis"
// The minimum call count for the direct-call target to be considered as the
// promotion candidate.
static cl::opt<unsigned>
ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
cl::init(1000),
cl::desc("The minimum count to the direct call target "
"for the promotion"));
// The percent threshold for the direct-call target (this call site vs the
// total call count) for it to be considered as the promotion target.
static cl::opt<unsigned>
ICPPercentThreshold("icp-percent-threshold", cl::init(33), cl::Hidden,
cl::ZeroOrMore,
cl::desc("The percentage threshold for the promotion"));
// Set the maximum number of targets to promote for a single indirect-call
// callsite.
static cl::opt<unsigned>
MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
cl::desc("Max number of promotions for a single indirect "
"call callsite"));
ICallPromotionAnalysis::ICallPromotionAnalysis() {
ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
}
bool ICallPromotionAnalysis::isPromotionProfitable(uint64_t Count,
uint64_t TotalCount) {
if (Count < ICPCountThreshold)
return false;
unsigned Percentage = (Count * 100) / TotalCount;
return (Percentage >= ICPPercentThreshold);
}
// Indirect-call promotion heuristic. The direct targets are sorted based on
// the count. Stop at the first target that is not promoted. Returns the
// number of candidates deemed profitable.
uint32_t ICallPromotionAnalysis::getProfitablePromotionCandidates(
const Instruction *Inst, uint32_t NumVals, uint64_t TotalCount) {
ArrayRef<InstrProfValueData> ValueDataRef(ValueDataArray.get(), NumVals);
DEBUG(dbgs() << " \nWork on callsite " << *Inst << " Num_targets: " << NumVals
<< "\n");
uint32_t I = 0;
for (; I < MaxNumPromotions && I < NumVals; I++) {
uint64_t Count = ValueDataRef[I].Count;
assert(Count <= TotalCount);
DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
<< " Target_func: " << ValueDataRef[I].Value << "\n");
if (!isPromotionProfitable(Count, TotalCount)) {
DEBUG(dbgs() << " Not promote: Cold target.\n");
return I;
}
TotalCount -= Count;
}
return I;
}
ArrayRef<InstrProfValueData>
ICallPromotionAnalysis::getPromotionCandidatesForInstruction(
const Instruction *I, uint32_t &NumVals, uint64_t &TotalCount,
uint32_t &NumCandidates) {
bool Res =
getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
ValueDataArray.get(), NumVals, TotalCount);
if (!Res) {
NumCandidates = 0;
return ArrayRef<InstrProfValueData>();
}
NumCandidates = getProfitablePromotionCandidates(I, NumVals, TotalCount);
return ArrayRef<InstrProfValueData>(ValueDataArray.get(), NumVals);
}
<commit_msg>[PGO] Adjust indirect call promotion threshold<commit_after>//===-- IndirectCallPromotionAnalysis.cpp - Find promotion candidates ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Helper methods for identifying profitable indirect call promotion
// candidates for an instruction when the indirect-call value profile metadata
// is available.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/IndirectCallSiteVisitor.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/Debug.h"
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "pgo-icall-prom-analysis"
// The minimum call count for the direct-call target to be considered as the
// promotion candidate.
static cl::opt<unsigned>
ICPCountThreshold("icp-count-threshold", cl::Hidden, cl::ZeroOrMore,
cl::init(1000),
cl::desc("The minimum count to the direct call target "
"for the promotion"));
// The percent threshold for the direct-call target (this call site vs the
// total call count) for it to be considered as the promotion target.
static cl::opt<unsigned>
ICPPercentThreshold("icp-percent-threshold", cl::init(30), cl::Hidden,
cl::ZeroOrMore,
cl::desc("The percentage threshold for the promotion"));
// Set the maximum number of targets to promote for a single indirect-call
// callsite.
static cl::opt<unsigned>
MaxNumPromotions("icp-max-prom", cl::init(2), cl::Hidden, cl::ZeroOrMore,
cl::desc("Max number of promotions for a single indirect "
"call callsite"));
ICallPromotionAnalysis::ICallPromotionAnalysis() {
ValueDataArray = llvm::make_unique<InstrProfValueData[]>(MaxNumPromotions);
}
bool ICallPromotionAnalysis::isPromotionProfitable(uint64_t Count,
uint64_t TotalCount) {
if (Count < ICPCountThreshold)
return false;
unsigned Percentage = (Count * 100) / TotalCount;
return (Percentage >= ICPPercentThreshold);
}
// Indirect-call promotion heuristic. The direct targets are sorted based on
// the count. Stop at the first target that is not promoted. Returns the
// number of candidates deemed profitable.
uint32_t ICallPromotionAnalysis::getProfitablePromotionCandidates(
const Instruction *Inst, uint32_t NumVals, uint64_t TotalCount) {
ArrayRef<InstrProfValueData> ValueDataRef(ValueDataArray.get(), NumVals);
DEBUG(dbgs() << " \nWork on callsite " << *Inst << " Num_targets: " << NumVals
<< "\n");
uint32_t I = 0;
for (; I < MaxNumPromotions && I < NumVals; I++) {
uint64_t Count = ValueDataRef[I].Count;
assert(Count <= TotalCount);
DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
<< " Target_func: " << ValueDataRef[I].Value << "\n");
if (!isPromotionProfitable(Count, TotalCount)) {
DEBUG(dbgs() << " Not promote: Cold target.\n");
return I;
}
TotalCount -= Count;
}
return I;
}
ArrayRef<InstrProfValueData>
ICallPromotionAnalysis::getPromotionCandidatesForInstruction(
const Instruction *I, uint32_t &NumVals, uint64_t &TotalCount,
uint32_t &NumCandidates) {
bool Res =
getValueProfDataFromInst(*I, IPVK_IndirectCallTarget, MaxNumPromotions,
ValueDataArray.get(), NumVals, TotalCount);
if (!Res) {
NumCandidates = 0;
return ArrayRef<InstrProfValueData>();
}
NumCandidates = getProfitablePromotionCandidates(I, NumVals, TotalCount);
return ArrayRef<InstrProfValueData>(ValueDataArray.get(), NumVals);
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MultiApp.h"
// Moose
#include "AppFactory.h"
#include "SetupInterface.h"
#include "Executioner.h"
#include "UserObject.h"
#include "FEProblem.h"
#include "Output.h"
#include "AppFactory.h"
#include "MooseUtils.h"
// libMesh
#include "libmesh/mesh_tools.h"
#include <iostream>
#include <iomanip>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm>
template<>
InputParameters validParams<MultiApp>()
{
InputParameters params = validParams<MooseObject>();
params.addPrivateParam<bool>("use_displaced_mesh", false);
std::ostringstream app_types_strings;
registeredMooseAppIterator it = AppFactory::instance()->registeredObjectsBegin();
while(it != AppFactory::instance()->registeredObjectsEnd())
{
app_types_strings << it->first;
++it;
if(it != AppFactory::instance()->registeredObjectsEnd())
app_types_strings<< ", ";
}
MooseEnum app_types_options(app_types_strings.str());
params.addRequiredParam<MooseEnum>("app_type", app_types_options, "The type of application to build.");
params.addParam<std::vector<Real> >("positions", "The positions of the App locations. Each set of 3 values will represent a Point. Either this must be supplied or 'positions_file'");
params.addParam<FileName>("positions_file", "A filename that should be looked in for positions. Each set of 3 values in that file will represent a Point. Either this must be supplied or 'positions'");
params.addRequiredParam<std::vector<std::string> >("input_files", "The input file for each App. If this parameter only contains one input file it will be used for all of the Apps.");
params.addPrivateParam<MPI_Comm>("_mpi_comm");
MooseEnum execute_options(SetupInterface::getExecuteOptions());
execute_options = "timestep_begin"; // set the default
params.addParam<MooseEnum>("execute_on", execute_options, "Set to (residual|jacobian|timestep|timestep_begin|custom) to execute only at that moment");
params.addPrivateParam<std::string>("built_by_action", "add_multi_app");
return params;
}
MultiApp::MultiApp(const std::string & name, InputParameters parameters):
MooseObject(name, parameters),
_fe_problem(getParam<FEProblem *>("_fe_problem")),
_app_type(getParam<MooseEnum>("app_type")),
_input_files(getParam<std::vector<std::string> >("input_files")),
_orig_comm(getParam<MPI_Comm>("_mpi_comm")),
_execute_on(getParam<MooseEnum>("execute_on"))
{
if(isParamValid("positions"))
_positions_vec = getParam<std::vector<Real> >("positions");
else if(isParamValid("positions_file"))
{
// Read the file on the root processor then broadcast it
if(libMesh::processor_id() == 0)
{
std::string positions_file = getParam<FileName>("positions_file");
MooseUtils::checkFileReadable(positions_file);
std::ifstream is(positions_file.c_str());
std::istream_iterator<Real> begin(is), end;
_positions_vec.insert(_positions_vec.begin(), begin, end);
}
unsigned int num_values = _positions_vec.size();
Parallel::broadcast(num_values);
_positions_vec.resize(num_values);
Parallel::broadcast(_positions_vec);
}
else
mooseError("Must supply either 'positions' or 'positions_file' for MultiApp "<<_name);
{ // Read the positions out of the vector
unsigned int num_vec_entries = _positions_vec.size();
mooseAssert(num_vec_entries % LIBMESH_DIM == 0, "Wrong number of entries in 'positions'");
_positions.reserve(num_vec_entries / LIBMESH_DIM);
for(unsigned int i=0; i<num_vec_entries; i+=3)
_positions.push_back(Point(_positions_vec[i], _positions_vec[i+1], _positions_vec[i+2]));
}
_total_num_apps = _positions.size();
mooseAssert(_input_files.size() == 1 || _positions.size() == _input_files.size(), "Number of positions and input files are not the same!");
/// Set up our Comm and set the number of apps we're going to be working on
buildComm();
MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);
_apps.resize(_my_num_apps);
for(unsigned int i=0; i<_my_num_apps; i++)
{
InputParameters app_params = AppFactory::instance()->getValidParams(_app_type);
MooseApp * app = AppFactory::instance()->create(_app_type, "multi_app", app_params);
std::ostringstream output_base;
// Create an output base by taking the output base of the master problem and appending
// the name of the multiapp + a number to it
output_base << _fe_problem->out().fileBase()
<< "_" << _name
<< std::setw(_total_num_apps/10)
<< std::setprecision(0)
<< std::setfill('0')
<< std::right
<< _first_local_app + i;
_apps[i] = app;
std::string input_file = "";
if(_input_files.size() == 1) // If only one input file was provide, use it for all the solves
input_file = _input_files[0];
else
input_file = _input_files[_first_local_app+i];
app->setInputFileName(input_file);
app->setOutputFileBase(output_base.str());
app->setupOptions();
app->runInputFile();
}
// Swap back
Moose::swapLibMeshComm(swapped);
}
MultiApp::~MultiApp()
{
for(unsigned int i=0; i<_my_num_apps; i++)
delete _apps[i];
}
Executioner *
MultiApp::getExecutioner(unsigned int app)
{
return _apps[globalAppToLocal(app)]->getExecutioner();
}
MeshTools::BoundingBox
MultiApp::getBoundingBox(unsigned int app)
{
FEProblem * problem = appProblem(app);
MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);
MooseMesh & mesh = problem->mesh();
MeshTools::BoundingBox bbox = MeshTools::bounding_box(mesh);
Moose::swapLibMeshComm(swapped);
return bbox;
}
FEProblem *
MultiApp::appProblem(unsigned int app)
{
unsigned int local_app = globalAppToLocal(app);
FEProblem * problem = dynamic_cast<FEProblem *>(&_apps[local_app]->getExecutioner()->problem());
mooseAssert(problem, "Not an FEProblem!");
return problem;
}
const UserObject &
MultiApp::appUserObjectBase(unsigned int app, const std::string & name)
{
return appProblem(app)->getUserObjectBase(name);
}
Real
MultiApp::appPostprocessorValue(unsigned int app, const std::string & name)
{
return appProblem(app)->getPostprocessorValue(name);
}
bool
MultiApp::hasLocalApp(unsigned int global_app)
{
if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1))
return true;
return false;
}
void
MultiApp::buildComm()
{
MPI_Comm_size(_orig_comm, (int*)&_orig_num_procs);
MPI_Comm_rank(_orig_comm, (int*)&_orig_rank);
// If we have more apps than processors then we're just going to divide up the work
if(_total_num_apps >= _orig_num_procs)
{
_my_comm = MPI_COMM_SELF;
_my_rank = 0;
_my_num_apps = _total_num_apps/_orig_num_procs;
_first_local_app = _my_num_apps * _orig_rank;
// The last processor will pick up any extra apps
if(_orig_rank == _orig_num_procs - 1)
_my_num_apps += _total_num_apps % _orig_num_procs;
return;
}
// In this case we need to divide up the processors that are going to work on each app
int rank;
MPI_Comm_rank(_orig_comm, &rank);
// sleep(rank);
int procs_per_app = _orig_num_procs / _total_num_apps;
int my_app = rank / procs_per_app;
int procs_for_my_app = procs_per_app;
if((unsigned int) my_app >= _total_num_apps-1) // The last app will gain any left-over procs
{
my_app = _total_num_apps - 1;
procs_for_my_app += _orig_num_procs % _total_num_apps;
}
// Only one app here
_first_local_app = my_app;
_my_num_apps = 1;
std::vector<int> ranks_in_my_group(procs_for_my_app);
// Add all the processors in that are in my group
for(int i=0; i<procs_for_my_app; i++)
ranks_in_my_group[i] = (my_app * procs_per_app) + i;
MPI_Group orig_group, new_group;
// Extract the original group handle
MPI_Comm_group(_orig_comm, &orig_group);
// Create a group
MPI_Group_incl(orig_group, procs_for_my_app, &ranks_in_my_group[0], &new_group);
// Create new communicator
MPI_Comm_create(_orig_comm, new_group, &_my_comm);
MPI_Comm_rank(_my_comm, (int*)&_my_rank);
}
unsigned int
MultiApp::globalAppToLocal(unsigned int global_app)
{
if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1))
return global_app-_first_local_app;
std::cout<<_first_local_app<<" "<<global_app<<std::endl;
mooseError("Invalid global_app!");
}
<commit_msg>fix zeros for outputting multiapp files ref #1845<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "MultiApp.h"
// Moose
#include "AppFactory.h"
#include "SetupInterface.h"
#include "Executioner.h"
#include "UserObject.h"
#include "FEProblem.h"
#include "Output.h"
#include "AppFactory.h"
#include "MooseUtils.h"
// libMesh
#include "libmesh/mesh_tools.h"
#include <iostream>
#include <iomanip>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm>
template<>
InputParameters validParams<MultiApp>()
{
InputParameters params = validParams<MooseObject>();
params.addPrivateParam<bool>("use_displaced_mesh", false);
std::ostringstream app_types_strings;
registeredMooseAppIterator it = AppFactory::instance()->registeredObjectsBegin();
while(it != AppFactory::instance()->registeredObjectsEnd())
{
app_types_strings << it->first;
++it;
if(it != AppFactory::instance()->registeredObjectsEnd())
app_types_strings<< ", ";
}
MooseEnum app_types_options(app_types_strings.str());
params.addRequiredParam<MooseEnum>("app_type", app_types_options, "The type of application to build.");
params.addParam<std::vector<Real> >("positions", "The positions of the App locations. Each set of 3 values will represent a Point. Either this must be supplied or 'positions_file'");
params.addParam<FileName>("positions_file", "A filename that should be looked in for positions. Each set of 3 values in that file will represent a Point. Either this must be supplied or 'positions'");
params.addRequiredParam<std::vector<std::string> >("input_files", "The input file for each App. If this parameter only contains one input file it will be used for all of the Apps.");
params.addPrivateParam<MPI_Comm>("_mpi_comm");
MooseEnum execute_options(SetupInterface::getExecuteOptions());
execute_options = "timestep_begin"; // set the default
params.addParam<MooseEnum>("execute_on", execute_options, "Set to (residual|jacobian|timestep|timestep_begin|custom) to execute only at that moment");
params.addPrivateParam<std::string>("built_by_action", "add_multi_app");
return params;
}
MultiApp::MultiApp(const std::string & name, InputParameters parameters):
MooseObject(name, parameters),
_fe_problem(getParam<FEProblem *>("_fe_problem")),
_app_type(getParam<MooseEnum>("app_type")),
_input_files(getParam<std::vector<std::string> >("input_files")),
_orig_comm(getParam<MPI_Comm>("_mpi_comm")),
_execute_on(getParam<MooseEnum>("execute_on"))
{
if(isParamValid("positions"))
_positions_vec = getParam<std::vector<Real> >("positions");
else if(isParamValid("positions_file"))
{
// Read the file on the root processor then broadcast it
if(libMesh::processor_id() == 0)
{
std::string positions_file = getParam<FileName>("positions_file");
MooseUtils::checkFileReadable(positions_file);
std::ifstream is(positions_file.c_str());
std::istream_iterator<Real> begin(is), end;
_positions_vec.insert(_positions_vec.begin(), begin, end);
}
unsigned int num_values = _positions_vec.size();
Parallel::broadcast(num_values);
_positions_vec.resize(num_values);
Parallel::broadcast(_positions_vec);
}
else
mooseError("Must supply either 'positions' or 'positions_file' for MultiApp "<<_name);
{ // Read the positions out of the vector
unsigned int num_vec_entries = _positions_vec.size();
mooseAssert(num_vec_entries % LIBMESH_DIM == 0, "Wrong number of entries in 'positions'");
_positions.reserve(num_vec_entries / LIBMESH_DIM);
for(unsigned int i=0; i<num_vec_entries; i+=3)
_positions.push_back(Point(_positions_vec[i], _positions_vec[i+1], _positions_vec[i+2]));
}
_total_num_apps = _positions.size();
mooseAssert(_input_files.size() == 1 || _positions.size() == _input_files.size(), "Number of positions and input files are not the same!");
/// Set up our Comm and set the number of apps we're going to be working on
buildComm();
MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);
_apps.resize(_my_num_apps);
for(unsigned int i=0; i<_my_num_apps; i++)
{
InputParameters app_params = AppFactory::instance()->getValidParams(_app_type);
MooseApp * app = AppFactory::instance()->create(_app_type, "multi_app", app_params);
std::ostringstream output_base;
// Create an output base by taking the output base of the master problem and appending
// the name of the multiapp + a number to it
output_base << _fe_problem->out().fileBase()
<< "_" << _name
<< std::setw(std::ceil(std::log10(_total_num_apps)))
<< std::setprecision(0)
<< std::setfill('0')
<< std::right
<< _first_local_app + i;
_apps[i] = app;
std::string input_file = "";
if(_input_files.size() == 1) // If only one input file was provide, use it for all the solves
input_file = _input_files[0];
else
input_file = _input_files[_first_local_app+i];
app->setInputFileName(input_file);
app->setOutputFileBase(output_base.str());
app->setupOptions();
app->runInputFile();
}
// Swap back
Moose::swapLibMeshComm(swapped);
}
MultiApp::~MultiApp()
{
for(unsigned int i=0; i<_my_num_apps; i++)
delete _apps[i];
}
Executioner *
MultiApp::getExecutioner(unsigned int app)
{
return _apps[globalAppToLocal(app)]->getExecutioner();
}
MeshTools::BoundingBox
MultiApp::getBoundingBox(unsigned int app)
{
FEProblem * problem = appProblem(app);
MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);
MooseMesh & mesh = problem->mesh();
MeshTools::BoundingBox bbox = MeshTools::bounding_box(mesh);
Moose::swapLibMeshComm(swapped);
return bbox;
}
FEProblem *
MultiApp::appProblem(unsigned int app)
{
unsigned int local_app = globalAppToLocal(app);
FEProblem * problem = dynamic_cast<FEProblem *>(&_apps[local_app]->getExecutioner()->problem());
mooseAssert(problem, "Not an FEProblem!");
return problem;
}
const UserObject &
MultiApp::appUserObjectBase(unsigned int app, const std::string & name)
{
return appProblem(app)->getUserObjectBase(name);
}
Real
MultiApp::appPostprocessorValue(unsigned int app, const std::string & name)
{
return appProblem(app)->getPostprocessorValue(name);
}
bool
MultiApp::hasLocalApp(unsigned int global_app)
{
if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1))
return true;
return false;
}
void
MultiApp::buildComm()
{
MPI_Comm_size(_orig_comm, (int*)&_orig_num_procs);
MPI_Comm_rank(_orig_comm, (int*)&_orig_rank);
// If we have more apps than processors then we're just going to divide up the work
if(_total_num_apps >= _orig_num_procs)
{
_my_comm = MPI_COMM_SELF;
_my_rank = 0;
_my_num_apps = _total_num_apps/_orig_num_procs;
_first_local_app = _my_num_apps * _orig_rank;
// The last processor will pick up any extra apps
if(_orig_rank == _orig_num_procs - 1)
_my_num_apps += _total_num_apps % _orig_num_procs;
return;
}
// In this case we need to divide up the processors that are going to work on each app
int rank;
MPI_Comm_rank(_orig_comm, &rank);
// sleep(rank);
int procs_per_app = _orig_num_procs / _total_num_apps;
int my_app = rank / procs_per_app;
int procs_for_my_app = procs_per_app;
if((unsigned int) my_app >= _total_num_apps-1) // The last app will gain any left-over procs
{
my_app = _total_num_apps - 1;
procs_for_my_app += _orig_num_procs % _total_num_apps;
}
// Only one app here
_first_local_app = my_app;
_my_num_apps = 1;
std::vector<int> ranks_in_my_group(procs_for_my_app);
// Add all the processors in that are in my group
for(int i=0; i<procs_for_my_app; i++)
ranks_in_my_group[i] = (my_app * procs_per_app) + i;
MPI_Group orig_group, new_group;
// Extract the original group handle
MPI_Comm_group(_orig_comm, &orig_group);
// Create a group
MPI_Group_incl(orig_group, procs_for_my_app, &ranks_in_my_group[0], &new_group);
// Create new communicator
MPI_Comm_create(_orig_comm, new_group, &_my_comm);
MPI_Comm_rank(_my_comm, (int*)&_my_rank);
}
unsigned int
MultiApp::globalAppToLocal(unsigned int global_app)
{
if(global_app >= _first_local_app && global_app <= _first_local_app + (_my_num_apps-1))
return global_app-_first_local_app;
std::cout<<_first_local_app<<" "<<global_app<<std::endl;
mooseError("Invalid global_app!");
}
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// C POSIX includes
#include <sys/stat.h>
// Moose includes
#include "Checkpoint.h"
#include "FEProblem.h"
#include "MooseApp.h"
#include "MaterialPropertyStorage.h"
#include "RestartableData.h"
#include "MooseMesh.h"
#include "libmesh/checkpoint_io.h"
#include "libmesh/enum_xdr_mode.h"
template <>
InputParameters
validParams<Checkpoint>()
{
// Get the parameters from the base classes
InputParameters params = validParams<FileOutput>();
// Typical checkpoint options
params.addParam<unsigned int>("num_files", 2, "Number of the restart files to save");
params.addParam<std::string>(
"suffix",
"cp",
"This will be appended to the file_base to create the directory name for checkpoint files.");
// Advanced settings
params.addParam<bool>("binary", true, "Toggle the output of binary files");
params.addParamNamesToGroup("binary", "Advanced");
return params;
}
Checkpoint::Checkpoint(const InputParameters & parameters)
: FileOutput(parameters),
_num_files(getParam<unsigned int>("num_files")),
_suffix(getParam<std::string>("suffix")),
_binary(getParam<bool>("binary")),
_parallel_mesh(_problem_ptr->mesh().isDistributedMesh()),
_restartable_data(_app.getRestartableData()),
_recoverable_data(_app.getRecoverableData()),
_material_property_storage(_problem_ptr->getMaterialPropertyStorage()),
_bnd_material_property_storage(_problem_ptr->getBndMaterialPropertyStorage()),
_restartable_data_io(RestartableDataIO(*_problem_ptr))
{
}
std::string
Checkpoint::filename()
{
// Get the time step with correct zero padding
std::ostringstream output;
output << directory() << "/" << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
<< std::right << timeStep();
return output.str();
}
std::string
Checkpoint::directory()
{
return _file_base + "_" + _suffix;
}
void
Checkpoint::output(const ExecFlagType & /*type*/)
{
// Start the performance log
Moose::perf_log.push("Checkpoint::output()", "Output");
// Create the output directory
std::string cp_dir = directory();
mkdir(cp_dir.c_str(), S_IRWXU | S_IRGRP);
// Create the output filename
std::string current_file = filename();
// Create the libMesh Checkpoint_IO object
MeshBase & mesh = _es_ptr->get_mesh();
CheckpointIO io(mesh, _binary);
// Set libHilbert renumbering flag to false. We don't support
// N-to-M restarts regardless, and if we're *never* going to do
// N-to-M restarts then libHilbert is just unnecessary computation
// and communication.
const bool renumber = false;
// Create checkpoint file structure
CheckpointFileNames current_file_struct;
if (_binary)
{
current_file_struct.checkpoint = current_file + "_mesh.cpr";
current_file_struct.system = current_file + ".xdr";
}
else
{
current_file_struct.checkpoint = current_file + "_mesh.cpa";
current_file_struct.system = current_file + ".xda";
}
current_file_struct.restart = current_file + ".rd";
// Write the checkpoint file
io.write(current_file_struct.checkpoint);
// Write the system data, using ENCODE vs WRITE based on xdr vs xda
_es_ptr->write(current_file_struct.system,
EquationSystems::WRITE_DATA | EquationSystems::WRITE_ADDITIONAL_DATA |
EquationSystems::WRITE_PARALLEL_FILES,
renumber);
// Write the restartable data
_restartable_data_io.writeRestartableData(
current_file_struct.restart, _restartable_data, _recoverable_data);
// Remove old checkpoint files
updateCheckpointFiles(current_file_struct);
// Stop the logging
Moose::perf_log.pop("Checkpoint::output()", "Output");
}
void
Checkpoint::updateCheckpointFiles(CheckpointFileNames file_struct)
{
// Update the list of stored files
_file_names.push_back(file_struct);
// Remove un-wanted files
if (_file_names.size() > _num_files)
{
// Extract the filenames to be removed
CheckpointFileNames delete_files = _file_names.front();
// Remove these filenames from the list
_file_names.pop_front();
// Get thread and proc information
processor_id_type proc_id = processor_id();
// Delete checkpoint files (_mesh.cpr)
if (proc_id == 0)
{
std::ostringstream oss;
oss << delete_files.checkpoint;
std::string file_name = oss.str();
CheckpointIO::cleanup(file_name, comm().size());
}
// Delete the system files (xdr and xdr.0000, ...)
if (proc_id == 0)
{
std::ostringstream oss;
oss << delete_files.system;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
{
std::ostringstream oss;
oss << delete_files.system << "." << std::setw(4) << std::setprecision(0) << std::setfill('0')
<< proc_id;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
unsigned int n_threads = libMesh::n_threads();
// Remove the restart files (rd)
{
for (THREAD_ID tid = 0; tid < n_threads; tid++)
{
std::ostringstream oss;
oss << delete_files.restart << "-" << proc_id;
if (n_threads > 1)
oss << "-" << tid;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
}
}
}
<commit_msg>Cleanup the right mesh files<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
// C POSIX includes
#include <sys/stat.h>
// Moose includes
#include "Checkpoint.h"
#include "FEProblem.h"
#include "MooseApp.h"
#include "MaterialPropertyStorage.h"
#include "RestartableData.h"
#include "MooseMesh.h"
#include "libmesh/checkpoint_io.h"
#include "libmesh/enum_xdr_mode.h"
template <>
InputParameters
validParams<Checkpoint>()
{
// Get the parameters from the base classes
InputParameters params = validParams<FileOutput>();
// Typical checkpoint options
params.addParam<unsigned int>("num_files", 2, "Number of the restart files to save");
params.addParam<std::string>(
"suffix",
"cp",
"This will be appended to the file_base to create the directory name for checkpoint files.");
// Advanced settings
params.addParam<bool>("binary", true, "Toggle the output of binary files");
params.addParamNamesToGroup("binary", "Advanced");
return params;
}
Checkpoint::Checkpoint(const InputParameters & parameters)
: FileOutput(parameters),
_num_files(getParam<unsigned int>("num_files")),
_suffix(getParam<std::string>("suffix")),
_binary(getParam<bool>("binary")),
_parallel_mesh(_problem_ptr->mesh().isDistributedMesh()),
_restartable_data(_app.getRestartableData()),
_recoverable_data(_app.getRecoverableData()),
_material_property_storage(_problem_ptr->getMaterialPropertyStorage()),
_bnd_material_property_storage(_problem_ptr->getBndMaterialPropertyStorage()),
_restartable_data_io(RestartableDataIO(*_problem_ptr))
{
}
std::string
Checkpoint::filename()
{
// Get the time step with correct zero padding
std::ostringstream output;
output << directory() << "/" << std::setw(_padding) << std::setprecision(0) << std::setfill('0')
<< std::right << timeStep();
return output.str();
}
std::string
Checkpoint::directory()
{
return _file_base + "_" + _suffix;
}
void
Checkpoint::output(const ExecFlagType & /*type*/)
{
// Start the performance log
Moose::perf_log.push("Checkpoint::output()", "Output");
// Create the output directory
std::string cp_dir = directory();
mkdir(cp_dir.c_str(), S_IRWXU | S_IRGRP);
// Create the output filename
std::string current_file = filename();
// Create the libMesh Checkpoint_IO object
MeshBase & mesh = _es_ptr->get_mesh();
CheckpointIO io(mesh, _binary);
// Set libHilbert renumbering flag to false. We don't support
// N-to-M restarts regardless, and if we're *never* going to do
// N-to-M restarts then libHilbert is just unnecessary computation
// and communication.
const bool renumber = false;
// Create checkpoint file structure
CheckpointFileNames current_file_struct;
if (_binary)
{
current_file_struct.checkpoint = current_file + "_mesh.cpr";
current_file_struct.system = current_file + ".xdr";
}
else
{
current_file_struct.checkpoint = current_file + "_mesh.cpa";
current_file_struct.system = current_file + ".xda";
}
current_file_struct.restart = current_file + ".rd";
// Write the checkpoint file
io.write(current_file_struct.checkpoint);
// Write the system data, using ENCODE vs WRITE based on xdr vs xda
_es_ptr->write(current_file_struct.system,
EquationSystems::WRITE_DATA | EquationSystems::WRITE_ADDITIONAL_DATA |
EquationSystems::WRITE_PARALLEL_FILES,
renumber);
// Write the restartable data
_restartable_data_io.writeRestartableData(
current_file_struct.restart, _restartable_data, _recoverable_data);
// Remove old checkpoint files
updateCheckpointFiles(current_file_struct);
// Stop the logging
Moose::perf_log.pop("Checkpoint::output()", "Output");
}
void
Checkpoint::updateCheckpointFiles(CheckpointFileNames file_struct)
{
// Update the list of stored files
_file_names.push_back(file_struct);
// Remove un-wanted files
if (_file_names.size() > _num_files)
{
// Extract the filenames to be removed
CheckpointFileNames delete_files = _file_names.front();
// Remove these filenames from the list
_file_names.pop_front();
// Get thread and proc information
processor_id_type proc_id = processor_id();
// Delete checkpoint files (_mesh.cpr)
if (proc_id == 0)
{
std::ostringstream oss;
oss << delete_files.checkpoint;
std::string file_name = oss.str();
CheckpointIO::cleanup(file_name, _parallel_mesh ? comm().size() : 1);
}
// Delete the system files (xdr and xdr.0000, ...)
if (proc_id == 0)
{
std::ostringstream oss;
oss << delete_files.system;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
{
std::ostringstream oss;
oss << delete_files.system << "." << std::setw(4) << std::setprecision(0) << std::setfill('0')
<< proc_id;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
unsigned int n_threads = libMesh::n_threads();
// Remove the restart files (rd)
{
for (THREAD_ID tid = 0; tid < n_threads; tid++)
{
std::ostringstream oss;
oss << delete_files.restart << "-" << proc_id;
if (n_threads > 1)
oss << "-" << tid;
std::string file_name = oss.str();
int ret = remove(file_name.c_str());
if (ret != 0)
mooseWarning("Error during the deletion of file '", file_name, "': ", std::strerror(ret));
}
}
}
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <io/FilePointer.hpp>
#include <io/Inet4Address.hpp>
#include <io/Resolv.hpp>
#include <io/ServerSocket.hpp>
#include <io/Socket.hpp>
#include <io/StringWriter.hpp>
#include <io/binary/StreamGetter.hpp>
#include <json/Json.hpp>
#include <json/JsonMercuryTempl.hpp>
#include <log/LogManager.hpp>
#include <log/LogServer.hpp>
#include <mercury/Mercury.hpp>
#include <os/Condition.hpp>
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
using namespace logger ;
using namespace std ;
using namespace io ;
using namespace os ;
using namespace json ;
byte mercury_magic_cookie[32] = {
0xe2, 0x1a, 0x14, 0xc8, 0xa2, 0x35, 0x0a, 0x92,
0xaf, 0x1a, 0xff, 0xd6, 0x35, 0x2b, 0xa4, 0xf3,
0x97, 0x79, 0xaf, 0xb5, 0xc1, 0x23, 0x43, 0xf0,
0xf7, 0x14, 0x17, 0x62, 0x53, 0x4a, 0xa9, 0x7e,
};
Mutex* g_mutex;
Condition* g_cond;
class MercuryConfig {
public:
MercuryConfig():
logEverything(false),
controller_url("http://127.0.0.1:5000/"),
bind_ip(new Inet4Address("127.0.0.1", 8639)),
log_out(NULL),
colors(true),
default_level(NULL),
log_server(NULL)
{}
bool logEverything;
std::string controller_url;
SocketAddress* bind_ip;
BaseIO* log_out;
bool colors;
LogLevel* default_level;
SocketAddress* log_server;
};
template<>
struct JsonBasicConvert<MercuryConfig> {
static MercuryConfig convert(const json::Json& jsn) {
MercuryConfig ret;
ret.logEverything = jsn.hasAttribute("logEverything") && jsn["logEverything"] != 0;
SocketAddress* old;
if(jsn.hasAttribute("controller_url")) {
ret.controller_url = jsn["controller_url"].stringValue();
}
if(jsn.hasAttribute("bind_ip")) {
old = ret.bind_ip;
ret.bind_ip = jsn["bind_ip"].convert<SocketAddress*>();
delete old;
}
if(jsn.hasAttribute("logFile")) {
FILE* f = fopen(jsn["logFile"].stringValue().c_str(), "w");
if(f) {
io::FilePointer* fp = new io::FilePointer(f);
ret.log_out = fp;
} else {
fprintf(stderr, "Unable to open log file. Logging to stdout\n");
}
}
if(jsn.hasAttribute("defaultLogLevel")) {
ret.default_level = LogLevel::getLogLevelByName(jsn["defaultLogLevel"].stringValue().c_str());
}
if(jsn.hasAttribute("logColors")) {
ret.colors = jsn["logColors"] != 0;
}
if(jsn.hasAttribute("logServerBindAddress")) {
ret.log_server = jsn["logServerBindAddress"].convert<SocketAddress*>();
if(ret.log_server->linkProtocol() == AF_UNIX) {
dynamic_cast<UnixAddress*>(ret.log_server)->unlink();
}
}
return ret;
}
};
void sigchld_hdlr(int sig) {
ScopedLock __sl(*g_mutex);
g_cond->signal();
}
void start_logging_service(int fd) {
/* start a logging service which will read on
* fd and wait for input */
pid_t child;
printf("Forking child\n");
if(!(child = fork())) {
LogContext::unlock();
LogContext& log = LogManager::instance().getLogContext("Child", "StdErr");
log.printfln(DEBUG, "Error logger started");
FILE* f = fdopen(fd, "r");
char read[1024];
read[1023] = 0;
while(true) {
fgets(read, sizeof(read)-1, f);
log.printfln(ERROR, read);
}
}
if(child < 0) {
perror("fork() failed");
}
}
int startMercury(LogContext& m_log, MercuryConfig& config) {
StreamServerSocket sock;
SocketAddress* bind_addr = config.bind_ip;
int error_pipe[2];
if(pipe(error_pipe)) {
perror("Error on pipe()\n");
return 1;
}
dup2(error_pipe[1], STDERR_FILENO);
/* Start the service that is only resposible for
* logging the stderr of the this process and
* its other children */
start_logging_service(error_pipe[0]);
m_log.printfln(INFO, "Binding to address: %s", bind_addr->toString().c_str());
sock.bind(*bind_addr);
sock.listen(1);
while(true) {
StreamSocket* client = sock.accept();
m_log.printfln(INFO, "Connection accepted");
/* simply get 64 bytes from the client and
* then close the connection */
byte recieve[64];
client->read(recieve, sizeof(recieve));
delete client;
/* make sure the cookie is equal to what we expect */
if(std::equal(recieve, recieve + 32, mercury_magic_cookie)) {
/* the cookie is equal to what we expect
* so continue with the fork() */
m_log.printfln(INFO, "Magic cookie accepted, forking new process");
pid_t child;
if(!(child = fork())) {
LogContext::unlock();
/* report all stderr to the error pipe */
fprintf(stderr, "Test stderr\n");
fflush(stderr);
/* Child process. Setup the config and boot
* the merucry state machine */
mercury::Config conf;
std::copy(recieve + 32, recieve + 64, conf.mercury_id);
conf.controller_url = config.controller_url;
mercury::Proxy& process = mercury::ProxyHolder::instance();
/* start mercury */
process.start(conf, NULL);
process.waitForExit();
exit(0);
} else {
/* parent */
m_log.printfln(INFO, "Child started pid=%d", child);
int res = 0;
pid_t pid;
/* Wait for the child to exit. this
* condition will be signaled by the
* sigchld handler */
if(!g_cond->timedwait(*g_mutex, 300 SECS)) {
/* The child is taking too long to return
* kill it */
m_log.printfln(WARN, "Child timeout, sending SIGTERM");
kill(child, SIGTERM);
if(!g_cond->timedwait(*g_mutex, 10 SECS)) {
/* The child still isn't dead */
m_log.printfln(WARN, "Child hard timeout, sending SIGKILL");
kill(child, SIGKILL);
}
}
if((pid = waitpid(child, &res, WNOHANG))) {
if(pid == -1) {
m_log.printfln(ERROR, "Error in waitpid %s", strerror(errno));
} else {
m_log.printfln(INFO, "Reap child (%d)\n", (int)pid);
}
}
if(WIFSIGNALED(res)) {
m_log.printfln(WARN, "Child was signaled with %d", WTERMSIG(res));
}
if(WEXITSTATUS(res)) {
m_log.printfln(WARN, "Child returned abnormal status: %d", WEXITSTATUS(res));
}
if(WIFSTOPPED(res)) {
m_log.printfln(WARN, "Child timed out and was killed by parent");
}
}
} else {
m_log.printfln(ERROR, "Bad magic cookie received. Timeout for 5 seconds");
sleep(5);
m_log.printfln(INFO, "Timeout complete");
}
}
return 0;
}
int main( int argc, char** argv ) {
(void) argc ; (void) argv ;
g_mutex = new Mutex();
g_cond = new Condition();
ScopedLock __sl(*g_mutex);
MercuryConfig conf;
SocketAddress* old = conf.bind_ip;
signal(SIGCHLD, sigchld_hdlr);
try {
Json* jsn = Json::fromFile("config.json");
conf = jsn->convert<MercuryConfig>();
delete old;
} catch(Exception& exp) {
fprintf(stderr, "Unable to load config file: %s\n", exp.getMessage());
};
if(conf.log_out) {
LogManager::instance().addLogOutput(conf.log_out, conf.colors);
}
if(conf.logEverything) {
LogManager::instance().logEverything();
}
if(conf.default_level) {
LogManager::instance().setDefaultLevel(*conf.default_level);
}
try {
if(conf.log_server) {
LogServer* log_server = new LogServer(*conf.log_server);
Thread* __th = new Thread(*log_server);
__th->start();
}
LogContext& m_log = LogManager::instance().getLogContext("Main", "Main");
m_log.printfln(INFO, "Mercury started");
return startMercury(m_log, conf);
} catch(Exception& exp) {
LogContext& m_log = LogManager::instance().getLogContext("Main", "Main");
m_log.printfln(FATAL, "Uncaught exception: %s", exp.getMessage());
return 127;
}
}
<commit_msg>removed printf<commit_after>#include <cstdio>
#include <io/FilePointer.hpp>
#include <io/Inet4Address.hpp>
#include <io/Resolv.hpp>
#include <io/ServerSocket.hpp>
#include <io/Socket.hpp>
#include <io/StringWriter.hpp>
#include <io/binary/StreamGetter.hpp>
#include <json/Json.hpp>
#include <json/JsonMercuryTempl.hpp>
#include <log/LogManager.hpp>
#include <log/LogServer.hpp>
#include <mercury/Mercury.hpp>
#include <os/Condition.hpp>
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
using namespace logger ;
using namespace std ;
using namespace io ;
using namespace os ;
using namespace json ;
byte mercury_magic_cookie[32] = {
0xe2, 0x1a, 0x14, 0xc8, 0xa2, 0x35, 0x0a, 0x92,
0xaf, 0x1a, 0xff, 0xd6, 0x35, 0x2b, 0xa4, 0xf3,
0x97, 0x79, 0xaf, 0xb5, 0xc1, 0x23, 0x43, 0xf0,
0xf7, 0x14, 0x17, 0x62, 0x53, 0x4a, 0xa9, 0x7e,
};
Mutex* g_mutex;
Condition* g_cond;
class MercuryConfig {
public:
MercuryConfig():
logEverything(false),
controller_url("http://127.0.0.1:5000/"),
bind_ip(new Inet4Address("127.0.0.1", 8639)),
log_out(NULL),
colors(true),
default_level(NULL),
log_server(NULL)
{}
bool logEverything;
std::string controller_url;
SocketAddress* bind_ip;
BaseIO* log_out;
bool colors;
LogLevel* default_level;
SocketAddress* log_server;
};
template<>
struct JsonBasicConvert<MercuryConfig> {
static MercuryConfig convert(const json::Json& jsn) {
MercuryConfig ret;
ret.logEverything = jsn.hasAttribute("logEverything") && jsn["logEverything"] != 0;
SocketAddress* old;
if(jsn.hasAttribute("controller_url")) {
ret.controller_url = jsn["controller_url"].stringValue();
}
if(jsn.hasAttribute("bind_ip")) {
old = ret.bind_ip;
ret.bind_ip = jsn["bind_ip"].convert<SocketAddress*>();
delete old;
}
if(jsn.hasAttribute("logFile")) {
FILE* f = fopen(jsn["logFile"].stringValue().c_str(), "w");
if(f) {
io::FilePointer* fp = new io::FilePointer(f);
ret.log_out = fp;
} else {
fprintf(stderr, "Unable to open log file. Logging to stdout\n");
}
}
if(jsn.hasAttribute("defaultLogLevel")) {
ret.default_level = LogLevel::getLogLevelByName(jsn["defaultLogLevel"].stringValue().c_str());
}
if(jsn.hasAttribute("logColors")) {
ret.colors = jsn["logColors"] != 0;
}
if(jsn.hasAttribute("logServerBindAddress")) {
ret.log_server = jsn["logServerBindAddress"].convert<SocketAddress*>();
if(ret.log_server->linkProtocol() == AF_UNIX) {
dynamic_cast<UnixAddress*>(ret.log_server)->unlink();
}
}
return ret;
}
};
void sigchld_hdlr(int sig) {
ScopedLock __sl(*g_mutex);
g_cond->signal();
}
void start_logging_service(int fd) {
/* start a logging service which will read on
* fd and wait for input */
pid_t child;
if(!(child = fork())) {
LogContext::unlock();
LogContext& log = LogManager::instance().getLogContext("Child", "StdErr");
log.printfln(DEBUG, "Error logger started");
FILE* f = fdopen(fd, "r");
char read[1024];
read[1023] = 0;
while(true) {
fgets(read, sizeof(read)-1, f);
log.printfln(ERROR, read);
}
}
if(child < 0) {
perror("fork() failed");
}
}
int startMercury(LogContext& m_log, MercuryConfig& config) {
StreamServerSocket sock;
SocketAddress* bind_addr = config.bind_ip;
int error_pipe[2];
if(pipe(error_pipe)) {
perror("Error on pipe()\n");
return 1;
}
/* Redirect stderr to the error_pipe. This will make it
* so we can still see stderr messages in the log */
dup2(error_pipe[1], STDERR_FILENO);
/* Start the service that is only resposible for
* logging the stderr of the this process and
* its other children */
start_logging_service(error_pipe[0]);
m_log.printfln(INFO, "Binding to address: %s", bind_addr->toString().c_str());
sock.bind(*bind_addr);
sock.listen(1);
while(true) {
StreamSocket* client = sock.accept();
m_log.printfln(INFO, "Connection accepted");
/* simply get 64 bytes from the client and
* then close the connection */
byte recieve[64];
client->read(recieve, sizeof(recieve));
delete client;
/* make sure the cookie is equal to what we expect */
if(std::equal(recieve, recieve + 32, mercury_magic_cookie)) {
/* the cookie is equal to what we expect
* so continue with the fork() */
m_log.printfln(INFO, "Magic cookie accepted, forking new process");
pid_t child;
if(!(child = fork())) {
LogContext::unlock();
/* report all stderr to the error pipe */
fprintf(stderr, "Test stderr\n");
fflush(stderr);
/* Child process. Setup the config and boot
* the merucry state machine */
mercury::Config conf;
std::copy(recieve + 32, recieve + 64, conf.mercury_id);
conf.controller_url = config.controller_url;
mercury::Proxy& process = mercury::ProxyHolder::instance();
/* start mercury */
process.start(conf, NULL);
process.waitForExit();
exit(0);
} else {
/* parent */
m_log.printfln(INFO, "Child started pid=%d", child);
int res = 0;
pid_t pid;
/* Wait for the child to exit. this
* condition will be signaled by the
* sigchld handler */
if(!g_cond->timedwait(*g_mutex, 300 SECS)) {
/* The child is taking too long to return
* kill it */
m_log.printfln(WARN, "Child timeout, sending SIGTERM");
kill(child, SIGTERM);
if(!g_cond->timedwait(*g_mutex, 10 SECS)) {
/* The child still isn't dead */
m_log.printfln(WARN, "Child hard timeout, sending SIGKILL");
kill(child, SIGKILL);
}
}
if((pid = waitpid(child, &res, WNOHANG))) {
if(pid == -1) {
m_log.printfln(ERROR, "Error in waitpid %s", strerror(errno));
} else {
m_log.printfln(INFO, "Reap child (%d)\n", (int)pid);
}
}
if(WIFSIGNALED(res)) {
m_log.printfln(WARN, "Child was signaled with %d", WTERMSIG(res));
}
if(WEXITSTATUS(res)) {
m_log.printfln(WARN, "Child returned abnormal status: %d", WEXITSTATUS(res));
}
if(WIFSTOPPED(res)) {
m_log.printfln(WARN, "Child timed out and was killed by parent");
}
}
} else {
m_log.printfln(ERROR, "Bad magic cookie received. Timeout for 5 seconds");
sleep(5);
m_log.printfln(INFO, "Timeout complete");
}
}
return 0;
}
int main( int argc, char** argv ) {
(void) argc ; (void) argv ;
g_mutex = new Mutex();
g_cond = new Condition();
ScopedLock __sl(*g_mutex);
MercuryConfig conf;
SocketAddress* old = conf.bind_ip;
signal(SIGCHLD, sigchld_hdlr);
try {
Json* jsn = Json::fromFile("config.json");
conf = jsn->convert<MercuryConfig>();
delete old;
} catch(Exception& exp) {
fprintf(stderr, "Unable to load config file: %s\n", exp.getMessage());
};
if(conf.log_out) {
LogManager::instance().addLogOutput(conf.log_out, conf.colors);
}
if(conf.logEverything) {
LogManager::instance().logEverything();
}
if(conf.default_level) {
LogManager::instance().setDefaultLevel(*conf.default_level);
}
try {
if(conf.log_server) {
LogServer* log_server = new LogServer(*conf.log_server);
Thread* __th = new Thread(*log_server);
__th->start();
}
LogContext& m_log = LogManager::instance().getLogContext("Main", "Main");
m_log.printfln(INFO, "Mercury started");
return startMercury(m_log, conf);
} catch(Exception& exp) {
LogContext& m_log = LogManager::instance().getLogContext("Main", "Main");
m_log.printfln(FATAL, "Uncaught exception: %s", exp.getMessage());
return 127;
}
}
<|endoftext|>
|
<commit_before>#ifndef HACK_HPP
#define HACK_HPP
#include <cstdint>
#include <string>
#include <unordered_map>
namespace Hasm {
namespace Hack {
using WORD = uint16_t;
const WORD INIT_RAM_ADDRESS{16};
const std::unordered_map<std::string, WORD> PREDEFINED_SYMBOLS{
{"SP", 0x00},
{"LCL", 0x01},
{"ARG", 0x02},
{"THIS", 0x03},
{"THAT", 0x04},
{"R0", 0x00},
{"R1", 0x01},
{"R2", 0x02},
{"R3", 0x03},
{"R4", 0x04},
{"R5", 0x05},
{"R6", 0x06},
{"R7", 0x07},
{"R8", 0x08},
{"R9", 0x09},
{"R10", 0x10},
{"R11", 0x11},
{"R12", 0x12},
{"R13", 0x13},
{"R14", 0x14},
{"R15", 0x15},
{"SCREEN", 0x4000},
{"KBD", 0x6000}
};
} // namespace Hack
} // namespace Hasm
#endif<commit_msg>Fix symbol values<commit_after>#ifndef HASM_HACK_HPP
#define HASM_HACK_HPP
#include <cstdint>
#include <string>
#include <unordered_map>
namespace Hasm {
namespace Hack {
using WORD = uint16_t;
const WORD INIT_RAM_ADDRESS{16};
const std::unordered_map<std::string, WORD> PREDEFINED_SYMBOLS{
{"SP", 0x0},
{"LCL", 0x1},
{"ARG", 0x2},
{"THIS", 0x3},
{"THAT", 0x4},
{"R0", 0x0},
{"R1", 0x1},
{"R2", 0x2},
{"R3", 0x3},
{"R4", 0x4},
{"R5", 0x5},
{"R6", 0x6},
{"R7", 0x7},
{"R8", 0x8},
{"R9", 0x9},
{"R10", 0xA},
{"R11", 0xB},
{"R12", 0xC},
{"R13", 0xD},
{"R14", 0xE},
{"R15", 0xF},
{"SCREEN", 0x4000},
{"KBD", 0x6000}
};
} // namespace Hack
} // namespace Hasm
#endif<|endoftext|>
|
<commit_before>#ifndef UTIL_HPP
#define UTIL_HPP
#include <vector>
#include <iterator>
#include <cstddef>
#include <boost/dynamic_bitset.hpp>
#include <iostream>
namespace rmatch {
/*!
given two bit vectors \a lowBits and \a topBits it finds the
bits for which we have ones only in either one of them
It returns the positions of those bits.
*/
template <typename output_container>
void retrieveRangeIndices(
const boost::dynamic_bitset<> & lowbits,
const boost::dynamic_bitset<> & topbits,
output_container& positions)
{
/*
we have the bitsets for the lower and the upper bound
obviously the lower bound is a subset of the upper bound
namely if we have 1 for some index in the lower bound, the we have it in the upper bound
we have to set those bits to 0
we just have to do an XOR
*/
const boost::dynamic_bitset<> XOR = lowbits ^ topbits;
/*
we have the bits now 1 where the suffix is in the given bound
we have to search for them.
XOR.count() gives the count of the bits where we have 1
*/
positions.reserve(XOR.count());
size_t i = XOR.find_first();
/*
find the next bit's position and store the index
note that if one decides to stop using the bitset and use multiple memory blocks to work with
the best way to find the next bit set is to use the expression
(val & -val) which is equivalen to (val & (~val + 1)) due to 2-complement of how integers are stored in memory
*/
while (i != XOR.npos)
{
positions.push_back(i);
i = XOR.find_next(i);
}
}
inline std::vector<size_t> retrieveRangeIndices(
const boost::dynamic_bitset<> & lowbits,
const boost::dynamic_bitset<> & topbits)
{
std::vector<size_t> positions;
retrieveRangeIndices(lowbits,topbits,positions);
return std::move(positions);
}
}
#endif // UTIL_HPP
<commit_msg>Fix u < l in util<commit_after>#ifndef UTIL_HPP
#define UTIL_HPP
#include <vector>
#include <iterator>
#include <cstddef>
#include <boost/dynamic_bitset.hpp>
#include <iostream>
namespace rmatch {
/*!
given two bit vectors \a lowBits and \a topBits it finds the
bits for which we have ones only in either one of them
It returns the positions of those bits.
*/
template <typename output_container>
void retrieveRangeIndices(
const boost::dynamic_bitset<> & lowbits,
const boost::dynamic_bitset<> & topbits,
output_container& positions)
{
/*
we have the bitsets for the lower and the upper bound
obviously the lower bound is a subset of the upper bound
namely if we have 1 for some index in the lower bound, the we have it in the upper bound
we have to set those bits to 0
we just have to do an XOR
*/
const boost::dynamic_bitset<> XOR = topbits - lowbits;
/*
we have the bits now 1 where the suffix is in the given bound
we have to search for them.
XOR.count() gives the count of the bits where we have 1
*/
positions.reserve(XOR.count());
size_t i = XOR.find_first();
/*
find the next bit's position and store the index
note that if one decides to stop using the bitset and use multiple memory blocks to work with
the best way to find the next bit set is to use the expression
(val & -val) which is equivalen to (val & (~val + 1)) due to 2-complement of how integers are stored in memory
*/
while (i != XOR.npos)
{
positions.push_back(i);
i = XOR.find_next(i);
}
}
inline std::vector<size_t> retrieveRangeIndices(
const boost::dynamic_bitset<> & lowbits,
const boost::dynamic_bitset<> & topbits)
{
std::vector<size_t> positions;
retrieveRangeIndices(lowbits,topbits,positions);
return std::move(positions);
}
}
#endif // UTIL_HPP
<|endoftext|>
|
<commit_before>// XXX This compiles, but is completely untested
#pragma once
#include "bitset.hh"
#include "cpu.hh"
#include "spinlock.hh"
#include "percpu.hh"
#include <atomic>
#include <cstdint>
#include <utility>
#include <vector>
// OpLog is a technique for scaling objects that are frequently
// written and rarely read. It works by logging modification
// operations to per-CPU logs and only applying these modification
// operations when a read needs to observe the object's state.
namespace oplog {
enum {
CACHE_SLOTS = 4096
};
// A base class for objects whose modification operations are logged
// and synchronized to the object's state only when the state needs
// to be observed.
//
// Classes wishing to apply OpLog should implement a "logger class"
// and subclass @c logged_object. Methods that modify the object's
// state should call @c get_logger to get an instance of the logger
// class and should call a method of the logger class to log the
// operation. Methods that read the object's state should call @c
// synchronize to apply all outstanding logged operations before
// they observe the object's state.
//
// @c logged_object takes care of making this memory-efficient:
// rather than simply keeping per-CPU logs for every object, it
// maintains a fixed size cache of logs per CPU so that only
// recently modified objects are likely to have logs.
//
// @tparam Logger A class that logs operations to be applied to the
// object later. This is the type returned by get_logger. There
// may be many Logger instances created per logged_object. Logger
// must have a default constructor, but there are no other
// requirements.
template<typename Logger>
class logged_object
{
public:
constexpr logged_object() : sync_lock_("logged_object") { }
// A Logger instance protected by a lock. Users of this class
// should not attempt to hold a reference to the protected logger
// longer than the locked_logger object remains live.
class locked_logger
{
lock_guard<spinlock> lock_;
Logger *logger_;
locked_logger(lock_guard<spinlock> &&lock, Logger *logger)
: lock_(std::move(lock)), logger_(logger) { }
public:
locked_logger(locked_logger &&o)
: lock_(std::move(o.lock_)), logger_(o.logger_)
{
o.logger_ = nullptr;
}
locked_logger &operator=(locked_logger &&o)
{
lock_ = std::move(o.lock_);
logger_ = o.logger_;
o.logger_ = nullptr;
}
// Return the protected Logger instance. Note that there is no
// operator*, since that would encourage decoupling the life
// time of the locked_logger from the lifetime of the Logger*.
Logger *operator->() const
{
return logger_;
}
};
protected:
// Return a locked operation logger for this object. In general,
// this logger will be CPU-local, meaning that operations from
// different cores can be performed in parallel and without
// communication.
locked_logger get_logger()
{
auto id = myid();
auto my_way = cache_[id].hash_way(this);
back_out:
auto guard = my_way->lock_.guard();
auto cur_obj = my_way->obj_.load(std::memory_order_relaxed);
if (cur_obj != this) {
if (cur_obj) {
// Evict this logger. In the unlikely event of a race
// between this and synchronize, we may deadlock here if we
// simply acquire cur_obj's sync lock. Hence, we perform
// deadlock avoidance.
auto sync_guard = cur_obj->sync_lock_.try_guard();
if (!sync_guard)
// We would deadlock with synchronize. Back out
goto back_out;
// XXX Since we don't do a full synchronize here, we lose
// some of the potential memory overhead benefits of the
// logger cache for ordered loggers like tsc_logged_object.
// These have to keep around all operations anyway until
// someone calls synchronize. We could keep track of this
// object in the locked_logger and call synchronize when it
// gets released.
cur_obj->flush_logger(&my_way->logger_);
cur_obj->cpus_.atomic_reset(id);
}
// Put this object in this way's tag
my_way->obj_.store(this, std::memory_order_relaxed);
cpus_.atomic_set(id);
}
return locked_logger(std::move(guard), &my_way->logger_);
}
// Acquire a per-object lock, apply all logged operations to this
// object, and return the per-object lock. The caller may keep
// this lock live for as long as it needs to prevent modifications
// to the object's synchronized value.
lock_guard<spinlock> synchronize()
{
auto guard = sync_lock_.guard();
// Repeatedly gather loggers until we see that the CPU set is
// empty. We can't check the whole CPU set atomically, but
// that's okay. Since we hold the sync lock, only we can clear
// bits in the CPU set, so while operations may happen between
// when we observe that CPU 0 is not in the set and when we
// observe that CPU n is not in the set, *if* we observe that
// all of the bits are zero, *then* we had a consistent snapshot
// as of when we observed that CPU 0's bit was zero.
while (1) {
bool any = false;
// Gather loggers
for (auto cpu : cpus_) {
// XXX Is the optimizer smart enough to lift the hash
// computation?
auto way = cache_[cpu].hash_way(this);
auto way_guard = way->lock_.guard();
auto cur_obj = way->obj_.load(std::memory_order_relaxed);
assert(cur_obj == this);
flush_logger(way->logger_);
cpus_.atomic_reset(cpu);
any = true;
}
if (!any)
break;
// Make sure we see concurrent updates to cpus_.
barrier();
}
// Tell the logged object that it has a consistent set of
// loggers and should do any final flushing.
flush_finish();
return std::move(guard);
}
// Flush one logger, resetting it to its initial state. This may
// update the object's state, but is not required to (for some
// loggers, this may be impossible when there are other loggers
// still cached). This is called with a locks that prevent
// concurrent flush_* calls and that prevent l from being returned
// by get_logger.
virtual void flush_logger(Logger *l) = 0;
// Perform final synchronization of the object's state. This is
// called by synchronize after it has flushed a consistent
// snapshot of loggers for this object. This is called with locks
// that prevents concurrent flush_* calls.
virtual void flush_finish() = 0;
private:
struct way
{
std::atomic<logged_object*> obj_;
spinlock lock_;
Logger logger_;
};
struct cache
{
way ways_[CACHE_SLOTS];
way *hash_way(logged_object *obj) const
{
// Hash based on Java's HashMap re-hashing function.
uint64_t wayno = (uintptr_t)obj;
wayno ^= (wayno >> 32) ^ (wayno >> 20) ^ (wayno >> 12);
wayno ^= (wayno >> 7) ^ (wayno >> 4);
wayno %= CACHE_SLOTS;
return &ways_[wayno];
}
};
// Per-type, per-CPU, per-object logger. The per-CPU part of this
// is unprotected because we lock internally.
static percpu<cache, NO_CRITICAL> cache_;
// Bitmask of CPUs that have logged operations for this object.
// Bits can be set without any lock, but can only be cleared when
// holding sync_lock_.
bitset<NCPU> cpus_;
// This lock serializes log flushes and protects clearing cpus_.
spinlock sync_lock_;
};
// The logger class used by tsc_logged_object.
class tsc_logger
{
class op
{
public:
const uint64_t tsc;
op(uint64_t tsc) : tsc(tsc) { }
virtual void run() = 0;
};
template<class CB>
class op_inst : public op
{
CB cb_;
public:
op_inst(uint64_t tsc, CB &&cb) : op(tsc), cb_(cb) { }
void run() override
{
cb_();
}
};
// Logged operations in TSC order
std::vector<op*> ops_;
static uint64_t rdtscp()
{
uint64_t a, d, c;
__asm __volatile("rdtscp" : "=a" (a), "=d" (d), "=c" (c));
return a | (d << 32);
}
void reset()
{
ops_.clear();
}
friend class tsc_logged_object;
public:
// Log the operation cb, which must be a callable. cb will be
// called with no arguments when the logs need to be
// synchronized.
template<typename CB>
void push(CB &&cb)
{
// We use rdtscp because all instructions before it must
// retire before it reads the time stamp, which means we must
// get a time stamp after the lock acquisition in get_logger.
// rdtscp does not prevent later instructions from issuing
// before it, but that's okay up to the lock release. The
// lock release will not move before the TSC read because we
// have to write the value of the TSC to memory, which
// introduces a data dependency from the rdtscp to this write,
// and the lock release also writes to memory, which
// introduces a TSO dependency from the TSC memory write to
// the lock release.
ops_.push_back(new op_inst<CB>(rdtscp(), std::forward<CB>(cb)));
}
};
// A logger that applies operations in global timestamp order using
// synchronized TSCs.
class tsc_logged_object : public logged_object<tsc_logger>
{
std::vector<tsc_logger> pending_;
void flush_logger(tsc_logger *l) override
{
pending_.emplace_back(std::move(*l));
l->reset();
}
// XXX Not implemented. This should heap-merge all of the loggers
// in pending_ and apply their operations in order.
void flush_finish() override;
};
// Problems with paper API:
// * Synchronize calls apply on each Queue object. Where do ordered
// queues actually get merged?
// * Supposedly it flushes long queues, but there's nowhere in the
// supposed API where that can happen. Object::queue doesn't know
// the length of the queue and Queue::push can't do the right
// locking.
// * Baking "Op" into the API is awkward for type-specific oplogs.
// * Evicting a queue on hash collision is actually really
// complicated. The paper says you synchronize the whole object,
// but the requires locking the other queues for that object,
// which is either racy or deadlock-prone. For many queue types,
// it's perfectly reasonable to flush a single queue. Even for
// queue types that require a global synchronization (e.g., to
// merge ordered queues), you can always flush the queue back to a
// per-object queue, and only apply that on sync.
// * Queue types have no convenient way to record per-object state
// (e.g., evicted but unapplied operations).
// * Type-specific Queue types don't automatically have access to
// the type's private fields, which is probably what they need to
// modify.
// * (Not really a problem, per se) The paper frames OpLog as the
// TSC-ordered approach that can then be optimized for specific
// types. I think this makes the API awkward, since the API is
// aimed at the TSC-ordered queue, rather than type-specific
// queues. Another way to look at it is that OpLog handles the
// mechanics of per-core queues, queue caching, and
// synchronization and that the user can plug in any queue type by
// implementing a simple interface. The TSC-ordered queue is then
// simply a very general queue type that the user may choose to
// plug in.
};
<commit_msg>oplog: Give logged_object a virtual destructor<commit_after>// XXX This compiles, but is completely untested
#pragma once
#include "bitset.hh"
#include "cpu.hh"
#include "spinlock.hh"
#include "percpu.hh"
#include <atomic>
#include <cstdint>
#include <utility>
#include <vector>
// OpLog is a technique for scaling objects that are frequently
// written and rarely read. It works by logging modification
// operations to per-CPU logs and only applying these modification
// operations when a read needs to observe the object's state.
namespace oplog {
enum {
CACHE_SLOTS = 4096
};
// A base class for objects whose modification operations are logged
// and synchronized to the object's state only when the state needs
// to be observed.
//
// Classes wishing to apply OpLog should implement a "logger class"
// and subclass @c logged_object. Methods that modify the object's
// state should call @c get_logger to get an instance of the logger
// class and should call a method of the logger class to log the
// operation. Methods that read the object's state should call @c
// synchronize to apply all outstanding logged operations before
// they observe the object's state.
//
// @c logged_object takes care of making this memory-efficient:
// rather than simply keeping per-CPU logs for every object, it
// maintains a fixed size cache of logs per CPU so that only
// recently modified objects are likely to have logs.
//
// @tparam Logger A class that logs operations to be applied to the
// object later. This is the type returned by get_logger. There
// may be many Logger instances created per logged_object. Logger
// must have a default constructor, but there are no other
// requirements.
template<typename Logger>
class logged_object
{
public:
constexpr logged_object() : sync_lock_("logged_object") { }
// logged_object is meant to be subclassed, so it needs a virtual
// destructor.
virtual ~logged_object() { }
// A Logger instance protected by a lock. Users of this class
// should not attempt to hold a reference to the protected logger
// longer than the locked_logger object remains live.
class locked_logger
{
lock_guard<spinlock> lock_;
Logger *logger_;
locked_logger(lock_guard<spinlock> &&lock, Logger *logger)
: lock_(std::move(lock)), logger_(logger) { }
public:
locked_logger(locked_logger &&o)
: lock_(std::move(o.lock_)), logger_(o.logger_)
{
o.logger_ = nullptr;
}
locked_logger &operator=(locked_logger &&o)
{
lock_ = std::move(o.lock_);
logger_ = o.logger_;
o.logger_ = nullptr;
}
// Return the protected Logger instance. Note that there is no
// operator*, since that would encourage decoupling the life
// time of the locked_logger from the lifetime of the Logger*.
Logger *operator->() const
{
return logger_;
}
};
protected:
// Return a locked operation logger for this object. In general,
// this logger will be CPU-local, meaning that operations from
// different cores can be performed in parallel and without
// communication.
locked_logger get_logger()
{
auto id = myid();
auto my_way = cache_[id].hash_way(this);
back_out:
auto guard = my_way->lock_.guard();
auto cur_obj = my_way->obj_.load(std::memory_order_relaxed);
if (cur_obj != this) {
if (cur_obj) {
// Evict this logger. In the unlikely event of a race
// between this and synchronize, we may deadlock here if we
// simply acquire cur_obj's sync lock. Hence, we perform
// deadlock avoidance.
auto sync_guard = cur_obj->sync_lock_.try_guard();
if (!sync_guard)
// We would deadlock with synchronize. Back out
goto back_out;
// XXX Since we don't do a full synchronize here, we lose
// some of the potential memory overhead benefits of the
// logger cache for ordered loggers like tsc_logged_object.
// These have to keep around all operations anyway until
// someone calls synchronize. We could keep track of this
// object in the locked_logger and call synchronize when it
// gets released.
cur_obj->flush_logger(&my_way->logger_);
cur_obj->cpus_.atomic_reset(id);
}
// Put this object in this way's tag
my_way->obj_.store(this, std::memory_order_relaxed);
cpus_.atomic_set(id);
}
return locked_logger(std::move(guard), &my_way->logger_);
}
// Acquire a per-object lock, apply all logged operations to this
// object, and return the per-object lock. The caller may keep
// this lock live for as long as it needs to prevent modifications
// to the object's synchronized value.
lock_guard<spinlock> synchronize()
{
auto guard = sync_lock_.guard();
// Repeatedly gather loggers until we see that the CPU set is
// empty. We can't check the whole CPU set atomically, but
// that's okay. Since we hold the sync lock, only we can clear
// bits in the CPU set, so while operations may happen between
// when we observe that CPU 0 is not in the set and when we
// observe that CPU n is not in the set, *if* we observe that
// all of the bits are zero, *then* we had a consistent snapshot
// as of when we observed that CPU 0's bit was zero.
while (1) {
bool any = false;
// Gather loggers
for (auto cpu : cpus_) {
// XXX Is the optimizer smart enough to lift the hash
// computation?
auto way = cache_[cpu].hash_way(this);
auto way_guard = way->lock_.guard();
auto cur_obj = way->obj_.load(std::memory_order_relaxed);
assert(cur_obj == this);
flush_logger(way->logger_);
cpus_.atomic_reset(cpu);
any = true;
}
if (!any)
break;
// Make sure we see concurrent updates to cpus_.
barrier();
}
// Tell the logged object that it has a consistent set of
// loggers and should do any final flushing.
flush_finish();
return std::move(guard);
}
// Flush one logger, resetting it to its initial state. This may
// update the object's state, but is not required to (for some
// loggers, this may be impossible when there are other loggers
// still cached). This is called with a locks that prevent
// concurrent flush_* calls and that prevent l from being returned
// by get_logger.
virtual void flush_logger(Logger *l) = 0;
// Perform final synchronization of the object's state. This is
// called by synchronize after it has flushed a consistent
// snapshot of loggers for this object. This is called with locks
// that prevents concurrent flush_* calls.
virtual void flush_finish() = 0;
private:
struct way
{
std::atomic<logged_object*> obj_;
spinlock lock_;
Logger logger_;
};
struct cache
{
way ways_[CACHE_SLOTS];
way *hash_way(logged_object *obj) const
{
// Hash based on Java's HashMap re-hashing function.
uint64_t wayno = (uintptr_t)obj;
wayno ^= (wayno >> 32) ^ (wayno >> 20) ^ (wayno >> 12);
wayno ^= (wayno >> 7) ^ (wayno >> 4);
wayno %= CACHE_SLOTS;
return &ways_[wayno];
}
};
// Per-type, per-CPU, per-object logger. The per-CPU part of this
// is unprotected because we lock internally.
static percpu<cache, NO_CRITICAL> cache_;
// Bitmask of CPUs that have logged operations for this object.
// Bits can be set without any lock, but can only be cleared when
// holding sync_lock_.
bitset<NCPU> cpus_;
// This lock serializes log flushes and protects clearing cpus_.
spinlock sync_lock_;
};
// The logger class used by tsc_logged_object.
class tsc_logger
{
class op
{
public:
const uint64_t tsc;
op(uint64_t tsc) : tsc(tsc) { }
virtual void run() = 0;
};
template<class CB>
class op_inst : public op
{
CB cb_;
public:
op_inst(uint64_t tsc, CB &&cb) : op(tsc), cb_(cb) { }
void run() override
{
cb_();
}
};
// Logged operations in TSC order
std::vector<op*> ops_;
static uint64_t rdtscp()
{
uint64_t a, d, c;
__asm __volatile("rdtscp" : "=a" (a), "=d" (d), "=c" (c));
return a | (d << 32);
}
void reset()
{
ops_.clear();
}
friend class tsc_logged_object;
public:
// Log the operation cb, which must be a callable. cb will be
// called with no arguments when the logs need to be
// synchronized.
template<typename CB>
void push(CB &&cb)
{
// We use rdtscp because all instructions before it must
// retire before it reads the time stamp, which means we must
// get a time stamp after the lock acquisition in get_logger.
// rdtscp does not prevent later instructions from issuing
// before it, but that's okay up to the lock release. The
// lock release will not move before the TSC read because we
// have to write the value of the TSC to memory, which
// introduces a data dependency from the rdtscp to this write,
// and the lock release also writes to memory, which
// introduces a TSO dependency from the TSC memory write to
// the lock release.
ops_.push_back(new op_inst<CB>(rdtscp(), std::forward<CB>(cb)));
}
};
// A logger that applies operations in global timestamp order using
// synchronized TSCs.
class tsc_logged_object : public logged_object<tsc_logger>
{
std::vector<tsc_logger> pending_;
void flush_logger(tsc_logger *l) override
{
pending_.emplace_back(std::move(*l));
l->reset();
}
// XXX Not implemented. This should heap-merge all of the loggers
// in pending_ and apply their operations in order.
void flush_finish() override;
};
// Problems with paper API:
// * Synchronize calls apply on each Queue object. Where do ordered
// queues actually get merged?
// * Supposedly it flushes long queues, but there's nowhere in the
// supposed API where that can happen. Object::queue doesn't know
// the length of the queue and Queue::push can't do the right
// locking.
// * Baking "Op" into the API is awkward for type-specific oplogs.
// * Evicting a queue on hash collision is actually really
// complicated. The paper says you synchronize the whole object,
// but the requires locking the other queues for that object,
// which is either racy or deadlock-prone. For many queue types,
// it's perfectly reasonable to flush a single queue. Even for
// queue types that require a global synchronization (e.g., to
// merge ordered queues), you can always flush the queue back to a
// per-object queue, and only apply that on sync.
// * Queue types have no convenient way to record per-object state
// (e.g., evicted but unapplied operations).
// * Type-specific Queue types don't automatically have access to
// the type's private fields, which is probably what they need to
// modify.
// * (Not really a problem, per se) The paper frames OpLog as the
// TSC-ordered approach that can then be optimized for specific
// types. I think this makes the API awkward, since the API is
// aimed at the TSC-ordered queue, rather than type-specific
// queues. Another way to look at it is that OpLog handles the
// mechanics of per-core queues, queue caching, and
// synchronization and that the user can plug in any queue type by
// implementing a simple interface. The TSC-ordered queue is then
// simply a very general queue type that the user may choose to
// plug in.
};
<|endoftext|>
|
<commit_before><commit_msg>Create pablo9696.cpp<commit_after><|endoftext|>
|
<commit_before><commit_msg>MainGame.cpp 누락된 것 추가<commit_after><|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
#include "MacabStatement.hxx"
#include "MacabResultSetMetaData.hxx"
#include <connectivity/FValue.hxx>
#include <com/sun/star/sdbc/XParameters.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <cppuhelper/implbase4.hxx>
namespace connectivity
{
namespace macab
{
class OBoundParam;
typedef ::cppu::ImplInheritanceHelper4< MacabCommonStatement,
::com::sun::star::sdbc::XPreparedStatement,
::com::sun::star::sdbc::XParameters,
::com::sun::star::sdbc::XResultSetMetaDataSupplier,
::com::sun::star::lang::XServiceInfo> MacabPreparedStatement_BASE;
class MacabPreparedStatement : public MacabPreparedStatement_BASE
{
protected:
::rtl::OUString m_sSqlStatement;
::rtl::Reference< MacabResultSetMetaData >
m_xMetaData;
sal_Bool m_bPrepared;
mutable sal_Int32 m_nParameterIndex;
OValueRow m_aParameterRow;
void checkAndResizeParameters(sal_Int32 nParams) throw(::com::sun::star::sdbc::SQLException);
void setMacabFields() const throw(::com::sun::star::sdbc::SQLException);
protected:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
virtual void resetParameters() const throw(::com::sun::star::sdbc::SQLException);
virtual void getNextParameter(::rtl::OUString &rParameter) const throw(::com::sun::star::sdbc::SQLException);
virtual ~MacabPreparedStatement();
public:
DECLARE_SERVICE_INFO();
MacabPreparedStatement(MacabConnection* _pConnection, const ::rtl::OUString& sql);
// OComponentHelper
virtual void SAL_CALL disposing();
// XPreparedStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XParameters
virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XResultSetMetaDataSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: make the overloaded-virtual mess here just a warning even with -Werror<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
#include "MacabStatement.hxx"
#include "MacabResultSetMetaData.hxx"
#include <connectivity/FValue.hxx>
#include <com/sun/star/sdbc/XParameters.hpp>
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#include <cppuhelper/implbase4.hxx>
#ifdef __clang__
#pragma clang diagnostic warning "-Woverloaded-virtual"
#endif
namespace connectivity
{
namespace macab
{
class OBoundParam;
typedef ::cppu::ImplInheritanceHelper4< MacabCommonStatement,
::com::sun::star::sdbc::XPreparedStatement,
::com::sun::star::sdbc::XParameters,
::com::sun::star::sdbc::XResultSetMetaDataSupplier,
::com::sun::star::lang::XServiceInfo> MacabPreparedStatement_BASE;
class MacabPreparedStatement : public MacabPreparedStatement_BASE
{
protected:
::rtl::OUString m_sSqlStatement;
::rtl::Reference< MacabResultSetMetaData >
m_xMetaData;
sal_Bool m_bPrepared;
mutable sal_Int32 m_nParameterIndex;
OValueRow m_aParameterRow;
void checkAndResizeParameters(sal_Int32 nParams) throw(::com::sun::star::sdbc::SQLException);
void setMacabFields() const throw(::com::sun::star::sdbc::SQLException);
protected:
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
sal_Int32 nHandle,
const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
virtual void resetParameters() const throw(::com::sun::star::sdbc::SQLException);
virtual void getNextParameter(::rtl::OUString &rParameter) const throw(::com::sun::star::sdbc::SQLException);
virtual ~MacabPreparedStatement();
public:
DECLARE_SERVICE_INFO();
MacabPreparedStatement(MacabConnection* _pConnection, const ::rtl::OUString& sql);
// OComponentHelper
virtual void SAL_CALL disposing();
// XPreparedStatement
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XParameters
virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XCloseable
virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// XResultSetMetaDataSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
}
#endif // _CONNECTIVITY_MACAB_PREPAREDSTATEMENT_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_browser_process_test.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/appcache/appcache_database.h"
#include "webkit/appcache/appcache_storage_impl.h"
#include "webkit/appcache/appcache_test_helper.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include <set>
namespace {
const FilePath::CharType kTestingAppCacheDirname[] =
FILE_PATH_LITERAL("Application Cache");
// Examples of a protected and an unprotected origin, to be used througout the
// test.
const char kProtectedManifest[] = "http://www.protected.com/cache.manifest";
const char kNormalManifest[] = "http://www.normal.com/cache.manifest";
} // namespace
namespace appcache {
class ChromeAppCacheServiceTest : public TestingBrowserProcessTest {
public:
ChromeAppCacheServiceTest()
: message_loop_(MessageLoop::TYPE_IO),
kProtectedManifestURL(kProtectedManifest),
kNormalManifestURL(kNormalManifest),
db_thread_(BrowserThread::DB, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
cache_thread_(BrowserThread::CACHE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {
}
protected:
scoped_refptr<ChromeAppCacheService> CreateAppCacheService(
const FilePath& appcache_path,
bool init_storage);
void InsertDataIntoAppCache(ChromeAppCacheService* appcache_service);
MessageLoop message_loop_;
ScopedTempDir temp_dir_;
const GURL kProtectedManifestURL;
const GURL kNormalManifestURL;
private:
BrowserThread db_thread_;
BrowserThread file_thread_;
BrowserThread cache_thread_;
BrowserThread io_thread_;
};
scoped_refptr<ChromeAppCacheService>
ChromeAppCacheServiceTest::CreateAppCacheService(
const FilePath& appcache_path,
bool init_storage) {
scoped_refptr<ChromeAppCacheService> appcache_service =
new ChromeAppCacheService(NULL);
const content::ResourceContext* resource_context = NULL;
scoped_refptr<quota::MockSpecialStoragePolicy> mock_policy =
new quota::MockSpecialStoragePolicy;
mock_policy->AddProtected(kProtectedManifestURL.GetOrigin());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(appcache_service.get(),
&ChromeAppCacheService::InitializeOnIOThread,
appcache_path,
resource_context,
mock_policy));
// Steps needed to initialize the storage of AppCache data.
message_loop_.RunAllPending();
if (init_storage) {
appcache::AppCacheStorageImpl* storage =
static_cast<appcache::AppCacheStorageImpl*>(
appcache_service->storage());
storage->database_->db_connection();
storage->disk_cache();
message_loop_.RunAllPending();
}
return appcache_service;
}
void ChromeAppCacheServiceTest::InsertDataIntoAppCache(
ChromeAppCacheService* appcache_service) {
AppCacheTestHelper appcache_helper;
appcache_helper.AddGroupAndCache(appcache_service, kNormalManifestURL);
appcache_helper.AddGroupAndCache(appcache_service, kProtectedManifestURL);
// Verify that adding the data succeeded
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
ASSERT_EQ(2UL, origins.size());
ASSERT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
ASSERT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}
TEST_F(ChromeAppCacheServiceTest, KeepOnDestruction) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);
// Create a ChromeAppCacheService and insert data into it
scoped_refptr<ChromeAppCacheService> appcache_service =
CreateAppCacheService(appcache_path, true);
ASSERT_TRUE(file_util::PathExists(appcache_path));
ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
InsertDataIntoAppCache(appcache_service);
// Test: delete the ChromeAppCacheService
appcache_service->set_clear_local_state_on_exit(false);
appcache_service = NULL;
message_loop_.RunAllPending();
// Recreate the appcache (for reading the data back)
appcache_service = CreateAppCacheService(appcache_path, false);
// The directory is still there
ASSERT_TRUE(file_util::PathExists(appcache_path));
// The appcache data is also there
AppCacheTestHelper appcache_helper;
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
EXPECT_EQ(2UL, origins.size());
EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}
TEST_F(ChromeAppCacheServiceTest, RemoveOnDestruction) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);
// Create a ChromeAppCacheService and insert data into it
scoped_refptr<ChromeAppCacheService> appcache_service =
CreateAppCacheService(appcache_path, true);
ASSERT_TRUE(file_util::PathExists(appcache_path));
ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
InsertDataIntoAppCache(appcache_service);
// Test: delete the ChromeAppCacheService
appcache_service->set_clear_local_state_on_exit(true);
appcache_service = NULL;
message_loop_.RunAllPending();
// Recreate the appcache (for reading the data back)
appcache_service = CreateAppCacheService(appcache_path, false);
// The directory is still there
ASSERT_TRUE(file_util::PathExists(appcache_path));
// The appcache data for the protected origin is there, and the data for the
// unprotected origin was deleted.
AppCacheTestHelper appcache_helper;
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
EXPECT_EQ(1UL, origins.size());
EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) == origins.end());
}
} // namespace appcache
<commit_msg>Make the membots happy again.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/scoped_temp_dir.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_browser_process_test.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/appcache/appcache_database.h"
#include "webkit/appcache/appcache_storage_impl.h"
#include "webkit/appcache/appcache_test_helper.h"
#include "webkit/quota/mock_special_storage_policy.h"
#include <set>
namespace {
const FilePath::CharType kTestingAppCacheDirname[] =
FILE_PATH_LITERAL("Application Cache");
// Examples of a protected and an unprotected origin, to be used througout the
// test.
const char kProtectedManifest[] = "http://www.protected.com/cache.manifest";
const char kNormalManifest[] = "http://www.normal.com/cache.manifest";
} // namespace
namespace appcache {
class ChromeAppCacheServiceTest : public TestingBrowserProcessTest {
public:
ChromeAppCacheServiceTest()
: message_loop_(MessageLoop::TYPE_IO),
kProtectedManifestURL(kProtectedManifest),
kNormalManifestURL(kNormalManifest),
db_thread_(BrowserThread::DB, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
cache_thread_(BrowserThread::CACHE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {
}
protected:
scoped_refptr<ChromeAppCacheService> CreateAppCacheService(
const FilePath& appcache_path,
bool init_storage);
void InsertDataIntoAppCache(ChromeAppCacheService* appcache_service);
MessageLoop message_loop_;
ScopedTempDir temp_dir_;
const GURL kProtectedManifestURL;
const GURL kNormalManifestURL;
private:
BrowserThread db_thread_;
BrowserThread file_thread_;
BrowserThread cache_thread_;
BrowserThread io_thread_;
};
scoped_refptr<ChromeAppCacheService>
ChromeAppCacheServiceTest::CreateAppCacheService(
const FilePath& appcache_path,
bool init_storage) {
scoped_refptr<ChromeAppCacheService> appcache_service =
new ChromeAppCacheService(NULL);
const content::ResourceContext* resource_context = NULL;
scoped_refptr<quota::MockSpecialStoragePolicy> mock_policy =
new quota::MockSpecialStoragePolicy;
mock_policy->AddProtected(kProtectedManifestURL.GetOrigin());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(appcache_service.get(),
&ChromeAppCacheService::InitializeOnIOThread,
appcache_path,
resource_context,
mock_policy));
// Steps needed to initialize the storage of AppCache data.
message_loop_.RunAllPending();
if (init_storage) {
appcache::AppCacheStorageImpl* storage =
static_cast<appcache::AppCacheStorageImpl*>(
appcache_service->storage());
storage->database_->db_connection();
storage->disk_cache();
message_loop_.RunAllPending();
}
return appcache_service;
}
void ChromeAppCacheServiceTest::InsertDataIntoAppCache(
ChromeAppCacheService* appcache_service) {
AppCacheTestHelper appcache_helper;
appcache_helper.AddGroupAndCache(appcache_service, kNormalManifestURL);
appcache_helper.AddGroupAndCache(appcache_service, kProtectedManifestURL);
// Verify that adding the data succeeded
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
ASSERT_EQ(2UL, origins.size());
ASSERT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
ASSERT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
}
TEST_F(ChromeAppCacheServiceTest, KeepOnDestruction) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);
// Create a ChromeAppCacheService and insert data into it
scoped_refptr<ChromeAppCacheService> appcache_service =
CreateAppCacheService(appcache_path, true);
ASSERT_TRUE(file_util::PathExists(appcache_path));
ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
InsertDataIntoAppCache(appcache_service);
// Test: delete the ChromeAppCacheService
appcache_service->set_clear_local_state_on_exit(false);
appcache_service = NULL;
message_loop_.RunAllPending();
// Recreate the appcache (for reading the data back)
appcache_service = CreateAppCacheService(appcache_path, false);
// The directory is still there
ASSERT_TRUE(file_util::PathExists(appcache_path));
// The appcache data is also there
AppCacheTestHelper appcache_helper;
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
EXPECT_EQ(2UL, origins.size());
EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) != origins.end());
// Delete and let cleanup tasks run prior to returning.
appcache_service = NULL;
message_loop_.RunAllPending();
}
TEST_F(ChromeAppCacheServiceTest, RemoveOnDestruction) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
FilePath appcache_path = temp_dir_.path().Append(kTestingAppCacheDirname);
// Create a ChromeAppCacheService and insert data into it
scoped_refptr<ChromeAppCacheService> appcache_service =
CreateAppCacheService(appcache_path, true);
ASSERT_TRUE(file_util::PathExists(appcache_path));
ASSERT_TRUE(file_util::PathExists(appcache_path.AppendASCII("Index")));
InsertDataIntoAppCache(appcache_service);
// Test: delete the ChromeAppCacheService
appcache_service->set_clear_local_state_on_exit(true);
appcache_service = NULL;
message_loop_.RunAllPending();
// Recreate the appcache (for reading the data back)
appcache_service = CreateAppCacheService(appcache_path, false);
// The directory is still there
ASSERT_TRUE(file_util::PathExists(appcache_path));
// The appcache data for the protected origin is there, and the data for the
// unprotected origin was deleted.
AppCacheTestHelper appcache_helper;
std::set<GURL> origins;
appcache_helper.GetOriginsWithCaches(appcache_service, &origins);
EXPECT_EQ(1UL, origins.size());
EXPECT_TRUE(origins.find(kProtectedManifestURL.GetOrigin()) != origins.end());
EXPECT_TRUE(origins.find(kNormalManifestURL.GetOrigin()) == origins.end());
// Delete and let cleanup tasks run prior to returning.
appcache_service = NULL;
message_loop_.RunAllPending();
}
} // namespace appcache
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdlib.h>
#include "glog/logging.h"
using namespace std;
enum level
{
INFO=0,
WARINIG=1,
ERROR=2,
FATAL=3
};
void test_glog()
{
for(int i = 1; i < 101; i++)
{
//满足i==100才会打印
LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;
//每隔10次打印一次,对于刷屏的日志控制很好
LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;
//满足i > 50的条件后,每隔10次打印一次,对于刷屏的日志控制很好
LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;
//只打印前5次
LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;
//每次都打印
LOG(ERROR) << "TEST BY TOPSLUO" << endl;
}
}
int test_glog_main(int argc)
{
google::InitGoogleLogging("vsc2");
FLAGS_stderrthreshold=google::INFO;
FLAGS_colorlogtostderr=true;
google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
google::SetLogDestination(google::ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
google::SetLogDestination(google::WARNING,"./log/warning_");
google::SetLogDestination(google::INFO,"./log/info_");
FLAGS_logbufsecs = 0;//缓冲日志输出,默认为30秒,此处改为立刻
FLAGS_max_log_size = 100;//最大日志大小为100M
FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时,停止日志输出
google::SetLogFilenameExtension("91_");//设置文件名扩展,如平台,或者其它需要区分的信息
google::InstallFailureSignalHandler();//捕捉core dumped
//google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr
test_glog();
google::ShutdownGoogleLogging();//GLOG内存清理,一般与 google::InitGoogleLogging配对使用
return 0;
}
int main(int, char**) {
std::cout << "Hello, world!\n";
test_glog_main(0);
#if __LINUX__
char path[256];
sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
FILE* fp = fopen(path, "rb");
if (!fp)
return -1;
int max_freq_khz = -1;
int nscan = fscanf(fp, "%d", &max_freq_khz);
std::cout << "fscanf, world! " << nscan << std::endl;
sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
sprintf(path, "/home/sf/time_in_state.txt");
FILE* fp1 = fopen(path, "rb");
max_freq_khz = 0;
while (!feof(fp1))
{
int freq_khz = 0;
int nscan = fscanf(fp1, "%d %*d", &freq_khz);
std::cout << "fscanf, freq_khz! " << nscan << std::endl;
if (nscan != 1)
break;
if (freq_khz > max_freq_khz)
max_freq_khz = freq_khz;
}
#endif
std::cout << "fscanf end \n";
}
<commit_msg>PREF c++ vscode test error C2039: 'INFO': is not a member of 'google'<commit_after>#include <iostream>
#include <stdlib.h>
#include "glog/logging.h"
using namespace std;
enum level
{
INFO=0,
WARINIG=1,
ERROR=2,
FATAL=3
};
void test_glog()
{
for(int i = 1; i < 101; i++)
{
//满足i==100才会打印
LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;
//每隔10次打印一次,对于刷屏的日志控制很好
LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;
//满足i > 50的条件后,每隔10次打印一次,对于刷屏的日志控制很好
LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;
//只打印前5次
LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;
//每次都打印
LOG(ERROR) << "TEST BY TOPSLUO" << endl;
}
}
int test_glog_main(int argc)
{
google::InitGoogleLogging("vsc2");
FLAGS_stderrthreshold=INFO;
FLAGS_colorlogtostderr=true;
google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
google::SetLogDestination(ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
google::SetLogDestination(WARNING,"./log/warning_");
google::SetLogDestination(INFO,"./log/info_");
FLAGS_logbufsecs = 0;//缓冲日志输出,默认为30秒,此处改为立刻
FLAGS_max_log_size = 100;//最大日志大小为100M
FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时,停止日志输出
google::SetLogFilenameExtension("91_");//设置文件名扩展,如平台,或者其它需要区分的信息
google::InstallFailureSignalHandler();//捕捉core dumped
//google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr
test_glog();
google::ShutdownGoogleLogging();//GLOG内存清理,一般与 google::InitGoogleLogging配对使用
return 0;
}
int main(int, char**) {
std::cout << "Hello, world!\n";
test_glog_main(0);
#if __LINUX__
char path[256];
sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
FILE* fp = fopen(path, "rb");
if (!fp)
return -1;
int max_freq_khz = -1;
int nscan = fscanf(fp, "%d", &max_freq_khz);
std::cout << "fscanf, world! " << nscan << std::endl;
sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
sprintf(path, "/home/sf/time_in_state.txt");
FILE* fp1 = fopen(path, "rb");
max_freq_khz = 0;
while (!feof(fp1))
{
int freq_khz = 0;
int nscan = fscanf(fp1, "%d %*d", &freq_khz);
std::cout << "fscanf, freq_khz! " << nscan << std::endl;
if (nscan != 1)
break;
if (freq_khz > max_freq_khz)
max_freq_khz = freq_khz;
}
#endif
std::cout << "fscanf end \n";
}
<|endoftext|>
|
<commit_before>//
// generateSimulatedData.cpp
// cPWP
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed
So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/
std::ofstream bamsFile;
bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);
std::cout << "**********\nChecking if processor is available to run pirs...";
if (system(NULL)) puts ("OK");
else exit (EXIT_FAILURE);
int pirsInd = 0;
while(pirsInd < numIndividuals) {
double mutRate = pirsInd * mutationRateStepSize;
// Covert the mutation rate into a string for the system command
std::ostringstream mutStr;
mutStr << mutRate;
std::string mutRateString = mutStr.str();
std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";
// Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
std::ostringstream pirsIndSS;
std::ostringstream pirsIndNumSS;
pirsIndSS << "ind" + pirsInd;
pirsIndNumSS << pirsInd;
std::string pirsIndNum = pirsIndNumSS.str();
std::string indName = pirsIndSS.str();
std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
std::string pirsGenomeSTDERR = indName + "_genome.stderr";
// Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
if (system((pirsCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
}
// The following file is output by the pirs diploid command:
std::string mutatedChromosome = indName + ".snp.fa";
// After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
std::string pirsSimSTDOUT = indName + "_reads.stdout";
std::string pirsSimSTDERR = indName + "_reads.stderr";
std::string indReadsPrefix = indName + "_reads";
std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
if (system((pirsSimulateCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
}
// Generate the bwa mem command and then run it using a system call
std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
std::string bamOut = "ind" + pirsIndNum + ".bam";
std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
if (system((bwaCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
}
bamsFile << bamOut << std::endl;
pirsInd++; // Move on to the next individual
}
/* Implementation with wgsim
std::cout << "**********\nChecking if processor is available to run wgsim...";
if (system(NULL)) puts ("Ok");
else exit (EXIT_FAILURE);
int step = 0;
while(step <= numIndividuals) {
double mutRate = step * mutationRateStepSize;
// Covert the mutation rate into a string for the system command
std::ostringstream mutStrs;
mutStrs << mutRate;
std::string mutRateString = mutStrs.str();
std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";
// Get the number of the individual as a string
std::ostringstream stepString;
stepString << step;
std::string ind = stepString.str();
// Generate the output file names as strings
std::string R1out = "ind" + ind + "_R1.fastq";
std::string R2out = "ind" + ind + "_R2.fastq";
std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";
// Generate the wgsim command and then run it using a system call
std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize + " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
if (system((wgsimCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";
}
// Generate the bwa mem command and then run it using a system call
std::string bamOut = "ind" + ind + ".bam";
std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
if (system((bwaCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
}
bamsFile << bamOut << std::endl;
step++; // Move on to the next individual
}
*/
bamsFile.close();
return 0;
}
/*
/home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1
*/
/*
wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq
samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam
echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt
/home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &
*/
/*
Usage: wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>
Options:
-e FLOAT base error rate [0.000]
-d INT outer distance between the two ends [500]
-s INT standard deviation [50]
-N INT number of read pairs [1000000]
-1 INT length of the first read [70]
-2 INT length of the second read [70]
-r FLOAT rate of mutations [0.0010]
-R FLOAT fraction of indels [0.15]
-X FLOAT probability an indel is extended [0.30]
-S INT seed for random generator [-1]
-h haplotype mode
*/
<commit_msg>minor changes<commit_after>//
// generateSimulatedData.cpp
// cPWP
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#include "generateSimulatedData.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {
/*// supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed
So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).
*/
std::ofstream bamsFile;
bamsFile.open("bamlist.txt", std::ios::out | std::ios::app);
std::cout << "**********\nChecking if processor is available to run pirs...";
if (system(NULL)) puts ("OK");
else exit (EXIT_FAILURE);
int pirsInd = 0;
while(pirsInd < numIndividuals) {
double mutRate = pirsInd * mutationRateStepSize;
// Covert the mutation rate into a string for the system command
std::ostringstream mutStr;
mutStr << mutRate;
std::string mutRateString = mutStr.str();
std::cout << "**********\nGenerating reference genome for individual " << pirsInd << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";
// Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names
std::ostringstream pirsIndSS;
std::ostringstream pirsIndNumSS;
pirsIndSS << "ind" << pirsInd;
pirsIndNumSS << pirsInd;
std::string pirsIndNum = pirsIndNumSS.str();
std::string indName = pirsIndSS.str();
std::string pirsGenomeSTDOUT = indName + "_genome.stdout";
std::string pirsGenomeSTDERR = indName + "_genome.stderr";
// Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize
std::string pirsCommandToRun = "pirs diploid -s " + mutRateString + " -d 0.00 -v 0.00 -S 1234 -o " + indName + " " + reference + " >" + pirsGenomeSTDOUT + " 2>" + pirsGenomeSTDERR;
if (system((pirsCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << pirsCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << pirsCommandToRun << "\n**********\n";
}
// The following file is output by the pirs diploid command:
std::string mutatedChromosome = indName + ".snp.fa";
// After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the
std::string pirsSimSTDOUT = indName + "_reads.stdout";
std::string pirsSimSTDERR = indName + "_reads.stderr";
std::string indReadsPrefix = indName + "_reads";
std::string pirsSimulateCommandToRun = "pirs simulate --diploid " + reference + " " + mutatedChromosome + " -l " + readLengths + " -x " + depth + " -m " + libFragmentSize + " -v " + stdevLibFragmentSize + " --no-substitution-errors --no-indel-errors --no-gc-content-bias -o " + indReadsPrefix + " >" + pirsSimSTDOUT + " 2>" + pirsSimSTDERR;
if (system((pirsSimulateCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << pirsSimulateCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << pirsSimulateCommandToRun << "\n**********\n";
}
// Generate the bwa mem command and then run it using a system call
std::string R1 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_1.fq";
std::string R2 = indReadsPrefix + "_" + readLengths + "_" + libFragmentSize + "_2.fq";
std::string bamOut = "ind" + pirsIndNum + ".bam";
std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1 + " " + R2 + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
if (system((bwaCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
}
bamsFile << bamOut << std::endl;
pirsInd++; // Move on to the next individual
}
/* Implementation with wgsim
std::cout << "**********\nChecking if processor is available to run wgsim...";
if (system(NULL)) puts ("Ok");
else exit (EXIT_FAILURE);
int step = 0;
while(step <= numIndividuals) {
double mutRate = step * mutationRateStepSize;
// Covert the mutation rate into a string for the system command
std::ostringstream mutStrs;
mutStrs << mutRate;
std::string mutRateString = mutStrs.str();
std::cout << "**********\nGenerating sequence reads for individual " << step << " using a mutation rate of " << mutRateString << " from the reference genome\n**********\n";
// Get the number of the individual as a string
std::ostringstream stepString;
stepString << step;
std::string ind = stepString.str();
// Generate the output file names as strings
std::string R1out = "ind" + ind + "_R1.fastq";
std::string R2out = "ind" + ind + "_R2.fastq";
std::string polymorphismFile = "ind" + ind + "_polymorphisms.txt";
// Generate the wgsim command and then run it using a system call
std::string wgsimCommandToRun = "wgsim -N " + numReadPairs + " -r " + mutRateString + " -R 0.00 -X 0.00 -d " + libFragmentSize + " -s " + stdevLibFragmentSize + " -1 " + readLengths + " -2 " + readLengths + " -S " + randomSeed + " -e0 " + reference + " " + R1out + " " + R2out + " > " + polymorphismFile; // No indels, no probability of indel extension, no base call error rates
if (system((wgsimCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << wgsimCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << wgsimCommandToRun << "\n**********\n";
}
// Generate the bwa mem command and then run it using a system call
std::string bamOut = "ind" + ind + ".bam";
std::string bwaCommandToRun = "bwa mem -t " + threads + " " + reference + " " + R1out + " " + R2out + " | samtools view -bS - | samtools sort -T temp -o " + bamOut + " -";
if (system((bwaCommandToRun).c_str()) != 0) {
std::cout << "**********\nFailure running the following command: " << bwaCommandToRun << "\n**********\n";
exit(EXIT_FAILURE);
} else {
std::cout << "**********\nExecuted the following command: " << bwaCommandToRun << "\n**********\n";
}
bamsFile << bamOut << std::endl;
step++; // Move on to the next individual
}
*/
bamsFile.close();
return 0;
}
/*
/home/evan/bin/angsd0.613/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1
*/
/*
wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt
wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq
bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq
samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam
samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam
echo -e "1XcoverageNoErrNoMutSorted.bam\n1XcoverageNoErr1PercentDivergentSorted.bam" > bamlist2sim.txt
/home/evan/bin/angsd0.613/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &
*/
/*
Usage: wgsim [options] <in.ref.fa> <out.read1.fq> <out.read2.fq>
Options:
-e FLOAT base error rate [0.000]
-d INT outer distance between the two ends [500]
-s INT standard deviation [50]
-N INT number of read pairs [1000000]
-1 INT length of the first read [70]
-2 INT length of the second read [70]
-r FLOAT rate of mutations [0.0010]
-R FLOAT fraction of indels [0.15]
-X FLOAT probability an indel is extended [0.30]
-S INT seed for random generator [-1]
-h haplotype mode
*/
<|endoftext|>
|
<commit_before>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
using namespace std;
int main ()
{
cout << "BBN X6-1000 Test Executable" << endl;
set_malibu_threading_enable(false);
int numDevices;
numDevices = get_numDevices();
cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "current logic temperature = " << get_logic_temperature(0) << endl;
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
cout << "enable ramp output" << endl;
enable_test_generator(0,0,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "enable sine wave output" << endl;
disable_test_generator(0);
enable_test_generator(0,1,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "disabling channel" << endl;
disable_test_generator(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
return 0;
}<commit_msg>First output through X6_1000 class<commit_after>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
using namespace std;
int main ()
{
cout << "BBN X6-1000 Test Executable" << endl;
set_malibu_threading_enable(false);
set_logging_level(5);
int numDevices;
numDevices = get_numDevices();
cout << numDevices << " X6 device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "current logic temperature = " << get_logic_temperature(0) << endl;
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
cout << "enable ramp output" << endl;
enable_test_generator(0,0,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "enable sine wave output" << endl;
disable_test_generator(0);
enable_test_generator(0,1,0.001);
std::this_thread::sleep_for(std::chrono::seconds(5));
cout << "disabling channel" << endl;
disable_test_generator(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
return 0;
}<|endoftext|>
|
<commit_before>#include "MacroAIModule.h"
#include <BasicTaskExecutor.h>
#include <SpiralBuildingPlacer.h>
#include <BFSBuildingPlacer.h>
#include <UnitPump.h>
#include <TerminateIfWorkerLost.h>
#include <TerminateIfEmpty.h>
#include <BasicWorkerFinder.h>
#include <UnitCompositionProducer.h>
#include <MacroManager.h>
#include <ResourceRates.h>
#include <MacroSupplyManager.h>
#include <MacroDependencyResolver.h>
using namespace BWAPI;
int drag_index = -1;
bool lastMouseClick = false;
UnitCompositionProducer* infantryProducer = NULL;
UnitCompositionProducer* vehicleProducer = NULL;
MacroAIModule::MacroAIModule()
{
}
MacroAIModule::~MacroAIModule()
{
if (TheMacroManager != NULL)
delete TheMacroManager;
if (TheMacroSupplyManager != NULL)
delete TheMacroSupplyManager;
if (TheMacroDependencyResolver != NULL)
delete TheMacroDependencyResolver;
if (TheResourceRates != NULL)
delete TheResourceRates;
if (infantryProducer != NULL)
delete infantryProducer;
if (vehicleProducer != NULL)
delete vehicleProducer;
}
void MacroAIModule::onStart()
{
Broodwar->enableFlag(Flag::UserInput);
MacroManager::create(&arbitrator);
MacroSupplyManager::create();
MacroDependencyResolver::create();
ResourceRates::create();
TaskStream* ts = new TaskStream();
TheMacroManager->taskStreams.push_back(ts);
Unit* worker = NULL;
for each(Unit* u in Broodwar->self()->getUnits())
{
if (u->getType()==UnitTypes::Terran_Command_Center)
worker = u;
}
ts->setWorker(worker);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new UnitPump(UnitTypes::Terran_SCV),true);
ts->attach(new TerminateIfWorkerLost(),true);
infantryProducer = new UnitCompositionProducer(UnitTypes::Terran_Barracks);
infantryProducer->setUnitWeight(UnitTypes::Terran_Marine,2.0);
infantryProducer->setUnitWeight(UnitTypes::Terran_Medic,1.0);
infantryProducer->setUnitWeight(UnitTypes::Terran_Firebat,0.5);
vehicleProducer = new UnitCompositionProducer(UnitTypes::Terran_Factory);
vehicleProducer->setUnitWeight(UnitTypes::Terran_Vulture,2.0);
vehicleProducer->setUnitWeight(UnitTypes::Terran_Siege_Tank_Tank_Mode,1.0);
}
void MacroAIModule::onEnd(bool isWinner)
{
}
void MacroAIModule::onFrame()
{
TheArbitrator->update();
infantryProducer->update();
vehicleProducer->update();
TheMacroSupplyManager->update();
TheMacroDependencyResolver->update();
TheMacroManager->update();
TheResourceRates->update();
std::set<Unit*> units=Broodwar->self()->getUnits();
for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++)
{
if (this->arbitrator.hasBid(*i))
{
int x=(*i)->getPosition().x();
int y=(*i)->getPosition().y();
std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i);
int y_off=0;
bool first = false;
const char activeColor = '\x07', inactiveColor = '\x16';
char color = activeColor;
for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++)
{
Broodwar->drawTextMap(x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second);
y_off+=15;
color = inactiveColor;
}
}
}
if (drag_index<0)
{
if (Broodwar->getMouseState(M_LEFT) && !lastMouseClick)
{
drag_index = (Broodwar->getMouseY()-25)/20;
if (drag_index<0) drag_index = 0;
}
if (drag_index>=(int)TheMacroManager->taskStreams.size())
drag_index=-1;
}
if (drag_index>=0)
{
int land_index = (Broodwar->getMouseY()-30)/20;
if (land_index<0) land_index = 0;
if (land_index>=(int)TheMacroManager->taskStreams.size())
land_index=(int)TheMacroManager->taskStreams.size()-1;
if (land_index!=drag_index)
{
std::list<TaskStream*>::iterator td=TheMacroManager->taskStreams.end();
std::list<TaskStream*>::iterator tl=TheMacroManager->taskStreams.end();
TaskStream* tm=NULL;
int j=0;
for(std::list<TaskStream*>::iterator i=TheMacroManager->taskStreams.begin();i!=TheMacroManager->taskStreams.end();i++)
{
if (j==drag_index)
td=i;
if (j==land_index)
tl=i;
j++;
}
if (td!=TheMacroManager->taskStreams.end() && tl!=TheMacroManager->taskStreams.end())
{
tm=*td;
*td=*tl;
*tl=tm;
}
drag_index = land_index;
}
if (!Broodwar->getMouseState(M_LEFT) && lastMouseClick)
{
drag_index=-1;
}
}
lastMouseClick = Broodwar->getMouseState(M_LEFT);
}
void MacroAIModule::onSendText(std::string text)
{
Broodwar->sendText(text.c_str());
if (text=="hide")
{
TheMacroManager->taskstream_list_visible = false;
}
if (text=="show")
{
TheMacroManager->taskstream_list_visible = true;
}
UnitType type=UnitTypes::getUnitType(text);
if (type!=UnitTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
{
TechType type=TechTypes::getTechType(text);
if (type!=TechTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
{
UpgradeType type=UpgradeTypes::getUpgradeType(text);
if (type!=UpgradeTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
Broodwar->printf("You typed '%s'!",text.c_str());
}
}
}
void MacroAIModule::onUnitDestroy(BWAPI::Unit* unit)
{
TheArbitrator->onRemoveObject(unit);
}
<commit_msg>A few initial changes to start working on protoss support for the macro manager, however I have yet to implement the main changes that will be needed:<commit_after>#include "MacroAIModule.h"
#include <BasicTaskExecutor.h>
#include <SpiralBuildingPlacer.h>
#include <BFSBuildingPlacer.h>
#include <UnitPump.h>
#include <TerminateIfWorkerLost.h>
#include <TerminateIfEmpty.h>
#include <BasicWorkerFinder.h>
#include <UnitCompositionProducer.h>
#include <MacroManager.h>
#include <ResourceRates.h>
#include <MacroSupplyManager.h>
#include <MacroDependencyResolver.h>
using namespace BWAPI;
int drag_index = -1;
bool lastMouseClick = false;
UnitCompositionProducer* infantryProducer = NULL;
UnitCompositionProducer* vehicleProducer = NULL;
MacroAIModule::MacroAIModule()
{
}
MacroAIModule::~MacroAIModule()
{
if (TheMacroManager != NULL)
delete TheMacroManager;
if (TheMacroSupplyManager != NULL)
delete TheMacroSupplyManager;
if (TheMacroDependencyResolver != NULL)
delete TheMacroDependencyResolver;
if (TheResourceRates != NULL)
delete TheResourceRates;
if (infantryProducer != NULL)
delete infantryProducer;
if (vehicleProducer != NULL)
delete vehicleProducer;
}
void MacroAIModule::onStart()
{
Broodwar->enableFlag(Flag::UserInput);
MacroManager::create(&arbitrator);
MacroSupplyManager::create();
MacroDependencyResolver::create();
ResourceRates::create();
TaskStream* ts = new TaskStream();
TheMacroManager->taskStreams.push_back(ts);
Unit* worker = NULL;
for each(Unit* u in Broodwar->self()->getUnits())
{
if (u->getType().isResourceDepot())
worker = u;
}
ts->setWorker(worker);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new UnitPump(Broodwar->self()->getRace().getWorker()),true);
ts->attach(new TerminateIfWorkerLost(),true);
if (Broodwar->self()->getRace()==Races::Terran)
{
infantryProducer = new UnitCompositionProducer(UnitTypes::Terran_Barracks);
infantryProducer->setUnitWeight(UnitTypes::Terran_Marine,2.0);
infantryProducer->setUnitWeight(UnitTypes::Terran_Medic,1.0);
infantryProducer->setUnitWeight(UnitTypes::Terran_Firebat,0.5);
vehicleProducer = new UnitCompositionProducer(UnitTypes::Terran_Factory);
vehicleProducer->setUnitWeight(UnitTypes::Terran_Vulture,2.0);
vehicleProducer->setUnitWeight(UnitTypes::Terran_Siege_Tank_Tank_Mode,1.0);
}
if (Broodwar->self()->getRace()==Races::Protoss)
{
infantryProducer = new UnitCompositionProducer(UnitTypes::Protoss_Gateway);
infantryProducer->setUnitWeight(UnitTypes::Protoss_Dragoon,2.0);
infantryProducer->setUnitWeight(UnitTypes::Protoss_Zealot,1.0);
}
}
void MacroAIModule::onEnd(bool isWinner)
{
}
void MacroAIModule::onFrame()
{
TheArbitrator->update();
if (infantryProducer)
infantryProducer->update();
if (vehicleProducer)
vehicleProducer->update();
TheMacroSupplyManager->update();
TheMacroDependencyResolver->update();
TheMacroManager->update();
TheResourceRates->update();
std::set<Unit*> units=Broodwar->self()->getUnits();
for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++)
{
if (this->arbitrator.hasBid(*i))
{
int x=(*i)->getPosition().x();
int y=(*i)->getPosition().y();
std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i);
int y_off=0;
bool first = false;
const char activeColor = '\x07', inactiveColor = '\x16';
char color = activeColor;
for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++)
{
Broodwar->drawTextMap(x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second);
y_off+=15;
color = inactiveColor;
}
}
}
if (drag_index<0)
{
if (Broodwar->getMouseState(M_LEFT) && !lastMouseClick)
{
drag_index = (Broodwar->getMouseY()-25)/20;
if (drag_index<0) drag_index = 0;
}
if (drag_index>=(int)TheMacroManager->taskStreams.size())
drag_index=-1;
}
if (drag_index>=0)
{
int land_index = (Broodwar->getMouseY()-30)/20;
if (land_index<0) land_index = 0;
if (land_index>=(int)TheMacroManager->taskStreams.size())
land_index=(int)TheMacroManager->taskStreams.size()-1;
if (land_index!=drag_index)
{
std::list<TaskStream*>::iterator td=TheMacroManager->taskStreams.end();
std::list<TaskStream*>::iterator tl=TheMacroManager->taskStreams.end();
TaskStream* tm=NULL;
int j=0;
for(std::list<TaskStream*>::iterator i=TheMacroManager->taskStreams.begin();i!=TheMacroManager->taskStreams.end();i++)
{
if (j==drag_index)
td=i;
if (j==land_index)
tl=i;
j++;
}
if (td!=TheMacroManager->taskStreams.end() && tl!=TheMacroManager->taskStreams.end())
{
tm=*td;
*td=*tl;
*tl=tm;
}
drag_index = land_index;
}
if (!Broodwar->getMouseState(M_LEFT) && lastMouseClick)
{
drag_index=-1;
}
}
lastMouseClick = Broodwar->getMouseState(M_LEFT);
}
void MacroAIModule::onSendText(std::string text)
{
Broodwar->sendText(text.c_str());
if (text=="hide")
{
TheMacroManager->taskstream_list_visible = false;
}
if (text=="show")
{
TheMacroManager->taskstream_list_visible = true;
}
UnitType type=UnitTypes::getUnitType(text);
if (type!=UnitTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
{
TechType type=TechTypes::getTechType(text);
if (type!=TechTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
{
UpgradeType type=UpgradeTypes::getUpgradeType(text);
if (type!=UpgradeTypes::Unknown)
{
TaskStream* ts = new TaskStream(Task(type));
TheMacroManager->taskStreams.push_back(ts);
ts->attach(new BasicWorkerFinder(),true);
ts->attach(BasicTaskExecutor::getInstance(),false);
ts->attach(new TerminateIfEmpty(),true);
ts->attach(BFSBuildingPlacer::getInstance(),false);
}
else
Broodwar->printf("You typed '%s'!",text.c_str());
}
}
}
void MacroAIModule::onUnitDestroy(BWAPI::Unit* unit)
{
TheArbitrator->onRemoveObject(unit);
}
<|endoftext|>
|
<commit_before>//
// DiskII.cpp
// Clock Signal
//
// Created by Thomas Harte on 23/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "DiskIICard.hpp"
using namespace AppleII;
DiskIICard::DiskIICard(const ROMMachine::ROMFetcher &rom_fetcher, bool is_16_sector) {
auto roms = rom_fetcher(
"DiskII",
{
"boot.rom",
"state-machine.rom"
});
boot_ = std::move(*roms[0]);
diskii_.set_state_machine(*roms[1]);
}
void DiskIICard::perform_bus_operation(CPU::MOS6502::BusOperation operation, uint16_t address, uint8_t *value) {
if(isReadOperation(operation) && address < 0x100) {
*value &= boot_[address];
} else {
using Control = Apple::DiskII::Control;
using Mode = Apple::DiskII::Mode;
switch(address & 0xf) {
case 0x0: diskii_.set_control(Control::P0, false); break;
case 0x1: diskii_.set_control(Control::P0, true); break;
case 0x2: diskii_.set_control(Control::P1, false); break;
case 0x3: diskii_.set_control(Control::P1, true); break;
case 0x4: diskii_.set_control(Control::P2, false); break;
case 0x5: diskii_.set_control(Control::P2, true); break;
case 0x6: diskii_.set_control(Control::P3, false); break;
case 0x7: diskii_.set_control(Control::P3, true); break;
case 0x8: diskii_.set_control(Control::Motor, false); break;
case 0x9: diskii_.set_control(Control::Motor, true); break;
case 0xa: diskii_.select_drive(0); break;
case 0xb: diskii_.select_drive(1); break;
case 0xc: {
/* shift register? */
const uint8_t shift_value = diskii_.get_shift_register();
if(isReadOperation(operation))
*value = shift_value;
} break;
case 0xd:
/* data register? */
diskii_.set_data_register(*value);
break;
case 0xe: diskii_.set_mode(Mode::Read); break;
case 0xf: diskii_.set_mode(Mode::Write); break;
}
}
}
void DiskIICard::run_for(Cycles cycles, int stretches) {
diskii_.run_for(Cycles(cycles.as_int() * 2));
}
void DiskIICard::set_disk(const std::shared_ptr<Storage::Disk::Disk> &disk, int drive) {
diskii_.set_disk(disk, drive);
}
<commit_msg>Ensures the contextually-proper boot and state machine ROMs are requested.<commit_after>//
// DiskII.cpp
// Clock Signal
//
// Created by Thomas Harte on 23/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "DiskIICard.hpp"
using namespace AppleII;
DiskIICard::DiskIICard(const ROMMachine::ROMFetcher &rom_fetcher, bool is_16_sector) {
auto roms = rom_fetcher(
"DiskII",
{
is_16_sector ? "boot-16.rom" : "boot-13.rom",
is_16_sector ? "state-machine-16.rom" : "state-machine-13.rom"
});
boot_ = std::move(*roms[0]);
diskii_.set_state_machine(*roms[1]);
}
void DiskIICard::perform_bus_operation(CPU::MOS6502::BusOperation operation, uint16_t address, uint8_t *value) {
if(isReadOperation(operation) && address < 0x100) {
*value &= boot_[address];
} else {
using Control = Apple::DiskII::Control;
using Mode = Apple::DiskII::Mode;
switch(address & 0xf) {
case 0x0: diskii_.set_control(Control::P0, false); break;
case 0x1: diskii_.set_control(Control::P0, true); break;
case 0x2: diskii_.set_control(Control::P1, false); break;
case 0x3: diskii_.set_control(Control::P1, true); break;
case 0x4: diskii_.set_control(Control::P2, false); break;
case 0x5: diskii_.set_control(Control::P2, true); break;
case 0x6: diskii_.set_control(Control::P3, false); break;
case 0x7: diskii_.set_control(Control::P3, true); break;
case 0x8: diskii_.set_control(Control::Motor, false); break;
case 0x9: diskii_.set_control(Control::Motor, true); break;
case 0xa: diskii_.select_drive(0); break;
case 0xb: diskii_.select_drive(1); break;
case 0xc: {
/* shift register? */
const uint8_t shift_value = diskii_.get_shift_register();
if(isReadOperation(operation))
*value = shift_value;
} break;
case 0xd:
/* data register? */
diskii_.set_data_register(*value);
break;
case 0xe: diskii_.set_mode(Mode::Read); break;
case 0xf: diskii_.set_mode(Mode::Write); break;
}
}
}
void DiskIICard::run_for(Cycles cycles, int stretches) {
diskii_.run_for(Cycles(cycles.as_int() * 2));
}
void DiskIICard::set_disk(const std::shared_ptr<Storage::Disk::Disk> &disk, int drive) {
diskii_.set_disk(disk, drive);
}
<|endoftext|>
|
<commit_before>#pragma once
#include "stdafx.h"
#define SafeDelete(x) {if((x) != nullptr) { delete (x); } x = nullptr; }
#define SafeDeleteArray(x) {if((x) != nullptr) { delete[] (x); } x = nullptr; }
namespace MCL
{
namespace Util
{
static std::string ReadWholeFile(const std::string& path)
{
std::ifstream in(path);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
static std::wstring StrToWStr(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
static std::string WStrToStr(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
}
namespace ClUtil
{
static const char* MapErrorToString(cl_int error)
{
static const char* errorString[] = {
"CL_SUCCESS",
"CL_DEVICE_NOT_FOUND",
"CL_DEVICE_NOT_AVAILABLE",
"CL_COMPILER_NOT_AVAILABLE",
"CL_MEM_OBJECT_ALLOCATION_FAILURE",
"CL_OUT_OF_RESOURCES",
"CL_OUT_OF_HOST_MEMORY",
"CL_PROFILING_INFO_NOT_AVAILABLE",
"CL_MEM_COPY_OVERLAP",
"CL_IMAGE_FORMAT_MISMATCH",
"CL_IMAGE_FORMAT_NOT_SUPPORTED",
"CL_BUILD_PROGRAM_FAILURE",
"CL_MAP_FAILURE",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"CL_INVALID_VALUE",
"CL_INVALID_DEVICE_TYPE",
"CL_INVALID_PLATFORM",
"CL_INVALID_DEVICE",
"CL_INVALID_CONTEXT",
"CL_INVALID_QUEUE_PROPERTIES",
"CL_INVALID_COMMAND_QUEUE",
"CL_INVALID_HOST_PTR",
"CL_INVALID_MEM_OBJECT - EX: WRONG R/W RIGHTS? WRONG STORAGE CLASS? WRONG ARG INDEX?",
"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",
"CL_INVALID_IMAGE_SIZE",
"CL_INVALID_SAMPLER",
"CL_INVALID_BINARY",
"CL_INVALID_BUILD_OPTIONS",
"CL_INVALID_PROGRAM",
"CL_INVALID_PROGRAM_EXECUTABLE",
"CL_INVALID_KERNEL_NAME",
"CL_INVALID_KERNEL_DEFINITION",
"CL_INVALID_KERNEL",
"CL_INVALID_ARG_INDEX",
"CL_INVALID_ARG_VALUE",
"CL_INVALID_ARG_SIZE",
"CL_INVALID_KERNEL_ARGS",
"CL_INVALID_WORK_DIMENSION",
"CL_INVALID_WORK_GROUP_SIZE",
"CL_INVALID_WORK_ITEM_SIZE",
"CL_INVALID_GLOBAL_OFFSET",
"CL_INVALID_EVENT_WAIT_LIST",
"CL_INVALID_EVENT",
"CL_INVALID_OPERATION",
"CL_INVALID_GL_OBJECT",
"CL_INVALID_BUFFER_SIZE",
"CL_INVALID_MIP_LEVEL",
"CL_INVALID_GLOBAL_WORK_SIZE",
};
const int errorCount = sizeof(errorString) / sizeof(errorString[0]);
const int index = -error;
return (index >= 0 && index < errorCount) ? errorString[index] : "";
}
static bool ResCheck(const cl_int val)
{
if (val != CL_SUCCESS)
{
std::string s;
s.append("\OpenCL Error -> ");
s.append(MapErrorToString(val));
s.append("\n\n");
std::wcout << s.c_str();
return true;
}
return false;
}
static size_t RoundUpToWGSize(int value, int wgSize)
{
int remaining = value % wgSize;
return value + (remaining == 0 ? 0 : (wgSize - remaining));
}
}
}<commit_msg>Update MCL_Utility.hpp<commit_after>#pragma once
#include "stdafx.h"
#define SafeDelete(x) {if((x) != nullptr) { delete (x); } x = nullptr; }
#define SafeDeleteArray(x) {if((x) != nullptr) { delete[] (x); } x = nullptr; }
namespace MUtil
{
namespace Gen
{
static std::string ReadWholeFile(const std::string& path)
{
std::ifstream in(path);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
static std::wstring StrToWStr(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
static std::string WStrToStr(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
}
namespace CL
{
static unsigned int INVALID_OBJECT = 0xFFFFFFFF;
static const wcahr_t* INVALID_NAME = L"[INVALID]";
static const char* MapErrorToString(cl_int error)
{
static const char* errorString[] = {
"CL_SUCCESS",
"CL_DEVICE_NOT_FOUND",
"CL_DEVICE_NOT_AVAILABLE",
"CL_COMPILER_NOT_AVAILABLE",
"CL_MEM_OBJECT_ALLOCATION_FAILURE",
"CL_OUT_OF_RESOURCES",
"CL_OUT_OF_HOST_MEMORY",
"CL_PROFILING_INFO_NOT_AVAILABLE",
"CL_MEM_COPY_OVERLAP",
"CL_IMAGE_FORMAT_MISMATCH",
"CL_IMAGE_FORMAT_NOT_SUPPORTED",
"CL_BUILD_PROGRAM_FAILURE",
"CL_MAP_FAILURE",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"CL_INVALID_VALUE",
"CL_INVALID_DEVICE_TYPE",
"CL_INVALID_PLATFORM",
"CL_INVALID_DEVICE",
"CL_INVALID_CONTEXT",
"CL_INVALID_QUEUE_PROPERTIES",
"CL_INVALID_COMMAND_QUEUE",
"CL_INVALID_HOST_PTR",
"CL_INVALID_MEM_OBJECT - EX: WRONG R/W RIGHTS? WRONG STORAGE CLASS? WRONG ARG INDEX?",
"CL_INVALID_IMAGE_FORMAT_DESCRIPTOR",
"CL_INVALID_IMAGE_SIZE",
"CL_INVALID_SAMPLER",
"CL_INVALID_BINARY",
"CL_INVALID_BUILD_OPTIONS",
"CL_INVALID_PROGRAM",
"CL_INVALID_PROGRAM_EXECUTABLE",
"CL_INVALID_KERNEL_NAME",
"CL_INVALID_KERNEL_DEFINITION",
"CL_INVALID_KERNEL",
"CL_INVALID_ARG_INDEX",
"CL_INVALID_ARG_VALUE",
"CL_INVALID_ARG_SIZE",
"CL_INVALID_KERNEL_ARGS",
"CL_INVALID_WORK_DIMENSION",
"CL_INVALID_WORK_GROUP_SIZE",
"CL_INVALID_WORK_ITEM_SIZE",
"CL_INVALID_GLOBAL_OFFSET",
"CL_INVALID_EVENT_WAIT_LIST",
"CL_INVALID_EVENT",
"CL_INVALID_OPERATION",
"CL_INVALID_GL_OBJECT",
"CL_INVALID_BUFFER_SIZE",
"CL_INVALID_MIP_LEVEL",
"CL_INVALID_GLOBAL_WORK_SIZE",
};
const int errorCount = sizeof(errorString) / sizeof(errorString[0]);
const int index = -error;
return (index >= 0 && index < errorCount) ? errorString[index] : "";
}
static bool ResultCheck(const cl_int val)
{
if (val != CL_SUCCESS)
{
std::string s;
s.append("\OpenCL Error -> ");
s.append(MapErrorToString(val));
s.append("\n\n");
std::wcout << s.c_str();
return true;
}
return false;
}
static size_t RoundUpToWGSize(int value, int wgSize)
{
int remaining = value % wgSize;
return value + (remaining == 0 ? 0 : (wgSize - remaining));
}
class CLImage2D
{
private:
cl_mem mMemObject; // OpenCL image memory object
std::wstring mName; // Readable name of the image object
cl_image_format mFormat; // OpenCL image format
cl_image_desc mDescr; // OpenCL image descriptor
public:
// Initializes the object with invalid values
CLImage2D()
: mMemObject(INVALID_OBJECT),
mName(INVALID_NAME)
{
}
// Creates the OpenCL image object and initializes internal variables. Throws and exception if failed.
void Initialize(cl_context clContext, const std::wstring& name, size_t w, size_t h, size_t rowPitch, cl_channel_order channelOrder, cl_channel_type channelType)
{
mName = name;
mFormat.image_channel_order = channelOrder;
mFormat.image_channel_data_type = channelType;
// Fill descriptor here
// Create object here
}
// Returns true if teh object is alread created and returns false if it is not initialized yet.
bool IsValid() const
{
return mMemObject == INVALID_OBJECT ? false : true;
}
// Returns the internal cl_mem object
cl_mem getMemObject() const
{
return mMemObject;
}
// Returns the name of the image object
std::wstring getName() const
{
return mName;
}
// Returns the format of the image
cl_image_format getFormat() const
{
return mFormat;
}
// Returns the description of the image
cl_image_desc getDescription() const
{
return mDescr;
}
}
}
}
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: CEGUIGeometryBuffer.cpp
created: Wed Jan 13 2010
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include <vector>
// Start of CEGUI namespace section
namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial) :
d_blendMode(BM_NORMAL)
, d_renderMaterial(renderMaterial)
{
}
//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
d_blendMode = mode;
}
//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
return d_blendMode;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
if(coloured_vertices.empty())
return;
appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const ColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
if(textured_vertices.empty())
return;
appendGeometry(&textured_vertices[0], textured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const TexturedColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
vertexData.push_back(vs->d_texCoords.x);
vertexData.push_back(vs->d_texCoords.y);
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
uint array_size)
{
std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
appendGeometry(vectorVertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[9];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
vertexData[7] = vertex.d_texCoords.x;
vertexData[8] = vertex.d_texCoords.y;
appendGeometry(vertexData, 9);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[7];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
appendGeometry(vertexData, 7);
}
//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
int count = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
count += 3;
break;
case VAT_COLOUR0:
count += 4;
break;
case VAT_TEXCOORD0:
count += 2;
break;
default:
break;
}
}
return count;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
d_vertexAttributes.clear();
}
//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
d_vertexAttributes.push_back(attribute);
}
//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
return d_renderMaterial;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
d_renderMaterial = render_material;
}
//---------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: format<commit_after>/***********************************************************************
filename: CEGUIGeometryBuffer.cpp
created: Wed Jan 13 2010
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/Vertex.h"
#include <vector>
namespace CEGUI
{
//---------------------------------------------------------------------------//
GeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)
: d_blendMode(BM_NORMAL)
, d_renderMaterial(renderMaterial)
, d_polygonFillRule(PFR_NONE)
{
}
//---------------------------------------------------------------------------//
GeometryBuffer::~GeometryBuffer()
{
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setBlendMode(const BlendMode mode)
{
d_blendMode = mode;
}
//---------------------------------------------------------------------------//
BlendMode GeometryBuffer::getBlendMode() const
{
return d_blendMode;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)
{
if(coloured_vertices.empty())
return;
appendGeometry(&coloured_vertices[0], coloured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const ColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)
{
if(textured_vertices.empty())
return;
appendGeometry(&textured_vertices[0], textured_vertices.size());
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,
uint vertex_count)
{
// Add the vertex data in their default order into an array
std::vector<float> vertexData;
const TexturedColouredVertex* vs = vertex_array;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// Add all the elements in the default order for textured and coloured
// geometry into the vector
vertexData.push_back(vs->d_position.x);
vertexData.push_back(vs->d_position.y);
vertexData.push_back(vs->d_position.z);
vertexData.push_back(vs->d_colour.getRed());
vertexData.push_back(vs->d_colour.getGreen());
vertexData.push_back(vs->d_colour.getBlue());
vertexData.push_back(vs->d_colour.getAlpha());
vertexData.push_back(vs->d_texCoords.x);
vertexData.push_back(vs->d_texCoords.y);
}
// Append the prepared geometry data
appendGeometry(vertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendGeometry(const float* const vertex_data,
uint array_size)
{
std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);
appendGeometry(vectorVertexData);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[9];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
vertexData[7] = vertex.d_texCoords.x;
vertexData[8] = vertex.d_texCoords.y;
appendGeometry(vertexData, 9);
}
//---------------------------------------------------------------------------//
void GeometryBuffer::appendVertex(const ColouredVertex& vertex)
{
// Add the vertex data in their default order into an array
float vertexData[7];
// Copy the vertex attributes into the array
vertexData[0] = vertex.d_position.x;
vertexData[1] = vertex.d_position.y;
vertexData[2] = vertex.d_position.z;
vertexData[3] = vertex.d_colour.getRed();
vertexData[4] = vertex.d_colour.getGreen();
vertexData[5] = vertex.d_colour.getBlue();
vertexData[6] = vertex.d_colour.getAlpha();
appendGeometry(vertexData, 7);
}
//---------------------------------------------------------------------------//
int GeometryBuffer::getVertexAttributeElementCount() const
{
int count = 0;
const unsigned int attribute_count = d_vertexAttributes.size();
for (unsigned int i = 0; i < attribute_count; ++i)
{
switch(d_vertexAttributes.at(i))
{
case VAT_POSITION0:
count += 3;
break;
case VAT_COLOUR0:
count += 4;
break;
case VAT_TEXCOORD0:
count += 2;
break;
default:
break;
}
}
return count;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::resetVertexAttributes()
{
d_vertexAttributes.clear();
}
//---------------------------------------------------------------------------//
void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)
{
d_vertexAttributes.push_back(attribute);
}
//---------------------------------------------------------------------------//
RefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const
{
return d_renderMaterial;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)
{
d_renderMaterial = render_material;
}
//---------------------------------------------------------------------------//
void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)
{
d_polygonFillRule = fill_rule;
}
//---------------------------------------------------------------------------//
}
<|endoftext|>
|
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>
// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>
namespace Dune
{
namespace Detailed {
namespace Discretizations
{
namespace DiscreteFunctionSpace
{
namespace Continuous
{
template< class FunctionSpaceImp, class GridPartImp, int polOrder >
class Lagrange
{
public:
typedef FunctionSpaceImp
FunctionSpaceType;
typedef GridPartImp
GridPartType;
typedef Dune::GridPartView< GridPartType > GridViewType;
enum{ polynomialOrder = polOrder };
typedef Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
ThisType;
typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
MapperType;
typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange< ThisType >
BaseFunctionSetType;
typedef typename FunctionSpaceType::DomainFieldType
DomainFieldType;
typedef typename FunctionSpaceType::DomainType
DomainType;
typedef typename FunctionSpaceType::RangeFieldType
RangeFieldType;
typedef typename FunctionSpaceType::RangeType
RangeType;
typedef typename FunctionSpaceType::JacobianRangeType
JacobianRangeType;
typedef typename FunctionSpaceType::HessianRangeType
HessianRangeType;
static const unsigned int dimDomain = FunctionSpaceType::dimDomain;
static const unsigned int dimRange = FunctionSpaceType::dimRange;
typedef std::map< unsigned int, std::set< unsigned int > > PatternType;
/**
@name Convenience typedefs
@{
**/
typedef typename GridPartType::template Codim< 0 >::IteratorType
IteratorType;
typedef typename IteratorType::Entity
EntityType;
/**
@}
**/
Lagrange( const GridPartType& gridPart )
: gridPart_( gridPart ),
gridView_(gridPart_),
mapper_( gridPart_ ),
baseFunctionSet_( *this )
{}
private:
//! copy constructor
Lagrange( const ThisType& other );
public:
const GridPartType& gridPart() const
{
return gridPart_;
}
const GridViewType& gridView() const
{
return gridView_;
}
const MapperType& map() const
{
return mapper_;
}
const BaseFunctionSetType& baseFunctionSet() const
{
return baseFunctionSet_;
}
int order() const
{
return polynomialOrder;
}
bool continuous() const
{
if( order() > 0 )
return false;
else
return true;
}
/**
@name Convenience methods
@{
**/
IteratorType begin() const
{
return gridPart_.template begin< 0 >();
}
IteratorType end() const
{
return gridPart_.template end< 0 >();
}
/**
@}
**/
template< class OtherDiscreteFunctionSpaceType>
PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
{
std::map< unsigned int, std::set< unsigned int > > ret;
// generate sparsity pattern
for (IteratorType it = begin(); it != end(); ++it) {
const EntityType& entity = *it;
for(unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
for(unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
const unsigned int globalI = map().toGlobal(entity, i);
const unsigned int globalJ = other.map().toGlobal(entity, j);
std::map< unsigned int, std::set< unsigned int > >::iterator result = ret.find(globalI);
if (result == ret.end())
ret.insert(std::pair< unsigned int, std::set< unsigned int > >(globalI, std::set< unsigned int >()));
result = ret.find(globalI);
assert(result != ret.end());
result->second.insert(globalJ);
}
}
} // generate sparsity pattern
return ret;
} // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
PatternType computePattern() const
{
return computePattern(*this);
}
protected:
//! assignment operator
ThisType& operator=( const ThisType& );
const GridPartType& gridPart_;
const GridViewType gridView_;
const MapperType mapper_;
const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange
} // end namespace Continuous
} // end namespace DiscreteFunctionSpace
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<commit_msg>[discretefunctionspace.continuous.lagrange] minor change (should perform better)<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
// dune-fem includes
#include <dune/fem/space/lagrangespace.hh>
#include <dune/fem/gridpart/gridpartview.hh>
// dune-detailed-discretizations includes
#include <dune/detailed/discretizations/basefunctionset/continuous/lagrange.hh>
#include <dune/detailed/discretizations/mapper/continuous/lagrange.hh>
namespace Dune
{
namespace Detailed {
namespace Discretizations
{
namespace DiscreteFunctionSpace
{
namespace Continuous
{
template< class FunctionSpaceImp, class GridPartImp, int polOrder >
class Lagrange
{
public:
typedef FunctionSpaceImp
FunctionSpaceType;
typedef GridPartImp
GridPartType;
typedef Dune::GridPartView< GridPartType > GridViewType;
enum{ polynomialOrder = polOrder };
typedef Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
ThisType;
typedef Dune::Detailed::Discretizations::Mapper::Continuous::Lagrange< FunctionSpaceType, GridPartType, polynomialOrder >
MapperType;
typedef Dune::Detailed::Discretizations::BaseFunctionSet::Continuous::Lagrange< ThisType >
BaseFunctionSetType;
typedef typename FunctionSpaceType::DomainFieldType
DomainFieldType;
typedef typename FunctionSpaceType::DomainType
DomainType;
typedef typename FunctionSpaceType::RangeFieldType
RangeFieldType;
typedef typename FunctionSpaceType::RangeType
RangeType;
typedef typename FunctionSpaceType::JacobianRangeType
JacobianRangeType;
typedef typename FunctionSpaceType::HessianRangeType
HessianRangeType;
static const unsigned int dimDomain = FunctionSpaceType::dimDomain;
static const unsigned int dimRange = FunctionSpaceType::dimRange;
typedef std::map< unsigned int, std::set< unsigned int > > PatternType;
/**
@name Convenience typedefs
@{
**/
typedef typename GridPartType::template Codim< 0 >::IteratorType
IteratorType;
typedef typename IteratorType::Entity
EntityType;
/**
@}
**/
Lagrange( const GridPartType& gridPart )
: gridPart_( gridPart ),
gridView_(gridPart_),
mapper_( gridPart_ ),
baseFunctionSet_( *this )
{}
private:
//! copy constructor
Lagrange( const ThisType& other );
public:
const GridPartType& gridPart() const
{
return gridPart_;
}
const GridViewType& gridView() const
{
return gridView_;
}
const MapperType& map() const
{
return mapper_;
}
const BaseFunctionSetType& baseFunctionSet() const
{
return baseFunctionSet_;
}
int order() const
{
return polynomialOrder;
}
bool continuous() const
{
if( order() > 0 )
return false;
else
return true;
}
/**
@name Convenience methods
@{
**/
IteratorType begin() const
{
return gridPart_.template begin< 0 >();
}
IteratorType end() const
{
return gridPart_.template end< 0 >();
}
/**
@}
**/
template< class OtherDiscreteFunctionSpaceType>
PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
{
std::map< unsigned int, std::set< unsigned int > > ret;
// generate sparsity pattern
for (IteratorType it = begin(); it != end(); ++it) {
const EntityType& entity = *it;
for(unsigned int i = 0; i < baseFunctionSet().local(entity).size(); ++i) {
const unsigned int globalI = map().toGlobal(entity, i);
std::map< unsigned int, std::set< unsigned int > >::iterator result = ret.find(globalI);
if (result == ret.end())
ret.insert(std::pair< unsigned int, std::set< unsigned int > >(globalI, std::set< unsigned int >()));
result = ret.find(globalI);
assert(result != ret.end());
for(unsigned int j = 0; j < other.baseFunctionSet().local(entity).size(); ++j) {
const unsigned int globalJ = other.map().toGlobal(entity, j);
result->second.insert(globalJ);
}
}
} // generate sparsity pattern
return ret;
} // PatternType computePattern(const OtherDiscreteFunctionSpaceType& other) const
PatternType computePattern() const
{
return computePattern(*this);
}
protected:
//! assignment operator
ThisType& operator=( const ThisType& );
const GridPartType& gridPart_;
const GridViewType gridView_;
const MapperType mapper_;
const BaseFunctionSetType baseFunctionSet_;
}; // end class Lagrange
} // end namespace Continuous
} // end namespace DiscreteFunctionSpace
} // namespace Discretizations
} // namespace Detailed
} // end namespace Dune
#endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTIONSPACE_CONTINUOUS_LAGRANGE_HH
<|endoftext|>
|
<commit_before>#include "platform/local_country_file.hpp"
#include "platform/platform.hpp"
#include "coding/internal/file_data.hpp"
#include "coding/file_name_utils.hpp"
#include "base/logging.hpp"
#include "std/sstream.hpp"
namespace platform
{
LocalCountryFile::LocalCountryFile()
: m_version(0), m_files(MapOptions::Nothing), m_mapSize(0), m_routingSize()
{
}
LocalCountryFile::LocalCountryFile(string const & directory, CountryFile const & countryFile,
int64_t version)
: m_directory(directory),
m_countryFile(countryFile),
m_version(version),
m_files(MapOptions::Nothing),
m_mapSize(0),
m_routingSize(0)
{
}
void LocalCountryFile::SyncWithDisk()
{
m_files = MapOptions::Nothing;
m_mapSize = 0;
m_routingSize = 0;
Platform & platform = GetPlatform();
if (platform.GetFileSizeByFullPath(GetPath(MapOptions::Map), m_mapSize))
m_files = SetOptions(m_files, MapOptions::Map);
string const routingPath = GetPath(MapOptions::CarRouting);
if (platform.GetFileSizeByFullPath(routingPath, m_routingSize))
m_files = SetOptions(m_files, MapOptions::CarRouting);
}
void LocalCountryFile::DeleteFromDisk(MapOptions files) const
{
for (MapOptions file : {MapOptions::Map, MapOptions::CarRouting})
{
if (OnDisk(file) && HasOptions(files, file))
{
if (!my::DeleteFileX(GetPath(file)))
LOG(LERROR, (file, "from", *this, "wasn't deleted from disk."));
}
}
}
string LocalCountryFile::GetPath(MapOptions file) const
{
// todo(@m): Refactor with MwmTraits after merge new-search branch.
bool singleFile = GetVersion() > 151215;
string const & countryFilePath = singleFile ? m_countryFile.GetNameWithExt(MapOptions::Map)
: m_countryFile.GetNameWithExt(file);
return my::JoinFoldersToPath(m_directory, countryFilePath);
}
uint32_t LocalCountryFile::GetSize(MapOptions filesMask) const
{
uint64_t size64 = 0;
if (HasOptions(filesMask, MapOptions::Map))
size64 += m_mapSize;
if (HasOptions(filesMask, MapOptions::CarRouting))
size64 += m_routingSize;
uint32_t const size32 = static_cast<uint32_t>(size64);
ASSERT_EQUAL(size32, size64, ());
return size32;
}
bool LocalCountryFile::operator<(LocalCountryFile const & rhs) const
{
if (m_countryFile != rhs.m_countryFile)
return m_countryFile < rhs.m_countryFile;
if (m_version != rhs.m_version)
return m_version < rhs.m_version;
if (m_directory != rhs.m_directory)
return m_directory < rhs.m_directory;
if (m_files != rhs.m_files)
return m_files < rhs.m_files;
return false;
}
bool LocalCountryFile::operator==(LocalCountryFile const & rhs) const
{
return m_directory == rhs.m_directory && m_countryFile == rhs.m_countryFile &&
m_version == rhs.m_version && m_files == rhs.m_files;
}
// static
LocalCountryFile LocalCountryFile::MakeForTesting(string const & countryFileName)
{
CountryFile const countryFile(countryFileName);
LocalCountryFile localFile(GetPlatform().WritableDir(), countryFile, 0 /* version */);
localFile.SyncWithDisk();
return localFile;
}
// static
LocalCountryFile LocalCountryFile::MakeTemporary(string const & fullPath)
{
string name = fullPath;
my::GetNameFromFullPath(name);
my::GetNameWithoutExt(name);
return LocalCountryFile(my::GetDirectory(fullPath), CountryFile(name), 0 /* version */);
}
string DebugPrint(LocalCountryFile const & file)
{
ostringstream os;
os << "LocalCountryFile [" << file.m_directory << ", " << DebugPrint(file.m_countryFile) << ", "
<< file.m_version << ", " << DebugPrint(file.m_files) << "]";
return os.str();
}
} // namespace platform
<commit_msg>[old map downloader] Fixing assert in Storage tests.<commit_after>#include "platform/local_country_file.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"
#include "coding/internal/file_data.hpp"
#include "coding/file_name_utils.hpp"
#include "base/logging.hpp"
#include "std/sstream.hpp"
namespace platform
{
LocalCountryFile::LocalCountryFile()
: m_version(0), m_files(MapOptions::Nothing), m_mapSize(0), m_routingSize()
{
}
LocalCountryFile::LocalCountryFile(string const & directory, CountryFile const & countryFile,
int64_t version)
: m_directory(directory),
m_countryFile(countryFile),
m_version(version),
m_files(MapOptions::Nothing),
m_mapSize(0),
m_routingSize(0)
{
}
void LocalCountryFile::SyncWithDisk()
{
m_files = MapOptions::Nothing;
m_mapSize = 0;
m_routingSize = 0;
Platform & platform = GetPlatform();
if (platform.GetFileSizeByFullPath(GetPath(MapOptions::Map), m_mapSize))
m_files = SetOptions(m_files, MapOptions::Map);
string const routingPath = GetPath(MapOptions::CarRouting);
if (platform.GetFileSizeByFullPath(routingPath, m_routingSize))
m_files = SetOptions(m_files, MapOptions::CarRouting);
}
void LocalCountryFile::DeleteFromDisk(MapOptions files) const
{
vector<MapOptions> const mapOptions =
version::IsSingleMwm(GetVersion()) ? vector<MapOptions>({MapOptions::Map})
: vector<MapOptions>({MapOptions::Map, MapOptions::CarRouting});
for (MapOptions file : mapOptions)
{
if (OnDisk(file) && HasOptions(files, file))
{
if (!my::DeleteFileX(GetPath(file)))
LOG(LERROR, (file, "from", *this, "wasn't deleted from disk."));
}
}
}
string LocalCountryFile::GetPath(MapOptions file) const
{
// todo(@m): Refactor with MwmTraits after merge new-search branch.
bool const singleFile = version::IsSingleMwm(GetVersion());
string const & countryFilePath = singleFile ? m_countryFile.GetNameWithExt(MapOptions::Map)
: m_countryFile.GetNameWithExt(file);
return my::JoinFoldersToPath(m_directory, countryFilePath);
}
uint32_t LocalCountryFile::GetSize(MapOptions filesMask) const
{
uint64_t size64 = 0;
if (HasOptions(filesMask, MapOptions::Map))
size64 += m_mapSize;
if (HasOptions(filesMask, MapOptions::CarRouting))
size64 += m_routingSize;
uint32_t const size32 = static_cast<uint32_t>(size64);
ASSERT_EQUAL(size32, size64, ());
return size32;
}
bool LocalCountryFile::operator<(LocalCountryFile const & rhs) const
{
if (m_countryFile != rhs.m_countryFile)
return m_countryFile < rhs.m_countryFile;
if (m_version != rhs.m_version)
return m_version < rhs.m_version;
if (m_directory != rhs.m_directory)
return m_directory < rhs.m_directory;
if (m_files != rhs.m_files)
return m_files < rhs.m_files;
return false;
}
bool LocalCountryFile::operator==(LocalCountryFile const & rhs) const
{
return m_directory == rhs.m_directory && m_countryFile == rhs.m_countryFile &&
m_version == rhs.m_version && m_files == rhs.m_files;
}
// static
LocalCountryFile LocalCountryFile::MakeForTesting(string const & countryFileName)
{
CountryFile const countryFile(countryFileName);
LocalCountryFile localFile(GetPlatform().WritableDir(), countryFile, 0 /* version */);
localFile.SyncWithDisk();
return localFile;
}
// static
LocalCountryFile LocalCountryFile::MakeTemporary(string const & fullPath)
{
string name = fullPath;
my::GetNameFromFullPath(name);
my::GetNameWithoutExt(name);
return LocalCountryFile(my::GetDirectory(fullPath), CountryFile(name), 0 /* version */);
}
string DebugPrint(LocalCountryFile const & file)
{
ostringstream os;
os << "LocalCountryFile [" << file.m_directory << ", " << DebugPrint(file.m_countryFile) << ", "
<< file.m_version << ", " << DebugPrint(file.m_files) << "]";
return os.str();
}
} // namespace platform
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BUsers.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:11:27 $
*
* 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 _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName)
{
return new OAdabasUser(m_pConnection,_rName);
}
// -------------------------------------------------------------------------
void OUsers::impl_refresh() throw(RuntimeException)
{
m_pParent->refreshUsers();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OUsers::createEmptyObject()
{
OUserExtend* pNew = new OUserExtend(m_pConnection);
return pNew;
}
// -------------------------------------------------------------------------
// XAppend
void OUsers::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE USER ");
::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( );
::rtl::OUString sUserName;
descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sUserName;
sUserName = sUserName.toAsciiUpperCase();
descriptor->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(sUserName));
aSql += ::dbtools::quoteName(aQuote,sUserName)
+ ::rtl::OUString::createFromAscii(" PASSWORD ")
+ getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)));
aSql += ::rtl::OUString::createFromAscii(" RESOURCE NOT EXCLUSIVE");
Reference< XStatement > xStmt = m_pConnection->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
// -------------------------------------------------------------------------
// XDrop
void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
{
// first we have to check if this user is live relevaant for the database
// which means with out these users the database will miss more than one important system table
::rtl::OUString sUsers = ::rtl::OUString::createFromAscii("SELECT USERMODE,USERNAME FROM DOMAIN.USERS WHERE USERNAME = '");
sUsers += _sElementName + ::rtl::OUString::createFromAscii("'");
Reference< XStatement > xStmt = m_pConnection->createStatement();
if(xStmt.is())
{
Reference<XResultSet> xRes = xStmt->executeQuery(sUsers);
Reference<XRow> xRow(xRes,UNO_QUERY);
if(xRes.is() && xRow.is() && xRes->next()) // there can only be one user with this name
{
static const ::rtl::OUString sDbaUser = ::rtl::OUString::createFromAscii("DBA");
if(xRow->getString(1) == sDbaUser)
{
::comphelper::disposeComponent(xStmt);
::dbtools::throwGenericSQLException(::rtl::OUString::createFromAscii("This user couldn't be deleted. Otherwise the database stays in a inconsistent state."),static_cast<XTypeProvider*>(this));
}
}
::comphelper::disposeComponent(xStmt);
}
}
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP USER ");
::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( );
aSql += ::dbtools::quoteName(aQuote,_sElementName);
Reference< XStatement > xStmt = m_pConnection->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS qiq (1.15.104); FILE MERGED 2006/06/27 14:05:40 fs 1.15.104.2: RESYNC: (1.15-1.16); FILE MERGED 2006/06/16 11:32:30 fs 1.15.104.1: during #i51143#:<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BUsers.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: obo $ $Date: 2006-07-10 14:22:50 $
*
* 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 _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName)
{
return new OAdabasUser(m_pConnection,_rName);
}
// -------------------------------------------------------------------------
void OUsers::impl_refresh() throw(RuntimeException)
{
m_pParent->refreshUsers();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OUsers::createDescriptor()
{
OUserExtend* pNew = new OUserExtend(m_pConnection);
return pNew;
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OUsers::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE USER ");
::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( );
::rtl::OUString sUserName( _rForName );
sUserName = sUserName.toAsciiUpperCase();
descriptor->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(sUserName));
aSql += ::dbtools::quoteName(aQuote,sUserName)
+ ::rtl::OUString::createFromAscii(" PASSWORD ")
+ getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)));
aSql += ::rtl::OUString::createFromAscii(" RESOURCE NOT EXCLUSIVE");
Reference< XStatement > xStmt = m_pConnection->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
return createObject( _rForName );
}
// -------------------------------------------------------------------------
// XDrop
void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
{
// first we have to check if this user is live relevaant for the database
// which means with out these users the database will miss more than one important system table
::rtl::OUString sUsers = ::rtl::OUString::createFromAscii("SELECT USERMODE,USERNAME FROM DOMAIN.USERS WHERE USERNAME = '");
sUsers += _sElementName + ::rtl::OUString::createFromAscii("'");
Reference< XStatement > xStmt = m_pConnection->createStatement();
if(xStmt.is())
{
Reference<XResultSet> xRes = xStmt->executeQuery(sUsers);
Reference<XRow> xRow(xRes,UNO_QUERY);
if(xRes.is() && xRow.is() && xRes->next()) // there can only be one user with this name
{
static const ::rtl::OUString sDbaUser = ::rtl::OUString::createFromAscii("DBA");
if(xRow->getString(1) == sDbaUser)
{
::comphelper::disposeComponent(xStmt);
::dbtools::throwGenericSQLException(::rtl::OUString::createFromAscii("This user couldn't be deleted. Otherwise the database stays in a inconsistent state."),static_cast<XTypeProvider*>(this));
}
}
::comphelper::disposeComponent(xStmt);
}
}
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP USER ");
::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( );
aSql += ::dbtools::quoteName(aQuote,_sElementName);
Reference< XStatement > xStmt = m_pConnection->createStatement( );
if(xStmt.is())
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>
// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"
static const char *REVISION = "$Rev$";
// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;
int main(int argc, char **argv)
{
cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
cout << REVISION << '\n' <<endl;
////////////////////////////////////////////////////////////////////////////////////////////
// Command line processing
variables_map vm;
// Command line processing
{
options_description cmdline_options("Allowed options");
cmdline_options.add_options()
("help,h", "print help message")
("data,d", value<string>(), "file containing the documents and context terms")
("topics,t", value<int>()->default_value(50), "number of topics")
("document-topics-out,o", value<string>(), "file to write the document topics to")
("default-topics-out", value<string>(), "file to write default term topic assignments.")
("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
("backoff-type", value<string>(), "backoff type: none|simple")
("filter-singleton-contexts", "filter singleton contexts")
("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
;
store(parse_command_line(argc, argv, cmdline_options), vm);
notify(vm);
if (vm.count("help")) {
cout << cmdline_options << "\n";
return 1;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
if (!vm.count("data")) {
cerr << "Please specify a file containing the data." << endl;
return 1;
}
// seed the random number generator
//mt_init_genrand(time(0));
PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));
// read the data
BackoffGenerator* backoff_gen=0;
if (vm.count("backoff-type")) {
if (vm["backoff-type"].as<std::string>() == "none") {
backoff_gen = 0;
}
else if (vm["backoff-type"].as<std::string>() == "simple") {
backoff_gen = new SimpleBackoffGenerator();
}
else {
cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
return(1);
}
}
ContextsCorpus contexts_corpus;
contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
model.set_backoff(contexts_corpus.backoff_index());
if (backoff_gen)
delete backoff_gen;
// train the sampler
model.sample(contexts_corpus, vm["samples"].as<int>());
if (vm.count("document-topics-out")) {
ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());
int document_id=0;
map<int,int> all_terms;
for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
vector<int> unique_terms;
for (Document::const_iterator docIt=corpusIt->begin();
docIt != corpusIt->end(); ++docIt) {
if (unique_terms.empty() || *docIt != unique_terms.back())
unique_terms.push_back(*docIt);
// increment this terms frequency
pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1));
if (!insert_result.second)
insert_result.first++;
}
documents_out << contexts_corpus.key(document_id) << '\t';
for (std::vector<int>::const_iterator termIt=unique_terms.begin();
termIt != unique_terms.end(); ++termIt) {
if (termIt != unique_terms.begin())
documents_out << " ||| ";
vector<std::string> strings = contexts_corpus.context2string(*termIt);
copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
documents_out << "||| C=" << model.max(document_id, *termIt);
}
documents_out <<endl;
}
documents_out.close();
ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
default_topics << model.max_topic() <<endl;
for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
vector<std::string> strings = contexts_corpus.context2string(termIt->first);
default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
default_topics <<endl;
}
}
if (vm.count("topic-words-out")) {
ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
model.print_topic_terms(topics_out);
topics_out.close();
}
cout <<endl;
return 0;
}
<commit_msg><commit_after>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>
// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"
static const char *REVISION = "$Rev$";
// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;
int main(int argc, char **argv)
{
cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
cout << REVISION << '\n' <<endl;
////////////////////////////////////////////////////////////////////////////////////////////
// Command line processing
variables_map vm;
// Command line processing
{
options_description cmdline_options("Allowed options");
cmdline_options.add_options()
("help,h", "print help message")
("data,d", value<string>(), "file containing the documents and context terms")
("topics,t", value<int>()->default_value(50), "number of topics")
("document-topics-out,o", value<string>(), "file to write the document topics to")
("default-topics-out", value<string>(), "file to write default term topic assignments.")
("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
("backoff-type", value<string>(), "backoff type: none|simple")
("filter-singleton-contexts", "filter singleton contexts")
("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
;
store(parse_command_line(argc, argv, cmdline_options), vm);
notify(vm);
if (vm.count("help")) {
cout << cmdline_options << "\n";
return 1;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
if (!vm.count("data")) {
cerr << "Please specify a file containing the data." << endl;
return 1;
}
// seed the random number generator
//mt_init_genrand(time(0));
PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));
// read the data
BackoffGenerator* backoff_gen=0;
if (vm.count("backoff-type")) {
if (vm["backoff-type"].as<std::string>() == "none") {
backoff_gen = 0;
}
else if (vm["backoff-type"].as<std::string>() == "simple") {
backoff_gen = new SimpleBackoffGenerator();
}
else {
cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
return(1);
}
}
ContextsCorpus contexts_corpus;
contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
model.set_backoff(contexts_corpus.backoff_index());
if (backoff_gen)
delete backoff_gen;
// train the sampler
model.sample(contexts_corpus, vm["samples"].as<int>());
if (vm.count("document-topics-out")) {
ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());
int document_id=0;
map<int,int> all_terms;
for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
vector<int> unique_terms;
for (Document::const_iterator docIt=corpusIt->begin();
docIt != corpusIt->end(); ++docIt) {
if (unique_terms.empty() || *docIt != unique_terms.back())
unique_terms.push_back(*docIt);
// increment this terms frequency
pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1));
if (!insert_result.second)
all_terms[*docIt] = all_terms[*docIt] + 1;
//insert_result.first++;
}
documents_out << contexts_corpus.key(document_id) << '\t';
for (std::vector<int>::const_iterator termIt=unique_terms.begin();
termIt != unique_terms.end(); ++termIt) {
if (termIt != unique_terms.begin())
documents_out << " ||| ";
vector<std::string> strings = contexts_corpus.context2string(*termIt);
copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
documents_out << "||| C=" << model.max(document_id, *termIt);
}
documents_out <<endl;
}
documents_out.close();
ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
default_topics << model.max_topic() <<endl;
for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
vector<std::string> strings = contexts_corpus.context2string(termIt->first);
default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
default_topics <<endl;
}
}
if (vm.count("topic-words-out")) {
ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
model.print_topic_terms(topics_out);
topics_out.close();
}
cout <<endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
Test module for atlas
Tests functions of class Object
by Gordon Hart, fex <who@which.net>
29 Jan 2000
*/
#include "../Object/Object.h"
using Atlas::Object;
#include <iostream>
using std::cout;
using std::endl;
//________________________________________________________________________________
//Global
bool verbose = true;
//________________________________________________________________________________
//Helper inlines
inline void print ( const string& output ) {
if (verbose) {
cout << output;
cout.flush();
}
}
inline void println ( const string& output ) {
if (verbose) {
cout << endl << output << endl;
cout.flush();
}
}
class TestError {};
inline void check( const bool test ) {
if (!test)
throw TestError();
print(".Ok");
}
//________________________________________________________________________________
//Proto
bool mapTest();
//________________________________________________________________________________
//Main
int main() {
println("Object test - ");
int error = 0;
error += mapTest();
println("Test run finished");
if ( error )
return -1;
return 0;
}
//________________________________________________________________________________
//subchecks
void mapTypeCheck( const Object& anObject) {
check( anObject.isMap() );
check( !anObject.isList() );
check( !anObject.isInt() );
check( !anObject.isFloat() );
check( !anObject.isString() );
}
//________________________________________________________________________________
//Main checks
bool mapTest() {
try {
println( "Creating map" );
Object map;
println( "Type check 1" );
mapTypeCheck( map );
println( "Check has()" );
check( !map.has( "" ) );
check( !map.has( "map") );
println( "Check length" );
check ( map.length() == 0 );
println( "Adding value" );
map.set( "string", "Stringval" );
println( "Consistency checks" );
check( map.length() == 1 );
check( map.has( "string" ) );
check( !map.has( "" ) );
println( "Overwriting value" );
map.set( "string", "stringval" );
check( map.length() == 1 );
check( map.has( "string" ) );
check( !map.has( "" ) );
println( "Delete check 1" );
map.del( "" );
check( map.has( "string" ) );
check( map.length() == 1 );
map.del( "string" );
check( !map.has( "string" ) );
check( map.length() == 0 );
println( "Delete check 2" );
map.set( "1", "2" );
map.set( "3", "4" );
check( map.length() == 2 );
check( map.has("1") );
check( map.has("3") );
check( !map.has("2" ) );
map.del( "1" );
check( map.length() == 1 );
check( !map.has( "1" ) );
map.del( "3" );
check( map.length() == 0 );
check( !map.has( "3" ) );
println( "Clearing map" );
map.set( "1", "2" );
map.set( "3", "4" );
map.clear();
check( map.length() == 0 );
println( "Integer add" );
map.set( "int", 9191 );
check( map.has( "int" ) );
check( map.length() == 1 );
println( "double add" );
map.set( "double", 2828.2828 );
check( map.has( "double" ) );
check( map.length() == 2 );
println( "string add" );
map.set( "string", "a test String" );
check( map.has( "string" ) );
check( map.length() == 3 );
println( "long add" );
map.set( "long", 12345678L );
check( map.has( "long" ) );
check( map.length() == 4 );
Object foo;
println( "Convert to value List check" );
foo = map.vals();
check( foo.length() == 4 );
println( "Convert to key List check" );
foo = map.vals();
check( foo.length() == 4 );
int ival= 0;
double dval= 0;
long lval= 0;
string sval= "";
println( "Integer true get" );
check( map.get( "int", ival ) );
check( ival == 9191 );
println( "Integer get as Long" );
check( map.get( "int", lval ) );
check( ival == 9191L );
println( "Bad type get" );
check( !map.get( "int", dval ) );
check( !map.get( "int", sval ) );
dval = lval = ival = 0;
sval = "";
println( "Double true get" );
check( map.get( "double", dval ) );
check( dval != 0 );
println( "Bad type get" );
check( !map.get( "double", ival ) );
check( !map.get( "double", sval ) );
check( !map.get( "double", lval ) );
dval = lval = ival = 0;
sval = "";
println( "Long true get" );
check( map.get( "long", lval ) );
check( lval == 12345678L );
println( "Long get as integer" );
check( map.get( "long", ival ) );
check( ival == 12345678L );
println( "Bad type get" );
check( !map.get( "long", dval ) );
check( !map.get( "long", sval ) );
dval = lval = ival = 0;
sval = "";
println( "String true get" );
check( map.get( "string", sval ) );
check( sval == "a test String" );
println( "Bad type get" );
check( !map.get( "string", ival ) );
check( !map.get( "string", dval ) );
check( !map.get( "string", lval ) );
println( "Embedded object test" );
Object bar;
Object bar2;
bar.set( "object", map );
check( bar.length() == 1);
check( map.length() == 4);
check( bar.has( "object" ) );
check( bar.get( "object", bar2 ) );
check( bar2.length() == 4 );
println( "Key list check" );
Object foobar = bar2.keys();
check( foobar.length() == 4 );
/*
println( "Out of bounds ndx check on key list" );
for ( int i = -10 ; i < 10; ++i) {
if ( ( i < 0) || ( i > 3 ) ) {
cout << " check not there ";
check( !foobar.get( i, sval ) );
}
else {
cout << " check there ";
check( foobar.get( i, sval ) );
println( sval );
}
}
*/
println( "Out of bounds ndx check on key list" );
for ( int i = -10 ; i < 10; ++i) {
sval = "";
cout << foobar.get( i, sval);
cout << "At map[" << i << "] is the string [" << sval << "]" << endl;
}
println( "Closing clear checks" );
bar.clear();
check( bar.length() == 0 );
check( map.length() == 4 );
map.clear();
check( map.length() == 0 );
return true;
} catch ( TestError& e ) {
print("...Failed\n");
return false;
}
}<commit_msg>*** empty log message ***<commit_after>/*
Test module for atlas
Tests functions of class Object
by Gordon Hart, fex <who@which.net>
29 Jan 2000
*/
#include "../Object/Object.h"
using Atlas::Object;
#include <iostream>
using std::cout;
using std::endl;
//________________________________________________________________________________
//Global
bool verbose = true;
//________________________________________________________________________________
//Helper inlines
inline void print ( const string& output ) {
if (verbose) {
cout << output;
cout.flush();
}
}
inline void println ( const string& output ) {
if (verbose) {
cout << endl << output << endl;
cout.flush();
}
}
class TestError {};
inline void check( const bool test ) {
if (!test)
throw TestError();
print(".Ok");
}
//________________________________________________________________________________
//Proto
bool mapTest();
//________________________________________________________________________________
//Main
int main() {
println("Object test - ");
int error = 0;
error += mapTest();
println("Test run finished");
if ( error )
return -1;
return 0;
}
//________________________________________________________________________________
//subchecks
void mapTypeCheck( const Object& anObject) {
check( anObject.isMap() );
check( !anObject.isList() );
check( !anObject.isInt() );
check( !anObject.isFloat() );
check( !anObject.isString() );
}
//________________________________________________________________________________
//Main checks
bool mapTest() {
try {
println( "Creating map" );
Object map;
println( "Type check 1" );
mapTypeCheck( map );
println( "Check has()" );
check( !map.has( "" ) );
check( !map.has( "map") );
println( "Check length" );
check ( map.length() == 0 );
println( "Adding value" );
map.set( "string", "Stringval" );
println( "Consistency checks" );
check( map.length() == 1 );
check( map.has( "string" ) );
check( !map.has( "" ) );
println( "Overwriting value" );
map.set( "string", "stringval" );
check( map.length() == 1 );
check( map.has( "string" ) );
check( !map.has( "" ) );
println( "Delete check 1" );
map.del( "" );
check( map.has( "string" ) );
check( map.length() == 1 );
map.del( "string" );
check( !map.has( "string" ) );
check( map.length() == 0 );
println( "Delete check 2" );
map.set( "1", "2" );
map.set( "3", "4" );
check( map.length() == 2 );
check( map.has("1") );
check( map.has("3") );
check( !map.has("2" ) );
map.del( "1" );
check( map.length() == 1 );
check( !map.has( "1" ) );
map.del( "3" );
check( map.length() == 0 );
check( !map.has( "3" ) );
println( "Clearing map" );
map.set( "1", "2" );
map.set( "3", "4" );
map.clear();
check( map.length() == 0 );
println( "Integer add" );
map.set( "int", 9191 );
check( map.has( "int" ) );
check( map.length() == 1 );
println( "double add" );
map.set( "double", 2828.2828 );
check( map.has( "double" ) );
check( map.length() == 2 );
println( "string add" );
map.set( "string", "a test String" );
check( map.has( "string" ) );
check( map.length() == 3 );
println( "long add" );
map.set( "long", 12345678L );
check( map.has( "long" ) );
check( map.length() == 4 );
Object foo;
println( "Convert to value List check" );
foo = map.vals();
check( foo.length() == 4 );
println( "Convert to key List check" );
foo = map.vals();
check( foo.length() == 4 );
int ival= 0;
double dval= 0;
long lval= 0;
string sval= "";
println( "Integer true get" );
check( map.get( "int", ival ) );
check( ival == 9191 );
println( "Integer get as Long" );
check( map.get( "int", lval ) );
check( ival == 9191L );
println( "Bad type get" );
check( !map.get( "int", dval ) );
check( !map.get( "int", sval ) );
dval = lval = ival = 0;
sval = "";
println( "Double true get" );
check( map.get( "double", dval ) );
check( dval != 0 );
println( "Bad type get" );
check( !map.get( "double", ival ) );
check( !map.get( "double", sval ) );
check( !map.get( "double", lval ) );
dval = lval = ival = 0;
sval = "";
println( "Long true get" );
check( map.get( "long", lval ) );
check( lval == 12345678L );
println( "Long get as integer" );
check( map.get( "long", ival ) );
check( ival == 12345678L );
println( "Bad type get" );
check( !map.get( "long", dval ) );
check( !map.get( "long", sval ) );
dval = lval = ival = 0;
sval = "";
println( "String true get" );
check( map.get( "string", sval ) );
check( sval == "a test String" );
println( "Bad type get" );
check( !map.get( "string", ival ) );
check( !map.get( "string", dval ) );
check( !map.get( "string", lval ) );
println( "Embedded object test" );
Object bar;
Object bar2;
bar.set( "object", map );
check( bar.length() == 1);
check( map.length() == 4);
check( bar.has( "object" ) );
check( bar.get( "object", bar2 ) );
check( bar2.length() == 4 );
println( "Key list check" );
Object foobar = bar2.keys();
check( foobar.length() == 4 );
/*
println( "Out of bounds ndx check on key list" );
for ( int i = -10 ; i < 10; ++i) {
if ( ( i < 0) || ( i > 3 ) ) {
cout << " check not there ";
check( !foobar.get( i, sval ) );
}
else {
cout << " check there ";
check( foobar.get( i, sval ) );
println( sval );
}
}
*/
// out of bound calls on list are broken,this shows it up
// the code above is the proper check for correct behaviour
println( "Out of bounds ndx check on key list" );
for ( int i = -10 ; i < 10; ++i) {
sval = "";
cout << foobar.get( i, sval);
cout << "At map[" << i << "] is the string [" << sval << "]" << endl;
}
println( "Closing clear checks" );
bar.clear();
check( bar.length() == 0 );
check( map.length() == 4 );
map.clear();
check( map.length() == 0 );
return true;
} catch ( TestError& e ) {
print("...Failed\n");
return false;
}
}<|endoftext|>
|
<commit_before>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* wxparaver *
* Paraver Trace Visualization and Analysis Tool *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL 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 *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
| @file: $HeadURL$
| @last_commit: $Date$
| @version: $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include "labelconstructor.h"
// Signal handling
#include <signal.h>
#include <stdio.h>
#include "wxparaverapp.h"
#include "connection.h"
#include <wx/filename.h>
////@begin XPM images
////@end XPM images
#ifndef WIN32
struct sigaction act;
#endif
/*!
* Application instance implementation
*/
////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app
/*!
* wxparaverApp type definition
*/
IMPLEMENT_CLASS( wxparaverApp, wxApp )
/*!
* wxparaverApp event table definition
*/
BEGIN_EVENT_TABLE( wxparaverApp, wxApp )
////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries
END_EVENT_TABLE()
/*!
* Constructor for wxparaverApp
*/
wxparaverApp::wxparaverApp()
{
Init();
}
/*!
* Member initialisation
*/
void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
globalTiming = false;
globalTimingBegin = 0;
globalTimingEnd = 0;
globalTimingCallDialog = NULL;
globalTimingBeginIsSet = false;
eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
m_locale.Init();
}
/*!
* Initialisation for wxparaverApp
*/
paraverMain* wxparaverApp::mainWindow = NULL;
#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;
void wxparaverApp::handler( int signalNumber )
{
sigdelset( &act.sa_mask, SIGUSR1 );
sigdelset( &act.sa_mask, SIGUSR2 );
// wxMutexGuiEnter();
// wxparaverApp::mainWindow->OnSignal( signalNumber );
// wxMutexGuiLeave();
if ( signalNumber == SIGUSR1 )
{
sig1 = true;
}
else
{
sig1 = false;
}
sig2 = !sig1;
// wxIdleEvent event;
// event.RequestMore();
// wxTheApp->SendIdleEvents( mainWindow, event );
mainWindow->Raise();
sigaddset( &act.sa_mask, SIGUSR1 );
sigaddset( &act.sa_mask, SIGUSR2 );
sigaction( SIGUSR1, &act, NULL );
sigaction( SIGUSR2, &act, NULL );
}
void wxparaverApp::presetUserSignals()
{
act.sa_handler = &handler;
act.sa_flags = 0;
if ( sigemptyset( &act.sa_mask ) != 0 )
{
/* Handle error */
}
if ( sigaddset( &act.sa_mask, SIGUSR1 ))
{
/* Handle error */
}
if ( sigaddset( &act.sa_mask, SIGUSR2 ))
{
/* Handle error */
}
if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
{
/* Handle error */
}
if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
{
/* Handle error */
}
}
#endif
bool wxparaverApp::OnInit()
{
wxCmdLineEntryDesc argumentsParseSyntax[] =
{
{ wxCMD_LINE_SWITCH,
wxT("v"),
wxT("version"),
wxT("Show wxparaver version."),
wxCMD_LINE_VAL_STRING },
{ wxCMD_LINE_SWITCH,
wxT("h"),
wxT("help"),
wxT("Show this help."),
wxCMD_LINE_VAL_STRING,
wxCMD_LINE_OPTION_HELP },
{ wxCMD_LINE_OPTION,
wxT("t"),
wxT("type"),
wxT("Event type to code linking."),
wxCMD_LINE_VAL_NUMBER,
wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_PARAM,
NULL,
NULL,
wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
wxCMD_LINE_VAL_STRING,
wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },
{ wxCMD_LINE_NONE }
};
wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
if ( paraverCommandLineParser.Parse( false ) != 0 )
{
paraverCommandLineParser.Usage();
return false;
}
if( paraverCommandLineParser.Found( wxT("v") ))
{
PrintVersion();
return false;
}
ParaverConfig::getInstance()->readParaverConfigFile();
if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
{
const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
m_checker = new wxSingleInstanceChecker(name);
if ( !m_checker->IsAnotherRunning() )
{
m_server = new stServer;
#ifdef WIN32
if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
if( !m_server->Create( service_name ) )
#endif
wxLogDebug( wxT( "Failed to create an IPC service." ) );
}
else
{
wxLogNull logNull;
stClient *client = new stClient;
wxString hostName = wxT( "localhost" );
#ifdef WIN32
wxConnectionBase *connection = client->MakeConnection( hostName,
wxT( "wxparaver_service" ),
wxT( "wxparaver" ) );
#else
const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
wxConnectionBase *connection = client->MakeConnection( hostName,
service_name,
wxT( "wxparaver" ) );
#endif
if( connection )
{
connection->Execute( wxT( "BEGIN" ) );
for( int i = 1; i < argc; ++i )
{
wxFileName tmpFile( wxT( argv[ i ] ) );
tmpFile.Normalize();
connection->Execute( tmpFile.GetFullPath().c_str() );
}
connection->Execute( wxT( "END" ) );
connection->Disconnect();
delete connection;
}
else
{
wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
}
delete client;
return false;
}
}
#if wxUSE_XPM
wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
wxImage::AddHandler(new wxGIFHandler);
#endif
wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
ParaverConfig::getInstance()->getMainWindowHeight() );
mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
//mainWindow = new paraverMain( NULL );
mainWindow->Show(true);
long int tmpType;
if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
eventTypeForCode = tmpType;
mainWindow->commandLineLoadings( paraverCommandLineParser );
/*
paraverMain *mainWindow;
mainWindow = new paraverMain( NULL );
mainWindow->Show(true);
mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
presetUserSignals();
#endif
return true;
}
/*!
* Cleanup for wxparaverApp
*/
int wxparaverApp::OnExit()
{
// double w, h;
// wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
// cout<<w<<" "<<h<<endl;
// cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
// wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
ParaverConfig::getInstance()->writeParaverConfigFile();
if( m_checker != NULL )
delete m_checker;
if( m_server != NULL )
delete m_server;
////@begin wxparaverApp cleanup
return wxApp::OnExit();
////@end wxparaverApp cleanup
}
#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
if ( event.GetEventType()==wxEVT_KEY_DOWN &&
((wxKeyEvent&)event).ControlDown() &&
((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
)
{
mainWindow->OnKeyCopy();
return true;
}
else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
((wxKeyEvent&)event).ControlDown() &&
((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
)
{
mainWindow->OnKeyPaste();
return true;
}
return -1;
}
#endif
void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
globalTimingCallDialog = whichDialog;
wxSetCursor( *wxCROSS_CURSOR );
globalTiming = true;
globalTimingBeginIsSet = false;
globalTimingCallDialog->Enable( false );
globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
globalTimingCallDialog->Iconize( true );
#endif
mainWindow->Raise();
}
void wxparaverApp::DeactivateGlobalTiming()
{
cout << "DeactivateGlobalTiming" << endl;
wxSetCursor( wxNullCursor );
globalTiming = false;
globalTimingBeginIsSet = false;
globalTimingCallDialog->Enable( true );
globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
globalTimingCallDialog->Iconize( false );
#endif
globalTimingCallDialog->Raise();
}
void wxparaverApp::PrintVersion()
{
cout << PACKAGE_STRING;
bool reverseOrder = true;
string auxDate = LabelConstructor::getDate( reverseOrder );
if ( auxDate.compare("") != 0 )
cout << " Build ";
cout << auxDate << endl;
}
<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* wxparaver *
* Paraver Trace Visualization and Analysis Tool *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL 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 *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
| @file: $HeadURL$
| @last_commit: $Date$
| @version: $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include "labelconstructor.h"
// Signal handling
#include <signal.h>
#include <stdio.h>
#include "wxparaverapp.h"
#include "connection.h"
#include <wx/filename.h>
////@begin XPM images
////@end XPM images
#ifndef WIN32
struct sigaction act;
#endif
/*!
* Application instance implementation
*/
////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app
/*!
* wxparaverApp type definition
*/
IMPLEMENT_CLASS( wxparaverApp, wxApp )
/*!
* wxparaverApp event table definition
*/
BEGIN_EVENT_TABLE( wxparaverApp, wxApp )
////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries
END_EVENT_TABLE()
/*!
* Constructor for wxparaverApp
*/
wxparaverApp::wxparaverApp()
{
Init();
}
/*!
* Member initialisation
*/
void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
globalTiming = false;
globalTimingBegin = 0;
globalTimingEnd = 0;
globalTimingCallDialog = NULL;
globalTimingBeginIsSet = false;
eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
m_locale.Init();
}
/*!
* Initialisation for wxparaverApp
*/
paraverMain* wxparaverApp::mainWindow = NULL;
#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;
void wxparaverApp::handler( int signalNumber )
{
sigdelset( &act.sa_mask, SIGUSR1 );
sigdelset( &act.sa_mask, SIGUSR2 );
// wxMutexGuiEnter();
// wxparaverApp::mainWindow->OnSignal( signalNumber );
// wxMutexGuiLeave();
if ( signalNumber == SIGUSR1 )
{
sig1 = true;
}
else
{
sig1 = false;
}
sig2 = !sig1;
// wxIdleEvent event;
// event.RequestMore();
// wxTheApp->SendIdleEvents( mainWindow, event );
mainWindow->Raise();
sigaddset( &act.sa_mask, SIGUSR1 );
sigaddset( &act.sa_mask, SIGUSR2 );
sigaction( SIGUSR1, &act, NULL );
sigaction( SIGUSR2, &act, NULL );
}
void wxparaverApp::presetUserSignals()
{
act.sa_handler = &handler;
act.sa_flags = 0;
if ( sigemptyset( &act.sa_mask ) != 0 )
{
/* Handle error */
}
if ( sigaddset( &act.sa_mask, SIGUSR1 ))
{
/* Handle error */
}
if ( sigaddset( &act.sa_mask, SIGUSR2 ))
{
/* Handle error */
}
if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
{
/* Handle error */
}
if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
{
/* Handle error */
}
}
#endif
bool wxparaverApp::OnInit()
{
wxCmdLineEntryDesc argumentsParseSyntax[] =
{
{ wxCMD_LINE_SWITCH,
wxT("v"),
wxT("version"),
wxT("Show wxparaver version."),
wxCMD_LINE_VAL_STRING },
{ wxCMD_LINE_SWITCH,
wxT("h"),
wxT("help"),
wxT("Show this help."),
wxCMD_LINE_VAL_STRING,
wxCMD_LINE_OPTION_HELP },
{ wxCMD_LINE_OPTION,
wxT("t"),
wxT("type"),
wxT("Event type to code linking."),
wxCMD_LINE_VAL_NUMBER,
wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_PARAM,
NULL,
NULL,
wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
wxCMD_LINE_VAL_STRING,
wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },
{ wxCMD_LINE_NONE }
};
wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
if ( paraverCommandLineParser.Parse( false ) != 0 )
{
paraverCommandLineParser.Usage();
return false;
}
if( paraverCommandLineParser.Found( wxT("v") ))
{
PrintVersion();
return false;
}
ParaverConfig::getInstance()->readParaverConfigFile();
if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
{
const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
m_checker = new wxSingleInstanceChecker(name);
if ( !m_checker->IsAnotherRunning() )
{
m_server = new stServer;
#ifdef WIN32
if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
if( !m_server->Create( service_name ) )
#endif
wxLogDebug( wxT( "Failed to create an IPC service." ) );
}
else
{
wxLogNull logNull;
stClient *client = new stClient;
wxString hostName = wxT( "localhost" );
#ifdef WIN32
wxConnectionBase *connection = client->MakeConnection( hostName,
wxT( "wxparaver_service" ),
wxT( "wxparaver" ) );
#else
const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
wxConnectionBase *connection = client->MakeConnection( hostName,
service_name,
wxT( "wxparaver" ) );
#endif
if( connection )
{
connection->Execute( wxT( "BEGIN" ) );
for( int i = 1; i < argc; ++i )
{
wxFileName tmpFile( argv[ i ] );
tmpFile.Normalize();
connection->Execute( tmpFile.GetFullPath().c_str() );
}
connection->Execute( wxT( "END" ) );
connection->Disconnect();
delete connection;
}
else
{
wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
}
delete client;
return false;
}
}
#if wxUSE_XPM
wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
wxImage::AddHandler(new wxGIFHandler);
#endif
wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
ParaverConfig::getInstance()->getMainWindowHeight() );
mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
//mainWindow = new paraverMain( NULL );
mainWindow->Show(true);
long int tmpType;
if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
eventTypeForCode = tmpType;
mainWindow->commandLineLoadings( paraverCommandLineParser );
/*
paraverMain *mainWindow;
mainWindow = new paraverMain( NULL );
mainWindow->Show(true);
mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
presetUserSignals();
#endif
return true;
}
/*!
* Cleanup for wxparaverApp
*/
int wxparaverApp::OnExit()
{
// double w, h;
// wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
// cout<<w<<" "<<h<<endl;
// cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
// wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
ParaverConfig::getInstance()->writeParaverConfigFile();
if( m_checker != NULL )
delete m_checker;
if( m_server != NULL )
delete m_server;
////@begin wxparaverApp cleanup
return wxApp::OnExit();
////@end wxparaverApp cleanup
}
#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
if ( event.GetEventType()==wxEVT_KEY_DOWN &&
((wxKeyEvent&)event).ControlDown() &&
((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
)
{
mainWindow->OnKeyCopy();
return true;
}
else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
((wxKeyEvent&)event).ControlDown() &&
((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
)
{
mainWindow->OnKeyPaste();
return true;
}
return -1;
}
#endif
void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
globalTimingCallDialog = whichDialog;
wxSetCursor( *wxCROSS_CURSOR );
globalTiming = true;
globalTimingBeginIsSet = false;
globalTimingCallDialog->Enable( false );
globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
globalTimingCallDialog->Iconize( true );
#endif
mainWindow->Raise();
}
void wxparaverApp::DeactivateGlobalTiming()
{
cout << "DeactivateGlobalTiming" << endl;
wxSetCursor( wxNullCursor );
globalTiming = false;
globalTimingBeginIsSet = false;
globalTimingCallDialog->Enable( true );
globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
globalTimingCallDialog->Iconize( false );
#endif
globalTimingCallDialog->Raise();
}
void wxparaverApp::PrintVersion()
{
cout << PACKAGE_STRING;
bool reverseOrder = true;
string auxDate = LabelConstructor::getDate( reverseOrder );
if ( auxDate.compare("") != 0 )
cout << " Build ";
cout << auxDate << endl;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, 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.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QList>
#include <QFile>
#include <QTextStream>
// Visomics includes
#include "voDataObject.h"
#include "voInputFileDataObject.h"
#include "voOneZoomDynView.h"
#include "voUtils.h"
// VTK includes
#include <vtkTree.h>
// --------------------------------------------------------------------------
class voOneZoomDynViewPrivate
{
public:
voOneZoomDynViewPrivate();
};
// --------------------------------------------------------------------------
// voOneZoomDynViewPrivate methods
// --------------------------------------------------------------------------
voOneZoomDynViewPrivate::voOneZoomDynViewPrivate()
{
}
// --------------------------------------------------------------------------
// voOneZoomDynView methods
// --------------------------------------------------------------------------
voOneZoomDynView::voOneZoomDynView(QWidget * newParent):
Superclass(newParent), d_ptr(new voOneZoomDynViewPrivate)
{
}
// --------------------------------------------------------------------------
voOneZoomDynView::~voOneZoomDynView()
{
}
// --------------------------------------------------------------------------
QString voOneZoomDynView::stringify(const voDataObject& dataObject)
{
vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
if (!tree)
{
qCritical() << "voOneZoomDynView - Failed to setDataObject - vtkTree data is expected !";
return QString();
}
//Ideally, a vtkNewickTreeWriter function can be used to convert a tree to a newick formated string;
//For now, we just use the original input file to obtain the newick string.
QString filename = dynamic_cast<voInputFileDataObject *> (const_cast<voDataObject*>(&dataObject))->fileName();
//read the tree file into a string
QFile file(filename);
QString treeString = "";
if (file.open (QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream stream ( &file );
treeString = stream.readAll();
}
file.close(); // when your done.
return treeString;
}
<commit_msg>make Wikipedia links from OneZoom work more reliably.<commit_after>/*=========================================================================
Program: Visomics
Copyright (c) Kitware, 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.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QList>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
// Visomics includes
#include "voDataObject.h"
#include "voInputFileDataObject.h"
#include "voOneZoomDynView.h"
#include "voUtils.h"
// VTK includes
#include <vtkTree.h>
// --------------------------------------------------------------------------
class voOneZoomDynViewPrivate
{
public:
voOneZoomDynViewPrivate();
};
// --------------------------------------------------------------------------
// voOneZoomDynViewPrivate methods
// --------------------------------------------------------------------------
voOneZoomDynViewPrivate::voOneZoomDynViewPrivate()
{
}
// --------------------------------------------------------------------------
// voOneZoomDynView methods
// --------------------------------------------------------------------------
voOneZoomDynView::voOneZoomDynView(QWidget * newParent):
Superclass(newParent), d_ptr(new voOneZoomDynViewPrivate)
{
}
// --------------------------------------------------------------------------
voOneZoomDynView::~voOneZoomDynView()
{
}
// --------------------------------------------------------------------------
QString voOneZoomDynView::stringify(const voDataObject& dataObject)
{
vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
if (!tree)
{
qCritical() << "voOneZoomDynView - Failed to setDataObject - vtkTree data is expected !";
return QString();
}
//Ideally, a vtkNewickTreeWriter function can be used to convert a tree to a newick formated string;
//For now, we just use the original input file to obtain the newick string.
QString filename = dynamic_cast<voInputFileDataObject *> (const_cast<voDataObject*>(&dataObject))->fileName();
//read the tree file into a string
QFile file(filename);
QString treeString = "";
if (file.open (QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream stream ( &file );
treeString = stream.readAll();
}
file.close(); // when your done.
//Massage the leaf node labels so Wikipedia linking works more reliably.
if (!treeString.contains("_"))
{
if (treeString.contains(" "))
{
treeString.replace(QString(" "), QString("_"));
}
else
{
QFileInfo fileInfo(file);
QString nameToAppend = fileInfo.baseName();
treeString.replace(QRegExp("([a-zA-Z]+)"), QString("%1_\\1").arg(nameToAppend));
}
}
return treeString;
}
<|endoftext|>
|
<commit_before>/*
The MIT License
Copyright (c) 2010 by Jorrit Tyberghein
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 "../apparesed.h"
#include "curvemode.h"
#include <wx/xrc/xmlres.h>
//---------------------------------------------------------------------------
BEGIN_EVENT_TABLE(CurveMode::Panel, wxPanel)
EVT_BUTTON (XRCID("rotLeftButton"), CurveMode::Panel::OnRotLeft)
EVT_BUTTON (XRCID("rotRightButton"), CurveMode::Panel::OnRotRight)
EVT_BUTTON (XRCID("rotResetButton"), CurveMode::Panel::OnRotReset)
EVT_BUTTON (XRCID("flattenButton"), CurveMode::Panel::OnFlatten)
EVT_CHECKBOX (XRCID("autoSmoothCheckBox"), CurveMode::Panel::OnAutoSmoothSelected)
END_EVENT_TABLE()
//---------------------------------------------------------------------------
CurveMode::CurveMode (wxWindow* parent, AresEdit3DView* aresed3d)
: ViewMode (aresed3d, "Curve")
{
panel = new Panel (parent, this);
parent->GetSizer ()->Add (panel, 1, wxALL | wxEXPAND);
wxXmlResource::Get()->LoadPanel (panel, parent, wxT ("CurveModePanel"));
editingCurveFactory = 0;
autoSmooth = true;
wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
autoSmoothCheckBox->SetValue (autoSmooth);
}
void CurveMode::UpdateMarkers ()
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
if (editingCurveFactory->GetPointCount () != markers.GetSize ())
{
Stop ();
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
{
iMarker* marker = aresed3d->GetMarkerManager ()->CreateMarker ();
markers.Push (marker);
marker->AttachMesh (mesh);
}
}
iMarkerColor* red = aresed3d->GetMarkerManager ()->FindMarkerColor ("red");
iMarkerColor* green = aresed3d->GetMarkerManager ()->FindMarkerColor ("green");
iMarkerColor* yellow = aresed3d->GetMarkerManager ()->FindMarkerColor ("yellow");
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
{
csVector3 pos = editingCurveFactory->GetPosition (i);
csVector3 front = editingCurveFactory->GetFront (i);
csVector3 up = editingCurveFactory->GetUp (i);
iMarker* marker = markers[i];
marker->Clear ();
marker->Line (MARKER_OBJECT, pos, pos+front, green, true);
marker->Line (MARKER_OBJECT, pos, pos+up, red, true);
marker->ClearHitAreas ();
iMarkerHitArea* hitArea = marker->HitArea (MARKER_OBJECT, pos, .1f, i, yellow);
csRef<MarkerCallback> cb;
cb.AttachNew (new MarkerCallback (this));
hitArea->DefineDrag (0, 0, MARKER_WORLD, CONSTRAIN_MESH, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT, MARKER_WORLD, CONSTRAIN_MESH, cb);
hitArea->DefineDrag (0, CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
hitArea->DefineDrag (0, CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
}
UpdateMarkerSelection ();
}
void CurveMode::UpdateMarkerSelection ()
{
for (size_t i = 0 ; i < markers.GetSize () ; i++)
markers[i]->SetSelectionLevel (SELECTION_NONE);
for (size_t i = 0 ; i < selectedPoints.GetSize () ; i++)
markers[selectedPoints[i]]->SetSelectionLevel (SELECTION_SELECTED);
}
void CurveMode::Start ()
{
ViewMode::Start ();
if (!aresed3d->GetSelection ()->HasSelection ()) return;
iDynamicObject* dynobj = aresed3d->GetSelection ()->GetFirst ();
csString name = dynobj->GetFactory ()->GetName ();
editingCurveFactory = aresed3d->GetCurvedMeshCreator ()->GetCurvedFactory (name);
ggen = scfQueryInterface<iGeometryGenerator> (editingCurveFactory);
selectedPoints.Empty ();
dragPoints.Empty ();
UpdateMarkers ();
}
void CurveMode::Stop ()
{
ViewMode::Stop ();
for (size_t i = 0 ; i < markers.GetSize () ; i++)
aresed3d->GetMarkerManager ()->DestroyMarker (markers[i]);
markers.Empty ();
}
void CurveMode::MarkerStartDragging (iMarker* marker, iMarkerHitArea* area,
const csVector3& pos, uint button, uint32 modifiers)
{
size_t idx = size_t (area->GetData ());
if (modifiers & CSMASK_SHIFT)
AddCurrentPoint (idx);
else
SetCurrentPoint (idx);
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
csVector3 wpos = GetWorldPosPoint (id);
DragPoint dob;
dob.kineOffset = pos - wpos;
dob.idx = id;
dragPoints.Push (dob);
}
}
void CurveMode::MarkerWantsMove (iMarker* marker, iMarkerHitArea* area,
const csVector3& pos)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
for (size_t i = 0 ; i < dragPoints.GetSize () ; i++)
{
csVector3 np = pos - dragPoints[i].kineOffset;
size_t idx = dragPoints[i].idx;
csVector3 rp = meshtrans.Other2This (np);
editingCurveFactory->ChangePoint (idx,
rp,
editingCurveFactory->GetFront (idx),
editingCurveFactory->GetUp (idx));
UpdateMarkers ();
}
if (autoSmooth) DoAutoSmooth ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::MarkerStopDragging (iMarker* marker, iMarkerHitArea* area)
{
StopDrag ();
}
void CurveMode::SetCurrentPoint (size_t idx)
{
if (selectedPoints.Find (idx) != csArrayItemNotFound) return;
selectedPoints.DeleteAll ();
selectedPoints.Push (idx);
UpdateMarkerSelection ();
}
void CurveMode::AddCurrentPoint (size_t idx)
{
if (selectedPoints.Find (idx) != csArrayItemNotFound)
{
selectedPoints.Delete (idx);
}
else
{
selectedPoints.Push (idx);
}
UpdateMarkerSelection ();
}
void CurveMode::StopDrag ()
{
dragPoints.DeleteAll ();
}
void CurveMode::FramePre()
{
ViewMode::FramePre ();
}
void CurveMode::Frame3D()
{
ViewMode::Frame3D ();
}
void CurveMode::Frame2D()
{
ViewMode::Frame2D ();
}
void CurveMode::DoAutoSmooth ()
{
if (editingCurveFactory->GetPointCount () <= 2) return;
for (size_t i = 1 ; i < editingCurveFactory->GetPointCount ()-1 ; i++)
SmoothPoint (i, false);
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::SmoothPoint (size_t idx, bool regen)
{
if (idx == 0 || idx >= editingCurveFactory->GetPointCount ()-1)
return;
const csVector3& p1 = editingCurveFactory->GetPosition (idx-1);
const csVector3& pos = editingCurveFactory->GetPosition (idx);
const csVector3& p2 = editingCurveFactory->GetPosition (idx+1);
csVector3 fr = ((p2 - pos).Unit () + (pos - p1).Unit ()) / 2.0;
csVector3 up = editingCurveFactory->GetUp (idx);
//csVector3 right = fr % up;
//up = - (fr % right).Unit ();
editingCurveFactory->ChangePoint (idx, pos, fr, up);
UpdateMarkers ();
if (regen)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
}
csVector3 CurveMode::GetWorldPosPoint (size_t idx)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
const csVector3& pos = editingCurveFactory->GetPosition (idx);
return meshtrans.This2Other (pos);
}
size_t CurveMode::FindCurvePoint (int mouseX, int mouseY)
{
int data;
iMarker* marker = aresed3d->GetMarkerManager ()->FindHitMarker (mouseX, mouseY, data);
if (!marker) return csArrayItemNotFound;
size_t idx = 0;
while (idx < markers.GetSize ())
if (markers[idx] == marker) return idx;
else idx++;
return csArrayItemNotFound;
}
void CurveMode::RotateCurrent (float baseAngle)
{
bool slow = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_CTRL);
bool fast = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_SHIFT);
float angle = baseAngle;
if (slow) angle /= 180.0;
else if (fast) angle /= 2.0;
else angle /= 8.0;
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
// @TODO: optimize!!!
const csVector3& pos = editingCurveFactory->GetPosition (id);
const csVector3& f = editingCurveFactory->GetFront (id);
const csVector3& u = editingCurveFactory->GetUp (id);
csVector3 r = f % u;
csMatrix3 m (r.x, r.y, r.z, u.x, u.y, u.z, f.x, f.y, f.z);
csReversibleTransform tr (m, pos);
tr.RotateOther (u, angle);
editingCurveFactory->ChangePoint (id, pos, tr.GetFront (), u);
UpdateMarkers ();
}
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::FlatPoint (size_t idx)
{
float sideHeight = editingCurveFactory->GetSideHeight ();
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
csVector3 pos = editingCurveFactory->GetPosition (idx);
pos = meshtrans.This2Other (pos);
const csVector3& f = editingCurveFactory->GetFront (idx);
const csVector3& u = editingCurveFactory->GetUp (idx);
pos.y += 100.0;
iSector* sector = aresed3d->GetCsCamera ()->GetSector ();
csFlags oldFlags = mesh->GetFlags ();
mesh->GetFlags ().Set (CS_ENTITY_NOHITBEAM);
csSectorHitBeamResult result = sector->HitBeamPortals (pos, pos - csVector3 (0, 1000, 0));
mesh->GetFlags ().SetAll (oldFlags.Get ());
if (result.mesh)
{
pos = result.isect;
pos.y += sideHeight / 2.0;
pos = meshtrans.Other2This (pos);
editingCurveFactory->ChangePoint (idx, pos, f, u);
UpdateMarkers ();
if (autoSmooth)
DoAutoSmooth ();
else
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
}
void CurveMode::OnFlatten ()
{
if (selectedPoints.GetSize () == 0)
{
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
FlatPoint (i);
}
else
{
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
FlatPoint (id);
}
}
}
void CurveMode::OnRotLeft ()
{
RotateCurrent (-PI);
}
void CurveMode::OnRotRight ()
{
RotateCurrent (PI);
}
void CurveMode::OnRotReset ()
{
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
SmoothPoint (id);
}
}
void CurveMode::OnAutoSmoothSelected ()
{
wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
autoSmooth = autoSmoothCheckBox->IsChecked ();
}
bool CurveMode::OnKeyboard (iEvent& ev, utf32_char code)
{
if (ViewMode::OnKeyboard (ev, code))
return true;
if (code == 'e')
{
size_t id = editingCurveFactory->GetPointCount ()-1;
const csVector3& pos = editingCurveFactory->GetPosition (id);
const csVector3& front = editingCurveFactory->GetFront (id);
const csVector3& up = editingCurveFactory->GetUp (id);
editingCurveFactory->AddPoint (pos + front, front, up);
if (autoSmooth) DoAutoSmooth ();
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
UpdateMarkers ();
}
return false;
}
bool CurveMode::OnMouseDown (iEvent& ev, uint but, int mouseX, int mouseY)
{
return ViewMode::OnMouseDown (ev, but, mouseX, mouseY);
}
bool CurveMode::OnMouseUp(iEvent& ev, uint but, int mouseX, int mouseY)
{
return ViewMode::OnMouseUp (ev, but, mouseX, mouseY);
}
bool CurveMode::OnMouseMove (iEvent& ev, int mouseX, int mouseY)
{
return ViewMode::OnMouseMove (ev, mouseX, mouseY);
}
<commit_msg>Fixed crasher in curve mode in case the selected object has no curve.<commit_after>/*
The MIT License
Copyright (c) 2010 by Jorrit Tyberghein
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 "../apparesed.h"
#include "curvemode.h"
#include <wx/xrc/xmlres.h>
//---------------------------------------------------------------------------
BEGIN_EVENT_TABLE(CurveMode::Panel, wxPanel)
EVT_BUTTON (XRCID("rotLeftButton"), CurveMode::Panel::OnRotLeft)
EVT_BUTTON (XRCID("rotRightButton"), CurveMode::Panel::OnRotRight)
EVT_BUTTON (XRCID("rotResetButton"), CurveMode::Panel::OnRotReset)
EVT_BUTTON (XRCID("flattenButton"), CurveMode::Panel::OnFlatten)
EVT_CHECKBOX (XRCID("autoSmoothCheckBox"), CurveMode::Panel::OnAutoSmoothSelected)
END_EVENT_TABLE()
//---------------------------------------------------------------------------
CurveMode::CurveMode (wxWindow* parent, AresEdit3DView* aresed3d)
: ViewMode (aresed3d, "Curve")
{
panel = new Panel (parent, this);
parent->GetSizer ()->Add (panel, 1, wxALL | wxEXPAND);
wxXmlResource::Get()->LoadPanel (panel, parent, wxT ("CurveModePanel"));
editingCurveFactory = 0;
autoSmooth = true;
wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
autoSmoothCheckBox->SetValue (autoSmooth);
}
void CurveMode::UpdateMarkers ()
{
if (!editingCurveFactory) return;
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
if (editingCurveFactory->GetPointCount () != markers.GetSize ())
{
Stop ();
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
{
iMarker* marker = aresed3d->GetMarkerManager ()->CreateMarker ();
markers.Push (marker);
marker->AttachMesh (mesh);
}
}
iMarkerColor* red = aresed3d->GetMarkerManager ()->FindMarkerColor ("red");
iMarkerColor* green = aresed3d->GetMarkerManager ()->FindMarkerColor ("green");
iMarkerColor* yellow = aresed3d->GetMarkerManager ()->FindMarkerColor ("yellow");
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
{
csVector3 pos = editingCurveFactory->GetPosition (i);
csVector3 front = editingCurveFactory->GetFront (i);
csVector3 up = editingCurveFactory->GetUp (i);
iMarker* marker = markers[i];
marker->Clear ();
marker->Line (MARKER_OBJECT, pos, pos+front, green, true);
marker->Line (MARKER_OBJECT, pos, pos+up, red, true);
marker->ClearHitAreas ();
iMarkerHitArea* hitArea = marker->HitArea (MARKER_OBJECT, pos, .1f, i, yellow);
csRef<MarkerCallback> cb;
cb.AttachNew (new MarkerCallback (this));
hitArea->DefineDrag (0, 0, MARKER_WORLD, CONSTRAIN_MESH, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT, MARKER_WORLD, CONSTRAIN_MESH, cb);
hitArea->DefineDrag (0, CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
hitArea->DefineDrag (0, CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
}
UpdateMarkerSelection ();
}
void CurveMode::UpdateMarkerSelection ()
{
for (size_t i = 0 ; i < markers.GetSize () ; i++)
markers[i]->SetSelectionLevel (SELECTION_NONE);
for (size_t i = 0 ; i < selectedPoints.GetSize () ; i++)
markers[selectedPoints[i]]->SetSelectionLevel (SELECTION_SELECTED);
}
void CurveMode::Start ()
{
ViewMode::Start ();
if (!aresed3d->GetSelection ()->HasSelection ()) return;
iDynamicObject* dynobj = aresed3d->GetSelection ()->GetFirst ();
csString name = dynobj->GetFactory ()->GetName ();
editingCurveFactory = aresed3d->GetCurvedMeshCreator ()->GetCurvedFactory (name);
if (editingCurveFactory)
ggen = scfQueryInterface<iGeometryGenerator> (editingCurveFactory);
else
ggen = 0;
selectedPoints.Empty ();
dragPoints.Empty ();
UpdateMarkers ();
}
void CurveMode::Stop ()
{
ViewMode::Stop ();
for (size_t i = 0 ; i < markers.GetSize () ; i++)
aresed3d->GetMarkerManager ()->DestroyMarker (markers[i]);
markers.Empty ();
}
void CurveMode::MarkerStartDragging (iMarker* marker, iMarkerHitArea* area,
const csVector3& pos, uint button, uint32 modifiers)
{
size_t idx = size_t (area->GetData ());
if (modifiers & CSMASK_SHIFT)
AddCurrentPoint (idx);
else
SetCurrentPoint (idx);
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
csVector3 wpos = GetWorldPosPoint (id);
DragPoint dob;
dob.kineOffset = pos - wpos;
dob.idx = id;
dragPoints.Push (dob);
}
}
void CurveMode::MarkerWantsMove (iMarker* marker, iMarkerHitArea* area,
const csVector3& pos)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
for (size_t i = 0 ; i < dragPoints.GetSize () ; i++)
{
csVector3 np = pos - dragPoints[i].kineOffset;
size_t idx = dragPoints[i].idx;
csVector3 rp = meshtrans.Other2This (np);
editingCurveFactory->ChangePoint (idx,
rp,
editingCurveFactory->GetFront (idx),
editingCurveFactory->GetUp (idx));
UpdateMarkers ();
}
if (autoSmooth) DoAutoSmooth ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::MarkerStopDragging (iMarker* marker, iMarkerHitArea* area)
{
StopDrag ();
}
void CurveMode::SetCurrentPoint (size_t idx)
{
if (selectedPoints.Find (idx) != csArrayItemNotFound) return;
selectedPoints.DeleteAll ();
selectedPoints.Push (idx);
UpdateMarkerSelection ();
}
void CurveMode::AddCurrentPoint (size_t idx)
{
if (selectedPoints.Find (idx) != csArrayItemNotFound)
{
selectedPoints.Delete (idx);
}
else
{
selectedPoints.Push (idx);
}
UpdateMarkerSelection ();
}
void CurveMode::StopDrag ()
{
dragPoints.DeleteAll ();
}
void CurveMode::FramePre()
{
ViewMode::FramePre ();
}
void CurveMode::Frame3D()
{
ViewMode::Frame3D ();
}
void CurveMode::Frame2D()
{
ViewMode::Frame2D ();
}
void CurveMode::DoAutoSmooth ()
{
if (editingCurveFactory->GetPointCount () <= 2) return;
for (size_t i = 1 ; i < editingCurveFactory->GetPointCount ()-1 ; i++)
SmoothPoint (i, false);
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::SmoothPoint (size_t idx, bool regen)
{
if (idx == 0 || idx >= editingCurveFactory->GetPointCount ()-1)
return;
const csVector3& p1 = editingCurveFactory->GetPosition (idx-1);
const csVector3& pos = editingCurveFactory->GetPosition (idx);
const csVector3& p2 = editingCurveFactory->GetPosition (idx+1);
csVector3 fr = ((p2 - pos).Unit () + (pos - p1).Unit ()) / 2.0;
csVector3 up = editingCurveFactory->GetUp (idx);
//csVector3 right = fr % up;
//up = - (fr % right).Unit ();
editingCurveFactory->ChangePoint (idx, pos, fr, up);
UpdateMarkers ();
if (regen)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
}
csVector3 CurveMode::GetWorldPosPoint (size_t idx)
{
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
const csVector3& pos = editingCurveFactory->GetPosition (idx);
return meshtrans.This2Other (pos);
}
size_t CurveMode::FindCurvePoint (int mouseX, int mouseY)
{
int data;
iMarker* marker = aresed3d->GetMarkerManager ()->FindHitMarker (mouseX, mouseY, data);
if (!marker) return csArrayItemNotFound;
size_t idx = 0;
while (idx < markers.GetSize ())
if (markers[idx] == marker) return idx;
else idx++;
return csArrayItemNotFound;
}
void CurveMode::RotateCurrent (float baseAngle)
{
bool slow = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_CTRL);
bool fast = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_SHIFT);
float angle = baseAngle;
if (slow) angle /= 180.0;
else if (fast) angle /= 2.0;
else angle /= 8.0;
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
// @TODO: optimize!!!
const csVector3& pos = editingCurveFactory->GetPosition (id);
const csVector3& f = editingCurveFactory->GetFront (id);
const csVector3& u = editingCurveFactory->GetUp (id);
csVector3 r = f % u;
csMatrix3 m (r.x, r.y, r.z, u.x, u.y, u.z, f.x, f.y, f.z);
csReversibleTransform tr (m, pos);
tr.RotateOther (u, angle);
editingCurveFactory->ChangePoint (id, pos, tr.GetFront (), u);
UpdateMarkers ();
}
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
void CurveMode::FlatPoint (size_t idx)
{
float sideHeight = editingCurveFactory->GetSideHeight ();
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
csVector3 pos = editingCurveFactory->GetPosition (idx);
pos = meshtrans.This2Other (pos);
const csVector3& f = editingCurveFactory->GetFront (idx);
const csVector3& u = editingCurveFactory->GetUp (idx);
pos.y += 100.0;
iSector* sector = aresed3d->GetCsCamera ()->GetSector ();
csFlags oldFlags = mesh->GetFlags ();
mesh->GetFlags ().Set (CS_ENTITY_NOHITBEAM);
csSectorHitBeamResult result = sector->HitBeamPortals (pos, pos - csVector3 (0, 1000, 0));
mesh->GetFlags ().SetAll (oldFlags.Get ());
if (result.mesh)
{
pos = result.isect;
pos.y += sideHeight / 2.0;
pos = meshtrans.Other2This (pos);
editingCurveFactory->ChangePoint (idx, pos, f, u);
UpdateMarkers ();
if (autoSmooth)
DoAutoSmooth ();
else
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}
}
void CurveMode::OnFlatten ()
{
if (selectedPoints.GetSize () == 0)
{
for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
FlatPoint (i);
}
else
{
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
FlatPoint (id);
}
}
}
void CurveMode::OnRotLeft ()
{
RotateCurrent (-PI);
}
void CurveMode::OnRotRight ()
{
RotateCurrent (PI);
}
void CurveMode::OnRotReset ()
{
csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
while (it.HasNext ())
{
size_t id = it.Next ();
SmoothPoint (id);
}
}
void CurveMode::OnAutoSmoothSelected ()
{
wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
autoSmooth = autoSmoothCheckBox->IsChecked ();
}
bool CurveMode::OnKeyboard (iEvent& ev, utf32_char code)
{
if (ViewMode::OnKeyboard (ev, code))
return true;
if (editingCurveFactory && code == 'e')
{
size_t id = editingCurveFactory->GetPointCount ()-1;
const csVector3& pos = editingCurveFactory->GetPosition (id);
const csVector3& front = editingCurveFactory->GetFront (id);
const csVector3& up = editingCurveFactory->GetUp (id);
editingCurveFactory->AddPoint (pos + front, front, up);
if (autoSmooth) DoAutoSmooth ();
iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
ggen->GenerateGeometry (mesh);
aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
UpdateMarkers ();
}
return false;
}
bool CurveMode::OnMouseDown (iEvent& ev, uint but, int mouseX, int mouseY)
{
return ViewMode::OnMouseDown (ev, but, mouseX, mouseY);
}
bool CurveMode::OnMouseUp(iEvent& ev, uint but, int mouseX, int mouseY)
{
return ViewMode::OnMouseUp (ev, but, mouseX, mouseY);
}
bool CurveMode::OnMouseMove (iEvent& ev, int mouseX, int mouseY)
{
return ViewMode::OnMouseMove (ev, mouseX, mouseY);
}
<|endoftext|>
|
<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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 "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
/**
* Add-on namespace.
*/
namespace addon_strided_add {
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param vtype typed array type
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
if ( vtype == napi_float64_array ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( vtype == napi_float32_array ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( vtype == napi_int32_array ) {
return STDLIB_NDARRAY_INT32;
}
if ( vtype == napi_uint32_array ) {
return STDLIB_NDARRAY_UINT32;
}
if ( vtype == napi_int16_array ) {
return STDLIB_NDARRAY_INT16;
}
if ( vtype == napi_uint16_array ) {
return STDLIB_NDARRAY_UINT16;
}
if ( vtype == napi_int8_array ) {
return STDLIB_NDARRAY_INT8;
}
if ( vtype == napi_uint8_array ) {
return STDLIB_NDARRAY_UINT8;
}
if ( vtype == napi_uint8_clamped_array ) {
return STDLIB_NDARRAY_UINT8;
}
// FIXME: handle BigInt64Array and BigUint64Array
}
/**
* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
*
* ## Notes
*
* - The function assumes the following argument order:
*
* ```text
* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
* ```
*
* where
*
* - `N` is the number of elements over which to iterate
* - `ia#` is an input strided array
* - `is#` is a corresponding input strided array stride (in units of elements)
* - `oa#` is an output strided array
* - `os#` is a corresponding output strided array stride (in units of elements)
*
* - We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
*
* @private
* @param env environment
* @param info arguments
* @param nargs total number of expected arguments
* @param nin number of input strided array arguments
* @param nout number of output strided array arguments
* @param arrays destination array containing pointers to both input and output strided byte arrays
* @param shape destination array containing the array shape (dimensions)
* @param strides destination array containing array strides (in bytes) for each strided array
* @param types destination array containing strided array argument data types
* @throws must provide expected number of input arguments
* @throws stride arguments must be numbers
* @throws input strided array arguments must be either typed arrays or scalars
* @throws output strided array arguments must be typed arrays
* @throws must provide at least one input strided array
* @return number of scalar strided "array" arguments
*/
int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
napi_status status;
int64_t i;
int64_t j;
// Compute the index of the first output strided array argument:
int64_t iout = ( nin*2 ) + 1;
// Initialize variables used to track scalar input arguments:
int64_t nsargs = 0;
int64_t sargs = 0;
// Get callback arguments:
size_t argc = 7;
napi_value argv[ 7 ];
status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
assert( status == napi_ok );
if ( (int64_t)argc != nargs ) {
napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
return -1;
}
// The first argument is always the number of elements over which to iterate...
napi_valuetype vtype0;
status = napi_typeof( env, argv[ 0 ], &vtype0 );
assert( status == napi_ok );
if ( vtype0 != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
return -1;
}
// Retrieve the number of elements:
int64_t N;
status = napi_get_value_int64( env, argv[ 0 ], &N );
assert( status == napi_ok );
shape[ 0 ] = N;
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
napi_valuetype vtype;
status = napi_typeof( env, argv[ i ], &vtype );
assert( status == napi_ok );
if ( vtype != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
return -1;
}
int64_t stride;
status = napi_get_value_int64( env, argv[ i ], &stride );
assert( status == napi_ok );
j = ( i-2 ) / 2;
strides[ j ] = stride;
}
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
bool res;
status = napi_is_typedarray( env, argv[ i ], &res );
assert( status == napi_ok );
if ( res == true ) {
napi_typedarray_type vtype;
size_t len;
void *TypedArray;
status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
assert( status == napi_ok );
if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
return -1;
}
arrays[ j ] = (uint8_t *)TypedArray;
types[ j ] = typed_array_data_type( vtype );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else {
double v;
status = napi_get_value_double( env, argv[ i ], &v );
if ( status != napi_ok ) {
napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
sargs |= (1<<j);
nsargs += 1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
bool res;
status = napi_is_typedarray( env, argv[ i ], &res );
assert( status == napi_ok );
if ( res == true ) {
napi_typedarray_type vtype;
size_t len;
void *TypedArray;
status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
assert( status == napi_ok );
if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
return -1;
}
arrays[ j ] = (uint8_t *)TypedArray;
types[ j ] = typed_array_data_type( vtype );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else {
napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
return -1;
}
}
// Check if we have been provided only scalar input arguments...
if ( nin > 0 && nsargs == nin ) {
napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
return -1;
}
return nsargs;
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* ## Notes
*
* - When called from JavaScript, the function expects the following arguments:
*
* - `N`: number of indexed elements
* - `X`: input array (or scalar constant)
* - `strideX`: `X` stride length
* - `Y`: input array (or scalar constant)
* - `strideY`: `Y` stride length
* - `Z`: destination array
* - `strideZ`: `Z` stride length
*/
napi_value node_add( napi_env env, napi_callback_info info ) {
enum STDLIB_NDARRAY_DTYPE types[ 3 ];
uint8_t *arrays[ 3 ];
int64_t strides[ 3 ];
int64_t shape[ 1 ];
int64_t nsargs;
int64_t nargs;
int64_t nout;
int64_t nin;
// Total number of input arguments:
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Process the provided arguments:
nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
if ( nsargs < 0 ) {
return nullptr;
}
// Broadcasting of scalar arguments...
if ( nsargs > 0 ) {
// FIXME
// Create an array having the closest "compatible" type...
// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
// Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
return nullptr;
}
napi_value Init( napi_env env, napi_value exports ) {
napi_status status;
napi_value fcn;
status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
assert( status == napi_ok );
return fcn;
}
NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<commit_msg>Resolve TODO item<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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 "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
/**
* Add-on namespace.
*/
namespace addon_strided_add {
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param vtype typed array type
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
if ( vtype == napi_float64_array ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( vtype == napi_float32_array ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( vtype == napi_int32_array ) {
return STDLIB_NDARRAY_INT32;
}
if ( vtype == napi_uint32_array ) {
return STDLIB_NDARRAY_UINT32;
}
if ( vtype == napi_int16_array ) {
return STDLIB_NDARRAY_INT16;
}
if ( vtype == napi_uint16_array ) {
return STDLIB_NDARRAY_UINT16;
}
if ( vtype == napi_int8_array ) {
return STDLIB_NDARRAY_INT8;
}
if ( vtype == napi_uint8_array ) {
return STDLIB_NDARRAY_UINT8;
}
if ( vtype == napi_uint8_clamped_array ) {
return STDLIB_NDARRAY_UINT8;
}
if ( vtype == napi_bigint64_array ) {
return STDLIB_NDARRAY_INT64;
}
return STDLIB_NDARRAY_UINT64; // vtype == napi_biguint64_array
}
/**
* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
*
* ## Notes
*
* - The function assumes the following argument order:
*
* ```text
* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
* ```
*
* where
*
* - `N` is the number of elements over which to iterate
* - `ia#` is an input strided array
* - `is#` is a corresponding input strided array stride (in units of elements)
* - `oa#` is an output strided array
* - `os#` is a corresponding output strided array stride (in units of elements)
*
* - We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
*
* @private
* @param env environment
* @param info arguments
* @param nargs total number of expected arguments
* @param nin number of input strided array arguments
* @param nout number of output strided array arguments
* @param arrays destination array containing pointers to both input and output strided byte arrays
* @param shape destination array containing the array shape (dimensions)
* @param strides destination array containing array strides (in bytes) for each strided array
* @param types destination array containing strided array argument data types
* @throws must provide expected number of input arguments
* @throws stride arguments must be numbers
* @throws input strided array arguments must be either typed arrays or scalars
* @throws output strided array arguments must be typed arrays
* @throws must provide at least one input strided array
* @return number of scalar strided "array" arguments
*/
int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
napi_status status;
int64_t i;
int64_t j;
// Compute the index of the first output strided array argument:
int64_t iout = ( nin*2 ) + 1;
// Initialize variables used to track scalar input arguments:
int64_t nsargs = 0;
int64_t sargs = 0;
// Get callback arguments:
size_t argc = 7;
napi_value argv[ 7 ];
status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
assert( status == napi_ok );
if ( (int64_t)argc != nargs ) {
napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
return -1;
}
// The first argument is always the number of elements over which to iterate...
napi_valuetype vtype0;
status = napi_typeof( env, argv[ 0 ], &vtype0 );
assert( status == napi_ok );
if ( vtype0 != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
return -1;
}
// Retrieve the number of elements:
int64_t N;
status = napi_get_value_int64( env, argv[ 0 ], &N );
assert( status == napi_ok );
shape[ 0 ] = N;
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
napi_valuetype vtype;
status = napi_typeof( env, argv[ i ], &vtype );
assert( status == napi_ok );
if ( vtype != napi_number ) {
napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
return -1;
}
int64_t stride;
status = napi_get_value_int64( env, argv[ i ], &stride );
assert( status == napi_ok );
j = ( i-2 ) / 2;
strides[ j ] = stride;
}
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
bool res;
status = napi_is_typedarray( env, argv[ i ], &res );
assert( status == napi_ok );
if ( res == true ) {
napi_typedarray_type vtype;
size_t len;
void *TypedArray;
status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
assert( status == napi_ok );
if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
return -1;
}
arrays[ j ] = (uint8_t *)TypedArray;
types[ j ] = typed_array_data_type( vtype );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else {
double v;
status = napi_get_value_double( env, argv[ i ], &v );
if ( status != napi_ok ) {
napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
sargs |= (1<<j);
nsargs += 1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
bool res;
status = napi_is_typedarray( env, argv[ i ], &res );
assert( status == napi_ok );
if ( res == true ) {
napi_typedarray_type vtype;
size_t len;
void *TypedArray;
status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
assert( status == napi_ok );
if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
return -1;
}
arrays[ j ] = (uint8_t *)TypedArray;
types[ j ] = typed_array_data_type( vtype );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else {
napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
return -1;
}
}
// Check if we have been provided only scalar input arguments...
if ( nin > 0 && nsargs == nin ) {
napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
return -1;
}
return nsargs;
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* ## Notes
*
* - When called from JavaScript, the function expects the following arguments:
*
* - `N`: number of indexed elements
* - `X`: input array (or scalar constant)
* - `strideX`: `X` stride length
* - `Y`: input array (or scalar constant)
* - `strideY`: `Y` stride length
* - `Z`: destination array
* - `strideZ`: `Z` stride length
*/
napi_value node_add( napi_env env, napi_callback_info info ) {
enum STDLIB_NDARRAY_DTYPE types[ 3 ];
uint8_t *arrays[ 3 ];
int64_t strides[ 3 ];
int64_t shape[ 1 ];
int64_t nsargs;
int64_t nargs;
int64_t nout;
int64_t nin;
// Total number of input arguments:
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Process the provided arguments:
nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
if ( nsargs < 0 ) {
return nullptr;
}
// Broadcasting of scalar arguments...
if ( nsargs > 0 ) {
// FIXME
// Create an array having the closest "compatible" type...
// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
// Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
return nullptr;
}
napi_value Init( napi_env env, napi_value exports ) {
napi_status status;
napi_value fcn;
status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
assert( status == napi_ok );
return fcn;
}
NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.