hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff6ae562d9a9ad053d94d30afdd64d831b21ab02 | 197 | cpp | C++ | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | engine/src/platform/android/pixelboost/network/networkHelpers.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #ifdef PIXELBOOST_PLATFORM_ANDROID
#include "pixelboost/network/networkHelpers.h"
namespace pb
{
namespace NetworkHelpers
{
std::string GetWifiAddress()
{
return "";
}
}
}
#endif | 9.85 | 46 | 0.705584 | pixelballoon |
ff74b57f3d608596dc87107d22efe349443c8f7a | 1,450 | cpp | C++ | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2019-08-05T04:04:34.000Z | 2021-11-15T11:03:39.000Z | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2020-12-09T03:40:28.000Z | 2021-03-17T13:03:50.000Z | pawno/include/YSI 2.0/Source/Utils.cpp | gebo96/samp-gamemode | b54b1961d13ce1d21e37f8b63f00c809c76c34e2 | [
"blessing"
] | 2 | 2020-10-31T19:01:00.000Z | 2021-08-14T23:09:51.000Z | /*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the YSI 2.0 SA:MP plugin.
*
* The Initial Developer of the Original Code is Alex "Y_Less" Cole.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Peter Beverloo
* Marcus Bauer
*/
#include "utils.h"
bool IsPointInRange(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < (float)(distance * distance));
}
bool IsPointInRangeSq(float x1, float y1, float z1, float x2, float y2, float z2, float distance)
{
return (GetRangeSquared(x1, y1, z1, x2, y2, z2) < distance);
}
float GetRangeSquared(float x1, float y1, float z1, float x2, float y2, float z2)
{
x1 -= x2;
y1 -= y2;
z1 -= z2;
return ((float)((float)(x1 * x1) + (float)(y1 * y1) + (float)(z1 * z1)));
}
| 32.954545 | 98 | 0.658621 | gebo96 |
ff775d6947292d8ed8448c5cacd7b351f45b67e5 | 2,911 | cpp | C++ | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 1 | 2015-09-24T17:42:49.000Z | 2015-09-24T17:42:49.000Z | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 3 | 2015-04-16T16:18:32.000Z | 2019-01-17T11:57:19.000Z | src/procx.cpp | michalwidera/jeton | 587665ad904f3dd4dea709a4f4e43b3b5d34a67d | [
"MIT"
] | 2 | 2016-09-02T16:08:44.000Z | 2019-01-16T22:51:57.000Z | #include "procx.h"
#include <assert.h>
ProcessClass::ProcessClass(void)
{
State = STATE_ON;
RodzajWej = '.';
RodzajWyj = '.';
PrevProcess = NULL;
NextProcess = NULL;
}
void ProcessClass::LocalDestructor(void)
{
if(NextProcess != NULL)
{
NextProcess->LocalDestructor();
delete NextProcess;
NextProcess = NULL;
}
}
ProcessClass::~ProcessClass(void)
{
LocalDestructor();
}
int ProcessClass::Init(int, char *[])
{
SygError("To nie powinno być wywoływane");
return RESULT_OFF;
}
int ProcessClass::Work(int, Byte *, int)
{
SygError("To nie powinno być wywoływane");
return 0;
}
ProcessClass * ProcessClass::FindUnusedPointer(void)
{
ProcessClass * tmp;
tmp = NULL;
if(NextProcess != NULL)
{
tmp = NextProcess->FindUnusedPointer();
}
else
{
if(RodzajWyj == 'M' || RodzajWyj == 'B')
{
tmp = this;
}
}
return tmp;
}
/* Podłącza w wolne miejsce wskaźnik następnego procesu. Wartość zwracana:
1 - OK, 0 - błąd */
int ProcessClass::ConnectPointer(ProcessClass * proc)
{
int status;
status = 0;
if(NextProcess == NULL)
{
NextProcess = proc;
proc->PrevProcess = this;
status = 1;
}
else
{
SygError("Proces twierdził, że ma miejsce na podłączenie następnego?");
}
return status;
}
/* Sprawdza, czy do aktualnego obiektu można podłączyć następny obiekt.
Dozwolone są tylko połączenia "B->M" i "M->B". Wartość zwrotna: 1 - typy
są zgodne, 0 - typy są niezgodne, co zabrania tworzenia takiego połączenia */
int ProcessClass::ZgodnyTyp(ProcessClass *proc)
{
int status;
status = 0;
if(RodzajWyj == 'B')
{
if(proc->RodzajWej == 'M')
{
status = 1;
}
}
else
{
if(RodzajWyj == 'M')
{
if(proc->RodzajWej == 'B')
{
status = 1;
}
}
}
return status;
}
/* Funkcja sprawdza, czy podany proces może pracować jako proces wejściowy.
Wartość zwrotna: 1 - tak, 0 - nie */
int ProcessClass::ProcesWejsciowy(void)
{
int status;
status = 0;
if(RodzajWej == '-')
{
status = 1;
}
return status;
}
/* Zmienia stan obiektu na podany. Jeśli to jest zmiana na STATE_OFF,
to od razu powiadamia sąsiadów z obu stron. */
void ProcessClass::ZmienStan(int nowy, int kier)
{
assert(nowy == STATE_OFF || nowy == STATE_EOF);
assert(kier == KIER_PROSTO || kier == KIER_WSTECZ || kier == KIER_INNY);
if(nowy == STATE_OFF)
{
if(State != nowy)
{
State = nowy;
if(kier != KIER_WSTECZ)
{
if(NextProcess != NULL)
{
NextProcess->Work(SAND_OFF, NULL, KIER_PROSTO);
}
}
}
}
else
{
State = nowy;
}
}
/* Tworzenie nowych wątków dla obsługi systemu i budzenie ich.
Wartość zwrotna: 1 - OK (udało się pomyślnie utworzyć nowe wątki),
0 - błąd (możemy kończyć pracę systemu, bo się nie udał przydział wątków */
int ProcessClass::Rozszczepianie(void)
{
int status;
status = 1; /* Tak ogólnie niczego nie trzeba rozszczepiać */
if(NextProcess != NULL)
{
status = NextProcess->Rozszczepianie();
}
return status;
}
| 18.424051 | 77 | 0.665751 | michalwidera |
ff7778c52ada84ac5349b0b126d952eb2d91777b | 535 | cpp | C++ | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 136 | 2018-10-04T17:21:52.000Z | 2022-03-19T11:00:52.000Z | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 1 | 2019-02-05T02:32:57.000Z | 2019-02-05T02:32:57.000Z | src/componentMask.cpp | taurheim/NomadECS | 0546833bf18d261cd7eb764279da1d17ce80954e | [
"MIT"
] | 23 | 2018-10-05T15:17:56.000Z | 2022-03-09T02:05:49.000Z | #include "componentMask.h"
#include "nomad.h"
namespace nomad {
bool ComponentMask::isNewMatch(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return matches(systemMask) && !oldMask.matches(systemMask);
}
bool ComponentMask::isNoLongerMatched(nomad::ComponentMask oldMask, nomad::ComponentMask systemMask) {
return oldMask.matches(systemMask) && !matches(systemMask);
}
bool ComponentMask::matches(nomad::ComponentMask systemMask) { return ((mask & systemMask.mask) == systemMask.mask); }
} // namespace nomad
| 35.666667 | 118 | 0.771963 | taurheim |
ff7c9635fa8d65737a8da4b201f35871c604abe3 | 8,050 | cpp | C++ | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 16 | 2019-05-23T08:10:39.000Z | 2021-12-21T11:20:37.000Z | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | null | null | null | test/qupzilla-master/src/lib/webengine/webscrollbarmanager.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 2 | 2019-05-23T18:37:43.000Z | 2021-08-24T21:29:40.000Z | /* ============================================================
* QupZilla - Qt web browser
* Copyright (C) 2016-2017 David Rosca <[email protected]>
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "webscrollbarmanager.h"
#include "webscrollbar.h"
#include "webview.h"
#include "webpage.h"
#include "mainapplication.h"
#include "scripts.h"
#include "settings.h"
#include <QPointer>
#include <QPaintEvent>
#include <QWebEngineProfile>
#include <QWebEngineScriptCollection>
#include <QStyle>
#include <QStyleOption>
Q_GLOBAL_STATIC(WebScrollBarManager, qz_web_scrollbar_manager)
class WebScrollBarCornerWidget : public QWidget
{
public:
explicit WebScrollBarCornerWidget(WebView *view)
: QWidget()
, m_view(view)
{
setAutoFillBackground(true);
}
void updateVisibility(bool visible, int thickness)
{
if (visible) {
setParent(m_view->overlayWidget());
resize(thickness, thickness);
move(m_view->width() - width(), m_view->height() - height());
show();
} else {
hide();
}
}
private:
void paintEvent(QPaintEvent *ev) override
{
Q_UNUSED(ev)
QStyleOption option;
option.initFrom(this);
option.rect = rect();
QPainter p(this);
if (mApp->styleName() == QL1S("breeze")) {
p.fillRect(ev->rect(), option.palette.background());
} else {
style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
}
}
WebView *m_view;
};
struct ScrollBarData {
~ScrollBarData() {
delete vscrollbar;
delete hscrollbar;
delete corner;
}
WebScrollBar *vscrollbar;
WebScrollBar *hscrollbar;
bool vscrollbarVisible = false;
bool hscrollbarVisible = false;
WebScrollBarCornerWidget *corner;
};
WebScrollBarManager::WebScrollBarManager(QObject *parent)
: QObject(parent)
{
m_scrollbarJs = QL1S("(function() {"
"var head = document.getElementsByTagName('head')[0];"
"if (!head) return;"
"var css = document.createElement('style');"
"css.setAttribute('type', 'text/css');"
"var size = %1 / window.devicePixelRatio + 'px';"
"css.appendChild(document.createTextNode('"
" body::-webkit-scrollbar{width:'+size+';height:'+size+';}"
"'));"
"head.appendChild(css);"
"})()");
loadSettings();
}
void WebScrollBarManager::loadSettings()
{
m_enabled = Settings().value(QSL("Web-Browser-Settings/UseNativeScrollbars"), false).toBool();
if (!m_enabled) {
for (WebView *view : m_scrollbars.keys()) {
removeWebView(view);
}
}
}
void WebScrollBarManager::addWebView(WebView *view)
{
if (!m_enabled) {
return;
}
delete m_scrollbars.value(view);
ScrollBarData *data = new ScrollBarData;
data->vscrollbar = new WebScrollBar(Qt::Vertical, view);
data->hscrollbar = new WebScrollBar(Qt::Horizontal, view);
data->corner = new WebScrollBarCornerWidget(view);
m_scrollbars[view] = data;
const int thickness = data->vscrollbar->thickness();
auto updateValues = [=]() {
const QSize viewport = viewportSize(view, thickness);
data->vscrollbar->updateValues(viewport);
data->vscrollbar->setVisible(data->vscrollbarVisible);
data->hscrollbar->updateValues(viewport);
data->hscrollbar->setVisible(data->hscrollbarVisible);
data->corner->updateVisibility(data->vscrollbarVisible && data->hscrollbarVisible, thickness);
};
connect(view, &WebView::viewportResized, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::scrollPositionChanged, data->vscrollbar, updateValues);
connect(view->page(), &WebPage::contentsSizeChanged, data->vscrollbar, [=]() {
const QString source = QL1S("var out = {"
"vertical: document.documentElement && window.innerWidth > document.documentElement.clientWidth,"
"horizontal: document.documentElement && window.innerHeight > document.documentElement.clientHeight"
"};out;");
QPointer<WebView> p(view);
view->page()->runJavaScript(source, WebPage::SafeJsWorld, [=](const QVariant &res) {
if (!p || !m_scrollbars.contains(view)) {
return;
}
const QVariantMap map = res.toMap();
data->vscrollbarVisible = map.value(QSL("vertical")).toBool();
data->hscrollbarVisible = map.value(QSL("horizontal")).toBool();
updateValues();
});
});
connect(view, &WebView::zoomLevelChanged, data->vscrollbar, [=]() {
view->page()->runJavaScript(m_scrollbarJs.arg(thickness));
});
if (m_scrollbars.size() == 1) {
createUserScript(thickness);
}
}
void WebScrollBarManager::removeWebView(WebView *view)
{
if (!m_scrollbars.contains(view)) {
return;
}
if (m_scrollbars.size() == 1) {
removeUserScript();
}
delete m_scrollbars.take(view);
}
QScrollBar *WebScrollBarManager::scrollBar(Qt::Orientation orientation, WebView *view) const
{
ScrollBarData *d = m_scrollbars.value(view);
if (!d) {
return nullptr;
}
return orientation == Qt::Vertical ? d->vscrollbar : d->hscrollbar;
}
WebScrollBarManager *WebScrollBarManager::instance()
{
return qz_web_scrollbar_manager();
}
void WebScrollBarManager::createUserScript(int thickness)
{
QWebEngineScript script;
script.setName(QSL("_qupzilla_scrollbar"));
script.setInjectionPoint(QWebEngineScript::DocumentReady);
script.setWorldId(WebPage::SafeJsWorld);
script.setSourceCode(m_scrollbarJs.arg(thickness));
mApp->webProfile()->scripts()->insert(script);
}
void WebScrollBarManager::removeUserScript()
{
QWebEngineScript script = mApp->webProfile()->scripts()->findScript(QSL("_qupzilla_scrollbar"));
mApp->webProfile()->scripts()->remove(script);
}
QSize WebScrollBarManager::viewportSize(WebView *view, int thickness) const
{
QSize viewport = view->size();
thickness /= view->devicePixelRatioF();
ScrollBarData *data = m_scrollbars.value(view);
Q_ASSERT(data);
if (data->vscrollbarVisible) {
viewport.setWidth(viewport.width() - thickness);
}
if (data->hscrollbarVisible) {
viewport.setHeight(viewport.height() - thickness);
}
#if 0
const QSize content = view->page()->contentsSize().toSize();
// Check both axis
if (content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
// Check again against adjusted size
if (viewport.height() == view->height() && content.width() - viewport.width() > 0) {
viewport.setHeight(viewport.height() - thickness);
}
if (viewport.width() == view->width() && content.height() - viewport.height() > 0) {
viewport.setWidth(viewport.width() - thickness);
}
#endif
return viewport;
}
| 31.081081 | 136 | 0.62087 | JamesMBallard |
ff839702e524b288f5c640431e1a0282882b616c | 8,100 | cpp | C++ | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 57 | 2018-04-18T11:06:31.000Z | 2022-01-26T22:15:01.000Z | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 24 | 2018-04-20T04:24:39.000Z | 2018-11-13T06:11:37.000Z | project/src/treewalk_interpreter/scanner.cpp | Jeff-Mott-OR/cpplox | 6b2b771c50fd3d0121283d1f2e54860e1d263bca | [
"MIT"
] | 6 | 2018-04-19T03:25:35.000Z | 2020-02-20T03:22:52.000Z | #include "scanner.hpp"
#include <cctype>
#include <algorithm>
#include <array>
#include <iterator>
#include <utility>
#include <boost/lexical_cast.hpp>
using std::isalnum;
using std::isalpha;
using std::isdigit;
using std::array;
using std::back_inserter;
using std::copy_if;
using std::find_if;
using std::move;
using std::pair;
using std::string;
using std::to_string;
using boost::lexical_cast;
// Allow the internal linkage section to access names
using namespace motts::lox;
// Not exported (internal linkage)
namespace {
const array<pair<const char*, Token_type>, 18> reserved_words {{
{"and", Token_type::and_},
{"class", Token_type::class_},
{"else", Token_type::else_},
{"false", Token_type::false_},
{"for", Token_type::for_},
{"fun", Token_type::fun_},
{"if", Token_type::if_},
{"nil", Token_type::nil_},
{"or", Token_type::or_},
{"print", Token_type::print_},
{"return", Token_type::return_},
{"super", Token_type::super_},
{"this", Token_type::this_},
{"true", Token_type::true_},
{"var", Token_type::var_},
{"while", Token_type::while_},
{"break", Token_type::break_},
{"continue", Token_type::continue_}
}};
}
// Exported (external linkage)
namespace motts { namespace lox {
Token_iterator::Token_iterator(const string& source) :
source_ {&source},
token_begin_ {source_->cbegin()},
token_end_ {source_->cbegin()},
token_ {consume_token()}
{}
Token_iterator::Token_iterator() = default;
Token_iterator& Token_iterator::operator++() {
if (token_begin_ != source_->end()) {
// We are at the beginning of the next lexeme
token_begin_ = token_end_;
token_ = consume_token();
} else {
source_ = nullptr;
}
return *this;
}
Token_iterator Token_iterator::operator++(int) {
Token_iterator copy {*this};
operator++();
return copy;
}
bool Token_iterator::operator==(const Token_iterator& rhs) const {
return (
(!source_ && !rhs.source_) ||
(source_ == rhs.source_ && token_begin_ == rhs.token_begin_)
);
}
bool Token_iterator::operator!=(const Token_iterator& rhs) const {
return !(*this == rhs);
}
const Token& Token_iterator::operator*() const & {
return token_;
}
Token&& Token_iterator::operator*() && {
return move(token_);
}
const Token* Token_iterator::operator->() const {
return &token_;
}
Token Token_iterator::make_token(Token_type token_type) {
return Token{token_type, string{token_begin_, token_end_}, {}, line_};
}
Token Token_iterator::make_token(Token_type token_type, Literal&& literal_value) {
return Token{token_type, string{token_begin_, token_end_}, move(literal_value), line_};
}
bool Token_iterator::advance_if_match(char expected) {
if (token_end_ != source_->end() && *token_end_ == expected) {
++token_end_;
return true;
}
return false;
}
Token Token_iterator::consume_string() {
while (token_end_ != source_->end() && *token_end_ != '"') {
if (*token_end_ == '\n') {
++line_;
}
++token_end_;
}
// Check unterminated string
if (token_end_ == source_->end()) {
throw Scanner_error{"Unterminated string.", line_};
}
// The closing "
++token_end_;
// Trim surrounding quotes and normalize line endings for literal value
string literal_value;
copy_if(token_begin_ + 1, token_end_ - 1, back_inserter(literal_value), [] (auto c) {
return c != '\r';
});
return make_token(Token_type::string, Literal{move(literal_value)});
}
Token Token_iterator::consume_number() {
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
// Look for a fractional part
if (
token_end_ != source_->end() && *token_end_ == '.' &&
(token_end_ + 1) != source_->end() && isdigit(*(token_end_ + 1))
) {
// Consume the "." and one digit
token_end_ += 2;
while (token_end_ != source_->end() && isdigit(*token_end_)) {
++token_end_;
}
}
return make_token(Token_type::number, Literal{lexical_cast<double>(string{token_begin_, token_end_})});
}
Token Token_iterator::consume_identifier() {
while (token_end_ != source_->end() && (isalnum(*token_end_) || *token_end_ == '_')) {
++token_end_;
}
const string identifier {token_begin_, token_end_};
const auto found = find_if(reserved_words.cbegin(), reserved_words.cend(), [&] (const auto& pair) {
return pair.first == identifier;
});
return make_token(found != reserved_words.cend() ? found->second : Token_type::identifier);
}
Token Token_iterator::consume_token() {
// Loop because we might skip some tokens
for (; token_end_ != source_->end(); token_begin_ = token_end_) {
auto c = *token_end_;
++token_end_;
switch (c) {
// Single char tokens
case '(': return make_token(Token_type::left_paren);
case ')': return make_token(Token_type::right_paren);
case '{': return make_token(Token_type::left_brace);
case '}': return make_token(Token_type::right_brace);
case ',': return make_token(Token_type::comma);
case '.': return make_token(Token_type::dot);
case '-': return make_token(Token_type::minus);
case '+': return make_token(Token_type::plus);
case ';': return make_token(Token_type::semicolon);
case '*': return make_token(Token_type::star);
// One or two char tokens
case '/':
if (advance_if_match('/')) {
// A comment goes until the end of the line
while (token_end_ != source_->end() && *token_end_ != '\n') {
++token_end_;
}
continue;
} else {
return make_token(Token_type::slash);
}
case '!':
return make_token(advance_if_match('=') ? Token_type::bang_equal : Token_type::bang);
case '=':
return make_token(advance_if_match('=') ? Token_type::equal_equal : Token_type::equal);
case '>':
return make_token(advance_if_match('=') ? Token_type::greater_equal : Token_type::greater);
case '<':
return make_token(advance_if_match('=') ? Token_type::less_equal : Token_type::less);
// Whitespace
case '\n':
++line_;
continue;
case ' ':
case '\r':
case '\t':
continue;
// Literals and Keywords
case '"': return consume_string();
default:
if (isdigit(c)) {
return consume_number();
} else if (isalpha(c) || c == '_') {
return consume_identifier();
} else {
throw Scanner_error{"Unexpected character.", line_};
}
}
}
// The final token is always EOF
return Token{Token_type::eof, "", {}, line_};
}
Scanner_error::Scanner_error(const string& what, int line) :
Runtime_error {"[Line " + to_string(line) + "] Error: " + what}
{}
}}
| 31.395349 | 111 | 0.534815 | Jeff-Mott-OR |
ff8569555ece5c7cf7ea227a9e981e6cfda0efd4 | 4,915 | hpp | C++ | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | ndn-cxx/encoding/estimator.hpp | AsteriosPar/ndn-cxx | 778ad714f0d6dff8f5e75bdfea2658002b95bbd1 | [
"OpenSSL"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2022 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx 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 3 of the License, or (at your option) any later version.
*
* ndn-cxx 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 copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_CXX_ENCODING_ESTIMATOR_HPP
#define NDN_CXX_ENCODING_ESTIMATOR_HPP
#include "ndn-cxx/encoding/block.hpp"
namespace ndn {
namespace encoding {
/**
* @brief Helper class to estimate size of TLV encoding.
*
* The interface of this class (mostly) matches that of the Encoder class.
*
* @sa Encoder
*/
class Estimator : noncopyable
{
public: // common interface between Encoder and Estimator
/**
* @brief Prepend a sequence of bytes
*/
constexpr size_t
prependBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Append a sequence of bytes
*/
constexpr size_t
appendBytes(span<const uint8_t> bytes) const noexcept
{
return bytes.size();
}
/**
* @brief Prepend a single byte
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Append a single byte
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByte(uint8_t) const noexcept
{
return 1;
}
/**
* @brief Prepend a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use prependBytes()")]]
constexpr size_t
prependByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Append a byte array @p array of length @p length
* @deprecated
*/
[[deprecated("use appendBytes()")]]
constexpr size_t
appendByteArray(const uint8_t*, size_t length) const noexcept
{
return length;
}
/**
* @brief Prepend bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
prependRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Append bytes from the range [@p first, @p last)
*/
template<class Iterator>
constexpr size_t
appendRange(Iterator first, Iterator last) const noexcept
{
return std::distance(first, last);
}
/**
* @brief Prepend @p n in VarNumber encoding
*/
constexpr size_t
prependVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Append @p n in VarNumber encoding
*/
constexpr size_t
appendVarNumber(uint64_t n) const noexcept
{
return tlv::sizeOfVarNumber(n);
}
/**
* @brief Prepend @p n in NonNegativeInteger encoding
*/
constexpr size_t
prependNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Append @p n in NonNegativeInteger encoding
*/
constexpr size_t
appendNonNegativeInteger(uint64_t n) const noexcept
{
return tlv::sizeOfNonNegativeInteger(n);
}
/**
* @brief Prepend TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated("use encoding::prependBinaryBlock()")]]
constexpr size_t
prependByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Append TLV block of type @p type and value from buffer @p array of size @p arraySize
* @deprecated
*/
[[deprecated]]
constexpr size_t
appendByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) const noexcept
{
return tlv::sizeOfVarNumber(type) + tlv::sizeOfVarNumber(arraySize) + arraySize;
}
/**
* @brief Prepend TLV block @p block
* @deprecated
*/
[[deprecated("use encoding::prependBlock()")]]
size_t
prependBlock(const Block& block) const;
/**
* @brief Append TLV block @p block
* @deprecated
*/
[[deprecated]]
size_t
appendBlock(const Block& block) const;
};
} // namespace encoding
} // namespace ndn
#endif // NDN_CXX_ENCODING_ESTIMATOR_HPP
| 24.452736 | 97 | 0.687284 | AsteriosPar |
ff86cc6e6d5cde82a5369865a56a3e333ea45ff8 | 5,788 | cpp | C++ | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 1 | 2021-02-28T19:37:04.000Z | 2021-02-28T19:37:04.000Z | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | 1 | 2016-05-06T05:07:37.000Z | 2016-05-09T23:40:50.000Z | tests/garbage_collection/gc_delete_test_coop.cpp | saurabhkadekodi/peloton-p3 | e0d84cdf59c0724850ad2d6b187fdb2ef1730369 | [
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// Peloton
//
// gc_delete_test_coop.cpp
//
// Identification: tests/executor/gc_delete_test_coop.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <atomic>
#include "harness.h"
#include "backend/catalog/schema.h"
#include "backend/common/value_factory.h"
#include "backend/common/types.h"
#include "backend/common/pool.h"
#include "backend/executor/executor_context.h"
#include "backend/executor/delete_executor.h"
#include "backend/executor/insert_executor.h"
#include "backend/executor/seq_scan_executor.h"
#include "backend/executor/update_executor.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/expression/expression_util.h"
#include "backend/expression/tuple_value_expression.h"
#include "backend/expression/comparison_expression.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/tile.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/table_factory.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "executor/executor_tests_util.h"
#include "executor/mock_executor.h"
#include "backend/planner/delete_plan.h"
#include "backend/planner/insert_plan.h"
#include "backend/planner/seq_scan_plan.h"
#include "backend/planner/update_plan.h"
using ::testing::NotNull;
using ::testing::Return;
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// GC Tests
//===--------------------------------------------------------------------===//
class GCDeleteTestCoop : public PelotonTest {};
std::atomic<int> tuple_id;
std::atomic<int> delete_tuple_id;
enum GCType type = GC_TYPE_COOPERATIVE;
void InsertTuple(storage::DataTable *table, VarlenPool *pool) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
for (oid_t tuple_itr = 0; tuple_itr < 10; tuple_itr++) {
auto tuple = ExecutorTestsUtil::GetTuple(table, ++tuple_id, pool);
planner::InsertPlan node(table, std::move(tuple));
executor::InsertExecutor executor(&node, context.get());
executor.Execute();
}
txn_manager.CommitTransaction();
}
void DeleteTuple(storage::DataTable *table) {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
std::vector<storage::Tuple *> tuples;
// Delete
planner::DeletePlan delete_node(table, false);
executor::DeleteExecutor delete_executor(&delete_node, context.get());
// Predicate
// WHERE ATTR_0 > 60
expression::TupleValueExpression *tup_val_exp =
new expression::TupleValueExpression(VALUE_TYPE_INTEGER, 0, 0);
expression::ConstantValueExpression *const_val_exp =
new expression::ConstantValueExpression(
ValueFactory::GetIntegerValue(60));
auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
EXPRESSION_TYPE_COMPARE_GREATERTHAN, tup_val_exp, const_val_exp);
// Seq scan
std::vector<oid_t> column_ids = {0};
std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
new planner::SeqScanPlan(table, predicate, column_ids));
executor::SeqScanExecutor seq_scan_executor(seq_scan_node.get(),
context.get());
// Parent-Child relationship
delete_node.AddChild(std::move(seq_scan_node));
delete_executor.AddChild(&seq_scan_executor);
EXPECT_TRUE(delete_executor.Init());
EXPECT_TRUE(delete_executor.Execute());
// EXPECT_TRUE(delete_executor.Execute());
txn_manager.CommitTransaction();
}
TEST_F(GCDeleteTestCoop, DeleteTest) {
peloton::gc::GCManagerFactory::Configure(type);
peloton::gc::GCManagerFactory::GetInstance().StartGC();
auto *table = ExecutorTestsUtil::CreateTable(1024);
auto &manager = catalog::Manager::GetInstance();
storage::Database db(DEFAULT_DB_ID);
manager.AddDatabase(&db);
db.AddTable(table);
// We are going to insert a tile group into a table in this test
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
auto before_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
LaunchParallelTest(1, InsertTuple, table, testing_pool);
auto after_insert = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_GT(after_insert, before_insert);
LaunchParallelTest(1, DeleteTuple, table);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
LOG_INFO("new transaction");
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
// Seq scan
std::vector<oid_t> column_ids = {0};
planner::SeqScanPlan seq_scan_node(table, nullptr, column_ids);
executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());
EXPECT_TRUE(seq_scan_executor.Init());
auto tuple_cnt = 0;
while (seq_scan_executor.Execute()) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
seq_scan_executor.GetOutput());
tuple_cnt += result_logical_tile->GetTupleCount();
}
txn_manager.CommitTransaction();
EXPECT_EQ(tuple_cnt, 6);
auto after_delete = catalog::Manager::GetInstance().GetMemoryFootprint();
EXPECT_EQ(after_insert, after_delete);
tuple_id = 0;
}
} // namespace test
} // namespace peloton
| 34.047059 | 80 | 0.708189 | saurabhkadekodi |
ff8981a48d12dfee9b4d9d2cd76e1659de010af6 | 493 | hpp | C++ | source/Engine/GameObject.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | 8 | 2018-06-27T00:34:11.000Z | 2018-09-07T06:56:20.000Z | source/Engine/GameObject.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | null | null | null | source/Engine/GameObject.hpp | rincew1nd/Minesweeper-Switch | 6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467 | [
"MIT"
] | 2 | 2018-06-28T03:02:07.000Z | 2019-01-26T06:02:17.000Z | #pragma once
#include "Input.hpp"
#include <switch.h>
#include "SDL2/SDL.h"
#include <vector>
#include <functional>
class GameObject
{
public:
GameObject(int, int, int, int);
void SetAction(std::function<void()>);
void Press() { if (_onPress != nullptr) _onPress(); };
bool Hovered(TouchInfo*);
void Move(int, int);
virtual ~GameObject() {};
protected:
SDL_Rect* _rect;
private:
std::function<void()> _onPress;
}; | 20.541667 | 62 | 0.592292 | rincew1nd |
ff89b78858cd90644eef2fcf23f7ed0c4eab2411 | 4,870 | cpp | C++ | Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | 2 | 2022-03-25T17:37:45.000Z | 2022-03-26T02:22:22.000Z | Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | null | null | null | Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp | jagt/KRG | ba20cd8798997b0450491b0cc04dc817c4a4bc76 | [
"MIT"
] | null | null | null | #include "Animation_RuntimeGraphNode_Ragdoll.h"
#include "Engine/Animation/TaskSystem/Tasks/Animation_Task_Ragdoll.h"
#include "Engine/Animation/TaskSystem/Tasks/Animation_Task_DefaultPose.h"
#include "Engine/Physics/PhysicsRagdoll.h"
#include "Engine/Physics/PhysicsScene.h"
#include "System/Core/Logging/Log.h"
//-------------------------------------------------------------------------
namespace KRG::Animation::GraphNodes
{
void PoweredRagdollNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const
{
auto pNode = CreateNode<PoweredRagdollNode>( nodePtrs, options );
SetOptionalNodePtrFromIndex( nodePtrs, m_physicsBlendWeightNodeIdx, pNode->m_pBlendWeightValueNode );
PassthroughNode::Settings::InstantiateNode( nodePtrs, pDataSet, GraphNode::Settings::InitOptions::OnlySetPointers );
pNode->m_pRagdollDefinition = pDataSet->GetResource<Physics::RagdollDefinition>( m_dataSlotIdx );
}
bool PoweredRagdollNode::IsValid() const
{
return PassthroughNode::IsValid() && m_pRagdollDefinition != nullptr && m_pRagdoll != nullptr;
}
void PoweredRagdollNode::InitializeInternal( GraphContext& context, SyncTrackTime const& initialTime )
{
KRG_ASSERT( context.IsValid() );
PassthroughNode::InitializeInternal( context, initialTime );
// Create ragdoll
if ( m_pRagdollDefinition != nullptr && context.m_pPhysicsScene != nullptr )
{
auto pNodeSettings = GetSettings<PoweredRagdollNode>();
m_pRagdoll = context.m_pPhysicsScene->CreateRagdoll( m_pRagdollDefinition, pNodeSettings->m_profileID, context.m_graphUserID );
m_pRagdoll->SetPoseFollowingEnabled( true );
m_pRagdoll->SetGravityEnabled( pNodeSettings->m_isGravityEnabled );
}
//-------------------------------------------------------------------------
if ( m_pBlendWeightValueNode != nullptr )
{
m_pBlendWeightValueNode->Initialize( context );
}
m_isFirstUpdate = true;
}
void PoweredRagdollNode::ShutdownInternal( GraphContext& context )
{
KRG_ASSERT( context.IsValid() );
if ( m_pBlendWeightValueNode != nullptr )
{
m_pBlendWeightValueNode->Shutdown( context );
}
//-------------------------------------------------------------------------
// Destroy the ragdoll
if ( m_pRagdoll != nullptr )
{
m_pRagdoll->RemoveFromScene();
KRG::Delete( m_pRagdoll );
}
PassthroughNode::ShutdownInternal( context );
}
GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context )
{
GraphPoseNodeResult result;
if ( IsValid() )
{
result = PassthroughNode::Update( context );
result = RegisterRagdollTasks( context, result );
}
else
{
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose );
}
return result;
}
GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context, SyncTrackTimeRange const& updateRange )
{
GraphPoseNodeResult result;
if ( IsValid() )
{
result = PassthroughNode::Update( context, updateRange );
result = RegisterRagdollTasks( context, result );
}
else
{
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose );
}
return result;
}
GraphPoseNodeResult PoweredRagdollNode::RegisterRagdollTasks( GraphContext& context, GraphPoseNodeResult const& childResult )
{
KRG_ASSERT( IsValid() );
GraphPoseNodeResult result = childResult;
//-------------------------------------------------------------------------
Tasks::RagdollSetPoseTask::InitOption const initOptions = m_isFirstUpdate ? Tasks::RagdollSetPoseTask::InitializeBodies : Tasks::RagdollSetPoseTask::DoNothing;
TaskIndex const setPoseTaskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollSetPoseTask>( m_pRagdoll, GetNodeIndex(), childResult.m_taskIdx, initOptions );
m_isFirstUpdate = false;
//-------------------------------------------------------------------------
float const physicsWeight = ( m_pBlendWeightValueNode != nullptr ) ? m_pBlendWeightValueNode->GetValue<float>( context ) : GetSettings<PoweredRagdollNode>()->m_physicsBlendWeight;
result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollGetPoseTask>( m_pRagdoll, GetNodeIndex(), setPoseTaskIdx, physicsWeight );
return result;
}
} | 39.593496 | 187 | 0.625667 | jagt |
ff8d44093357788ed0f52884afcd51ab01a92478 | 1,270 | cpp | C++ | modules/moduleTest/testCommon.cpp | helinux/FFdynamic | d65959641fd0f8e69e1d799b8b439c8ad2793600 | [
"MIT"
] | 299 | 2018-10-21T03:28:53.000Z | 2022-03-20T12:04:13.000Z | modules/moduleTest/testCommon.cpp | helinux/FFdynamic | d65959641fd0f8e69e1d799b8b439c8ad2793600 | [
"MIT"
] | 31 | 2018-11-13T12:46:15.000Z | 2022-01-19T19:30:16.000Z | modules/moduleTest/testCommon.cpp | helinux/FFdynamic | d65959641fd0f8e69e1d799b8b439c8ad2793600 | [
"MIT"
] | 68 | 2018-11-02T14:05:00.000Z | 2022-03-01T19:16:29.000Z | #include "testCommon.h"
using namespace ff_dynamic;
namespace test_common {
std::atomic<bool> g_bExit = ATOMIC_VAR_INIT(false);
std::atomic<int> g_bInterruptCount = ATOMIC_VAR_INIT(0);
void sigIntHandle(int sig) {
g_bExit = true;
LOG(INFO) << "sig " << sig << " captured. count" << g_bInterruptCount;
if (++g_bInterruptCount >= 3) {
LOG(INFO) << "exit program";
exit(1);
}
}
int testInit(const string & logtag) {
google::InitGoogleLogging(logtag.c_str());
google::InstallFailureSignalHandler();
FLAGS_stderrthreshold = 0;
FLAGS_logtostderr = 1;
auto & sigHandle = GlobalSignalHandle::getInstance();
sigHandle.registe(SIGINT, sigIntHandle);
av_log_set_callback([] (void *ptr, int level, const char *fmt, va_list vl) {
if (level > AV_LOG_WARNING)
return ;
char message[8192];
const char *ffmpegModule = nullptr;
if (ptr) {
AVClass *avc = *(AVClass**) ptr;
if (avc->item_name)
ffmpegModule = avc->item_name(ptr);
}
vsnprintf(message, sizeof(message), fmt, vl);
LOG(WARNING) << "[FFMPEG][" << (ffmpegModule ? ffmpegModule : "") << "]" << message;
});
return 0;
}
} // namespace test_common
| 28.222222 | 92 | 0.611024 | helinux |
ff8dfd03a24507754cb34b9f3f9288977bab48f3 | 14,769 | cpp | C++ | src/splinesonic/sim/Test.cpp | Ryp/Reaper | ccaef540013db7e8bf873db6e597e9036184d100 | [
"MIT"
] | 11 | 2016-11-07T07:47:46.000Z | 2018-07-19T16:04:45.000Z | src/splinesonic/sim/Test.cpp | Ryp/Reaper | ccaef540013db7e8bf873db6e597e9036184d100 | [
"MIT"
] | null | null | null | src/splinesonic/sim/Test.cpp | Ryp/Reaper | ccaef540013db7e8bf873db6e597e9036184d100 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// Reaper
///
/// Copyright (c) 2015-2022 Thibault Schueller
/// This file is distributed under the MIT License
////////////////////////////////////////////////////////////////////////////////
#include "Test.h"
#if defined(REAPER_USE_BULLET_PHYSICS)
# include <BulletCollision/CollisionShapes/btBoxShape.h>
# include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h>
# include <BulletCollision/CollisionShapes/btTriangleMesh.h>
# include <BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h>
# include <btBulletDynamicsCommon.h>
#endif
#include "mesh/Mesh.h"
#include "core/Assert.h"
#include "profiling/Scope.h"
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/projection.hpp>
#include <glm/vec3.hpp>
#include <bit>
namespace SplineSonic
{
namespace
{
#if defined(REAPER_USE_BULLET_PHYSICS)
inline glm::vec3 toGlm(btVector3 const& vec) { return glm::vec3(vec.getX(), vec.getY(), vec.getZ()); }
inline glm::quat toGlm(btQuaternion const& quat)
{
return glm::quat(quat.getW(), quat.getX(), quat.getY(), quat.getZ());
}
inline glm::fmat4x3 toGlm(const btTransform& transform)
{
const btMatrix3x3 basis = transform.getBasis();
const glm::fvec3 translation = toGlm(transform.getOrigin());
return glm::fmat4x3(toGlm(basis[0]), toGlm(basis[1]), toGlm(basis[2]), translation);
}
inline btVector3 toBt(glm::vec3 const& vec) { return btVector3(vec.x, vec.y, vec.z); }
inline btMatrix3x3 m33toBt(const glm::fmat3x3& m)
{
return btMatrix3x3(m[0].x, m[1].x, m[2].x, m[0].y, m[1].y, m[2].y, m[0].z, m[1].z, m[2].z);
}
// inline btQuaternion toBt(glm::quat const& quat) { return btQuaternion(quat.w, quat.x, quat.y, quat.z); }
inline btTransform toBt(const glm::fmat4x3& transform)
{
btMatrix3x3 mat = m33toBt(glm::fmat3x3(transform));
btTransform ret = btTransform(mat, toBt(glm::column(transform, 3)));
return ret;
}
static const int SimulationMaxSubStep = 3; // FIXME
glm::fvec3 forward() { return glm::vec3(1.0f, 0.0f, 0.0f); }
glm::fvec3 up() { return glm::vec3(0.0f, 0.0f, 1.0f); }
void pre_tick(PhysicsSim& sim, const ShipInput& input, float /*dt*/)
{
REAPER_PROFILE_SCOPE_FUNC();
btRigidBody* playerRigidBody = sim.players[0];
const glm::fmat4x3 player_transform = toGlm(playerRigidBody->getWorldTransform());
const glm::fvec3 player_position_ws = player_transform[3];
const glm::quat player_orientation = toGlm(playerRigidBody->getWorldTransform().getRotation());
float min_dist_sq = 10000000.f;
const btRigidBody* closest_track_chunk = nullptr;
for (auto track_chunk : sim.static_rigid_bodies)
{
glm::fvec3 delta = player_position_ws - toGlm(track_chunk->getWorldTransform().getOrigin());
float dist_sq = glm::dot(delta, delta);
if (dist_sq < min_dist_sq)
{
min_dist_sq = dist_sq;
closest_track_chunk = track_chunk;
}
}
Assert(closest_track_chunk);
// FIXME const glm::fmat4x3 projected_transform = toGlm(closest_track_chunk->getWorldTransform());
const glm::quat projected_orientation = toGlm(closest_track_chunk->getWorldTransform().getRotation());
glm::vec3 shipUp;
glm::vec3 shipFwd;
shipUp = projected_orientation * up();
shipFwd = player_orientation * forward();
// shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane
// Re-eval ship orientation
// FIXME player_orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp)));
const glm::fvec3 linear_speed = toGlm(playerRigidBody->getLinearVelocity());
// change steer angle
{
// float steerMultiplier = 0.035f;
// float inclinationMax = 2.6f;
// float inclForce = (log(glm::length(linear_speed * 0.5f) + 1.0f) + 0.2f) * input.steer;
// float inclinationRepel = -movement.inclination * 5.0f;
// movement.inclination =
// glm::clamp(movement.inclination + (inclForce + inclinationRepel) * dtSecs, -inclinationMax,
// inclinationMax);
// movement.orientation *= glm::angleAxis(-input.steer * steerMultiplier, up());
}
ShipStats ship_stats;
ship_stats.thrust = 100.f;
ship_stats.braking = 10.f;
// Integrate forces
glm::vec3 forces = {};
forces += -shipUp * 98.331f; // 10x earth gravity
forces += shipFwd * input.throttle * ship_stats.thrust; // Engine thrust
// forces += shipFwd * player.getAcceleration(); // Engine thrust
forces += -glm::proj(linear_speed, shipFwd) * input.brake * ship_stats.braking; // Brakes force
// forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * sim.pHandling; // Handling term
forces += -linear_speed * sim.linear_friction;
forces += -linear_speed * glm::length(linear_speed) * sim.quadratic_friction;
// Progressive repelling force that pushes the ship downwards
// FIXME
// float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp));
// if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f)
// forces += player_orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f);
playerRigidBody->clearForces();
playerRigidBody->applyCentralForce(toBt(forces));
}
/*
{
shipUp = projection.orientation * glm::up();
shipFwd = movement.orientation * glm::forward();
shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane
// Re-eval ship orientation
movement.orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp)));
// change steer angle
steer(dt, movement, factors.getTurnFactor());
// sum all forces
// forces += - shipUp * 98.331f; // 10x earth gravity
forces += -shipUp * 450.0f; // lot of times earth gravity
forces += shipFwd * factors.getThrustFactor() * player->getAcceleration(); // Engine thrust
forces += -glm::proj(movement.speed, shipFwd) * factors.getBrakeFactor() * _pBrakesForce; // Brakes force
forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * _pHandling; // Handling term
forces += -movement.speed * linear_friction; // Linear friction
term forces += -movement.speed * glm::length(movement.speed) * _pQuadFriction; // Quadratic friction
term
// Progressive repelling force that pushes the ship downwards
float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp));
if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f)
forces += movement.orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f);
playerRigidBody->clearForces();
playerRigidBody->applyCentralForce(toBt(forces));
}
*/
void post_tick(PhysicsSim& sim, float /*dt*/)
{
REAPER_PROFILE_SCOPE_FUNC();
btRigidBody* playerRigidBody = sim.players.front(); // FIXME
toGlm(playerRigidBody->getLinearVelocity());
toGlm(playerRigidBody->getOrientation());
}
#endif
} // namespace
PhysicsSim create_sim()
{
PhysicsSim sim = {};
// Physics tweakables
sim.linear_friction = 4.0f;
sim.quadratic_friction = 0.01f;
#if defined(REAPER_USE_BULLET_PHYSICS)
// Boilerplate code for a standard rigidbody simulation
sim.broadphase = new btDbvtBroadphase();
sim.collisionConfiguration = new btDefaultCollisionConfiguration();
sim.dispatcher = new btCollisionDispatcher(sim.collisionConfiguration);
btGImpactCollisionAlgorithm::registerAlgorithm(sim.dispatcher);
sim.solver = new btSequentialImpulseConstraintSolver;
// Putting all of that together
sim.dynamicsWorld =
new btDiscreteDynamicsWorld(sim.dispatcher, sim.broadphase, sim.solver, sim.collisionConfiguration);
#endif
return sim;
}
void destroy_sim(PhysicsSim& sim)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
for (auto player_rigid_body : sim.players)
{
sim.dynamicsWorld->removeRigidBody(player_rigid_body);
delete player_rigid_body->getMotionState();
delete player_rigid_body;
}
for (auto rb : sim.static_rigid_bodies)
{
sim.dynamicsWorld->removeRigidBody(rb);
delete rb->getMotionState();
delete rb;
}
for (auto collision_shape : sim.collision_shapes)
{
delete collision_shape;
}
for (auto vb : sim.vertexArrayInterfaces)
delete vb;
// Delete the rest of the bullet context
delete sim.dynamicsWorld;
delete sim.solver;
delete sim.dispatcher;
delete sim.collisionConfiguration;
delete sim.broadphase;
#else
static_cast<void>(sim);
#endif
}
namespace
{
#if defined(REAPER_USE_BULLET_PHYSICS)
void pre_tick_callback(btDynamicsWorld* world, btScalar dt)
{
PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo());
Assert(sim_ptr);
PhysicsSim& sim = *sim_ptr;
pre_tick(sim, sim.last_input, dt);
}
void post_tick_callback(btDynamicsWorld* world, btScalar dt)
{
PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo());
Assert(sim_ptr);
post_tick(*sim_ptr, dt);
}
#endif
} // namespace
void sim_start(PhysicsSim* sim)
{
REAPER_PROFILE_SCOPE_FUNC();
Assert(sim);
#if defined(REAPER_USE_BULLET_PHYSICS)
sim->dynamicsWorld->setInternalTickCallback(pre_tick_callback, sim, true);
sim->dynamicsWorld->setInternalTickCallback(post_tick_callback, sim, false);
#endif
}
void sim_update(PhysicsSim& sim, const ShipInput& input, float dt)
{
REAPER_PROFILE_SCOPE_FUNC();
sim.last_input = input; // FIXME
#if defined(REAPER_USE_BULLET_PHYSICS)
sim.dynamicsWorld->stepSimulation(dt, SimulationMaxSubStep);
#else
static_cast<void>(sim);
static_cast<void>(dt);
#endif
}
glm::fmat4x3 get_player_transform(PhysicsSim& sim)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
const btRigidBody* playerRigidBody = sim.players.front();
const btMotionState* playerMotionState = playerRigidBody->getMotionState();
btTransform output;
playerMotionState->getWorldTransform(output);
return toGlm(output);
#else
static_cast<void>(sim);
AssertUnreachable();
return glm::fmat4x3(1.f); // FIXME
#endif
}
void sim_register_static_collision_meshes(PhysicsSim& sim, const nonstd::span<Mesh> meshes,
nonstd::span<const glm::fmat4x3> transforms_no_scale,
nonstd::span<const glm::fvec3> scales)
{
// FIXME Assert scale values
#if defined(REAPER_USE_BULLET_PHYSICS)
Assert(meshes.size() == transforms_no_scale.size());
Assert(scales.empty() || scales.size() == transforms_no_scale.size());
for (u32 i = 0; i < meshes.size(); i++)
{
const Mesh& mesh = meshes[i];
// Describe how the mesh is laid out in memory
btIndexedMesh indexedMesh;
indexedMesh.m_numTriangles = mesh.indexes.size() / 3;
indexedMesh.m_triangleIndexBase = reinterpret_cast<const u8*>(mesh.indexes.data());
indexedMesh.m_triangleIndexStride = 3 * sizeof(mesh.indexes[0]);
indexedMesh.m_numVertices = mesh.positions.size();
indexedMesh.m_vertexBase = reinterpret_cast<const u8*>(mesh.positions.data());
indexedMesh.m_vertexStride = sizeof(mesh.positions[0]);
indexedMesh.m_indexType = PHY_INTEGER;
indexedMesh.m_vertexType = PHY_FLOAT;
// Create bullet collision shape based on the mesh described
btTriangleIndexVertexArray* meshInterface = new btTriangleIndexVertexArray();
sim.vertexArrayInterfaces.push_back(meshInterface);
meshInterface->addIndexedMesh(indexedMesh);
btBvhTriangleMeshShape* meshShape = new btBvhTriangleMeshShape(meshInterface, true);
sim.collision_shapes.push_back(meshShape);
const btVector3 scale = scales.empty() ? btVector3(1.f, 1.f, 1.f) : toBt(scales[i]);
btScaledBvhTriangleMeshShape* scaled_mesh_shape = new btScaledBvhTriangleMeshShape(meshShape, scale);
sim.collision_shapes.push_back(scaled_mesh_shape);
btDefaultMotionState* chunkMotionState = new btDefaultMotionState(btTransform(toBt(transforms_no_scale[i])));
// Create the rigidbody with the collision shape
btRigidBody::btRigidBodyConstructionInfo staticMeshRigidBodyInfo(0, chunkMotionState, scaled_mesh_shape);
btRigidBody* staticRigidMesh = new btRigidBody(staticMeshRigidBodyInfo);
sim.static_rigid_bodies.push_back(staticRigidMesh);
// Add it to our scene
sim.dynamicsWorld->addRigidBody(staticRigidMesh);
}
#else
static_cast<void>(sim);
static_cast<void>(meshes);
static_cast<void>(transforms_no_scale);
static_cast<void>(scales);
#endif
}
void sim_create_player_rigid_body(PhysicsSim& sim, const glm::fmat4x3& player_transform, const glm::fvec3& shape_extent)
{
#if defined(REAPER_USE_BULLET_PHYSICS)
btMotionState* motionState = new btDefaultMotionState(toBt(player_transform));
btCollisionShape* collisionShape = new btBoxShape(toBt(shape_extent));
sim.collision_shapes.push_back(collisionShape);
btScalar mass = 10.f; // FIXME
btVector3 inertia(0.f, 0.f, 0.f);
collisionShape->calculateLocalInertia(mass, inertia);
btRigidBody::btRigidBodyConstructionInfo constructInfo(mass, motionState, collisionShape, inertia);
btRigidBody* player_rigid_body = new btRigidBody(constructInfo);
player_rigid_body->setFriction(0.1f);
player_rigid_body->setRollingFriction(0.8f);
// FIXME doesn't do anything? Wrong collision mesh?
player_rigid_body->setCcdMotionThreshold(0.05f);
player_rigid_body->setCcdSweptSphereRadius(shape_extent.x);
sim.dynamicsWorld->addRigidBody(player_rigid_body);
sim.players.push_back(player_rigid_body);
#else
static_cast<void>(sim);
static_cast<void>(player_transform);
static_cast<void>(shape_extent);
#endif
}
} // namespace SplineSonic
| 36.647643 | 120 | 0.658 | Ryp |
ff9250213626d9179509c8cd779d17b5770051d8 | 2,719 | cpp | C++ | source/backend/opengl/execution/GLPool.cpp | xindongzhang/MNN | f4740c78dc8fc67ee4596552d2257f12c48af067 | [
"Apache-2.0"
] | 1 | 2019-08-09T03:16:49.000Z | 2019-08-09T03:16:49.000Z | source/backend/opengl/execution/GLPool.cpp | xindongzhang/MNN | f4740c78dc8fc67ee4596552d2257f12c48af067 | [
"Apache-2.0"
] | null | null | null | source/backend/opengl/execution/GLPool.cpp | xindongzhang/MNN | f4740c78dc8fc67ee4596552d2257f12c48af067 | [
"Apache-2.0"
] | 1 | 2021-08-23T03:40:09.000Z | 2021-08-23T03:40:09.000Z | //
// GLPool.cpp
// MNN
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "GLPool.hpp"
#include "AllShader.hpp"
#include "GLBackend.hpp"
#include "Macro.h"
namespace MNN {
namespace OpenGL {
ErrorCode GLPool::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) {
auto inputTensor = inputs[0];
auto pool = mPool;
if (!pool->isGlobal()) {
int kx = pool->kernelX();
int ky = pool->kernelY();
int sx = pool->strideX();
int sy = pool->strideY();
int px = pool->padX();
int py = pool->padY();
mSetUniform = [=] {
glUniform2i(2, kx, ky);
glUniform2i(3, sx, sy);
glUniform2i(4, px, py);
};
} else {
mSetUniform = [=] {
glUniform2i(2, inputTensor->width(), inputTensor->height());
glUniform2i(3, 1, 1);
glUniform2i(4, 0, 0);
};
}
return NO_ERROR;
}
ErrorCode GLPool::onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) {
auto imageInput = inputs[0]->deviceId();
auto imageOutput = outputs[0]->deviceId();
auto outputTensor = outputs[0];
auto inputTensor = inputs[0];
MNN_ASSERT(mPoolProgram.get() != NULL);
mPoolProgram->useProgram();
glBindImageTexture(0, imageInput, 0, GL_TRUE, 0, GL_READ_ONLY, TEXTURE_FORMAT);
glBindImageTexture(1, imageOutput, 0, GL_TRUE, 0, GL_WRITE_ONLY, TEXTURE_FORMAT);
mSetUniform();
glUniform3i(10, outputTensor->width(), outputTensor->height(), UP_DIV(outputTensor->channel(), 4));
glUniform3i(11, inputTensor->width(), inputTensor->height(), UP_DIV(inputTensor->channel(), 4));
OPENGL_CHECK_ERROR;
auto depthQuad = UP_DIV(outputTensor->channel(), 4);
((GLBackend *)backend())->compute(UP_DIV(outputTensor->width(), 2), UP_DIV(outputTensor->height(), 2), UP_DIV(depthQuad, 16));
OPENGL_CHECK_ERROR;
return NO_ERROR;
}
GLPool::~GLPool() {
}
GLPool::GLPool(const std::vector<Tensor *> &inputs, const Op *op, Backend *bn) : Execution(bn) {
auto extra = (GLBackend *)bn;
auto pool = op->main_as_Pool();
switch (pool->type()) {
case PoolType_MAXPOOL:
mPoolProgram = extra->getProgram("maxPool", glsl_maxpool_glsl);
break;
case PoolType_AVEPOOL:
mPoolProgram = extra->getProgram("meanPool", glsl_avgpool_glsl);
break;
default:
MNN_ASSERT(false);
break;
}
mPool = pool;
}
GLCreatorRegister<TypedCreator<GLPool>> __pool_op(OpType_Pooling);
} // namespace OpenGL
} // namespace MNN
| 31.252874 | 130 | 0.606841 | xindongzhang |
910d156efe41482750f26a50252b38056131dfff | 494 | cpp | C++ | src/ktlexcept.cpp | Shtan7/KTL | 9c0adf8fac2f0bb481060b7bbb15b1356089af3c | [
"MIT"
] | 38 | 2020-12-16T22:12:50.000Z | 2022-03-24T04:07:14.000Z | src/ktlexcept.cpp | Shtan7/KTL | 9c0adf8fac2f0bb481060b7bbb15b1356089af3c | [
"MIT"
] | 165 | 2020-11-11T21:22:23.000Z | 2022-03-26T14:30:40.000Z | src/ktlexcept.cpp | Shtan7/KTL | 9c0adf8fac2f0bb481060b7bbb15b1356089af3c | [
"MIT"
] | 5 | 2021-07-16T19:05:28.000Z | 2021-12-22T11:46:42.000Z | #include <ktlexcept.hpp>
#include <string.hpp>
namespace ktl {
NTSTATUS out_of_range::code() const noexcept {
return STATUS_ARRAY_BOUNDS_EXCEEDED;
}
NTSTATUS range_error::code() const noexcept {
return STATUS_RANGE_NOT_FOUND;
}
NTSTATUS overflow_error::code() const noexcept {
return STATUS_BUFFER_OVERFLOW;
}
NTSTATUS kernel_error::code() const noexcept {
return m_code;
}
NTSTATUS format_error::code() const noexcept {
return STATUS_BAD_DESCRIPTOR_FORMAT;
}
} // namespace ktl | 20.583333 | 48 | 0.771255 | Shtan7 |
91191747f06046dd61ef2f8fef4f1f0bba7ec5b7 | 424 | cpp | C++ | day02/main.cpp | wuggy-ianw/AoC2017 | 138c66bdd407e76f6ad71c9d68df50e0afa2251a | [
"Unlicense"
] | null | null | null | day02/main.cpp | wuggy-ianw/AoC2017 | 138c66bdd407e76f6ad71c9d68df50e0afa2251a | [
"Unlicense"
] | null | null | null | day02/main.cpp | wuggy-ianw/AoC2017 | 138c66bdd407e76f6ad71c9d68df50e0afa2251a | [
"Unlicense"
] | null | null | null | //
// Created by wuggy on 02/12/2017.
//
#include <fstream>
#include "day02.h"
#include "../utils/aocutils.h"
int main()
{
std::ifstream ifs("input.txt");
std::vector< std::vector<std::size_t> > sheet = AOCUtils::parseByLines<std::vector<std::size_t> >(ifs, AOCUtils::parseItem<std::size_t>);
std::cout << Day2::solve_part1(sheet) << std::endl;
std::cout << Day2::solve_part2(sheet) << std::endl;
return 0;
}
| 21.2 | 139 | 0.648585 | wuggy-ianw |
911db9de6e667c6f419998033a3f3f1dd4e83062 | 27,348 | cpp | C++ | MainWindow.cpp | mrQzs/LVGLBuilder | 41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5 | [
"MIT"
] | null | null | null | MainWindow.cpp | mrQzs/LVGLBuilder | 41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5 | [
"MIT"
] | null | null | null | MainWindow.cpp | mrQzs/LVGLBuilder | 41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5 | [
"MIT"
] | null | null | null | #include "MainWindow.h"
#include <QDebug>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QSettings>
#include <QSortFilterProxyModel>
#include "LVGLDialog.h"
#include "LVGLFontData.h"
#include "LVGLFontDialog.h"
#include "LVGLHelper.h"
#include "LVGLItem.h"
#include "LVGLNewDialog.h"
#include "LVGLObjectModel.h"
#include "LVGLProject.h"
#include "LVGLPropertyModel.h"
#include "LVGLSimulator.h"
#include "LVGLStyleModel.h"
#include "LVGLWidgetListView.h"
#include "LVGLWidgetModel.h"
#include "LVGLWidgetModelDisplay.h"
#include "LVGLWidgetModelInput.h"
#include "ListDelegate.h"
#include "ListViewItem.h"
#include "TabWidget.h"
#include "lvgl/lvgl.h"
#include "ui_MainWindow.h"
#include "widgets/LVGLWidgets.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent),
m_ui(new Ui::MainWindow),
m_zoom_slider(new QSlider(Qt::Horizontal)),
m_project(nullptr),
m_maxFileNr(5),
m_curSimulation(nullptr),
m_proxyModel(nullptr),
m_objectModel(nullptr),
m_proxyModelDPW(nullptr),
m_proxyModelIPW(nullptr),
m_widgetModel(nullptr),
m_widgetModelDPW(nullptr),
m_widgetModelIPW(nullptr),
m_filter(nullptr),
m_curTabWIndex(-1),
m_frun(true) {
m_ui->setupUi(this);
m_ui->style_tree->setStyleSheet(
"QTreeView::item{border:1px solid "
"#f2f2f2;}");
m_ui->property_tree->setStyleSheet(
"QTreeView::item{border:1px solid "
"#f2f2f2;}");
m_propertyModel = new LVGLPropertyModel();
m_ld1 = new ListDelegate(m_ui->list_widgets->getlistview());
m_ld2 = new ListDelegate(m_ui->list_widgets_2->getlistview());
m_ld3 = new ListDelegate(m_ui->list_widgets_3->getlistview());
m_ui->property_tree->setModel(m_propertyModel);
m_ui->property_tree->setItemDelegate(new LVGLPropertyDelegate);
m_ui->button_remove_image->setEnabled(false);
m_ui->button_remove_font->setEnabled(false);
m_zoom_slider->setRange(-2, 2);
m_ui->statusbar->addPermanentWidget(m_zoom_slider);
m_styleModel = new LVGLStyleModel;
connect(m_styleModel, &LVGLStyleModel::styleChanged, this,
&MainWindow::styleChanged);
m_ui->style_tree->setModel(m_styleModel);
m_ui->style_tree->setItemDelegate(
new LVGLStyleDelegate(m_styleModel->styleBase()));
m_ui->style_tree->expandAll();
connect(m_ui->action_new, &QAction::triggered, this,
&MainWindow::openNewProject);
// recent configurations
QAction *recentFileAction = nullptr;
for (int i = 0; i < m_maxFileNr; i++) {
recentFileAction = new QAction(this);
recentFileAction->setVisible(false);
connect(recentFileAction, &QAction::triggered, this,
&MainWindow::loadRecent);
m_recentFileActionList.append(recentFileAction);
m_ui->menu_resent_filess->addAction(recentFileAction);
}
updateRecentActionList();
// add style editor dock to property dock and show the property dock
tabifyDockWidget(m_ui->PropertyEditor, m_ui->ObjecInspector);
m_ui->PropertyEditor->raise();
m_ui->StyleEditor->raise();
// add font editor dock to image dock and show the image dock
tabifyDockWidget(m_ui->ImageEditor, m_ui->FontEditor);
m_ui->ImageEditor->raise();
m_liststate << LV_STATE_DEFAULT << LV_STATE_CHECKED << LV_STATE_FOCUSED
<< LV_STATE_EDITED << LV_STATE_HOVERED << LV_STATE_PRESSED
<< LV_STATE_DISABLED;
connect(m_ui->tabWidget, &QTabWidget::currentChanged, this,
&MainWindow::tabChanged);
// initcodemap();
// initNewWidgets();
LVGLHelper::getInstance().setMainW(this);
}
MainWindow::~MainWindow() { delete m_ui; }
LVGLSimulator *MainWindow::simulator() const { return m_curSimulation; }
void MainWindow::updateProperty() {
LVGLObject *o = m_curSimulation->selectedObject();
if (o == nullptr) return;
LVGLProperty *p = o->widgetClass()->property("Geometry");
if (p == nullptr) return;
for (int i = 0; i < p->count(); ++i) {
auto index = m_propertyModel->propIndex(p->child(i), o->widgetClass(), 1);
emit m_propertyModel->dataChanged(index, index);
}
}
void MainWindow::setCurrentObject(LVGLObject *obj) {
m_ui->combo_style->clear();
m_ui->combo_state->setCurrentIndex(0);
m_propertyModel->setObject(obj);
if (obj) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setPart(parts[0]);
m_styleModel->setState(LV_STATE_DEFAULT);
m_styleModel->setObj(obj->obj());
m_ui->combo_style->addItems(obj->widgetClass()->styles());
m_styleModel->setStyle(obj->style(0, 0),
obj->widgetClass()->editableStyles(0));
updateItemDelegate();
} else {
m_styleModel->setStyle(nullptr);
}
}
void MainWindow::styleChanged() {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj) {
int index = m_ui->combo_style->currentIndex();
obj->widgetClass()->setStyle(obj->obj(), index, obj->style(index));
// refresh_children_style(obj->obj());
// lv_obj_refresh_style(obj->obj());
}
}
void MainWindow::loadRecent() {
QAction *action = qobject_cast<QAction *>(QObject::sender());
if (action == nullptr) return;
loadProject(action->data().toString());
}
void MainWindow::openNewProject() {
LVGLNewDialog dialog(this);
if (dialog.exec() == QDialog::Accepted) {
if (m_curSimulation != nullptr) revlvglConnect();
TabWidget *tabw = new TabWidget(dialog.selectedName(), this);
lvgl = tabw->getCore();
const auto res = dialog.selectedResolution();
lvgl->init(res.width(), res.height());
if (m_frun) {
m_frun = false;
initNewWidgets();
initcodemap();
}
lvgl->initw(m_widgets);
lvgl->initwDP(m_widgetsDisplayW);
lvgl->initwIP(m_widgetsInputW);
m_coreRes[lvgl] = res;
m_listTabW.push_back(tabw);
m_ui->tabWidget->addTab(tabw, tabw->getName());
m_ui->tabWidget->setCurrentIndex(m_listTabW.size() - 1);
setEnableBuilder(true);
m_curSimulation->clear();
m_project = tabw->getProject();
m_project->setres(res);
lvgl->changeResolution(res);
} else if (m_project == nullptr) {
setEnableBuilder(false);
setWindowTitle("LVGL Builder");
}
}
void MainWindow::addImage(LVGLImageData *img, QString name) {
LVGLImageDataCast cast;
cast.ptr = img;
QListWidgetItem *item = new QListWidgetItem(img->icon(), name);
item->setData(Qt::UserRole + 3, cast.i);
m_ui->list_images->addItem(item);
}
void MainWindow::updateImages() {
m_ui->list_images->clear();
for (LVGLImageData *i : lvgl->images()) {
if (i->fileName().isEmpty()) continue;
QString name = QFileInfo(i->fileName()).baseName() +
QString(" [%1x%2]").arg(i->width()).arg(i->height());
addImage(i, name);
}
}
void MainWindow::addFont(LVGLFontData *font, QString name) {
LVGLFontDataCast cast;
cast.ptr = font;
QListWidgetItem *item = new QListWidgetItem(name);
item->setData(Qt::UserRole + 3, cast.i);
m_ui->list_fonts->addItem(item);
}
void MainWindow::updateFonts() {
m_ui->list_fonts->clear();
for (const LVGLFontData *f : lvgl->customFonts())
addFont(const_cast<LVGLFontData *>(f), f->name());
}
void MainWindow::updateRecentActionList() {
QSettings settings("at.fhooe.lvgl", "LVGL Builder");
QStringList recentFilePaths;
for (const QString &f : settings.value("recentFiles").toStringList()) {
if (QFile(f).exists()) recentFilePaths.push_back(f);
}
int itEnd = m_maxFileNr;
if (recentFilePaths.size() <= m_maxFileNr) itEnd = recentFilePaths.size();
for (int i = 0; i < itEnd; i++) {
QString strippedName = QFileInfo(recentFilePaths.at(i)).fileName();
m_recentFileActionList.at(i)->setText(strippedName);
m_recentFileActionList.at(i)->setData(recentFilePaths.at(i));
m_recentFileActionList.at(i)->setVisible(true);
}
for (int i = itEnd; i < m_maxFileNr; i++)
m_recentFileActionList.at(i)->setVisible(false);
}
void MainWindow::adjustForCurrentFile(const QString &fileName) {
QSettings settings("at.fhooe.lvgl", "LVGL Builder");
QStringList recentFilePaths = settings.value("recentFiles").toStringList();
recentFilePaths.removeAll(fileName);
recentFilePaths.prepend(fileName);
while (recentFilePaths.size() > m_maxFileNr) recentFilePaths.removeLast();
settings.setValue("recentFiles", recentFilePaths);
updateRecentActionList();
}
void MainWindow::loadProject(const QString &fileName) {
delete m_project;
m_curSimulation->clear();
m_project = LVGLProject::load(fileName);
if (m_project == nullptr) {
QMessageBox::critical(this, "Error", "Could not load lvgl file!");
setWindowTitle("LVGL Builder");
setEnableBuilder(false);
} else {
adjustForCurrentFile(fileName);
setWindowTitle("LVGL Builder - [" + m_project->name() + "]");
lvgl->changeResolution(m_project->resolution());
m_curSimulation->changeResolution(m_project->resolution());
setEnableBuilder(true);
}
updateImages();
updateFonts();
}
void MainWindow::setEnableBuilder(bool enable) {
m_ui->action_save->setEnabled(enable);
m_ui->action_export_c->setEnabled(enable);
m_ui->action_run->setEnabled(enable);
m_ui->WidgeBox->setEnabled(enable);
m_ui->ImageEditor->setEnabled(enable);
m_ui->FontEditor->setEnabled(enable);
}
void MainWindow::updateItemDelegate() {
auto it = m_ui->style_tree->itemDelegate();
if (nullptr != it) delete it;
m_ui->style_tree->setItemDelegate(
new LVGLStyleDelegate(m_styleModel->styleBase()));
}
void MainWindow::on_action_load_triggered() {
QString path;
if (m_project != nullptr) path = m_project->fileName();
QString fileName =
QFileDialog::getOpenFileName(this, "Load lvgl", path, "LVGL (*.lvgl)");
if (fileName.isEmpty()) return;
loadProject(fileName);
}
void MainWindow::on_action_save_triggered() {
QString path;
if (m_project != nullptr) path = m_project->fileName();
QString fileName =
QFileDialog::getSaveFileName(this, "Save lvgl", path, "LVGL (*.lvgl)");
if (fileName.isEmpty()) return;
if (!m_project->save(fileName)) {
QMessageBox::critical(this, "Error", "Could not save lvgl file!");
} else {
adjustForCurrentFile(fileName);
}
}
void MainWindow::on_combo_style_currentIndexChanged(int index) {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj && (index >= 0)) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setState(m_liststate[m_ui->combo_state->currentIndex()]);
m_styleModel->setPart(parts[index]);
m_styleModel->setStyle(
obj->style(index, m_ui->combo_state->currentIndex()),
obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex()));
m_ui->combo_state->setCurrentIndex(0);
on_combo_state_currentIndexChanged(0);
}
}
void MainWindow::on_action_export_c_triggered() {
QString dir;
if (m_project != nullptr) {
QFileInfo fi(m_project->fileName());
dir = fi.absoluteFilePath();
}
QString path = QFileDialog::getExistingDirectory(this, "Export C files", dir);
if (path.isEmpty()) return;
if (m_project->exportCode(path))
QMessageBox::information(this, "Export", "C project exported!");
}
void MainWindow::on_button_add_image_clicked() {
QString dir;
if (m_project != nullptr) {
QFileInfo fi(m_project->fileName());
dir = fi.absoluteFilePath();
}
QStringList fileNames = QFileDialog::getOpenFileNames(
this, "Import image", dir, "Image (*.png *.jpg *.bmp *.jpeg)");
for (const QString &fileName : fileNames) {
QImage image(fileName);
if (image.isNull()) continue;
if (image.width() >= 2048 || image.height() >= 2048) {
QMessageBox::critical(
this, "Error Image Size",
tr("Image size must be under 2048! (Src: '%1')").arg(fileName));
continue;
}
QString name = QFileInfo(fileName).baseName();
LVGLImageData *i = lvgl->addImage(fileName, name);
name += QString(" [%1x%2]").arg(i->width()).arg(i->height());
addImage(i, name);
}
}
void MainWindow::on_button_remove_image_clicked() {
QListWidgetItem *item = m_ui->list_images->currentItem();
if (item == nullptr) return;
const int row = m_ui->list_images->currentRow();
LVGLImageDataCast cast;
cast.i = item->data(Qt::UserRole + 3).toLongLong();
if (lvgl->removeImage(cast.ptr)) m_ui->list_images->takeItem(row);
}
void MainWindow::on_list_images_customContextMenuRequested(const QPoint &pos) {
QPoint item = m_ui->list_images->mapToGlobal(pos);
QListWidgetItem *listItem = m_ui->list_images->itemAt(pos);
if (listItem == nullptr) return;
QMenu menu;
QAction *save = menu.addAction("Save as ...");
QAction *color = menu.addAction("Set output color ...");
QAction *sel = menu.exec(item);
if (sel == save) {
LVGLImageDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
QStringList options({"C Code (*.c)", "Binary (*.bin)"});
QString selected;
QString fileName = QFileDialog::getSaveFileName(
this, "Save image as c file", cast.ptr->codeName(), options.join(";;"),
&selected);
if (fileName.isEmpty()) return;
bool ok = false;
if (selected == options.at(0))
ok = cast.ptr->saveAsCode(fileName);
else if (selected == options.at(1))
ok = cast.ptr->saveAsBin(fileName);
if (!ok) {
QMessageBox::critical(this, "Error",
tr("Could not save image '%1'").arg(fileName));
}
} else if (sel == color) {
LVGLImageDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
int index = static_cast<int>(cast.ptr->colorFormat());
QString ret =
QInputDialog::getItem(this, "Output color", "Select output color",
LVGLImageData::colorFormats(), index, false);
index = LVGLImageData::colorFormats().indexOf(ret);
if (index >= 0)
cast.ptr->setColorFormat(static_cast<LVGLImageData::ColorFormat>(index));
}
}
void MainWindow::on_list_images_currentItemChanged(QListWidgetItem *current,
QListWidgetItem *previous) {
Q_UNUSED(previous)
m_ui->button_remove_image->setEnabled(current != nullptr);
}
void MainWindow::on_button_add_font_clicked() {
LVGLFontDialog dialog(this);
if (dialog.exec() != QDialog::Accepted) return;
LVGLFontData *f =
lvgl->addFont(dialog.selectedFontPath(), dialog.selectedFontSize());
if (f)
addFont(f, f->name());
else
QMessageBox::critical(this, "Error", "Could not load font!");
}
void MainWindow::on_button_remove_font_clicked() {
QListWidgetItem *item = m_ui->list_fonts->currentItem();
if (item == nullptr) return;
const int row = m_ui->list_fonts->currentRow();
LVGLFontDataCast cast;
cast.i = item->data(Qt::UserRole + 3).toLongLong();
if (lvgl->removeFont(cast.ptr)) m_ui->list_fonts->takeItem(row);
}
void MainWindow::on_list_fonts_customContextMenuRequested(const QPoint &pos) {
QPoint item = m_ui->list_fonts->mapToGlobal(pos);
QListWidgetItem *listItem = m_ui->list_fonts->itemAt(pos);
if (listItem == nullptr) return;
QMenu menu;
QAction *save = menu.addAction("Save as ...");
QAction *sel = menu.exec(item);
if (sel == save) {
LVGLFontDataCast cast;
cast.i = listItem->data(Qt::UserRole + 3).toLongLong();
QStringList options({"C Code (*.c)", "Binary (*.bin)"});
QString selected;
QString fileName = QFileDialog::getSaveFileName(
this, "Save font as c file", cast.ptr->codeName(), options.join(";;"),
&selected);
if (fileName.isEmpty()) return;
bool ok = false;
if (selected == options.at(0)) ok = cast.ptr->saveAsCode(fileName);
if (!ok) {
QMessageBox::critical(this, "Error",
tr("Could not save font '%1'").arg(fileName));
}
}
}
void MainWindow::on_list_fonts_currentItemChanged(QListWidgetItem *current,
QListWidgetItem *previous) {
Q_UNUSED(previous)
m_ui->button_remove_font->setEnabled(current != nullptr);
}
void MainWindow::on_action_run_toggled(bool run) {
m_curSimulation->setMouseEnable(run);
m_curSimulation->setSelectedObject(nullptr);
}
void MainWindow::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
if (m_project == nullptr)
QTimer::singleShot(50, this, SLOT(openNewProject()));
}
QPixmap MainWindow::getPix(int type) {
QPixmap p;
switch (type) {
case 0:
p.load(":/icons/Arc.png");
break;
case 1:
p.load(":/icons/Bar.png");
break;
case 2:
p.load(":/icons/Button.png");
break;
case 3:
p.load(":/icons/Button Matrix.png");
break;
case 4:
p.load(":/icons/Calendar.png");
break;
case 5:
p.load(":/icons/Canvas.png");
break;
case 6:
p.load(":/icons/Check box.png");
break;
case 7:
p.load(":/icons/Chart.png");
break;
case 8:
p.load(":/icons/Container.png");
break;
case 9:
p.load(":/icons/Color picker.png");
break;
case 10:
p.load(":/icons/Dropdown.png");
break;
case 11:
p.load(":/icons/Gauge.png");
break;
case 12:
p.load(":/icons/Image.png");
break;
case 13:
p.load(":/icons/Image button.png");
break;
case 16:
p.load(":/icons/Keyboard.png");
break;
case 17:
p.load(":/icons/Label.png");
break;
case 18:
p.load(":/icons/LED.png");
break;
case 19:
p.load(":/icons/Line.png");
break;
case 20:
p.load(":/icons/List.png");
break;
case 21:
p.load(":/icons/Line meter.png");
break;
case 22:
p.load(":/icons/Message box.png");
break;
case 23:
p.load(":/icons/ObjectMask.png");
break;
case 24:
p.load(":/icons/Page.png");
break;
case 25:
p.load(":/icons/Roller.png");
break;
case 26:
p.load(":/icons/Slider.png");
break;
case 27:
p.load(":/icons/Spinbox.png");
break;
case 28:
p.load(":/icons/Spinner.png");
break;
case 29:
p.load(":/icons/Switch.png");
break;
case 30:
p.load(":/icons/Table.png");
break;
case 31:
p.load(":/icons/Tabview.png");
break;
case 32:
p.load(":/icons/Text area.png");
break;
case 33:
p.load(":/icons/TileView.png");
break;
case 34:
p.load(":/icons/Window.png");
break;
}
return p;
}
void MainWindow::addWidget(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgets.insert(w->className(), w);
}
void MainWindow::addWidgetDisplayW(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgetsDisplayW.insert(w->className(), w);
}
void MainWindow::addWidgetInputW(LVGLWidget *w) {
w->setPreview(getPix(w->type()));
m_widgetsInputW.insert(w->className(), w);
}
void MainWindow::initcodemap() {
auto pt = lv_obj_create(NULL, NULL);
m_codemap[0] = lv_arc_create(pt, NULL);
m_codemap[1] = lv_bar_create(pt, NULL);
m_codemap[2] = lv_btn_create(pt, NULL);
m_codemap[3] = lv_btnmatrix_create(pt, NULL);
m_codemap[4] = lv_calendar_create(pt, NULL);
m_codemap[5] = lv_canvas_create(pt, NULL);
m_codemap[6] = lv_checkbox_create(pt, NULL);
m_codemap[7] = lv_chart_create(pt, NULL);
m_codemap[8] = lv_cont_create(pt, NULL);
m_codemap[9] = lv_cpicker_create(pt, NULL);
m_codemap[10] = lv_dropdown_create(pt, NULL);
m_codemap[11] = lv_gauge_create(pt, NULL);
m_codemap[12] = lv_img_create(pt, NULL);
m_codemap[13] = lv_imgbtn_create(pt, NULL);
m_codemap[16] = lv_keyboard_create(pt, NULL);
m_codemap[17] = lv_label_create(pt, NULL);
m_codemap[18] = lv_led_create(pt, NULL);
m_codemap[19] = lv_line_create(pt, NULL);
m_codemap[20] = lv_list_create(pt, NULL);
m_codemap[21] = lv_linemeter_create(pt, NULL);
m_codemap[22] = lv_msgbox_create(pt, NULL);
m_codemap[23] = lv_objmask_create(pt, NULL);
m_codemap[24] = lv_page_create(pt, NULL);
m_codemap[25] = lv_roller_create(pt, NULL);
m_codemap[26] = lv_slider_create(pt, NULL);
m_codemap[27] = lv_spinbox_create(pt, NULL);
m_codemap[28] = lv_spinner_create(pt, NULL);
m_codemap[29] = lv_switch_create(pt, NULL);
m_codemap[30] = lv_table_create(pt, NULL);
m_codemap[31] = lv_tabview_create(pt, NULL);
m_codemap[32] = lv_textarea_create(pt, NULL);
m_codemap[33] = lv_tileview_create(pt, NULL);
m_codemap[34] = lv_win_create(pt, NULL);
}
void MainWindow::initNewWidgets() {
addWidget(new LVGLButton);
addWidget(new LVGLButtonMatrix);
addWidget(new LVGLImageButton);
addWidgetDisplayW(new LVGLArc);
addWidgetDisplayW(new LVGLBar);
addWidgetDisplayW(new LVGLImage);
addWidgetDisplayW(new LVGLLabel);
addWidgetDisplayW(new LVGLLED);
addWidgetDisplayW(new LVGLMessageBox);
addWidgetDisplayW(new LVGLObjectMask);
addWidgetDisplayW(new LVGLPage);
addWidgetDisplayW(new LVGLTable);
addWidgetDisplayW(new LVGLTabview);
addWidgetDisplayW(new LVGLTileView);
addWidgetDisplayW(new LVGLTextArea);
addWidgetDisplayW(new LVGLWindow);
addWidgetInputW(new LVGLCalendar);
addWidgetInputW(new LVGLCanvas);
addWidgetInputW(new LVGLChart);
addWidgetInputW(new LVGLCheckBox);
addWidgetInputW(new LVGLColorPicker);
addWidgetInputW(new LVGLContainer);
addWidgetInputW(new LVGLDropDownList);
addWidgetInputW(new LVGLGauge);
addWidgetInputW(new LVGLKeyboard);
addWidgetInputW(new LVGLLine);
addWidgetInputW(new LVGLList);
addWidgetInputW(new LVGLLineMeter);
addWidgetInputW(new LVGLRoller);
addWidgetInputW(new LVGLSlider);
addWidgetInputW(new LVGLSpinbox);
addWidgetInputW(new LVGLSpinner);
addWidgetInputW(new LVGLSwitch);
}
void MainWindow::initlvglConnect() {
if (m_objectModel) delete m_objectModel;
if (m_proxyModel) delete m_proxyModel;
if (m_proxyModelDPW) delete m_proxyModelDPW;
if (m_proxyModelIPW) delete m_proxyModelIPW;
if (m_widgetModel) delete m_widgetModel;
if (m_widgetModelDPW) delete m_widgetModelDPW;
if (m_widgetModelIPW) delete m_widgetModelIPW;
m_objectModel = new LVGLObjectModel(this);
m_widgetModel = new LVGLWidgetModel(this);
m_widgetModelDPW = new LVGLWidgetModelDisplay(this);
m_widgetModelIPW = new LVGLWidgetModelInput(this);
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModelDPW = new QSortFilterProxyModel(this);
m_proxyModelIPW = new QSortFilterProxyModel(this);
m_ui->object_tree->setModel(m_objectModel);
m_curSimulation->setObjectModel(m_objectModel);
m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModel->setSourceModel(m_widgetModel);
m_proxyModel->sort(0);
m_proxyModelDPW->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModelDPW->setSourceModel(m_widgetModelDPW);
m_proxyModelDPW->sort(0);
m_proxyModelIPW->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModelIPW->setSourceModel(m_widgetModelIPW);
m_proxyModelIPW->sort(0);
m_ui->list_widgets->getlistview()->setItemDelegate(m_ld1);
m_ui->list_widgets_2->getlistview()->setItemDelegate(m_ld2);
m_ui->list_widgets_3->getlistview()->setItemDelegate(m_ld3);
m_ui->list_widgets->getlistview()->setModel(m_proxyModel);
m_ui->list_widgets_2->getlistview()->setModel(m_proxyModelDPW);
m_ui->list_widgets_3->getlistview()->setModel(m_proxyModelIPW);
m_ui->list_widgets->settoolbtnText(tr("Button"));
m_ui->list_widgets_2->settoolbtnText(tr("DisplayWidgets"));
m_ui->list_widgets_3->settoolbtnText(tr("InputWidgts"));
connect(m_curSimulation, &LVGLSimulator::objectSelected, this,
&MainWindow::setCurrentObject);
connect(m_curSimulation, &LVGLSimulator::objectSelected, m_ui->property_tree,
&QTreeView::expandAll);
connect(m_curSimulation->item(), &LVGLItem::geometryChanged, this,
&MainWindow::updateProperty);
connect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree,
&QTreeView::expandAll);
connect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel,
&LVGLObjectModel::setCurrentObject);
connect(m_ui->object_tree, &QTreeView::doubleClicked, this,
[this](const QModelIndex &index) {
m_curSimulation->setSelectedObject(m_objectModel->object(index));
});
connect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation,
&LVGLSimulator::setZoomLevel);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel,
&QSortFilterProxyModel::setFilterWildcard);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW,
&QSortFilterProxyModel::setFilterWildcard);
connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW,
&QSortFilterProxyModel::setFilterWildcard);
if (m_filter != nullptr) delete m_filter;
m_filter = new LVGLKeyPressEventFilter(m_curSimulation, qApp);
qApp->installEventFilter(m_filter);
m_ui->combo_state->clear();
QStringList statelist;
statelist << "LV_STATE_DEFAULT"
<< "LV_STATE_CHECKED"
<< "LV_STATE_FOCUSED"
<< "LV_STATE_EDITED"
<< "LV_STATE_HOVERED"
<< "LV_STATE_PRESSED"
<< "LV_STATE_DISABLED";
m_ui->combo_state->addItems(statelist);
}
void MainWindow::revlvglConnect() {
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW,
&QSortFilterProxyModel::setFilterWildcard);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected, this,
&MainWindow::setCurrentObject);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected,
m_ui->property_tree, &QTreeView::expandAll);
disconnect(m_curSimulation->item(), &LVGLItem::geometryChanged, this,
&MainWindow::updateProperty);
disconnect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree,
&QTreeView::expandAll);
disconnect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel,
&LVGLObjectModel::setCurrentObject);
disconnect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation,
&LVGLSimulator::setZoomLevel);
}
void MainWindow::on_combo_state_currentIndexChanged(int index) {
LVGLObject *obj = m_curSimulation->selectedObject();
if (obj && (index >= 0)) {
auto parts = obj->widgetClass()->parts();
m_styleModel->setPart(parts[m_ui->combo_style->currentIndex()]);
m_styleModel->setState(m_liststate[index]);
m_styleModel->setStyle(
obj->style(m_ui->combo_style->currentIndex(), index),
obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex()));
updateItemDelegate();
}
}
void MainWindow::tabChanged(int index) {
if (index != m_curTabWIndex) {
if (nullptr != m_curSimulation) m_curSimulation->setSelectedObject(nullptr);
m_curSimulation = m_listTabW[index]->getSimulator();
lvgl = m_listTabW[index]->getCore();
m_project = m_listTabW[index]->getProject(); // dont need
initlvglConnect();
lvgl->changeResolution(m_coreRes[lvgl]);
m_curSimulation->changeResolution(m_coreRes[lvgl]);
m_curSimulation->repaint();
m_curTabWIndex = index;
}
}
| 33.229648 | 80 | 0.685644 | mrQzs |
911dd4796f0fde651220d48ea1b63b48ce2d0be8 | 2,964 | cpp | C++ | lib/os/thread_win32.cpp | paulhuggett/pstore2 | a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c | [
"Apache-2.0"
] | 11 | 2018-02-02T21:24:49.000Z | 2020-12-11T04:06:03.000Z | lib/os/thread_win32.cpp | SNSystems/pstore | 74e9dd960245d6bfc125af03ed964d8ad660a62d | [
"Apache-2.0"
] | 63 | 2018-02-05T17:24:59.000Z | 2022-03-22T17:26:28.000Z | lib/os/thread_win32.cpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 5 | 2020-01-13T22:47:11.000Z | 2021-05-14T09:31:15.000Z | //===- lib/os/thread_win32.cpp --------------------------------------------===//
//* _ _ _ *
//* | |_| |__ _ __ ___ __ _ __| | *
//* | __| '_ \| '__/ _ \/ _` |/ _` | *
//* | |_| | | | | | __/ (_| | (_| | *
//* \__|_| |_|_| \___|\__,_|\__,_| *
//* *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file thread.cpp
#include "pstore/os/thread.hpp"
#ifdef _WIN32
# include <array>
# include <cerrno>
# include <cstring>
# include <system_error>
# include "pstore/config/config.hpp"
# include "pstore/support/error.hpp"
namespace pstore {
namespace threads {
static thread_local char thread_name[name_size];
void set_name (gsl::not_null<gsl::czstring> name) {
// This code taken from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
// Sadly, threads don't actually have names in Win32. The process via
// RaiseException is just a "Secret Handshake" with the VS Debugger, who
// actually stores the thread -> name mapping. Windows itself has no
// notion of a thread "name".
std::strncpy (thread_name, name, name_size);
thread_name[name_size - 1] = '\0';
# ifndef NDEBUG
DWORD const MS_VC_EXCEPTION = 0x406D1388;
# pragma pack(push, 8)
struct THREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
};
# pragma pack(pop)
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = GetCurrentThreadId ();
info.dwFlags = 0;
__try {
RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR),
(ULONG_PTR *) &info);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
# endif // NDEBUG
}
gsl::czstring get_name (gsl::span<char, name_size> name /*out*/) {
auto const length = name.size ();
if (name.data () == nullptr || length < 1) {
raise (errno_erc{EINVAL});
}
std::strncpy (name.data (), thread_name, length);
name[length - 1] = '\0';
return name.data ();
}
} // end namespace threads
} // end namespace pstore
#endif //_WIN32
| 35.285714 | 89 | 0.501012 | paulhuggett |
9128bace1e9e94ff0e730643982c5494b5a74fab | 1,055 | cpp | C++ | src/lox/Object.cpp | dylanclark/loxplusplus | a533389e73f86c067ad705a317c3a3cc0f66b63f | [
"MIT"
] | null | null | null | src/lox/Object.cpp | dylanclark/loxplusplus | a533389e73f86c067ad705a317c3a3cc0f66b63f | [
"MIT"
] | null | null | null | src/lox/Object.cpp | dylanclark/loxplusplus | a533389e73f86c067ad705a317c3a3cc0f66b63f | [
"MIT"
] | null | null | null | #include <loxpp_pch.h>
#include <Object.h>
#include <VisitHelpers.h>
namespace Loxpp::Object {
// Handy template class and function to cast from a variant T1 to variant T2,
// where T2 is a superset of T1: https://stackoverflow.com/a/47204507/15150338
template <class... Args> struct variant_cast_proxy {
std::variant<Args...> v;
template <class... ToArgs> operator std::variant<ToArgs...>() const {
return std::visit(
[](auto&& arg) -> std::variant<ToArgs...> { return arg; }, v);
}
};
template <class... Args>
auto variant_cast(const std::variant<Args...>& v)
-> variant_cast_proxy<Args...> {
return {v};
}
LoxObj FromLiteralValue(const Lexer::LiteralValue& value) {
return LoxObj{variant_cast(value)};
}
bool IsTruthy(const LoxObj& obj) {
return std::visit(overloaded{[](std::monostate /*m*/) { return false; },
[](bool b) { return b; },
[](auto&& arg) { return true; }},
obj);
}
} // namespace Loxpp::Object | 29.305556 | 78 | 0.595261 | dylanclark |
912bc5f9488b04a8bb775c60c37d5c0327a8f8d7 | 1,243 | cpp | C++ | arrays/largestBand.cpp | kaushikbalasundar/cpp_dsa_solutions | 6a74bd6d114a882b5c95c5e4cc74447d58bbae7b | [
"MIT"
] | null | null | null | arrays/largestBand.cpp | kaushikbalasundar/cpp_dsa_solutions | 6a74bd6d114a882b5c95c5e4cc74447d58bbae7b | [
"MIT"
] | null | null | null | arrays/largestBand.cpp | kaushikbalasundar/cpp_dsa_solutions | 6a74bd6d114a882b5c95c5e4cc74447d58bbae7b | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<unordered_set>
#include<algorithm>
using namespace std;
//find the longest band in a given array of integers
//Input: {1,9,3,0,5,2,4,10,7,12,6}
//Output: 8 {0,1,2,3,4,5,6,7}
int longestBand(vector<int> arr){
int result = 0;
unordered_set<int> os;
for(int element : arr){
os.insert(element);
}
for(auto element: os){ //note that you can iterate through an unordered set like this. You looked this up.
int parent = element -1 ; // find the root of a sequence
if(os.find(parent)==os.end()){ // if root is found
int count = 1; // start counting
int next_element = element + 1; //find next element
while(os.find(next_element)!=os.end()){ //keep incrementing as long as the sequence holds
count++;
next_element++;
}
if(count > result){// update maximum sequence found till now
result = count;
}
}
}
return result; //return maximum sequence
}
int main(){
int result = longestBand({1,9,3,0,5,4,10,7,12,6});
cout << "The longest band is: " << result << endl;
return 0;
} | 23.018519 | 111 | 0.565567 | kaushikbalasundar |
912c40f76e858930903aa926c3d49888dda1bc63 | 1,939 | cpp | C++ | client/src/Helper.cpp | bendelec/Grandma | d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8 | [
"MIT"
] | 2 | 2020-05-25T11:12:19.000Z | 2022-01-18T01:38:19.000Z | client/src/Helper.cpp | bendelec/Grandma | d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8 | [
"MIT"
] | 1 | 2020-03-28T03:47:22.000Z | 2020-03-28T03:47:22.000Z | client/src/Helper.cpp | bendelec/Grandma | d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8 | [
"MIT"
] | 1 | 2022-01-18T01:50:30.000Z | 2022-01-18T01:50:30.000Z | /** ***************************************************************************
* Various helper functions
*
* (c)2020 Christian Bendele
*
*/
#include "Helper.h"
#include <sstream>
#include <iostream>
namespace Grandma {
std::vector<std::string> Helper::vectorize_path(const std::string path) {
std::stringstream ss;
if(path[0] == '/') {
ss << path.substr(1);
} else {
ss << path;
}
std::string segment;
std::vector<std::string> vectorized;
while(getline(ss, segment, '/')) {
vectorized.push_back(segment);
}
return vectorized;
}
// TODO: this can hardly be called a real URL parser. It is very simplicistic and supports only a
// small part of RFCxxxx. Also, string operations in C++ are not my forte...
bool Helper::URL::parse_from_string(std::string s_uri) {
std::cout << "Parsing URI " << s_uri << std::endl;
// parse protocol
size_t delim = s_uri.find("://");
if(delim == std::string::npos) return false;
std::string proto_s = s_uri.substr(0, delim);
std::cout << "proto_s is " << proto_s << std::endl;
if("http" == proto_s || "HTTP" == proto_s) {
protocol = Protocol::HTTP;
} else if("https" == proto_s || "HTTPS" == proto_s) {
protocol = Protocol::HTTPS;
} else {
return false;
}
s_uri = s_uri.substr(delim+3);
// parse path
delim = s_uri.find("/");
if(delim == std::string::npos) {
path = "/";
} else {
path = s_uri.substr(delim);
s_uri = s_uri.substr(0, delim);
}
std::cout << "Path is " << path << std::endl;
//parse port
delim = s_uri.find(":");
if(delim == std::string::npos) {
port = 8080;
} else {
std::string s_port = s_uri.substr(delim+1);
port = std::stoi(s_port); // FIXME: may throw exception
}
std::cout << "Port is " << port << std::endl;
// reminder is server
server = s_uri.substr(0, delim);
std::cout << "server is " << server << std::endl;
return true;
}
} // namespace
| 23.646341 | 97 | 0.580712 | bendelec |
912cc52e2b2b978b1892fd6af1f65cdde82d667b | 996 | cpp | C++ | srcs/utils/datetime.cpp | alexandretea/ddti | d81fd3069e67402ba695a2ada50a67f90ea45fb9 | [
"MIT"
] | 3 | 2020-11-30T01:57:35.000Z | 2021-06-15T01:36:10.000Z | srcs/utils/datetime.cpp | alexandretea/ddti | d81fd3069e67402ba695a2ada50a67f90ea45fb9 | [
"MIT"
] | null | null | null | srcs/utils/datetime.cpp | alexandretea/ddti | d81fd3069e67402ba695a2ada50a67f90ea45fb9 | [
"MIT"
] | 1 | 2020-11-30T01:57:48.000Z | 2020-11-30T01:57:48.000Z | // C/C++ File
// Author: Alexandre Tea <[email protected]>
// File: /Users/alexandretea/Work/ddti/srcs/utils/datetime.cpp
// Purpose: datetime utilities
// Created: 2017-07-29 22:52:26
// Modified: 2017-08-23 23:19:15
#include <ctime>
#include "datetime.hpp"
namespace utils {
namespace datetime {
std::string
now_str(char const* format)
{
std::time_t t = std::time(0);
char cstr[128];
std::strftime(cstr, sizeof(cstr), format, std::localtime(&t));
return cstr;
}
// Timer class
Timer::Timer()
: _start(chrono::system_clock::now()),
_end(chrono::system_clock::now())
{
}
Timer::~Timer()
{
}
void
Timer::start()
{
_start = chrono::system_clock::now();
_end = chrono::system_clock::now();
}
void
Timer::stop()
{
_end = chrono::system_clock::now();
}
void
Timer::reset()
{
_start = chrono::system_clock::now();
_end = chrono::system_clock::now();
}
} // end of namespace datetime
} // end of namespace utils
| 17.172414 | 66 | 0.631526 | alexandretea |
9135f5762b1991c7b3549b6f7a47b86fe68019ac | 318 | cpp | C++ | Demos/ODFAEGVIDEOTUTORIAL/bar.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 5 | 2015-06-13T13:11:59.000Z | 2020-04-17T23:10:23.000Z | Demos/ODFAEGVIDEOTUTORIAL/bar.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 4 | 2019-01-07T11:46:21.000Z | 2020-02-14T15:04:15.000Z | Demos/ODFAEGVIDEOTUTORIAL/bar.cpp | Cwc-Test/ODFAEG | 5e5bd13e3145764c3d0182225aad591040691481 | [
"Zlib"
] | 4 | 2016-01-05T09:54:57.000Z | 2021-01-06T18:52:26.000Z | #include "bar.hpp"
using namespace odfaeg::graphic;
using namespace odfaeg::math;
using namespace odfaeg::physic;
Bar::Bar(Vec2f position, Vec2f size) : Entity(position, size, size * 0.5f, "E_BAR") {
BoundingVolume* bv = new BoundingBox(position.x, position.y, 0 ,size.x, size.y, 0);
setCollisionVolume(bv);
}
| 35.333333 | 87 | 0.716981 | Cwc-Test |
913cb13eefd820e77540f03164b2ed79872be779 | 640 | hpp | C++ | ShadowPeople/sound/Mixer.hpp | SamuelSiltanen/ShadowPeople | 58f94a4397dc5084d9705d4378599cae480b4776 | [
"Apache-2.0"
] | null | null | null | ShadowPeople/sound/Mixer.hpp | SamuelSiltanen/ShadowPeople | 58f94a4397dc5084d9705d4378599cae480b4776 | [
"Apache-2.0"
] | null | null | null | ShadowPeople/sound/Mixer.hpp | SamuelSiltanen/ShadowPeople | 58f94a4397dc5084d9705d4378599cae480b4776 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <memory>
#include <random>
#include "../Types.hpp"
#include "AudioFormat.hpp"
namespace sound
{
class RawAudioBuffer;
class Mixer
{
public:
Mixer(const AudioFormat& format);
void setFormat(const AudioFormat& format);
void mix(std::shared_ptr<RawAudioBuffer> rawAudioBuffer);
private:
void mixUnorm8(Range<uint8_t> data);
void mixUnorm16(Range<uint16_t> data);
void mixUnorm32(Range<uint32_t> data);
void mixFloat32(Range<float> data);
AudioFormat m_format;
float m_mixerTime;
std::mt19937 m_gen;
};
}
| 20 | 65 | 0.635938 | SamuelSiltanen |
913ea9d2070980d26d18cb720a52ff488776a0aa | 14,789 | cpp | C++ | Source/PluginProcessorReceive.cpp | jmaibaum/Camomile | 5801804fd69ad17ef29a026afbff5b5f89224297 | [
"BSD-2-Clause"
] | null | null | null | Source/PluginProcessorReceive.cpp | jmaibaum/Camomile | 5801804fd69ad17ef29a026afbff5b5f89224297 | [
"BSD-2-Clause"
] | null | null | null | Source/PluginProcessorReceive.cpp | jmaibaum/Camomile | 5801804fd69ad17ef29a026afbff5b5f89224297 | [
"BSD-2-Clause"
] | null | null | null | /*
// Copyright (c) 2015-2018 Pierre Guillot.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/
#include "PluginProcessor.h"
#include "PluginParameter.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// MIDI METHODS //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receiveNoteOn(const int channel, const int pitch, const int velocity)
{
if(velocity == 0)
{
m_midi_buffer_out.addEvent(MidiMessage::noteOff(channel, pitch, uint8(0)), m_audio_advancement);
}
else
{
m_midi_buffer_out.addEvent(MidiMessage::noteOn(channel, pitch, static_cast<uint8>(velocity)), m_audio_advancement);
}
}
void CamomileAudioProcessor::receiveControlChange(const int channel, const int controller, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::controllerEvent(channel, controller, value), m_audio_advancement);
}
void CamomileAudioProcessor::receiveProgramChange(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::programChange(channel, value), m_audio_advancement);
}
void CamomileAudioProcessor::receivePitchBend(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::pitchWheel(channel, value + 8192), m_audio_advancement);
}
void CamomileAudioProcessor::receiveAftertouch(const int channel, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::channelPressureChange(channel, value), m_audio_advancement);
}
void CamomileAudioProcessor::receivePolyAftertouch(const int channel, const int pitch, const int value)
{
m_midi_buffer_out.addEvent(MidiMessage::aftertouchChange(channel, pitch, value), m_audio_advancement);
}
void CamomileAudioProcessor::receiveMidiByte(const int port, const int byte)
{
m_midi_buffer_out.addEvent(MidiMessage(byte), m_audio_advancement);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// PRINT METHOD //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receivePrint(const std::string& message)
{
if(!message.empty())
{
if(!message.compare(0, 6, "error:"))
{
std::string const temp(message.begin()+7, message.end());
add(ConsoleLevel::Error, temp);
}
else if(!message.compare(0, 11, "verbose(4):"))
{
std::string const temp(message.begin()+12, message.end());
add(ConsoleLevel::Error, temp);
}
else if(!message.compare(0, 5, "tried"))
{
add(ConsoleLevel::Log, message);
}
else if(!message.compare(0, 16, "input channels ="))
{
add(ConsoleLevel::Log, message);
}
else
{
add(ConsoleLevel::Normal, message);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// MESSAGE METHOD //
//////////////////////////////////////////////////////////////////////////////////////////////
void CamomileAudioProcessor::receiveMessage(const std::string& msg, const std::vector<pd::Atom>& list)
{
if(msg == std::string("param"))
{
if(list.size() >= 2 && list[0].isSymbol() && list[1].isFloat())
{
std::string const method = list[0].getSymbol();
int const index = static_cast<int>(list[1].getFloat()) - 1;
if(method == "set")
{
if(list.size() >= 3 && list[2].isFloat())
{
CamomileAudioParameter* param = static_cast<CamomileAudioParameter *>(getParameters()[index]);
if(param)
{
param->setOriginalScaledValueNotifyingHost(list[2].getFloat());
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter set method extra arguments"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter set method index: out of range"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter set method: wrong argument"); }
}
else if(method == "change")
{
if(list.size() >= 3 && list[2].isFloat())
{
AudioProcessorParameter* param = getParameters()[index];
if(param)
{
if(list[2].getFloat() > std::numeric_limits<float>::epsilon())
{
if(m_params_states[index])
{
add(ConsoleLevel::Error,
"camomile parameter change " + std::to_string(index+1) + " already started");
}
else
{
param->beginChangeGesture();
m_params_states[index] = true;
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter change method extra arguments"); }
}
}
else
{
if(!m_params_states[index])
{
add(ConsoleLevel::Error,
"camomile parameter change " + std::to_string(index+1) + " not started");
}
else
{
param->endChangeGesture();
m_params_states[index] = false;
if(list.size() > 3) { add(ConsoleLevel::Error,
"camomile parameter change method extra arguments"); }
}
}
}
else { add(ConsoleLevel::Error,
"camomile parameter change method index: out of range"); }
}
else { add(ConsoleLevel::Error,
"camomile parameter change method: wrong argument"); }
}
else { add(ConsoleLevel::Error,
"camomile param no method: " + method); }
}
else { add(ConsoleLevel::Error,
"camomile param error syntax: method index..."); }
}
else if(msg == std::string("program"))
{
parseProgram(list);
}
else if(msg == std::string("openpanel"))
{
parseOpenPanel(list);
}
else if(msg == std::string("savepanel"))
{
parseSavePanel(list);
}
else if(msg == std::string("array"))
{
parseArray(list);
}
else if(msg == std::string("save"))
{
parseSaveInformation(list);
}
else if(msg == std::string("gui"))
{
parseGui(list);
}
else if(msg == std::string("audio"))
{
parseAudio(list);
}
else { add(ConsoleLevel::Error, "camomile unknow message : " + msg); }
}
void CamomileAudioProcessor::parseProgram(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1 && list[0].isSymbol() && list[0].getSymbol() == "updated")
{
updateHostDisplay();
}
else
{
add(ConsoleLevel::Error, "camomile program method accepts updated method only");
}
}
void CamomileAudioProcessor::parseOpenPanel(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list.size() > 1)
{
if(list[1].isSymbol())
{
if(list[1].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string("-s")});
}
else if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[1].getSymbol(), std::string("-s")});
}
else
{
add(ConsoleLevel::Error, "camomile openpanel one argument must be a flag \"-s\"");
}
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile openpanel method extra arguments");
}
}
else
{
add(ConsoleLevel::Error, "camomile openpanel second argument must be a symbol");
}
}
else
{
if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string("-s")});
}
else
{
m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string()});
}
}
}
else
{
add(ConsoleLevel::Error, "camomile openpanel method argument must be a symbol");
}
}
else
{
m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string()});
}
}
void CamomileAudioProcessor::parseSavePanel(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list.size() > 1)
{
if(list[1].isSymbol())
{
if(list[1].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string("-s")});
}
else if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[1].getSymbol(), std::string("-s")});
}
else
{
add(ConsoleLevel::Error, "camomile savepanel one argument must be a flag \"-s\"");
}
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile savepanel method extra arguments");
}
}
else
{
add(ConsoleLevel::Error, "camomile savepanel second argument must be a symbol");
}
}
else
{
if(list[0].getSymbol() == "-s")
{
m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string("-s")});
}
else
{
m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string()});
}
}
}
else
{
add(ConsoleLevel::Error, "camomile savepanel method argument must be a symbol");
}
}
else
{
m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string()});
}
}
void CamomileAudioProcessor::parseArray(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
m_queue_gui.try_enqueue({std::string("array"), list[0].getSymbol(), ""});
if(list.size() > 1)
{
add(ConsoleLevel::Error, "camomile array method extra arguments");
}
}
else { add(ConsoleLevel::Error, "camomile array method argument must be a symbol"); }
}
else
{
add(ConsoleLevel::Error, "camomile array needs a name");
}
}
void CamomileAudioProcessor::parseGui(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
m_queue_gui.try_enqueue({std::string("gui"), list[0].getSymbol(), ""});
if(list.size() > 1)
{
add(ConsoleLevel::Error, "camomile gui method extra arguments");
}
}
else { add(ConsoleLevel::Error, "camomile gui method argument must be a symbol"); }
}
else
{
add(ConsoleLevel::Error, "camomile gui needs a command");
}
}
void CamomileAudioProcessor::parseAudio(const std::vector<pd::Atom>& list)
{
if(list.size() >= 1)
{
if(list[0].isSymbol())
{
if(list[0].getSymbol() == std::string("latency"))
{
if(list.size() >= 2 && list[1].isFloat())
{
const int latency = static_cast<int>(list[1].getFloat());
if(latency >= 0)
{
setLatencySamples(latency + Instance::getBlockSize());
if(list.size() > 2)
{
add(ConsoleLevel::Error, "camomile audio method: latency option extra arguments");
}
if(CamomileEnvironment::isLatencyInitialized())
{
add(ConsoleLevel::Error, "camomile audio method: latency overwrites the preferences");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: latency must be positive or null");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: latency option expects a number");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: unknown option \"" + list[0].getSymbol() + "\"");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: first argument must be an option");
}
}
else
{
add(ConsoleLevel::Error, "camomile audio method: expects arguments");
}
}
| 36.070732 | 123 | 0.451349 | jmaibaum |
913ec1eb1a1e01c777765330a73ea5f9d8a3a13c | 3,585 | hpp | C++ | include/staticlib/tinydir/file_sink.hpp | staticlibs/staticlib_tinydir | c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610 | [
"Apache-2.0"
] | 1 | 2021-03-13T03:12:23.000Z | 2021-03-13T03:12:23.000Z | include/staticlib/tinydir/file_sink.hpp | staticlibs/staticlib_tinydir | c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610 | [
"Apache-2.0"
] | 1 | 2018-10-18T21:31:26.000Z | 2018-10-18T21:31:26.000Z | include/staticlib/tinydir/file_sink.hpp | staticlibs/staticlib_tinydir | c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610 | [
"Apache-2.0"
] | 2 | 2017-03-05T02:30:03.000Z | 2018-05-21T16:17:31.000Z | /*
* Copyright 2017, alex at staticlibs.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* File: file_sink.hpp
* Author: alex
*
* Created on February 6, 2017, 2:44 PM
*/
#ifndef STATICLIB_TINYDIR_FILE_SINK_HPP
#define STATICLIB_TINYDIR_FILE_SINK_HPP
#include <string>
#include "staticlib/config.hpp"
#include "staticlib/io/span.hpp"
#include "staticlib/tinydir/tinydir_exception.hpp"
namespace staticlib {
namespace tinydir {
/**
* Implementation of a file descriptor/handle wrapper with a
* unified interface for *nix and windows
*/
class file_sink {
#ifdef STATICLIB_WINDOWS
void* handle = nullptr;
#else // STATICLIB_WINDOWS
/**
* Native file descriptor (handle on windows)
*/
int fd = -1;
#endif // STATICLIB_WINDOWS
/**
* Path to file
*/
std::string file_path;
public:
/**
* File open mode
*/
enum class open_mode {
create, append, from_file
};
/**
* Constructor
*
* @param file_path path to file
*/
file_sink(const std::string& file_path, open_mode mode = open_mode::create);
/**
* Destructor, will close the descriptor
*/
~file_sink() STATICLIB_NOEXCEPT;
/**
* Deleted copy constructor
*
* @param other instance
*/
file_sink(const file_sink&) = delete;
/**
* Deleted copy assignment operator
*
* @param other instance
* @return this instance
*/
file_sink& operator=(const file_sink&) = delete;
/**
* Move constructor
*
* @param other other instance
*/
file_sink(file_sink&& other) STATICLIB_NOEXCEPT;
/**
* Move assignment operator
*
* @param other other instance
* @return this instance
*/
file_sink& operator=(file_sink&& other) STATICLIB_NOEXCEPT;
/**
* Writes specified number of bytes to this file descriptor
*
* @param buf source buffer
* @param count number of bytes to write
* @return number of bytes successfully written
*/
std::streamsize write(sl::io::span<const char> span);
/**
* Writes the contents of the specified file to this file descriptor
*
* @param string source file path
* @return number of bytes successfully written
*/
std::streamsize write_from_file(const std::string& source_file);
/**
* Seeks over this file descriptor
*
* @param offset offset to seek with starting from the current position
* @return resulting offset location as measured in bytes from the beginning of the file
*/
std::streampos seek(std::streamsize offset);
/**
* No-op
*
* @return zero
*/
std::streamsize flush();
/**
* Closed the underlying file descriptor, will be called automatically
* on destruction
*/
void close() STATICLIB_NOEXCEPT;
/**
* File path accessor
*
* @return path to this file
*/
const std::string& path() const;
};
} // namespace
}
#endif /* STATICLIB_TINYDIR_FILE_SINK_HPP */
| 22.980769 | 92 | 0.642678 | staticlibs |
91401b573cbfc972a277cf047c1f76ed67d81f83 | 2,598 | cpp | C++ | test/module/libs/converter/string_converter_test.cpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | test/module/libs/converter/string_converter_test.cpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | test/module/libs/converter/string_converter_test.cpp | alohamora/iroha | aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include <gtest/gtest.h>
#include "common/byteutils.hpp"
using namespace iroha;
using namespace std::string_literals;
/**
* @given hex string
* @when hex string was converted to binary string
* @then converted string match the result we are expected
*/
TEST(StringConverterTest, ConvertHexToBinary) {
std::string hex = "ff000233551117daa110050399";
std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s;
ASSERT_EQ(hexstringToBytestring(hex).value(), bin);
}
/**
* @given invalid hex string
* @when string is converted to binary string
* @then std::nullopt is returned
*/
TEST(StringConverterTest, InvalidHexToBinary) {
std::string invalid_hex = "au";
ASSERT_FALSE(hexstringToBytestring(invalid_hex));
}
/**
* @given binary string
* @when binary string was converted to hex string
* @then converted string match the result we are expected
*/
TEST(StringConverterTest, ConvertBinaryToHex) {
std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s;
ASSERT_EQ(bytestringToHexstring(bin), "ff000233551117daa110050399");
}
/**
* @given hex string of length 256 with all possible byte values
* @when convert it to byte string and back
* @then resulted string is the same as given one
*/
TEST(StringConverterTest, ConvertHexToBinaryAndBack) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (int i = 0; i < 256; ++i) {
ss << std::setw(2) << i;
}
ASSERT_EQ(ss.str(),
bytestringToHexstring(hexstringToBytestring(ss.str()).value()));
}
/**
* @given numeric value
* @when converting it to a hex string
* @then converted string match expected result
*/
TEST(StringConverterTest, ConvertNumToHex) {
// Testing uint64_t values
std::vector<uint64_t> vals64{
0x4234324309085, 0x34532, 0x0, 0x1, 0x3333333333333333};
std::vector<std::string> hexes{"0004234324309085",
"0000000000034532",
"0000000000000000",
"0000000000000001",
"3333333333333333"};
for (size_t i = 0; i < vals64.size(); i++)
ASSERT_EQ(numToHexstring(vals64[i]), hexes[i]);
// Testing int32_t values
std::vector<int32_t> vals32{0x42343243, 0x34532, 0x0, 0x1, 0x79999999};
std::vector<std::string> hexes2{
"42343243", "00034532", "00000000", "00000001", "79999999"};
for (size_t i = 0; i < vals32.size(); i++)
ASSERT_EQ(numToHexstring(vals32[i]), hexes2[i]);
}
| 31.682927 | 76 | 0.669746 | alohamora |
91409ed7e7e1fad82fdd8058dadd1918cf6ab2f6 | 4,744 | hpp | C++ | octree/Octree.hpp | Koukan/voxomap | 104a068b4bc84f7a208460248f824dfcde49f470 | [
"MIT"
] | 2 | 2019-03-01T16:34:02.000Z | 2020-10-08T21:27:52.000Z | octree/Octree.hpp | Koukan/voxomap | 104a068b4bc84f7a208460248f824dfcde49f470 | [
"MIT"
] | null | null | null | octree/Octree.hpp | Koukan/voxomap | 104a068b4bc84f7a208460248f824dfcde49f470 | [
"MIT"
] | null | null | null | #ifndef _VOXOMAP_OCTREE_HPP_
#define _VOXOMAP_OCTREE_HPP_
#include <cstdint>
#include <memory>
#include <vector>
#include <assert.h>
namespace voxomap
{
/*!
\defgroup Octree Octree
Classes use for define the octree
*/
/*! \class Octree
\ingroup Octree
\brief Octree container
*/
template <class T_Node>
class Octree
{
public:
using Node = T_Node;
/*!
\brief Default constructor
*/
Octree();
/*!
\brief Copy constructor
*/
Octree(Octree const& other);
/*!
\brief Move constructor
*/
Octree(Octree&& other);
/*!
\brief Default virtual destructor
*/
virtual ~Octree() = default;
/*!
\brief Assignement operator
\param other Right operand
\return Reference to \a this
*/
Octree& operator=(Octree const& other);
/*!
\brief Assignement move operator
\param other Right operand
\return Reference to \a this
*/
Octree& operator=(Octree&& other);
/*!
\brief Pushes \a node into the octree
\param node Node to push
*/
virtual T_Node* push(T_Node& node);
/*!
\brief Removes \a node from the octree
\return
*/
virtual std::unique_ptr<T_Node> pop(T_Node& node);
/*!
\brief Search the node that corresponds to the parameters
\param x X coordinate of the node
\param y Y coordinate of the node
\param z Z coordinate of the node
\param size Size of the node
\return Pointer to the node if it exists otherwise nullptr
*/
T_Node* findNode(int x, int y, int z, uint32_t size) const;
/*!
\brief Clear the octree
Removes all nodes and all elements.
*/
virtual void clear();
/*!
\brief Getter of the root node
\return The root node
*/
T_Node* getRootNode() const;
protected:
// Node method
/*!
\brief Set \a child as child of \a parent
\param parent Parent node
\param child Child node
*/
void setChild(T_Node& parent, T_Node& child);
/*!
\brief Set \a child as child of \a parent
\param parent Parent node
\param child Child node
\param childId Id of the child inside parent's children array
*/
void setChild(T_Node& parent, T_Node& child, uint8_t childId);
/*!
\brief Remove \a child from its parent and so from the octree
*/
void removeFromParent(T_Node& child);
/*!
\brief Remove the child with \a id from the \a parent node
\return The removed node
*/
T_Node* removeChild(T_Node& parent, uint8_t id);
/*!
\brief Find node inside \a parent that can contain \a node
\param parent Parent node
\param node The new node
\param childId Id of the node inside the found parent
\return The found parent node, nullptr if not exist
*/
T_Node* findParentNode(T_Node& parent, T_Node& node, uint8_t& childId) const;
/*!
\brief Push \a node inside \a parent
\param parent Parent node
\param node Node to push
\return Node added, can be different than \a node if a similar node already exist
*/
T_Node* push(T_Node& parent, T_Node& node);
/*!
\brief Push \a node inside \a parent
\param parent Parent node
\param child Child node
\param childId Id of the child inside parent's children array
\return Node added, can be different than \a node if a similar node already exist
*/
T_Node* push(T_Node& parent, T_Node& child, uint8_t childId);
/*!
\brief Create an intermediate node that can contain \a child and \a newChild and push it into octree
*/
void insertIntermediateNode(T_Node& child, T_Node& newChild);
/*!
\brief Merge two nodes
\param currentNode Node already present in the octree
\param newNode Node to merge inside
*/
void merge(T_Node& currentNode, T_Node& newNode);
/*!
\brief Remove useless intermediate node, intermediate node with only one child
\param node The intermediate node
*/
void removeUselessIntermediateNode(T_Node& node);
/*!
\brief Compute the new coordinates and size of the NegPosRootNode
*/
void recomputeNegPosRootNode();
/*!
\brief Called when \a node is remove from the octree
*/
virtual void notifyNodeRemoving(T_Node& node);
std::unique_ptr<T_Node> _rootNode; //!< Main node of the octree
};
}
#include "Octree.ipp"
#endif // _VOXOMAP_OCTREE_HPP_ | 28.578313 | 108 | 0.60645 | Koukan |
914132746cecdd6b5bb28f6a9916459143ab1fed | 2,785 | cpp | C++ | rtc/src/main.cpp | Bergi84/vihaltests_ext | 6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e | [
"BSD-2-Clause"
] | null | null | null | rtc/src/main.cpp | Bergi84/vihaltests_ext | 6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e | [
"BSD-2-Clause"
] | null | null | null | rtc/src/main.cpp | Bergi84/vihaltests_ext | 6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e | [
"BSD-2-Clause"
] | null | null | null | // file: main.cpp (uart)
// brief: VIHAL UART Test
// created: 2021-10-03
// authors: nvitya
#include "platform.h"
#include "cppinit.h"
#include "clockcnt.h"
#include "traces.h"
#include "hwclk.h"
#include "hwpins.h"
#include "hwuart.h"
#include "hwrtc.h"
#include "board_pins.h"
THwRtc gRtc;
volatile unsigned hbcounter = 0;
extern "C" __attribute__((noreturn)) void _start(unsigned self_flashing) // self_flashing = 1: self-flashing required for RAM-loaded applications
{
// after ram setup and region copy the cpu jumps here, with probably RC oscillator
mcu_disable_interrupts();
// Set the interrupt vector table offset, so that the interrupts and exceptions work
mcu_init_vector_table();
// run the C/C++ initialization (variable initializations, constructors)
cppinit();
if (!hwclk_init(EXTERNAL_XTAL_HZ, MCU_CLOCK_SPEED)) // if the EXTERNAL_XTAL_HZ == 0, then the internal RC oscillator will be used
{
while (1)
{
// error
}
}
hwlsclk_init(true);
mcu_enable_fpu(); // enable coprocessor if present
mcu_enable_icache(); // enable instruction cache if present
clockcnt_init();
// go on with the hardware initializations
board_pins_init();
gRtc.init();
THwRtc::time_t startTime, lastTime;
startTime.msec = 768;
startTime.sec = 13;
startTime.min = 43;
startTime.hour = 13;
startTime.day = 13;
startTime.month = 03;
startTime.year = 22;
gRtc.setTime(startTime, lastTime);
THwRtc::time_t aktTime;
gRtc.getTime(aktTime);
TRACE("\r\n--------------------------------------\r\n");
TRACE("%sHello From VIHAL !\r\n", CC_BLU);
TRACE("Board: %s\r\n", BOARD_NAME);
TRACE("SystemCoreClock: %u\r\n", SystemCoreClock);
TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year);
gRtc.enableWakeupIRQ();
gRtc.setWakeupTimer(100);
mcu_enable_interrupts();
// Infinite loop
while (1)
{
}
}
extern "C" void IRQ_Handler_03()
{
++hbcounter;
if (hbcounter == 20)
{
gRtc.setWakeupTimer(500);
}
THwRtc::time_t aktTime;
gRtc.getTime(aktTime);
switch(hbcounter%8)
{
case 0: TRACE("%s", CC_NRM); break;
case 1: TRACE("%s", CC_RED); break;
case 2: TRACE("%s", CC_GRN); break;
case 3: TRACE("%s", CC_YEL); break;
case 4: TRACE("%s", CC_BLU); break;
case 5: TRACE("%s", CC_MAG); break;
case 6: TRACE("%s", CC_CYN); break;
case 7: TRACE("%s", CC_WHT); break;
}
TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year);
gRtc.clearWakeupIRQ();
}
// ----------------------------------------------------------------------------
| 25.09009 | 159 | 0.644883 | Bergi84 |
91424f7e6fffe7065a55386e569947453016e96f | 18,465 | cpp | C++ | Source Code/Rendering/PostFX/PostFX.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Rendering/PostFX/PostFX.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | Source Code/Rendering/PostFX/PostFX.cpp | IonutCava/trunk | 19dc976bbd7dc637f467785bd0ca15f34bc31ed5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Headers/PostFX.h"
#include "Headers/PreRenderOperator.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/PlatformContext.h"
#include "Core/Headers/StringHelper.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Geometry/Shapes/Predefined/Headers/Quad3D.h"
#include "Managers/Headers/SceneManager.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/CommandBuffer.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Rendering/Camera/Headers/Camera.h"
namespace Divide {
const char* PostFX::FilterName(const FilterType filter) noexcept {
switch (filter) {
case FilterType::FILTER_SS_ANTIALIASING: return "SS_ANTIALIASING";
case FilterType::FILTER_SS_REFLECTIONS: return "SS_REFLECTIONS";
case FilterType::FILTER_SS_AMBIENT_OCCLUSION: return "SS_AMBIENT_OCCLUSION";
case FilterType::FILTER_DEPTH_OF_FIELD: return "DEPTH_OF_FIELD";
case FilterType::FILTER_MOTION_BLUR: return "MOTION_BLUR";
case FilterType::FILTER_BLOOM: return "BLOOM";
case FilterType::FILTER_LUT_CORECTION: return "LUT_CORRECTION";
case FilterType::FILTER_UNDERWATER: return "UNDERWATER";
case FilterType::FILTER_NOISE: return "NOISE";
case FilterType::FILTER_VIGNETTE: return "VIGNETTE";
default: break;
}
return "Unknown";
};
PostFX::PostFX(PlatformContext& context, ResourceCache* cache)
: PlatformContextComponent(context),
_preRenderBatch(context.gfx(), *this, cache)
{
std::atomic_uint loadTasks = 0u;
context.paramHandler().setParam<bool>(_ID("postProcessing.enableVignette"), false);
DisableAll(_postFXTarget._drawMask);
SetEnabled(_postFXTarget._drawMask, RTAttachmentType::Colour, to_U8(GFXDevice::ScreenTargets::ALBEDO), true);
Console::printfn(Locale::Get(_ID("START_POST_FX")));
ShaderModuleDescriptor vertModule = {};
vertModule._moduleType = ShaderType::VERTEX;
vertModule._sourceFile = "baseVertexShaders.glsl";
vertModule._variant = "FullScreenQuad";
ShaderModuleDescriptor fragModule = {};
fragModule._moduleType = ShaderType::FRAGMENT;
fragModule._sourceFile = "postProcessing.glsl";
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCREEN %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_NOISE %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_NOISE)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_BORDER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_BORDER)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_UNDERWATER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SSR %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SSR)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_DATA %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_VELOCITY %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_LINDEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH)));
fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_DEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH)));
ShaderProgramDescriptor postFXShaderDescriptor = {};
postFXShaderDescriptor._modules.push_back(vertModule);
postFXShaderDescriptor._modules.push_back(fragModule);
_drawConstantsCmd._constants.set(_ID("_noiseTile"), GFX::PushConstantType::FLOAT, 0.1f);
_drawConstantsCmd._constants.set(_ID("_noiseFactor"), GFX::PushConstantType::FLOAT, 0.02f);
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false);
_drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, vec2<F32>(0.01f, 500.0f));
TextureDescriptor texDescriptor(TextureType::TEXTURE_2D);
ImageTools::ImportOptions options;
options._isNormalMap = true;
options._useDDSCache = true;
options._outputSRGB = false;
options._alphaChannelTransparency = false;
texDescriptor.textureOptions(options);
ResourceDescriptor textureWaterCaustics("Underwater Normal Map");
textureWaterCaustics.assetName(ResourcePath("terrain_water_NM.jpg"));
textureWaterCaustics.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
textureWaterCaustics.propertyDescriptor(texDescriptor);
textureWaterCaustics.waitForReady(false);
_underwaterTexture = CreateResource<Texture>(cache, textureWaterCaustics, loadTasks);
options._isNormalMap = false;
texDescriptor.textureOptions(options);
ResourceDescriptor noiseTexture("noiseTexture");
noiseTexture.assetName(ResourcePath("bruit_gaussien.jpg"));
noiseTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
noiseTexture.propertyDescriptor(texDescriptor);
noiseTexture.waitForReady(false);
_noise = CreateResource<Texture>(cache, noiseTexture, loadTasks);
ResourceDescriptor borderTexture("borderTexture");
borderTexture.assetName(ResourcePath("vignette.jpeg"));
borderTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation);
borderTexture.propertyDescriptor(texDescriptor);
borderTexture.waitForReady(false);
_screenBorder = CreateResource<Texture>(cache, borderTexture), loadTasks;
_noiseTimer = 0.0;
_tickInterval = 1.0f / 24.0f;
_randomNoiseCoefficient = 0;
_randomFlashCoefficient = 0;
ResourceDescriptor postFXShader("postProcessing");
postFXShader.propertyDescriptor(postFXShaderDescriptor);
_postProcessingShader = CreateResource<ShaderProgram>(cache, postFXShader, loadTasks);
_postProcessingShader->addStateCallback(ResourceState::RES_LOADED, [this, &context](CachedResource*) {
PipelineDescriptor pipelineDescriptor;
pipelineDescriptor._stateHash = context.gfx().get2DStateBlock();
pipelineDescriptor._shaderProgramHandle = _postProcessingShader->handle();
pipelineDescriptor._primitiveTopology = PrimitiveTopology::TRIANGLES;
_drawPipeline = context.gfx().newPipeline(pipelineDescriptor);
});
WAIT_FOR_CONDITION(loadTasks.load() == 0);
}
PostFX::~PostFX()
{
}
void PostFX::updateResolution(const U16 newWidth, const U16 newHeight) {
if (_resolutionCache.width == newWidth &&
_resolutionCache.height == newHeight||
newWidth < 1 || newHeight < 1)
{
return;
}
_resolutionCache.set(newWidth, newHeight);
_preRenderBatch.reshape(newWidth, newHeight);
_setCameraCmd._cameraSnapshot = Camera::GetUtilityCamera(Camera::UtilityCamera::_2D)->snapshot();
}
void PostFX::prePass(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) {
static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: PrePass" };
GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd);
GFX::EnqueueCommand<GFX::PushCameraCommand>(bufferInOut)->_cameraSnapshot = _setCameraCmd._cameraSnapshot;
_preRenderBatch.prePass(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut);
GFX::EnqueueCommand<GFX::PopCameraCommand>(bufferInOut);
GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut);
}
void PostFX::apply(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) {
static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: Apply" };
GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd);
GFX::EnqueueCommand(bufferInOut, _setCameraCmd);
_preRenderBatch.execute(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut);
GFX::BeginRenderPassCommand beginRenderPassCmd{};
beginRenderPassCmd._target = RenderTargetNames::SCREEN;
beginRenderPassCmd._descriptor = _postFXTarget;
beginRenderPassCmd._name = "DO_POSTFX_PASS";
GFX::EnqueueCommand(bufferInOut, beginRenderPassCmd);
GFX::EnqueueCommand(bufferInOut, GFX::BindPipelineCommand{ _drawPipeline });
if (_filtersDirty) {
_drawConstantsCmd._constants.set(_ID("vignetteEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_VIGNETTE));
_drawConstantsCmd._constants.set(_ID("noiseEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_NOISE));
_drawConstantsCmd._constants.set(_ID("underwaterEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_UNDERWATER));
_drawConstantsCmd._constants.set(_ID("lutCorrectionEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_LUT_CORECTION));
_filtersDirty = false;
};
_drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, cameraSnapshot._zPlanes);
_drawConstantsCmd._constants.set(_ID("_invProjectionMatrix"), GFX::PushConstantType::VEC2, cameraSnapshot._invProjectionMatrix);
GFX::EnqueueCommand(bufferInOut, _drawConstantsCmd);
const auto& rtPool = context().gfx().renderTargetPool();
const auto& prbAtt = _preRenderBatch.getOutput(false)._rt->getAttachment(RTAttachmentType::Colour, 0);
const auto& linDepthDataAtt =_preRenderBatch.getLinearDepthRT()._rt->getAttachment(RTAttachmentType::Colour, 0);
const auto& ssrDataAtt = rtPool.getRenderTarget(RenderTargetNames::SSR_RESULT)->getAttachment(RTAttachmentType::Colour, 0);
const auto& sceneDataAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::NORMALS));
const auto& velocityAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::VELOCITY));
const auto& depthAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Depth_Stencil, 0);
SamplerDescriptor defaultSampler = {};
defaultSampler.wrapUVW(TextureWrap::REPEAT);
const size_t samplerHash = defaultSampler.getHash();
DescriptorSet& set = GFX::EnqueueCommand<GFX::BindDescriptorSetsCommand>(bufferInOut)->_set;
set._usage = DescriptorSetUsage::PER_DRAW_SET;
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { prbAtt->texture()->data(), prbAtt->descriptor()._samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { depthAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { linDepthDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SSR);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { ssrDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { sceneDataAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { velocityAtt->texture()->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _underwaterTexture->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_NOISE);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _noise->data(), samplerHash };
}
{
auto& binding = set._bindings.emplace_back();
binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER;
binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_BORDER);
binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT;
binding._data.As<DescriptorCombinedImageSampler>() = { _screenBorder->data(), samplerHash };
}
GFX::EnqueueCommand<GFX::DrawCommand>(bufferInOut);
GFX::EnqueueCommand(bufferInOut, GFX::EndRenderPassCommand{});
GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut);
}
void PostFX::idle(const Configuration& config) {
OPTICK_EVENT();
// Update states
if (getFilterState(FilterType::FILTER_NOISE)) {
_noiseTimer += Time::Game::ElapsedMilliseconds();
if (_noiseTimer > _tickInterval) {
_noiseTimer = 0.0;
_randomNoiseCoefficient = Random(1000) * 0.001f;
_randomFlashCoefficient = Random(1000) * 0.001f;
}
_drawConstantsCmd._constants.set(_ID("randomCoeffNoise"), GFX::PushConstantType::FLOAT, _randomNoiseCoefficient);
_drawConstantsCmd._constants.set(_ID("randomCoeffFlash"), GFX::PushConstantType::FLOAT, _randomFlashCoefficient);
}
}
void PostFX::update(const U64 deltaTimeUSFixed, const U64 deltaTimeUSApp) {
OPTICK_EVENT();
if (_fadeActive) {
_currentFadeTimeMS += Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp);
F32 fadeStrength = to_F32(std::min(_currentFadeTimeMS / _targetFadeTimeMS , 1.0));
if (!_fadeOut) {
fadeStrength = 1.0f - fadeStrength;
}
if (fadeStrength > 0.99) {
if (_fadeWaitDurationMS < std::numeric_limits<D64>::epsilon()) {
if (_fadeOutComplete) {
_fadeOutComplete();
_fadeOutComplete = DELEGATE<void>();
}
} else {
_fadeWaitDurationMS -= Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp);
}
}
_drawConstantsCmd._constants.set(_ID("_fadeStrength"), GFX::PushConstantType::FLOAT, fadeStrength);
_fadeActive = fadeStrength > std::numeric_limits<D64>::epsilon();
if (!_fadeActive) {
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false);
if (_fadeInComplete) {
_fadeInComplete();
_fadeInComplete = DELEGATE<void>();
}
}
}
_preRenderBatch.update(deltaTimeUSApp);
}
void PostFX::setFadeOut(const UColour3& targetColour, const D64 durationMS, const D64 waitDurationMS, DELEGATE<void> onComplete) {
_drawConstantsCmd._constants.set(_ID("_fadeColour"), GFX::PushConstantType::VEC4, Util::ToFloatColour(targetColour));
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true);
_targetFadeTimeMS = durationMS;
_currentFadeTimeMS = 0.0;
_fadeWaitDurationMS = waitDurationMS;
_fadeOut = true;
_fadeActive = true;
_fadeOutComplete = MOV(onComplete);
}
// clear any fading effect currently active over the specified time interval
// set durationMS to instantly clear the fade effect
void PostFX::setFadeIn(const D64 durationMS, DELEGATE<void> onComplete) {
_targetFadeTimeMS = durationMS;
_currentFadeTimeMS = 0.0;
_fadeOut = false;
_fadeActive = true;
_drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true);
_fadeInComplete = MOV(onComplete);
}
void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 waitDurationMS) {
if (waitDurationMS > 0.0) {
setFadeOutIn(targetColour, waitDurationMS * 0.5, waitDurationMS * 0.5, durationFadeOutMS);
}
}
void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 durationFadeInMS, const D64 waitDurationMS) {
setFadeOut(targetColour, durationFadeOutMS, waitDurationMS, [this, durationFadeInMS]() {setFadeIn(durationFadeInMS); });
}
};
| 51.008287 | 167 | 0.730355 | IonutCava |
91446e3be5af90f48f56537f2b0d19e44bf57785 | 35,694 | cpp | C++ | mp/src/game/server/hl2mp/hl2mp_client.cpp | Code4Cookie/Atomic-Secobmod | 9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70 | [
"Unlicense"
] | null | null | null | mp/src/game/server/hl2mp/hl2mp_client.cpp | Code4Cookie/Atomic-Secobmod | 9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70 | [
"Unlicense"
] | null | null | null | mp/src/game/server/hl2mp/hl2mp_client.cpp | Code4Cookie/Atomic-Secobmod | 9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70 | [
"Unlicense"
] | null | null | null | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
/*
===== tf_client.cpp ========================================================
HL2 client/server game specific stuff
*/
#include "cbase.h"
#include "hl2mp_player.h"
#include "hl2mp_gamerules.h"
#include "gamerules.h"
#include "teamplay_gamerules.h"
#include "entitylist.h"
#include "physics.h"
#include "game.h"
#include "player_resource.h"
#include "engine/IEngineSound.h"
#include "team.h"
#include "viewport_panel_names.h"
#include "tier0/vprof.h"
#ifdef SecobMod__SAVERESTORE
#include "filesystem.h"
#endif //SecobMod__SAVERESTORE
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
void Host_Say(edict_t *pEdict, bool teamonly);
ConVar sv_motd_unload_on_dismissal("sv_motd_unload_on_dismissal", "0", 0, "If enabled, the MOTD contents will be unloaded when the player closes the MOTD.");
extern CBaseEntity* FindPickerEntityClass(CBasePlayer *pPlayer, char *classname);
extern bool g_fGameOver;
#ifdef SecobMod__USE_PLAYERCLASSES
void SSPlayerClassesBGCheck(CHL2MP_Player *pPlayer)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
UserMessageBegin(user, "SSPlayerClassesBGCheck");
MessageEnd();
}
void ShowSSPlayerClasses(CHL2MP_Player *pPlayer)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
UserMessageBegin(user, "ShowSSPlayerClasses");
MessageEnd();
}
CON_COMMAND(ss_classes_default, "The current map is a background level - do default spawn")
{
CHL2MP_Player *pPlayer = ToHL2MPPlayer(UTIL_GetCommandClient());
if (pPlayer != NULL)
{
CSingleUserRecipientFilter user(pPlayer);
user.MakeReliable();
pPlayer->InitialSpawn();
pPlayer->Spawn();
pPlayer->m_Local.m_iHideHUD |= HIDEHUD_ALL;
pPlayer->RemoveAllItems(true);
//SecobMod__Information These are now commented out because for your own mod you'll have to use the black room spawn method anyway.
// That is for your own maps, you create a seperate room with fully black textures, no light and a single info_player_start.
//You may end up needing to uncomment it if you don't use playerclasses, but you'll figure that out for yourself when you cant see anything but your HUD.
//color32 black = {0,0,0,255};
//UTIL_ScreenFade( pPlayer, black, 0.0f, 0.0f, FFADE_IN|FFADE_PURGE );
}
}
#endif //SecobMod__USE_PLAYERCLASSES
void FinishClientPutInServer(CHL2MP_Player *pPlayer)
{
#ifdef SecobMod__USE_PLAYERCLASSES
pPlayer->InitialSpawn();
pPlayer->Spawn();
pPlayer->RemoveAllItems(true);
SSPlayerClassesBGCheck(pPlayer);
#else
pPlayer->InitialSpawn();
pPlayer->Spawn();
#endif //SecobMod__USE_PLAYERCLASSES
char sName[128];
Q_strncpy(sName, pPlayer->GetPlayerName(), sizeof(sName));
// First parse the name and remove any %'s
for (char *pApersand = sName; pApersand != NULL && *pApersand != 0; pApersand++)
{
// Replace it with a space
if (*pApersand == '%')
*pApersand = ' ';
}
// notify other clients of player joining the game
UTIL_ClientPrintAll(HUD_PRINTNOTIFY, "#Game_connected", sName[0] != 0 ? sName : "<unconnected>");
if (HL2MPRules()->IsTeamplay() == true)
{
ClientPrint(pPlayer, HUD_PRINTTALK, "You are on team %s1\n", pPlayer->GetTeam()->GetName());
}
const ConVar *hostname = cvar->FindVar("hostname");
const char *title = (hostname) ? hostname->GetString() : "MESSAGE OF THE DAY";
KeyValues *data = new KeyValues("data");
data->SetString("title", title); // info panel title
data->SetString("type", "1"); // show userdata from stringtable entry
data->SetString("msg", "motd"); // use this stringtable entry
data->SetBool("unload", sv_motd_unload_on_dismissal.GetBool());
pPlayer->ShowViewPortPanel(PANEL_INFO, true, data);
#ifndef SecobMod__SAVERESTORE
#ifdef SecobMod__USE_PLAYERCLASSES
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
#endif //SecobMod__USE_PLAYERCLASSES
#endif //SecobMod__SAVERESTORE
#ifdef SecobMod__SAVERESTORE
//if (Transitioned)
//{
//SecobMod
KeyValues *pkvTransitionRestoreFile = new KeyValues("transition.cfg");
//Msg ("Transition path is: %s !!!!!\n",TransitionPath);
if (pkvTransitionRestoreFile->LoadFromFile(filesystem, "transition.cfg"))
{
while (pkvTransitionRestoreFile)
{
const char *pszSteamID = pkvTransitionRestoreFile->GetName(); //Gets our header, which we use the players SteamID for.
const char *PlayerSteamID = engine->GetPlayerNetworkIDString(pPlayer->edict()); //Finds the current players Steam ID.
Msg("In-File SteamID is %s.\n", pszSteamID);
Msg("In-Game SteamID is %s.\n", PlayerSteamID);
if (Q_strcmp(PlayerSteamID, pszSteamID) != 0)
{
if (pkvTransitionRestoreFile == NULL)
{
break;
}
//SecobMod__Information No SteamID found for this person, maybe they're new to the game or have "STEAM_ID_PENDING". Show them the class menu and break the loop.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
break;
}
Msg("SteamID Match Found!");
#ifdef SecobMod__USE_PLAYERCLASSES
//Class.
KeyValues *pkvCurrentClass = pkvTransitionRestoreFile->FindKey("CurrentClass");
#endif //SecobMod__USE_PLAYERCLASSES
//Health
KeyValues *pkvHealth = pkvTransitionRestoreFile->FindKey("Health");
//Armour
KeyValues *pkvArmour = pkvTransitionRestoreFile->FindKey("Armour");
//CurrentHeldWeapon
KeyValues *pkvActiveWep = pkvTransitionRestoreFile->FindKey("ActiveWeapon");
//Weapon_0.
KeyValues *pkvWeapon_0 = pkvTransitionRestoreFile->FindKey("Weapon_0");
KeyValues *pkvWeapon_0_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClip");
KeyValues *pkvWeapon_0_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClip");
KeyValues *pkvWeapon_0_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmo");
KeyValues *pkvWeapon_0_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmo");
KeyValues *pkvWeapon_0_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmoLeft");
KeyValues *pkvWeapon_0_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmoLeft");
//Weapon_1.
KeyValues *pkvWeapon_1 = pkvTransitionRestoreFile->FindKey("Weapon_1");
KeyValues *pkvWeapon_1_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClip");
KeyValues *pkvWeapon_1_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClip");
KeyValues *pkvWeapon_1_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmo");
KeyValues *pkvWeapon_1_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmo");
KeyValues *pkvWeapon_1_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmoLeft");
KeyValues *pkvWeapon_1_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmoLeft");
//Weapon_2.
KeyValues *pkvWeapon_2 = pkvTransitionRestoreFile->FindKey("Weapon_2");
KeyValues *pkvWeapon_2_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClip");
KeyValues *pkvWeapon_2_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClip");
KeyValues *pkvWeapon_2_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmo");
KeyValues *pkvWeapon_2_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmo");
KeyValues *pkvWeapon_2_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmoLeft");
KeyValues *pkvWeapon_2_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmoLeft");
//Weapon_3.
KeyValues *pkvWeapon_3 = pkvTransitionRestoreFile->FindKey("Weapon_3");
KeyValues *pkvWeapon_3_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClip");
KeyValues *pkvWeapon_3_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClip");
KeyValues *pkvWeapon_3_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmo");
KeyValues *pkvWeapon_3_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmo");
KeyValues *pkvWeapon_3_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmoLeft");
KeyValues *pkvWeapon_3_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmoLeft");
//Weapon_4.
KeyValues *pkvWeapon_4 = pkvTransitionRestoreFile->FindKey("Weapon_4");
KeyValues *pkvWeapon_4_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClip");
KeyValues *pkvWeapon_4_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClip");
KeyValues *pkvWeapon_4_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmo");
KeyValues *pkvWeapon_4_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmo");
KeyValues *pkvWeapon_4_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmoLeft");
KeyValues *pkvWeapon_4_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmoLeft");
//Weapon_5.
KeyValues *pkvWeapon_5 = pkvTransitionRestoreFile->FindKey("Weapon_5");
KeyValues *pkvWeapon_5_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClip");
KeyValues *pkvWeapon_5_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClip");
KeyValues *pkvWeapon_5_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmo");
KeyValues *pkvWeapon_5_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmo");
KeyValues *pkvWeapon_5_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmoLeft");
KeyValues *pkvWeapon_5_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmoLeft");
//Weapon_6.
KeyValues *pkvWeapon_6 = pkvTransitionRestoreFile->FindKey("Weapon_6");
KeyValues *pkvWeapon_6_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClip");
KeyValues *pkvWeapon_6_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClip");
KeyValues *pkvWeapon_6_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmo");
KeyValues *pkvWeapon_6_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmo");
KeyValues *pkvWeapon_6_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmoLeft");
KeyValues *pkvWeapon_6_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmoLeft");
//Weapon_7.
KeyValues *pkvWeapon_7 = pkvTransitionRestoreFile->FindKey("Weapon_7");
KeyValues *pkvWeapon_7_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClip");
KeyValues *pkvWeapon_7_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClip");
KeyValues *pkvWeapon_7_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmo");
KeyValues *pkvWeapon_7_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmo");
KeyValues *pkvWeapon_7_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmoLeft");
KeyValues *pkvWeapon_7_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmoLeft");
//Weapon_8.
KeyValues *pkvWeapon_8 = pkvTransitionRestoreFile->FindKey("Weapon_8");
KeyValues *pkvWeapon_8_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClip");
KeyValues *pkvWeapon_8_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClip");
KeyValues *pkvWeapon_8_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmo");
KeyValues *pkvWeapon_8_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmo");
KeyValues *pkvWeapon_8_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmoLeft");
KeyValues *pkvWeapon_8_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmoLeft");
//Weapon_9.
KeyValues *pkvWeapon_9 = pkvTransitionRestoreFile->FindKey("Weapon_9");
KeyValues *pkvWeapon_9_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClip");
KeyValues *pkvWeapon_9_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClip");
KeyValues *pkvWeapon_9_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmo");
KeyValues *pkvWeapon_9_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmo");
KeyValues *pkvWeapon_9_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmoLeft");
KeyValues *pkvWeapon_9_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmoLeft");
//Weapon_10.
KeyValues *pkvWeapon_10 = pkvTransitionRestoreFile->FindKey("Weapon_10");
KeyValues *pkvWeapon_10_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClip");
KeyValues *pkvWeapon_10_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClip");
KeyValues *pkvWeapon_10_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmo");
KeyValues *pkvWeapon_10_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmo");
KeyValues *pkvWeapon_10_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmoLeft");
KeyValues *pkvWeapon_10_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmoLeft");
//Weapon_11.
KeyValues *pkvWeapon_11 = pkvTransitionRestoreFile->FindKey("Weapon_11");
KeyValues *pkvWeapon_11_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClip");
KeyValues *pkvWeapon_11_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClip");
KeyValues *pkvWeapon_11_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmo");
KeyValues *pkvWeapon_11_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmo");
KeyValues *pkvWeapon_11_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmoLeft");
KeyValues *pkvWeapon_11_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmoLeft");
//Weapon_12.
KeyValues *pkvWeapon_12 = pkvTransitionRestoreFile->FindKey("Weapon_12");
KeyValues *pkvWeapon_12_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClip");
KeyValues *pkvWeapon_12_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClip");
KeyValues *pkvWeapon_12_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmo");
KeyValues *pkvWeapon_12_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmo");
KeyValues *pkvWeapon_12_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmoLeft");
KeyValues *pkvWeapon_12_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmoLeft");
//=====================================================================
if (pszSteamID)
{
//Set ints for the class,health and armour.
#ifdef SecobMod__USE_PLAYERCLASSES
int PlayerClassValue = pkvCurrentClass->GetInt();
#endif
int PlayerHealthValue = pkvHealth->GetInt();
int PlayerArmourValue = pkvArmour->GetInt();
//Current Active Weapon
const char *pkvActiveWep_Value = pkvActiveWep->GetString();
//============================================================================================
#ifdef SecobMod__USE_PLAYERCLASSES
if (PlayerClassValue == 1)
{
pPlayer->m_iCurrentClass = 1;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
Msg("Respawning...\n");
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 125;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(50);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(640);
pPlayer->CBasePlayer::SetJumpHeight(200.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Assaulter");
pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_assaulter", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
else if (PlayerClassValue == 2)
{
pPlayer->m_iCurrentClass = 2;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
Msg("Respawning...\n");
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 100;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(500);
pPlayer->CBasePlayer::SetJumpHeight(150.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Supporter");
pPlayer->SetModel("models/sdk/Humans/Group03/l7h_rebel.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_supporter", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
else if (PlayerClassValue == 3)
{
pPlayer->m_iCurrentClass = 3;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 80;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(0);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(320);
pPlayer->CBasePlayer::SetJumpHeight(100.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Medic");
pPlayer->SetModel("models/sdk/Humans/Group03/male_05.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_medic", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
pPlayer->EquipSuit(false);
}
else if (PlayerClassValue == 4)
{
pPlayer->m_iCurrentClass = 4;
pPlayer->m_iClientClass = pPlayer->m_iCurrentClass;
pPlayer->ForceHUDReload(pPlayer);
pPlayer->PlayerCanChangeClass = false;
pPlayer->RemoveAllItems(true);
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 150;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetMaxArmorValue(200);
pPlayer->CBasePlayer::SetWalkSpeed(150);
pPlayer->CBasePlayer::SetNormSpeed(190);
pPlayer->CBasePlayer::SetSprintSpeed(320);
pPlayer->CBasePlayer::SetJumpHeight(40.0);
//SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix.
pPlayer->CBasePlayer::KeyValue("targetname", "Heavy");
pPlayer->SetModel("models/sdk/Humans/Group03/police_05.mdl");
//SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start.
CBaseEntity *pEntity = NULL;
Vector pEntityOrigin;
pEntity = gEntList.FindEntityByClassnameNearest("info_player_heavy", pEntityOrigin, 0);
if (pEntity != NULL)
{
pEntityOrigin = pEntity->GetAbsOrigin();
pPlayer->SetAbsOrigin(pEntityOrigin);
}
//PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
}
#endif //SecobMod__USE_PLAYERCLASSES
#ifndef SecobMod__USE_PLAYERCLASSES
pPlayer->m_iHealth = PlayerHealthValue;
pPlayer->m_iMaxHealth = 125;
pPlayer->SetArmorValue(PlayerArmourValue);
pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl");
//Bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required.
pPlayer->EquipSuit();
pPlayer->StartSprinting();
pPlayer->StopSprinting();
#endif //SecobMod__USE_PLAYERCLASSES NOT
const char *pkvWeapon_Value = NULL;
int Weapon_PriClip_Value = 0;
const char *pkvWeapon_PriClipAmmo_Value = NULL;
int Weapon_SecClip_Value = 0;
const char *pkvWeapon_SecClipAmmo_Value = NULL;
int Weapon_PriClipCurrent_Value = 0;
int Weapon_SecClipCurrent_Value = 0;
//Loop through all of our weapon slots.
for (int i = 0; i < 12; i++)
{
if (i == 0)
{
pkvWeapon_Value = pkvWeapon_0->GetString();
Weapon_PriClip_Value = pkvWeapon_0_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_0_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_0_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_0_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_0_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_0_SecClipAmmoLeft->GetInt();
}
else if (i == 1)
{
pkvWeapon_Value = pkvWeapon_1->GetString();
Weapon_PriClip_Value = pkvWeapon_1_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_1_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_1_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_1_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_1_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_1_SecClipAmmoLeft->GetInt();
}
else if (i == 2)
{
pkvWeapon_Value = pkvWeapon_2->GetString();
Weapon_PriClip_Value = pkvWeapon_2_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_2_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_2_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_2_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_2_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_2_SecClipAmmoLeft->GetInt();
}
else if (i == 3)
{
pkvWeapon_Value = pkvWeapon_3->GetString();
Weapon_PriClip_Value = pkvWeapon_3_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_3_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_3_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_3_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_3_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_3_SecClipAmmoLeft->GetInt();
}
else if (i == 4)
{
pkvWeapon_Value = pkvWeapon_4->GetString();
Weapon_PriClip_Value = pkvWeapon_4_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_4_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_4_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_4_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_4_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_4_SecClipAmmoLeft->GetInt();
}
else if (i == 5)
{
pkvWeapon_Value = pkvWeapon_5->GetString();
Weapon_PriClip_Value = pkvWeapon_5_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_5_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_5_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_5_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_5_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_5_SecClipAmmoLeft->GetInt();
}
else if (i == 6)
{
pkvWeapon_Value = pkvWeapon_6->GetString();
Weapon_PriClip_Value = pkvWeapon_6_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_6_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_6_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_6_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_6_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_6_SecClipAmmoLeft->GetInt();
}
else if (i == 7)
{
pkvWeapon_Value = pkvWeapon_7->GetString();
Weapon_PriClip_Value = pkvWeapon_7_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_7_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_7_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_7_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_7_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_7_SecClipAmmoLeft->GetInt();
}
else if (i == 8)
{
pkvWeapon_Value = pkvWeapon_8->GetString();
Weapon_PriClip_Value = pkvWeapon_8_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_8_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_8_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_8_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_8_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_8_SecClipAmmoLeft->GetInt();
}
else if (i == 9)
{
pkvWeapon_Value = pkvWeapon_9->GetString();
Weapon_PriClip_Value = pkvWeapon_9_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_9_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_9_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_9_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_9_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_9_SecClipAmmoLeft->GetInt();
}
else if (i == 10)
{
pkvWeapon_Value = pkvWeapon_10->GetString();
Weapon_PriClip_Value = pkvWeapon_10_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_10_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_10_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_10_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_10_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_10_SecClipAmmoLeft->GetInt();
}
else if (i == 11)
{
pkvWeapon_Value = pkvWeapon_11->GetString();
Weapon_PriClip_Value = pkvWeapon_11_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_11_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_11_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_11_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_11_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_11_SecClipAmmoLeft->GetInt();
}
else if (i == 12)
{
pkvWeapon_Value = pkvWeapon_12->GetString();
Weapon_PriClip_Value = pkvWeapon_12_PriClip->GetInt();
pkvWeapon_PriClipAmmo_Value = pkvWeapon_12_PriClipAmmo->GetString();
Weapon_SecClip_Value = pkvWeapon_12_SecClip->GetInt();
pkvWeapon_SecClipAmmo_Value = pkvWeapon_12_SecClipAmmo->GetString();
Weapon_PriClipCurrent_Value = pkvWeapon_12_PriClipAmmoLeft->GetInt();
Weapon_SecClipCurrent_Value = pkvWeapon_12_SecClipAmmoLeft->GetInt();
}
//Now give the weapon and ammo.
pPlayer->GiveNamedItem((pkvWeapon_Value));
pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvWeapon_Value));
if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo1())
{
if (Weapon_PriClipCurrent_Value != -1)
{
if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0)
{
pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value;
pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value;
pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value);
}
else
{
pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value;
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, pkvWeapon_PriClipAmmo_Value);
//Msg("Weapon primary clip value should be: %i\n", Weapon_PriClipCurrent_Value);
}
}
}
else
{
pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value;
pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value);
}
if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo2())
{
if (Weapon_SecClipCurrent_Value != -1)
{
if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0)
{
pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value;
pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value;
pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value);
}
else
{
pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value;
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, pkvWeapon_SecClipAmmo_Value);
}
}
}
else
{
pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value;
pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value));
pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value);
}
}
//Now restore the players Active Weapon (the weapon they had out at the level transition).
pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvActiveWep_Value));
}
else
{
//Something went wrong show the class panel.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
}
break;
}
}
else
{
//Something went wrong show the class panel.
pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL);
}
#endif //SecobMod__SAVERESTORE
#ifdef SecobMod__ENABLE_MAP_BRIEFINGS
pPlayer->ShowViewPortPanel(PANEL_INFO, false, NULL);
const char *brief_title = "Briefing: ";//(hostname) ? hostname->GetString() : "MESSAGE OF THE DAY";
KeyValues *brief_data = new KeyValues("brief_data");
brief_data->SetString("title", brief_title); // info panel title
brief_data->SetString("type", "1"); // show userdata from stringtable entry
brief_data->SetString("msg", "briefing"); // use this stringtable entry
pPlayer->ShowViewPortPanel(PANEL_INFO, true, brief_data);
#endif //SecobMod__ENABLE_MAP_BRIEFINGS
data->deleteThis();
}
/*
===========
ClientPutInServer
called each time a player is spawned into the game
============
*/
void ClientPutInServer(edict_t *pEdict, const char *playername)
{
// Allocate a CBaseTFPlayer for pev, and call spawn
CHL2MP_Player *pPlayer = CHL2MP_Player::CreatePlayer("player", pEdict);
pPlayer->SetPlayerName(playername);
}
void ClientActive(edict_t *pEdict, bool bLoadGame)
{
// Can't load games in CS!
Assert(!bLoadGame);
CHL2MP_Player *pPlayer = ToHL2MPPlayer(CBaseEntity::Instance(pEdict));
FinishClientPutInServer(pPlayer);
}
/*
===============
const char *GetGameDescription()
Returns the descriptive name of this .dll. E.g., Half-Life, or Team Fortress 2
===============
*/
const char *GetGameDescription()
{
if (g_pGameRules) // this function may be called before the world has spawned, and the game rules initialized
return g_pGameRules->GetGameDescription();
else
return "Half-Life 2 Deathmatch";
}
//-----------------------------------------------------------------------------
// Purpose: Given a player and optional name returns the entity of that
// classname that the player is nearest facing
//
// Input :
// Output :
//-----------------------------------------------------------------------------
CBaseEntity* FindEntity(edict_t *pEdict, char *classname)
{
// If no name was given set bits based on the picked
if (FStrEq(classname, ""))
{
return (FindPickerEntityClass(static_cast<CBasePlayer*>(GetContainingEntity(pEdict)), classname));
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Precache game-specific models & sounds
//-----------------------------------------------------------------------------
void ClientGamePrecache(void)
{
CBaseEntity::PrecacheModel("models/player.mdl");
CBaseEntity::PrecacheModel("models/gibs/agibs.mdl");
CBaseEntity::PrecacheModel("models/weapons/v_hands.mdl");
CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowAmmo");
CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowHealth");
CBaseEntity::PrecacheScriptSound("FX_AntlionImpact.ShellImpact");
CBaseEntity::PrecacheScriptSound("Missile.ShotDown");
CBaseEntity::PrecacheScriptSound("Bullets.DefaultNearmiss");
CBaseEntity::PrecacheScriptSound("Bullets.GunshipNearmiss");
CBaseEntity::PrecacheScriptSound("Bullets.StriderNearmiss");
CBaseEntity::PrecacheScriptSound("Geiger.BeepHigh");
CBaseEntity::PrecacheScriptSound("Geiger.BeepLow");
}
// called by ClientKill and DeadThink
void respawn(CBaseEntity *pEdict, bool fCopyCorpse)
{
CHL2MP_Player *pPlayer = ToHL2MPPlayer(pEdict);
if (pPlayer)
{
if (gpGlobals->curtime > pPlayer->GetDeathTime() + DEATH_ANIMATION_TIME)
{
// respawn player
pPlayer->Spawn();
}
else
{
pPlayer->SetNextThink(gpGlobals->curtime + 0.1f);
}
}
}
void GameStartFrame(void)
{
VPROF("GameStartFrame()");
if (g_fGameOver)
return;
gpGlobals->teamplay = (teamplay.GetInt() != 0);
#ifdef DEBUG
extern void Bot_RunAll();
Bot_RunAll();
#endif
}
//=========================================================
// instantiate the proper game rules object
//=========================================================
void InstallGameRules()
{
// vanilla deathmatch
CreateGameRulesObject("CHL2MPRules");
}
| 44.230483 | 177 | 0.734885 | Code4Cookie |
9149d2a1b7940bbed03cb6426d69eaecbbd1b6e1 | 2,320 | cpp | C++ | Source/FactoryGame/FGActorRepresentation.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGActorRepresentation.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGActorRepresentation.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | // This file has been automatically generated by the Unreal Header Implementation tool
#include "FGActorRepresentation.h"
bool UFGActorRepresentation::IsSupportedForNetworking() const{ return bool(); }
void UFGActorRepresentation::GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps) const{ }
FVector UFGActorRepresentation::GetActorLocation() const{ return FVector(); }
FRotator UFGActorRepresentation::GetActorRotation() const{ return FRotator(); }
UTexture2D* UFGActorRepresentation::GetRepresentationTexture() const{ return nullptr; }
FText UFGActorRepresentation::GetRepresentationText() const{ return FText(); }
FLinearColor UFGActorRepresentation::GetRepresentationColor() const{ return FLinearColor(); }
ERepresentationType UFGActorRepresentation::GetRepresentationType() const{ return ERepresentationType(); }
bool UFGActorRepresentation::GetShouldShowInCompass() const{ return bool(); }
bool UFGActorRepresentation::GetShouldShowOnMap() const{ return bool(); }
EFogOfWarRevealType UFGActorRepresentation::GetFogOfWarRevealType() const{ return EFogOfWarRevealType(); }
float UFGActorRepresentation::GetFogOfWarRevealRadius() const{ return float(); }
void UFGActorRepresentation::SetIsOnClient( bool onClient){ }
ECompassViewDistance UFGActorRepresentation::GetCompassViewDistance() const{ return ECompassViewDistance(); }
void UFGActorRepresentation::SetLocalCompassViewDistance( ECompassViewDistance compassViewDistance){ }
AFGActorRepresentationManager* UFGActorRepresentation::GetActorRepresentationManager(){ return nullptr; }
void UFGActorRepresentation::UpdateLocation(){ }
void UFGActorRepresentation::UpdateRotation(){ }
void UFGActorRepresentation::UpdateRepresentationText(){ }
void UFGActorRepresentation::UpdateRepresentationTexture(){ }
void UFGActorRepresentation::UpdateRepresentationColor(){ }
void UFGActorRepresentation::UpdateShouldShowInCompass(){ }
void UFGActorRepresentation::UpdateShouldShowOnMap(){ }
void UFGActorRepresentation::UpdateFogOfWarRevealType(){ }
void UFGActorRepresentation::UpdateFogOfWarRevealRadius(){ }
void UFGActorRepresentation::UpdateCompassViewDistance(){ }
void UFGActorRepresentation::OnRep_ShouldShowInCompass(){ }
void UFGActorRepresentation::OnRep_ShouldShowOnMap(){ }
void UFGActorRepresentation::OnRep_ActorRepresentationUpdated(){ }
| 68.235294 | 110 | 0.840948 | iam-Legend |
9153ce528d3233d5711d659b095c160f2610f2fe | 7,655 | cpp | C++ | ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp | morpheus-org/morpheus-interoperability | 66161199fa1926914e16c1feb02eb910ffef5ed4 | [
"Apache-2.0"
] | null | null | null | ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp | morpheus-org/morpheus-interoperability | 66161199fa1926914e16c1feb02eb910ffef5ed4 | [
"Apache-2.0"
] | 3 | 2021-10-09T16:17:19.000Z | 2021-10-12T21:31:23.000Z | ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp | morpheus-org/morpheus-fortran-interop | 66161199fa1926914e16c1feb02eb910ffef5ed4 | [
"Apache-2.0"
] | null | null | null | /**
* Morpheus_Ccl_CsrMatrix.cpp
*
* EPCC, The University of Edinburgh
*
* (c) 2021 The University of Edinburgh
*
* Contributing Authors:
* Christodoulos Stylianou ([email protected])
*
* 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 <phost/Morpheus_Ccl_CsrMatrix.hpp>
void ccl_phmat_csr_create_default(ccl_phmat_csr** A) {
*A = (new ccl_phmat_csr());
}
void ccl_phmat_csr_create(ccl_phmat_csr** A, ccl_index_t nrows,
ccl_index_t ncols, ccl_index_t nnnz) {
*A = (new ccl_phmat_csr("ccl_phmat_csr::", nrows, ncols, nnnz));
}
void ccl_phmat_csr_create_from_phmat_csr(ccl_phmat_csr* src,
ccl_phmat_csr** dst) {
*dst = (new ccl_phmat_csr(*src));
}
void ccl_phmat_csr_create_from_phmat_dyn(ccl_phmat_dyn* src,
ccl_phmat_csr** dst) {
*dst = (new ccl_phmat_csr(*src));
}
void ccl_phmat_csr_resize(ccl_phmat_csr* A, const ccl_index_t num_rows,
const ccl_index_t num_cols,
const ccl_index_t num_nnz) {
A->resize(num_rows, num_cols, num_nnz);
}
// Assumes dst matrix is always created
void ccl_phmat_csr_allocate_from_phmat_csr(ccl_phmat_csr* src,
ccl_phmat_csr* dst) {
dst->allocate("ccl_phmat_csr::allocate::", *src);
}
void ccl_phmat_csr_destroy(ccl_phmat_csr** A) { delete (*A); }
ccl_index_t ccl_phmat_csr_nrows(ccl_phmat_csr* A) { return A->nrows(); }
ccl_index_t ccl_phmat_csr_ncols(ccl_phmat_csr* A) { return A->ncols(); }
ccl_index_t ccl_phmat_csr_nnnz(ccl_phmat_csr* A) { return A->nnnz(); }
void ccl_phmat_csr_set_nrows(ccl_phmat_csr* A, ccl_index_t nrows) {
A->set_nrows(nrows);
}
void ccl_phmat_csr_set_ncols(ccl_phmat_csr* A, ccl_index_t ncols) {
A->set_ncols(ncols);
}
void ccl_phmat_csr_set_nnnz(ccl_phmat_csr* A, ccl_index_t nnnz) {
A->set_nnnz(nnnz);
}
ccl_index_t ccl_phmat_csr_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->row_offsets(i);
}
ccl_index_t ccl_phmat_csr_column_indices_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->column_indices(i);
}
ccl_value_t ccl_phmat_csr_values_at(ccl_phmat_csr* A, ccl_index_t i) {
return A->values(i);
}
ccl_phvec_dense_i* ccl_phmat_csr_row_offsets(ccl_phmat_csr* A) {
return &(A->row_offsets());
}
ccl_phvec_dense_i* ccl_phmat_csr_column_indices(ccl_phmat_csr* A) {
return &(A->column_indices());
}
ccl_phvec_dense_v* ccl_phmat_csr_values(ccl_phmat_csr* A) {
return &(A->values());
}
void ccl_phmat_csr_set_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_index_t val) {
A->row_offsets(i) = val;
}
void ccl_phmat_csr_set_column_indices_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_index_t val) {
A->column_indices(i) = val;
}
void ccl_phmat_csr_set_values_at(ccl_phmat_csr* A, ccl_index_t i,
ccl_value_t val) {
A->values(i) = val;
}
ccl_formats_e ccl_phmat_csr_format_enum(ccl_phmat_csr* A) {
return A->format_enum();
}
int ccl_phmat_csr_format_index(ccl_phmat_csr* A) { return A->format_index(); }
void ccl_phmat_csr_hostmirror_create_default(ccl_phmat_csr_hostmirror** A) {
*A = (new ccl_phmat_csr_hostmirror());
}
void ccl_phmat_csr_hostmirror_create(ccl_phmat_csr_hostmirror** A,
ccl_index_t nrows, ccl_index_t ncols,
ccl_index_t nnnz) {
*A = (new ccl_phmat_csr_hostmirror("ccl_phmat_csr_hostmirror::", nrows, ncols,
nnnz));
}
void ccl_phmat_csr_hostmirror_create_from_phmat_csr_hostmirror(
ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror** dst) {
*dst = (new ccl_phmat_csr_hostmirror(*src));
}
void ccl_phmat_csr_hostmirror_create_from_phmat_dyn_hostmirror(
ccl_phmat_dyn_hostmirror* src, ccl_phmat_csr_hostmirror** dst) {
*dst = (new ccl_phmat_csr_hostmirror(*src));
}
void ccl_phmat_csr_hostmirror_resize(ccl_phmat_csr_hostmirror* A,
const ccl_index_t num_rows,
const ccl_index_t num_cols,
const ccl_index_t num_nnz) {
A->resize(num_rows, num_cols, num_nnz);
}
// Assumes dst matrix is always created
void ccl_phmat_csr_hostmirror_allocate_from_phmat_csr_hostmirror(
ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror* dst) {
dst->allocate("ccl_phmat_csr_hostmirror::allocate::", *src);
}
void ccl_phmat_csr_hostmirror_destroy(ccl_phmat_csr_hostmirror** A) {
delete (*A);
}
ccl_index_t ccl_phmat_csr_hostmirror_nrows(ccl_phmat_csr_hostmirror* A) {
return A->nrows();
}
ccl_index_t ccl_phmat_csr_hostmirror_ncols(ccl_phmat_csr_hostmirror* A) {
return A->ncols();
}
ccl_index_t ccl_phmat_csr_hostmirror_nnnz(ccl_phmat_csr_hostmirror* A) {
return A->nnnz();
}
void ccl_phmat_csr_hostmirror_set_nrows(ccl_phmat_csr_hostmirror* A,
ccl_index_t nrows) {
A->set_nrows(nrows);
}
void ccl_phmat_csr_hostmirror_set_ncols(ccl_phmat_csr_hostmirror* A,
ccl_index_t ncols) {
A->set_ncols(ncols);
}
void ccl_phmat_csr_hostmirror_set_nnnz(ccl_phmat_csr_hostmirror* A,
ccl_index_t nnnz) {
A->set_nnnz(nnnz);
}
ccl_index_t ccl_phmat_csr_hostmirror_row_offsets_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i) {
return A->row_offsets(i);
}
ccl_index_t ccl_phmat_csr_hostmirror_column_indices_at(
ccl_phmat_csr_hostmirror* A, ccl_index_t i) {
return A->column_indices(i);
}
ccl_value_t ccl_phmat_csr_hostmirror_values_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i) {
return A->values(i);
}
ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_row_offsets(
ccl_phmat_csr_hostmirror* A) {
return &(A->row_offsets());
}
ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_column_indices(
ccl_phmat_csr_hostmirror* A) {
return &(A->column_indices());
}
ccl_phvec_dense_v_hostmirror* ccl_phmat_csr_hostmirror_values(
ccl_phmat_csr_hostmirror* A) {
return &(A->values());
}
void ccl_phmat_csr_hostmirror_set_row_offsets_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i,
ccl_index_t val) {
A->row_offsets(i) = val;
}
void ccl_phmat_csr_hostmirror_set_column_indices_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i,
ccl_index_t val) {
A->column_indices(i) = val;
}
void ccl_phmat_csr_hostmirror_set_values_at(ccl_phmat_csr_hostmirror* A,
ccl_index_t i, ccl_value_t val) {
A->values(i) = val;
}
ccl_formats_e ccl_phmat_csr_hostmirror_format_enum(
ccl_phmat_csr_hostmirror* A) {
return A->format_enum();
}
int ccl_phmat_csr_hostmirror_format_index(ccl_phmat_csr_hostmirror* A) {
return A->format_index();
}
| 31.632231 | 80 | 0.677335 | morpheus-org |
9155d85b095ad63a3ce325cf87816c7be6bda86c | 41 | cpp | C++ | Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 5 | 2021-04-20T17:00:41.000Z | 2022-01-18T20:16:03.000Z | Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 7 | 2021-08-22T21:30:50.000Z | 2022-01-14T16:56:34.000Z | Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | null | null | null | #include "Mesh.h"
namespace Ahwassa {
} | 8.2 | 19 | 0.682927 | Liech |
915d64b41290a639c0c8a2e2ac5971ae28637546 | 4,787 | inl | C++ | sfml-extensions/Extensions/Vector4.inl | degski/SFML-Extensions | 13236325da2e9bef2e24f7ad80ec78db6bf33879 | [
"MIT"
] | null | null | null | sfml-extensions/Extensions/Vector4.inl | degski/SFML-Extensions | 13236325da2e9bef2e24f7ad80ec78db6bf33879 | [
"MIT"
] | null | null | null | sfml-extensions/Extensions/Vector4.inl | degski/SFML-Extensions | 13236325da2e9bef2e24f7ad80ec78db6bf33879 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila ([email protected])
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>::Vector4() :
v0(0),
v1(0),
v2(0),
v3(0)
{
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>::Vector4(T V0, T V1, T V2, T V3) :
v0(V0),
v1(V1),
v2(V2),
v3(V3)
{
}
////////////////////////////////////////////////////////////
template <typename T>
template <typename U>
inline Vector4<T>::Vector4(const Vector4<U>& vector) :
v0(static_cast<T>(vector.v0)),
v1(static_cast<T>(vector.v1)),
v2(static_cast<T>(vector.v2)),
v3(static_cast<T>(vector.v3))
{
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator -(const Vector4<T>& left)
{
return Vector4<T>(-left.v0, -left.v1, -left.v2, -left.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator +=(Vector4<T>& left, const Vector4<T>& right)
{
left.v0 += right.v0;
left.v1 += right.v1;
left.v2 += right.v2;
left.v3 += right.v3;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator -=(Vector4<T>& left, const Vector4<T>& right)
{
left.v0 -= right.v0;
left.v1 -= right.v1;
left.v2 -= right.v2;
left.v3 -= right.v3;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator +(const Vector4<T>& left, const Vector4<T>& right)
{
return Vector4<T>(left.v0 + right.v0, left.v1 + right.v1, left.v2 + right.v2, left.v3 + right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator -(const Vector4<T>& left, const Vector4<T>& right)
{
return Vector4<T>(left.v0 - right.v0, left.v1 - right.v1, left.v2 - right.v2, left.v3 - right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator *(const Vector4<T>& left, T right)
{
return Vector4<T>(left.v0 * right, left.v1 * right, left.v2 * right, left.v3 * right);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator *(T left, const Vector4<T>& right)
{
return Vector4<T>(left * right.v0, left * right.v1, left * right.v2, left * right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator *=(Vector4<T>& left, T right)
{
left.v0 *= right;
left.v1 *= right;
left.v2 *= right;
left.v3 *= right;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T> operator /(const Vector4<T>& left, T right)
{
return Vector4<T>(left.v0 / right, left.v1 / right, left.v2 / right, left.v3 / right);
}
////////////////////////////////////////////////////////////
template <typename T>
inline Vector4<T>& operator /=(Vector4<T>& left, T right)
{
left.v0 /= right;
left.v1 /= right;
left.v2 /= right;
left.v3 /= right;
return left;
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator ==(const Vector4<T>& left, const Vector4<T>& right)
{
return (left.v0 == right.v0) && (left.v1 == right.v1) && (left.v2 == right.v2) && (left.v3 == right.v3);
}
////////////////////////////////////////////////////////////
template <typename T>
inline bool operator !=(const Vector4<T>& left, const Vector4<T>& right)
{
return (left.v0 != right.v0) && (left.v1 != right.v1) && (left.v2 != right.v2) && (left.v3 != right.v3);
}
| 27.198864 | 108 | 0.519323 | degski |
9160e358a516a4aab8384bdc37461f8af33bc3f7 | 542 | cc | C++ | cses/1084.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | cses/1084.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | cses/1084.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://cses.fi/problemset/task/1084/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vi;
int main() {
int n, m, k;
cin >> n >> m >> k;
vi a(m);
for (int i = 0; i < n; i++) cin >> a[i];
vi b(m);
for (int i = 0; i < m; i++) cin >> b[i];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int i = 0;
int j = 0;
int c = 0;
while (i < n && j < m)
if (a[i] + k < b[j]) i++;
else if (a[i] - k > b[j]) j++;
else { i++; j++; c++; }
cout << c << endl;
}
| 19.357143 | 42 | 0.47048 | Ashindustry007 |
9168643a5f8ec02fc865ff9fa16ef7cf29c61ce9 | 308 | cpp | C++ | Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 4 | 2020-06-11T00:35:03.000Z | 2020-06-23T11:57:52.000Z | Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 1 | 2020-03-17T13:34:16.000Z | 2020-03-17T13:34:16.000Z | Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp | Renondedju/Daemon | 8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6 | [
"MIT"
] | 2 | 2020-03-19T12:20:17.000Z | 2020-09-03T07:49:06.000Z |
#include "Vulkan/Resources/TextureLoadingDescriptor.hpp"
USING_RUKEN_NAMESPACE
#pragma region Constructor
TextureLoadingDescriptor::TextureLoadingDescriptor(Renderer const& in_renderer, RkChar const* in_path) noexcept:
renderer {in_renderer},
path {in_path}
{
}
#pragma endregion | 20.533333 | 112 | 0.766234 | Renondedju |
9168dd9019c6a142e4da3d36e2c18e93877a61b0 | 1,126 | cpp | C++ | 545_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 545_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 545_c.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | // Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int n;
long long x[100007], h[100007];
long long last=-1000000007;
int wyn;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
scanf("%d", &n);
for (int i=1; i<=n; i++)
{
scanf("%lld%lld", &x[i], &h[i]);
}
for (int i=1; i<n; i++)
{
if (x[i]-h[i]>last)
{
wyn++;
last=x[i];
continue;
}
if (x[i]+h[i]<x[i+1])
{
wyn++;
last=x[i]+h[i];
continue;
}
last=x[i];
}
wyn++;
printf("%d", wyn);
return 0;
} | 20.851852 | 106 | 0.515986 | onexmaster |
916b055dad09ff569d36ae770d7a317bb59ce520 | 2,320 | cpp | C++ | Source/Core/AS_SFML/Joystick.cpp | ace13/LD34 | 82ecda6bdd69208be1ec6d03c3eb250313c4b7d1 | [
"MIT"
] | 1 | 2017-01-05T01:55:16.000Z | 2017-01-05T01:55:16.000Z | Source/Core/AS_SFML/Joystick.cpp | ace13/AngelscriptMP | 583d481fdbef75e4d96a45eb2942a21189087c77 | [
"MIT"
] | null | null | null | Source/Core/AS_SFML/Joystick.cpp | ace13/AngelscriptMP | 583d481fdbef75e4d96a45eb2942a21189087c77 | [
"MIT"
] | null | null | null | #include "Shared.hpp"
#include <SFML/Window/Joystick.hpp>
namespace
{
enum Stick
{
Left = 0,
Right,
Pov
};
void getStickPosition(asIScriptGeneric* gen)
{
uint32_t id = gen->GetArgDWord(0);
Stick stick = Stick(gen->GetArgDWord(1));
switch (stick)
{
case Left:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::X),
sf::Joystick::getAxisPosition(id, sf::Joystick::Y)
); break;
case Right:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::R),
sf::Joystick::getAxisPosition(id, sf::Joystick::U)
); break;
case Pov:
new (gen->GetAddressOfReturnLocation()) sf::Vector2f(
sf::Joystick::getAxisPosition(id, sf::Joystick::PovX),
sf::Joystick::getAxisPosition(id, sf::Joystick::PovY)
); break;
}
}
}
void as::priv::RegJoystick(asIScriptEngine* eng)
{
AS_ASSERT(eng->SetDefaultNamespace("sf::Joystick"));
AS_ASSERT(eng->RegisterEnum("Axis"));
AS_ASSERT(eng->RegisterEnumValue ("Axis", "X", sf::Joystick::X));
AS_ASSERT(eng->RegisterEnumValue("Axis", "Y", sf::Joystick::Y));
AS_ASSERT(eng->RegisterEnumValue("Axis", "Z", sf::Joystick::Z));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RX", sf::Joystick::R));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RY", sf::Joystick::U));
AS_ASSERT(eng->RegisterEnumValue("Axis", "RZ", sf::Joystick::V));
AS_ASSERT(eng->RegisterEnumValue("Axis", "PovX", sf::Joystick::PovX));
AS_ASSERT(eng->RegisterEnumValue("Axis", "PovY", sf::Joystick::PovY));
AS_ASSERT(eng->RegisterEnum("Stick"));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Left", 0));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Right", 1));
AS_ASSERT(eng->RegisterEnumValue("Stick", "Pov", 2));
AS_ASSERT(eng->RegisterGlobalFunction("bool IsConnected(uint)", asFUNCTION(sf::Joystick::isConnected), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("bool IsPressed(uint,uint)", asFUNCTION(sf::Joystick::isButtonPressed), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("float AxisPosition(uint,Axis)", asFUNCTION(sf::Joystick::getAxisPosition), asCALL_CDECL));
AS_ASSERT(eng->RegisterGlobalFunction("Vec2 StickPosition(uint,Stick=Left)", asFUNCTION(getStickPosition), asCALL_GENERIC));
AS_ASSERT(eng->SetDefaultNamespace(""));
}
| 35.151515 | 130 | 0.709914 | ace13 |
9170c9869e819713d8036fa207df18ea7f74be52 | 1,365 | cpp | C++ | aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ssm-contacts/model/ListContactChannelsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::SSMContacts::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListContactChannelsResult::ListContactChannelsResult()
{
}
ListContactChannelsResult::ListContactChannelsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListContactChannelsResult& ListContactChannelsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("NextToken"))
{
m_nextToken = jsonValue.GetString("NextToken");
}
if(jsonValue.ValueExists("ContactChannels"))
{
Array<JsonView> contactChannelsJsonList = jsonValue.GetArray("ContactChannels");
for(unsigned contactChannelsIndex = 0; contactChannelsIndex < contactChannelsJsonList.GetLength(); ++contactChannelsIndex)
{
m_contactChannels.push_back(contactChannelsJsonList[contactChannelsIndex].AsObject());
}
}
return *this;
}
| 27.3 | 126 | 0.768498 | perfectrecall |
9176cd1e0a82f1e5bdb12346c0452393f36b4acb | 38,747 | cpp | C++ | Src/lunaui/notifications/DashboardWindowManager.cpp | ericblade/luna-sysmgr | 82d5d7ced4ba21d3802eb2c8ae063236b6562331 | [
"Apache-2.0"
] | 3 | 2018-11-16T14:51:17.000Z | 2019-11-21T10:55:24.000Z | Src/lunaui/notifications/DashboardWindowManager.cpp | penk/luna-sysmgr | 60c7056a734cdb55a718507f3a739839c9d74edf | [
"Apache-2.0"
] | 1 | 2021-02-20T13:12:15.000Z | 2021-02-20T13:12:15.000Z | Src/lunaui/notifications/DashboardWindowManager.cpp | ericblade/luna-sysmgr | 82d5d7ced4ba21d3802eb2c8ae063236b6562331 | [
"Apache-2.0"
] | null | null | null | /* @@@LICENSE
*
* Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P.
*
* 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.
*
* LICENSE@@@ */
#include "Common.h"
#include <glib.h>
#include <QGraphicsSceneMouseEvent>
#include <QStateMachine>
#include <QState>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeContext>
#include "DashboardWindowManager.h"
#include "AlertWindow.h"
#include "BannerWindow.h"
#include "DashboardWindow.h"
#include "DashboardWindowContainer.h"
#include "DashboardWindowManagerStates.h"
#include "CoreNaviManager.h"
#include "DisplayManager.h"
#include "GraphicsItemContainer.h"
#include "HostBase.h"
#include "Logging.h"
#include "NewContentIndicatorEvent.h"
#include "NotificationPolicy.h"
#include "PersistentWindowCache.h"
#include "Settings.h"
#include "SystemUiController.h"
#include "Time.h"
#include "WebAppMgrProxy.h"
#include "Window.h"
#include "WindowServer.h"
#include "WindowServerLuna.h"
#include "Preferences.h"
#include "Utils.h"
#include "FlickGesture.h"
#include "DockModeWindowManager.h"
#include <QGraphicsPixmapItem>
static const int kTabletAlertWindowPadding = 5;
static const int kTabletNotificationContentWidth = 320;
DashboardWindowManager::DashboardWindowManager(int maxWidth, int maxHeight)
: WindowManagerBase(maxWidth, maxHeight)
,m_stateMachine(0)
,m_stateDashboardOpen(0)
,m_stateAlertOpen(0)
,m_stateClosed(0)
,m_stateCurrent(0)
,m_bannerWin(0)
,m_bgItem(0)
,m_alertWinContainer(0)
,m_transientContainer(0)
,m_dashboardWinContainer(0)
,m_dashboardRightOffset(0)
,m_qmlNotifMenu(0)
,m_menuObject(0)
,m_notifMenuRightEdgeOffset(0)
,m_activeTransientAlert(0)
{
setObjectName("DashboardWindowManager");
m_notificationPolicy = new NotificationPolicy();
m_bannerHasContent = false;
m_AlertWindowFadeOption = Invalid;
m_deleteWinAfterAnimation = NULL;
m_deleteTransientWinAfterAnimation = false;
m_previousActiveAlertWindow = NULL;
m_inDockModeAnimation = false;
// grab all gestures handled by the scenes viewport widget so
// we can prevent them from being propogated to items below the dashboard
grabGesture(Qt::TapGesture);
grabGesture(Qt::TapAndHoldGesture);
grabGesture(Qt::PinchGesture);
grabGesture((Qt::GestureType) SysMgrGestureFlick);
grabGesture((Qt::GestureType) SysMgrGestureSingleClick);
SystemUiController* suc = SystemUiController::instance();
m_isOverlay = !suc->dashboardOwnsNegativeSpace();
// Connect to this signal only if we own the negative space.
if(!m_isOverlay) {
connect(suc, SIGNAL(signalNegativeSpaceChanged(const QRect&)),
this, SLOT(slotNegativeSpaceChanged(const QRect&)));
connect(suc, SIGNAL(signalNegativeSpaceChangeFinished(const QRect&)),
this, SLOT(slotNegativeSpaceChangeFinished(const QRect&)));
}
else {
connect(suc, SIGNAL(signalPositiveSpaceChanged(const QRect&)),
this, SLOT(slotPositiveSpaceChanged(const QRect&)));
connect(suc, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)),
this, SLOT(slotPositiveSpaceChangeFinished(const QRect&)));
setFlag(QGraphicsItem::ItemHasNoContents, true);
}
connect(SystemUiController::instance(), SIGNAL(signalCloseDashboard(bool)),
this, SLOT(slotCloseDashboard(bool)));
connect(SystemUiController::instance(), SIGNAL(signalOpenDashboard()),
this, SLOT(slotOpenDashboard()));
connect(SystemUiController::instance(), SIGNAL(signalCloseAlert()),
this, SLOT(slotCloseAlert()));
}
DashboardWindowManager::~DashboardWindowManager()
{
}
void DashboardWindowManager::init()
{
int width = boundingRect().toRect().width();
int height = boundingRect().toRect().height();
if(m_isOverlay) {
QDeclarativeEngine* qmlEngine = WindowServer::instance()->declarativeEngine();
if(qmlEngine) {
QDeclarativeContext* context = qmlEngine->rootContext();
m_dashboardWinContainer = new DashboardWindowContainer(this, kTabletNotificationContentWidth, 0);
if(context) {
context->setContextProperty("DashboardContainer", m_dashboardWinContainer);
}
Settings* settings = Settings::LunaSettings();
std::string systemMenuQmlPath = settings->lunaQmlUiComponentsPath + "DashboardMenu/DashboardMenu.qml";
QUrl url = QUrl::fromLocalFile(systemMenuQmlPath.c_str());
m_qmlNotifMenu = new QDeclarativeComponent(qmlEngine, url, this);
if(m_qmlNotifMenu) {
m_menuObject = qobject_cast<QGraphicsObject *>(m_qmlNotifMenu->create());
if(m_menuObject) {
m_menuObject->setParentItem(this);
m_notifMenuRightEdgeOffset = m_menuObject->property("edgeOffset").toInt();
QMetaObject::invokeMethod(m_menuObject, "setMaximumHeight", Q_ARG(QVariant, m_dashboardWinContainer->getMaximumHeightForMenu()));
}
}
}
}
if(!m_isOverlay)
{
m_dashboardWinContainer = new DashboardWindowContainer(this, width, height);
m_alertWinContainer = new GraphicsItemContainer(width, height, GraphicsItemContainer::SolidRectBackground);
}
else {
m_alertWinContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::PopupBackground);
m_alertWinContainer->setBlockGesturesAndMouse(true);
m_alertWinContainer->setAcceptTouchEvents(true);
}
m_transientContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::TransientAlertBackground);
m_transientContainer->setBlockGesturesAndMouse(true);
m_transientContainer->setOpacity(0.0);
m_transientContainer->setVisible(true);
m_transientContainer->setAcceptTouchEvents(true);
m_transAlertAnimation.setTargetObject(m_transientContainer);
m_transAlertAnimation.setPropertyName("opacity");
// Connect the signal to process events after animation is complete
connect(&m_transAlertAnimation, SIGNAL(finished()), SLOT(slotTransientAnimationFinished()));
connect(m_dashboardWinContainer, SIGNAL(signalWindowAdded(DashboardWindow*)),
SLOT(slotDashboardWindowAdded(DashboardWindow*)));
connect(m_dashboardWinContainer, SIGNAL(signalWindowsRemoved(DashboardWindow*)),
SLOT(slotDashboardWindowsRemoved(DashboardWindow*)));
connect(m_dashboardWinContainer, SIGNAL(signalViewportHeightChanged()),
SLOT(slotDashboardViewportHeightChanged()));
connect(SystemUiController::instance()->statusBar(), SIGNAL(signalDashboardAreaRightEdgeOffset(int)),
this, SLOT(slotDashboardAreaRightEdgeOffset(int)));
m_bannerWin = new BannerWindow(this, width, Settings::LunaSettings()->positiveSpaceTopPadding);
m_bgItem = new GraphicsItemContainer(width, height, m_isOverlay ? GraphicsItemContainer::NoBackground : GraphicsItemContainer::SolidRectBackground);
if(!m_isOverlay) {
m_dashboardWinContainer->setParentItem(this);
}
// Listen for dock mode
DockModeWindowManager* dmwm = 0;
dmwm = ((DockModeWindowManager*)((WindowServerLuna*)WindowServer::instance())->dockModeManager());
// Listen for dock mode animation to ignore dashboard open / close requests
connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationStarted()),
this, SLOT(slotDockModeAnimationStarted()));
connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationComplete()),
this, SLOT(slotDockModeAnimationComplete()));
m_alertWinContainer->setParentItem(this);
m_bgItem->setParentItem(this);
m_bannerWin->setParentItem(m_bgItem);
if(m_isOverlay) {
m_transientContainer->setParentItem(this);
// Set the pos of the Alert Containers correctly.
positionAlertWindowContainer();
positionTransientWindowContainer();
if (m_menuObject) {
int uiHeight = SystemUiController::instance()->currentUiHeight();
// temporary location just until the status bar tell us where to place the dashboard container
m_menuObject->setPos(0, -uiHeight/2 + Settings::LunaSettings()->positiveSpaceTopPadding);
}
// Connect the signal to process events after animation is complete
connect(&m_fadeInOutAnimation, SIGNAL(finished()), SLOT(slotDeleteAnimationFinished()));
}
else {
setPosTopLeft(m_alertWinContainer, 0, 0);
m_alertWinContainer->setBrush(Qt::black);
m_bgItem->setBrush(Qt::black);
}
setPosTopLeft(m_bgItem, 0, 0);
setPosTopLeft(m_bannerWin, 0, 0);
setupStateMachine();
}
void DashboardWindowManager::setupStateMachine()
{
m_stateMachine = new QStateMachine(this);
m_stateDashboardOpen = new DWMStateOpen(this);
m_stateAlertOpen = new DWMStateAlertOpen(this);
m_stateClosed = new DWMStateClosed(this);
m_stateMachine->addState(m_stateDashboardOpen);
m_stateMachine->addState(m_stateAlertOpen);
m_stateMachine->addState(m_stateClosed);
// ------------------------------------------------------------------------------
m_stateDashboardOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed);
m_stateAlertOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed);
m_stateDashboardOpen->addTransition(m_dashboardWinContainer, SIGNAL(signalEmpty()), m_stateClosed);
m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, this, SIGNAL(signalActiveAlertWindowChanged())));
m_stateClosed->addTransition(this, SIGNAL(signalOpen()), m_stateDashboardOpen);
m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, m_stateClosed, SIGNAL(signalNegativeSpaceAnimationFinished())));
m_stateDashboardOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
m_stateAlertOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
m_stateClosed->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed);
// ------------------------------------------------------------------------------
m_stateMachine->setInitialState(m_stateClosed);
m_stateMachine->start();
}
int DashboardWindowManager::sTabletUiWidth()
{
return kTabletNotificationContentWidth;
}
int DashboardWindowManager::bannerWindowHeight()
{
return m_bannerWin->boundingRect().height();
}
bool DashboardWindowManager::canCloseDashboard() const
{
return m_stateCurrent == m_stateDashboardOpen;
}
bool DashboardWindowManager::dashboardOpen() const
{
return m_stateCurrent == m_stateDashboardOpen;
}
bool DashboardWindowManager::hasDashboardContent() const
{
return m_bannerHasContent || !m_dashboardWinContainer->empty();
}
void DashboardWindowManager::openDashboard()
{
if (m_inDockModeAnimation)
return;
if(!SystemUiController::instance()->statusBarAndNotificationAreaShown())
return;
if (!m_alertWinArray.empty() || m_dashboardWinContainer->empty()) {
return ;
}
Q_EMIT signalOpen();
}
void DashboardWindowManager::slotPositiveSpaceChanged(const QRect& r)
{
positionAlertWindowContainer(r);
positionTransientWindowContainer(r);
positionDashboardContainer(r);
}
void DashboardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r)
{
positionAlertWindowContainer(r);
positionTransientWindowContainer(r);
positionDashboardContainer(r);
}
void DashboardWindowManager::slotNegativeSpaceChanged(const QRect& r)
{
negativeSpaceChanged(r);
}
void DashboardWindowManager::negativeSpaceChanged(const QRect& r)
{
setPos(0, r.y());
update();
}
void DashboardWindowManager::slotNegativeSpaceChangeFinished(const QRect& r)
{
if (G_UNLIKELY(m_stateCurrent == 0)) {
g_critical("m_stateCurrent is null");
return;
}
m_stateCurrent->negativeSpaceAnimationFinished();
}
void DashboardWindowManager::slotOpenDashboard()
{
openDashboard();
}
void DashboardWindowManager::slotCloseDashboard(bool forceClose)
{
if (!forceClose && !m_stateCurrent->allowsSoftClose())
return;
Q_EMIT signalClose(forceClose);
}
void DashboardWindowManager::slotCloseAlert()
{
AlertWindow* win = topAlertWindow();
if(!win)
return;
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
win->close();
}
void DashboardWindowManager::slotDashboardAreaRightEdgeOffset(int offset)
{
if (m_menuObject) {
m_dashboardRightOffset = offset;
m_menuObject->setX((boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset);
}
}
void DashboardWindowManager::slotDeleteAnimationFinished()
{
switch(m_AlertWindowFadeOption) {
case FadeInAndOut:
case FadeOutOnly:
// Reset the dimensions and position of the dashboardwindow container to the orignal one.
m_alertWinContainer->resize(kTabletNotificationContentWidth, 0);
positionAlertWindowContainer();
if(m_previousActiveAlertWindow) {
m_previousActiveAlertWindow->setParent(NULL);
m_previousActiveAlertWindow->setVisible(false);
m_previousActiveAlertWindow = NULL;
}
if(m_deleteWinAfterAnimation) {
delete m_deleteWinAfterAnimation;
m_deleteWinAfterAnimation = NULL;
}
if(FadeOutOnly == m_AlertWindowFadeOption) {
// Change the state to closed.
Q_EMIT signalActiveAlertWindowChanged();
}
else if(topAlertWindow()) {
// we need to fade in the new alert window
m_AlertWindowFadeOption = FadeInOnly;
resizeAlertWindowContainer(topAlertWindow(), true);
animateAlertWindow();
notifyActiveAlertWindowActivated (topAlertWindow());
} else {
m_AlertWindowFadeOption = Invalid;
}
m_AlertWindowFadeOption = Invalid;
break;
default:
m_AlertWindowFadeOption = Invalid;
break;
}
}
void DashboardWindowManager::slotTransientAnimationFinished()
{
if(m_deleteTransientWinAfterAnimation) {
if(m_activeTransientAlert) {
delete m_activeTransientAlert;
m_activeTransientAlert = NULL;
}
m_deleteTransientWinAfterAnimation = false;
}
if(m_transientContainer->opacity() == 0.0)
m_transientContainer->setVisible(false);
}
void DashboardWindowManager::setBannerHasContent(bool val)
{
m_bannerHasContent = val;
if (val || !m_dashboardWinContainer->empty()) {
SystemUiController::instance()->setDashboardHasContent(true);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentAdded();
}
else {
SystemUiController::instance()->setDashboardHasContent(false);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentRemoved();
}
update();
}
void DashboardWindowManager::focusWindow(Window* w)
{
// we listen to focus and blur only for alert windows
if (!(w->type() == Window::Type_PopupAlert ||
w->type() == Window::Type_BannerAlert))
return;
AlertWindow* win = static_cast<AlertWindow*>(w);
// And only for persistable windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win))
return;
addAlertWindow(win);
}
void DashboardWindowManager::unfocusWindow(Window* w)
{
// we listen to focus and blur only for alert windows
if (w->type() != Window::Type_PopupAlert &&
w->type() != Window::Type_BannerAlert)
return;
AlertWindow* win = static_cast<AlertWindow*>(w);
// Is this window in our current list of windows? If no,
// nothing to do
if (!m_alertWinArray.contains(win))
return;
// Look only for persistable windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win))
return;
// Add to persistent cache if not already in there
if (!persistCache->hasWindow(win))
persistCache->addWindow(win);
hideOrCloseAlertWindow(win);
}
void DashboardWindowManager::animateAlertWindow()
{
// We are running on a tablet and we need to fade the AlertWindows in or out. There are two cases:
// 1: If there are no more alert windows, just animate this one out and be done with it.
// 2: If we have other alert windows, activate them.
// Stop the existing animation
m_fadeInOutAnimation.stop();
m_fadeInOutAnimation.clear();
AlertWindow* w = NULL;
qreal endValue = 0.0;
// Set the opacity of the window to 0;
switch(m_AlertWindowFadeOption) {
case FadeInOnly:
w = topAlertWindow();
m_alertWinContainer->setOpacity(0.0);
w->show();
w->activate();
endValue = 1.0;
break;
case FadeInAndOut:
case FadeOutOnly:
if(m_previousActiveAlertWindow) {
w = m_previousActiveAlertWindow;
}
else {
w = m_deleteWinAfterAnimation;
}
endValue = 0.0;
break;
default:
return;
}
// Start the animation
QPropertyAnimation* a = new QPropertyAnimation(m_alertWinContainer, "opacity");
a->setEndValue(endValue);
// TODO - CHANGE DURATION TO READ FROM ANIMATIONSETTINGS.H
a->setDuration(400);
a->setEasingCurve(QEasingCurve::Linear);
m_fadeInOutAnimation.addAnimation(a);
m_fadeInOutAnimation.start();
}
void DashboardWindowManager::animateTransientAlertWindow(bool in)
{
// Stop the existing animation
m_transAlertAnimation.stop();
if(!m_activeTransientAlert)
return;
qreal endValue = 0.0;
if(in) {
m_transientContainer->setVisible(true);
m_activeTransientAlert->show();
m_activeTransientAlert->activate();
endValue = 1.0;
} else {
endValue = 0.0;
}
// Start the animation
m_transAlertAnimation.setStartValue(m_transientContainer->opacity());
m_transAlertAnimation.setEndValue(endValue);
m_transAlertAnimation.setDuration(400);
m_transAlertAnimation.setEasingCurve(QEasingCurve::Linear);
m_transAlertAnimation.start();
}
void DashboardWindowManager::hideOrCloseAlertWindow(AlertWindow* win)
{
bool isActiveAlert = false;
if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win))
isActiveAlert = true;
int removeIndex = m_alertWinArray.indexOf(win);
if (removeIndex != -1)
m_alertWinArray.remove(removeIndex);
// Is this a window that we want to persist?
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!persistCache->shouldPersistWindow(win)) {
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
}
// No. Close it
win->close();
return;
}
if (!persistCache->hasWindow(win))
persistCache->addWindow(win);
persistCache->hideWindow(win);
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
Q_EMIT signalActiveAlertWindowChanged();
}
}
void DashboardWindowManager::resizeAlertWindowContainer(AlertWindow* w, bool repositionWindow)
{
if(!w)
return;
// This should not be executed if we are running on a phone.
if(!isOverlay())
return;
bool wasResized = false;
QRectF bRect = m_alertWinContainer->boundingRect();
if(w->initialHeight() != bRect.height() || w->initialWidth() != bRect.width()) {
m_alertWinContainer->resize(w->initialWidth(), w->initialHeight());
positionAlertWindowContainer();
wasResized = true;
}
if(true == repositionWindow) {
if(true == wasResized) {
w->setPos(0,0);
}
}
}
void DashboardWindowManager::addAlertWindow(AlertWindow* win)
{
if(win->isTransientAlert()) {
// transient alerts are handled separately
addTransientAlertWindow(win);
return;
}
// This window may have already been added because a persistent
// window called focus before the corresponding webapp was ready
if (m_alertWinArray.contains(win))
return;
bool reSignalOpenAlert = false;
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (persistCache->shouldPersistWindow(win)) {
if (!persistCache->hasWindow(win)) {
persistCache->addWindow(win);
}
}
AlertWindow* oldActiveWindow = 0;
if (!m_alertWinArray.empty())
oldActiveWindow = m_alertWinArray[0];
addAlertWindowBasedOnPriority(win);
// Set the flags depending on whether we are running on phone/tablet.
if(isOverlay()) {
if(Invalid == m_AlertWindowFadeOption) {
m_AlertWindowFadeOption = FadeInOnly;
}
// resize the alertwindowcontainer if there are no other active alert windows.
if(m_stateCurrent != m_stateAlertOpen) {
resizeAlertWindowContainer(win, false);
}
}
if(!isOverlay()) {
if(win->boundingRect().width() != SystemUiController::instance()->currentUiWidth())
{
win->resizeEventSync(SystemUiController::instance()->currentUiWidth(), win->initialHeight());
setPosTopLeft(win, 0, 0);
}
}
else {
win->setPos(0,0);
}
if (!win->parentItem()) {
win->setParentItem(m_alertWinContainer);
if(!m_isOverlay)
setPosTopLeft(win, 0, 0);
else
win->setPos(0,0);
// Initially set the visibility to false
win->setVisible(false);
}
AlertWindow* newActiveWindow = m_alertWinArray[0];
if (oldActiveWindow && (oldActiveWindow == newActiveWindow)) {
// Adding the new window did not displace the current active window.
// Nothing to do further
return;
}
if (oldActiveWindow) {
reSignalOpenAlert = true;
m_previousActiveAlertWindow = oldActiveWindow;
// Displaced the current active window. Need to hide it
if (persistCache->shouldPersistWindow(oldActiveWindow)) {
if (!persistCache->hasWindow(oldActiveWindow))
persistCache->addWindow(oldActiveWindow);
persistCache->hideWindow(oldActiveWindow);
}
else {
oldActiveWindow->deactivate();
}
// Set that we need to fade the existing window out and the new window in.
m_AlertWindowFadeOption = FadeInAndOut;
} else if(FadeOutOnly == m_AlertWindowFadeOption) {
// currently in the process of closing the dashboard (last alert just got deactivated before the new window was added),
// so mark the fade option as Fade Ina dn Out to bring it back with the new alert window
m_AlertWindowFadeOption = FadeInAndOut;
return;
}
if(!isOverlay()) {
Q_EMIT signalActiveAlertWindowChanged();
}
else {
// Check if we need to resignal to show the latest alert.
if(false == reSignalOpenAlert) {
// Dashboard was open. The first signal will close the dashbaord. Resignal to open the alert
if(m_stateCurrent == m_stateDashboardOpen)
reSignalOpenAlert = true;
}
// Signal once to move the state to closed
Q_EMIT signalActiveAlertWindowChanged();
// signal again to move the state to display the active alert window
if(true == reSignalOpenAlert) {
Q_EMIT signalActiveAlertWindowChanged();
}
}
}
void DashboardWindowManager::addTransientAlertWindow(AlertWindow* win)
{
if (m_activeTransientAlert == win)
return;
if(m_activeTransientAlert) {
// only one transient alert is allowed at any given time, so close the current one
m_activeTransientAlert->deactivate();
m_deleteTransientWinAfterAnimation = NULL;
m_transAlertAnimation.stop();
notifyTransientAlertWindowDeactivated(m_activeTransientAlert);
delete m_activeTransientAlert;
m_activeTransientAlert = 0;
}
m_activeTransientAlert = win;
win->setParentItem(m_transientContainer);
win->setVisible(true);
win->setOpacity(1.0);
win->setPos(0,0);
win->resizeEventSync(win->initialWidth(), win->initialHeight());
// resize the transient alert window container if there are no other active alert windows.
QRectF bRect = m_transientContainer->boundingRect();
if(win->initialHeight() != bRect.height() || win->initialWidth() != bRect.width()) {
m_transientContainer->resize(win->initialWidth(), win->initialHeight());
}
positionTransientWindowContainer();
notifyTransientAlertWindowActivated(m_activeTransientAlert);
animateTransientAlertWindow(true);
}
void DashboardWindowManager::removeAlertWindow(AlertWindow* win)
{
if(win->isTransientAlert()) {
// transient alerts are handled separately
removeTransientAlertWindow(win);
return;
}
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
if (!m_alertWinArray.contains(win)) {
// This can happen in two cases:
// * a window was stuffed int the persistent window cache on hiding
// * a window was closed before being added to the window manager
if (persistCache->hasWindow(win)) {
persistCache->removeWindow(win);
}
delete win;
return;
}
if (persistCache->hasWindow(win))
persistCache->removeWindow(win);
bool isActiveAlert = false;
if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win))
isActiveAlert = true;
int removeIndex = m_alertWinArray.indexOf(win);
if (removeIndex != -1) {
m_alertWinArray.remove(removeIndex);
}
if (isActiveAlert) {
win->deactivate();
notifyActiveAlertWindowDeactivated(win);
}
// If we are running on the phone, just signal the state to enter closed.
if(!isOverlay()) {
delete win;
if(isActiveAlert) {
Q_EMIT signalActiveAlertWindowChanged();
}
}
else {
m_deleteWinAfterAnimation = win;
if (isActiveAlert) {
// Change the state if there are more alert windows in the system
if(!m_alertWinArray.empty()) {
// This will cause the state to enter stateClosed.
Q_EMIT signalActiveAlertWindowChanged();
// If we are running on a tablet and if this flag is set to true, signal that we need to display the next alert
if (G_UNLIKELY(m_stateCurrent == 0)) {
g_critical("m_stateCurrent is null");
return;
}
// Set that we need to fade the existing window out and the new window in.
m_AlertWindowFadeOption = FadeInAndOut;
// Signal that we need to bring the next active window in
m_stateCurrent->negativeSpaceAnimationFinished();
}
else {
m_AlertWindowFadeOption = FadeOutOnly;
animateAlertWindow();
}
}
}
}
void DashboardWindowManager::removeTransientAlertWindow(AlertWindow* win)
{
if (m_activeTransientAlert != win) {
delete win;
return;
}
win->deactivate();
notifyTransientAlertWindowDeactivated(win);
m_deleteTransientWinAfterAnimation = true;
animateTransientAlertWindow(false);
}
void DashboardWindowManager::addAlertWindowBasedOnPriority(AlertWindow* win)
{
if (m_alertWinArray.empty()) {
m_alertWinArray.append(win);
return;
}
AlertWindow* activeAlertWin = m_alertWinArray[0];
// Add the window to the list of alert windows, sorted by priority
int newWinPriority = m_notificationPolicy->popupAlertPriority(win->appId(), win->name());
if (newWinPriority == m_notificationPolicy->defaultPriority()) {
// optimization. if we are at default priority we don't need to walk the list
// we will just queue up this window
int oldSize = m_alertWinArray.size();
m_alertWinArray.append(win);
}
else if (newWinPriority < m_notificationPolicy->popupAlertPriority(activeAlertWin->appId(),
activeAlertWin->name())) {
// if the priority of new window is higher than the currently shown window, then we push
// both the windows in the queue with the new window in front
QVector<AlertWindow*>::iterator it = qFind(m_alertWinArray.begin(), m_alertWinArray.end(), activeAlertWin);
Q_ASSERT(it != m_alertWinArray.end());
m_alertWinArray.insert(it, win);
}
else {
bool added = false;
QMutableVectorIterator<AlertWindow*> it(m_alertWinArray);
while (it.hasNext()) {
AlertWindow* a = it.next();
if (newWinPriority < m_notificationPolicy->popupAlertPriority(a->appId(), a->name())) {
it.insert(win);
added = true;
break;
}
}
if (!added)
m_alertWinArray.append(win);
}
}
void DashboardWindowManager::addWindow(Window* win)
{
if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert)
addAlertWindow(static_cast<AlertWindow*>(win));
else if (win->type() == Window::Type_Dashboard)
m_dashboardWinContainer->addWindow(static_cast<DashboardWindow*>(win));
}
void DashboardWindowManager::removeWindow(Window* win)
{
if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert)
removeAlertWindow(static_cast<AlertWindow*>(win));
else if (win->type() == Window::Type_Dashboard)
m_dashboardWinContainer->removeWindow(static_cast<DashboardWindow*>(win));
/* if dashboard is empty, all throb requests should have been dismissed
* this is defensive coding to ensure that all requests are cleared
*/
if (m_dashboardWinContainer->empty() && m_alertWinArray.empty())
CoreNaviManager::instance()->clearAllStandbyRequests();
}
int DashboardWindowManager::activeAlertWindowHeight()
{
const Window* alert = getActiveAlertWin();
if(!alertOpen() || !alert) {
if(!isOverlay())
return Settings::LunaSettings()->positiveSpaceBottomPadding;
else
return 0;
}
return alert->boundingRect().height();
}
bool DashboardWindowManager::doesMousePressFallInBannerWindow(QGraphicsSceneMouseEvent* event)
{
QPointF pos = mapToItem(m_bannerWin, event->pos());
if(m_bannerWin->boundingRect().contains(pos)) {
return true;
}
else {
return false;
}
}
/*
BannerWindow is invisible when the DashboardWinContainer is up. So if the user clicks in the BannerWindow area, it will not get any notifications.
So, we need to have this workaround in DashboardWinMgr::mousePressEvent that will detect if the user clicked on BannerWindow area and prevent it
from launching the dashboard again as a part of Qt::GestureComplete
*/
void DashboardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
event->accept();
} else {
event->ignore();
}
}
}
void DashboardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
event->accept();
} else {
event->ignore();
}
}
}
void DashboardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if(!m_isOverlay) {
event->accept();
}
else {
// if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container.
if(true == dashboardOpen()) {
hideDashboardWindow();
event->accept();
if(true == doesMousePressFallInBannerWindow(event)) {
m_bannerWin->resetIgnoreGestureUpEvent();
}
m_dashboardWinContainer->resetLocalState();
} else {
event->ignore();
}
}
}
bool DashboardWindowManager::sceneEvent(QEvent* event)
{
switch (event->type()) {
case QEvent::GestureOverride: {
QGestureEvent* ge = static_cast<QGestureEvent*>(event);
QList<QGesture*> activeGestures = ge->activeGestures();
Q_FOREACH(QGesture* g, activeGestures) {
if (g->hasHotSpot()) {
QPointF pt = ge->mapToGraphicsScene(g->hotSpot());
if (dashboardOpen()) {
ge->accept(g);
}
else {
ge->ignore(g);
}
}
}
break;
}
default:
break;
}
return WindowManagerBase::sceneEvent(event);
}
void DashboardWindowManager::raiseAlertWindow(AlertWindow* window)
{
g_message("%s", __PRETTY_FUNCTION__);
m_alertWinContainer->show();
m_alertWinContainer->raiseChild(window);
m_bgItem->hide();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
void DashboardWindowManager::raiseDashboardWindowContainer()
{
g_message("%s", __PRETTY_FUNCTION__);
if(!m_isOverlay)
m_dashboardWinContainer->show();
m_alertWinContainer->hide();
m_bgItem->hide();
}
void DashboardWindowManager::raiseBackgroundWindow()
{
if(m_stateCurrent != m_stateAlertOpen) {
g_message("%s", __PRETTY_FUNCTION__);
m_alertWinContainer->hide();
m_bgItem->show();
m_bannerWin->show();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
} else {
g_message("%s: In alert state. raise alert window container", __PRETTY_FUNCTION__);
m_alertWinContainer->show();
m_bgItem->hide();
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
}
void DashboardWindowManager::hideDashboardWindow()
{
if(m_stateCurrent == m_stateDashboardOpen) {
Q_EMIT signalClose(true);
}
if(!m_isOverlay)
m_dashboardWinContainer->hide();
}
void DashboardWindowManager::sendClicktoDashboardWindow(int num, int x, int y, bool whileLocked)
{
m_dashboardWinContainer->sendClickToDashboardWindow(num, QPointF(x, y), true);
}
void DashboardWindowManager::notifyActiveAlertWindowActivated(AlertWindow* win)
{
if (win->isIncomingCallAlert())
DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_ACTIVATED);
else
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED);
// NOTE: order matters, the DisplayManager needs to act on the alert before anyone else
SystemUiController::instance()->notifyAlertActivated();
Q_EMIT signalAlertWindowActivated(win);
}
void DashboardWindowManager::notifyActiveAlertWindowDeactivated(AlertWindow* win)
{
if (win->isIncomingCallAlert())
DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_DEACTIVATED);
else
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED);
SystemUiController::instance()->notifyAlertDeactivated();
Q_EMIT signalAlertWindowDeactivated();
}
void DashboardWindowManager::notifyTransientAlertWindowActivated(AlertWindow* win)
{
if(!alertOpen())
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED);
// NOTE: order matters, the DisplayManager needs to act on the alert before anyone else
SystemUiController::instance()->notifyTransientAlertActivated();
}
void DashboardWindowManager::notifyTransientAlertWindowDeactivated(AlertWindow* win)
{
if(!alertOpen())
DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED);
SystemUiController::instance()->notifyTransientAlertDeactivated();
}
void DashboardWindowManager::slotDashboardWindowAdded(DashboardWindow* w)
{
SystemUiController::instance()->setDashboardHasContent(true);
m_bgItem->update();
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentAdded();
}
void DashboardWindowManager::slotDashboardWindowsRemoved(DashboardWindow* w)
{
m_bgItem->update();
if (m_bannerHasContent || !m_dashboardWinContainer->empty())
return;
SystemUiController::instance()->setDashboardHasContent(false);
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardContentRemoved();
}
void DashboardWindowManager::slotDashboardViewportHeightChanged()
{
if (G_LIKELY(m_stateCurrent))
m_stateCurrent->dashboardViewportHeightChanged();
}
void DashboardWindowManager::resize(int width, int height)
{
QRectF bRect = boundingRect();
// accept requests for resizing to the current dimensions, in case we are doing a force resize
WindowManagerBase::resize(width, height);
if(!m_isOverlay) {
m_dashboardWinContainer->resize(width, height);
setPosTopLeft(m_dashboardWinContainer, 0, 0);
m_dashboardWinContainer->resizeWindowsEventSync(width);
m_alertWinContainer->resize(width, height);
setPosTopLeft(m_alertWinContainer, 0, 0);
resizeAlertWindows(width);
}
else {
int yLocCommon = -(height/2) + Settings::LunaSettings()->positiveSpaceTopPadding;
int xLocDashWinCtr;
if (m_menuObject) {
xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset;
} else {
xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset + m_notifMenuRightEdgeOffset;
}
int yLocDashWinCtr = yLocCommon;
int yLocAlertWinCtr = (m_stateCurrent != m_stateAlertOpen)?yLocCommon:(yLocCommon + topAlertWindow()->initialHeight()/2 + kTabletAlertWindowPadding);
// Set the new position of the m_dashboardWinContainer
if (m_menuObject) {
m_menuObject->setPos(xLocDashWinCtr, yLocDashWinCtr);
}
positionAlertWindowContainer();
}
if(!m_isOverlay) {
// reposition the banner window and the backgound item
m_bgItem->resize(width, height);
setPosTopLeft(m_bgItem, 0, 0);
m_bannerWin->resize(width, Settings::LunaSettings()->positiveSpaceTopPadding);
setPosTopLeft(m_bannerWin, 0, 0);
if((alertOpen())) {
setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - activeAlertWindowHeight() - Settings::LunaSettings()->positiveSpaceBottomPadding));
} else if (hasDashboardContent()) {
setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - Settings::LunaSettings()->positiveSpaceBottomPadding));
} else {
setPos(0, SystemUiController::instance()->currentUiHeight()/2 + height/2);
}
}
m_stateCurrent->handleUiResizeEvent();
// resize all cached Alert Windows
PersistentWindowCache* persistCache = PersistentWindowCache::instance();
std::set<Window*>* cachedWindows = persistCache->getCachedWindows();
if(cachedWindows) {
std::set<Window*>::iterator it;
it=cachedWindows->begin();
for ( it=cachedWindows->begin() ; it != cachedWindows->end(); it++ ) {
Window* w = *it;
if(w->type() == Window::Type_PopupAlert || w->type() == Window::Type_BannerAlert) {
((AlertWindow*)w)->resizeEventSync((m_isOverlay ? kTabletNotificationContentWidth : width),
((AlertWindow*)w)->initialHeight());
}
}
}
}
void DashboardWindowManager::resizeAlertWindows(int width)
{
Q_FOREACH(AlertWindow* a, m_alertWinArray) {
if (a) {
a->resizeEventSync(width, a->initialHeight());
if(!m_isOverlay)
setPosTopLeft(a, 0, 0);
else
a->setPos(0,0);
}
}
}
void DashboardWindowManager::slotDockModeAnimationStarted()
{
m_inDockModeAnimation = true;
}
void DashboardWindowManager::slotDockModeAnimationComplete()
{
m_inDockModeAnimation = false;
}
void DashboardWindowManager::positionDashboardContainer(const QRect& posSpace)
{
if (m_menuObject) {
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
m_menuObject->setY(-uiHeight/2 + positiveSpace.y());
}
}
void DashboardWindowManager::positionAlertWindowContainer(const QRect& posSpace)
{
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
m_alertWinContainer->setPos(QPoint(positiveSpace.width()/2 - kTabletAlertWindowPadding - m_alertWinContainer->width()/2,
-uiHeight/2 + positiveSpace.y() + kTabletAlertWindowPadding + m_alertWinContainer->height()/2));
}
void DashboardWindowManager::positionTransientWindowContainer(const QRect& posSpace)
{
QRect positiveSpace;
if(posSpace.isValid())
positiveSpace = posSpace;
else
positiveSpace = SystemUiController::instance()->positiveSpaceBounds();
int uiHeight = SystemUiController::instance()->currentUiHeight();
int uiWidth = SystemUiController::instance()->currentUiWidth();
m_transientContainer->setPos(QPoint(positiveSpace.center().x() - uiWidth/2, positiveSpace.center().y() - uiHeight/2));
}
| 29.398331 | 162 | 0.750665 | ericblade |
9177c39579b2d5034dc3556aa2cb796e77d693b8 | 584 | cpp | C++ | tests/test_list.cpp | ToruNiina/wad | f5f0445f7f0a53efd31988ce7d381bccb463b951 | [
"MIT"
] | null | null | null | tests/test_list.cpp | ToruNiina/wad | f5f0445f7f0a53efd31988ce7d381bccb463b951 | [
"MIT"
] | null | null | null | tests/test_list.cpp | ToruNiina/wad | f5f0445f7f0a53efd31988ce7d381bccb463b951 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "wad/list.hpp"
#include "wad/integer.hpp"
#include "utility.hpp"
TEST_CASE( "std::list save/load", "[std::list]" )
{
std::list<int> upto_16;
std::list<int> upto_u16;
std::list<int> upto_u32;
for(int i=0; i< 5; ++i) {upto_16 .push_back(i);}
for(int i=0; i< 20; ++i) {upto_u16.push_back(i);}
for(int i=0; i<70000; ++i) {upto_u32.push_back(i);}
REQUIRE(wad::save_load(upto_16) == upto_16);
REQUIRE(wad::save_load(upto_u16) == upto_u16);
REQUIRE(wad::save_load(upto_u32) == upto_u32);
}
| 27.809524 | 55 | 0.633562 | ToruNiina |
917b03dd4a82d7015337584227ba1f3a8cf8e663 | 53,037 | cc | C++ | src/topo_ma.cc | erdemeren/VDlib | 23091adbea4ba26379eaf941be53d925304a0560 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/topo_ma.cc | erdemeren/VDlib | 23091adbea4ba26379eaf941be53d925304a0560 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/topo_ma.cc | erdemeren/VDlib | 23091adbea4ba26379eaf941be53d925304a0560 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include <tgmath.h>
#include<algorithm>
#include "apf.h"
#include "ma.h"
#include "maMesh.h"
#include "topo_extinfo.h"
#include "topo_geom.h"
#include "topo_ma.h"
// Get the lowest quality element and it's quality.
std::pair<apf::MeshEntity*, double> calc_valid_q(apf::Mesh2* m,
ma::SizeField* s_f) {
apf::MeshEntity* e_valid = NULL;
double valid = 1;
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
while(elem = m->iterate(it)) {
double q_temp = measureTetQuality(m, s_f, elem);
if(q_temp < valid) {
e_valid = elem;
valid = q_temp;
}
}
m->end(it);
if(valid < std::numeric_limits<double>::min()) {
valid = std::fabs(valid);
}
return std::make_pair(e_valid,valid/5);
}
// Collect elements with quality less than threshold.
double get_low_q(apf::Mesh2* m, ma::SizeField* s_f, std::vector<apf::MeshEntity*> &tets, double q_th) {
std::map<apf::MeshEntity*, bool> low{};
std::map<apf::MeshEntity*, double> qual{};
int nbr = 0;
double valid = 1;
tets.clear();
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
while(elem = m->iterate(it)) {
double q_temp = measureTetQuality(m, s_f, elem);
if(q_temp < q_th) {
nbr = nbr + 1;
low[elem] = true;
qual[elem] = q_temp;
}
if(q_temp < valid)
valid = q_temp;
}
m->end(it);
tets.reserve(nbr);
it = m->begin(3);
while(elem = m->iterate(it)) {
if(low[elem]) {
tets.push_back(elem);
}
}
m->end(it);
if(valid < std::numeric_limits<double>::min()) {
valid = std::fabs(valid);
}
return valid;
}
double calc_good_vol(apf::Mesh2* m, double ref_len, double m_len) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_e;
apf::Downward d_s;
v.at(0) = apf::Vector3(0,0,0);
v.at(1) = apf::Vector3(m_len,0,0);
v.at(2) = apf::Vector3(0,ref_len,0);
v.at(3) = apf::Vector3(0,0,ref_len);
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
double vol = vd_volume_tet(m, elem);
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return vol;
}
bool vd_chk_vol_valid(apf::Mesh2* m, apf::MeshEntity* tet, apf::MeshEntity* ent) {
int ent_type = m->getType(ent);
int d = m->typeDimension[ent_type];
assert(d > -1 and d < 3);
bool valid = true;
if(d > 0) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_v2;
m->getDownward(tet, 0, d_v);
std::map<apf::MeshEntity*, apf::Vector3> old_pos{};
for(int i = 0; i < 4; i++) {
m->getPoint(d_v[i], 0, v.at(i));
old_pos[d_v[i]] = v.at(i);
}
int dc = m->getDownward(tet, d, d_v2);
int e1 = findIn(d_v2, dc, ent);
assert(e1 > -1);
dc = m->getDownward(ent, 0, d_v2);
apf::Vector3 midpoint(0,0,0);
midpoint = vd_get_pos(m, ent);
for(int j = 0; j < dc; j++) {
m->setPoint(d_v2[j], 0, midpoint);
bool vol = vd_volume_tet_sign(m, tet);
valid = (valid and vol);
m->setPoint(d_v2[j], 0, old_pos[d_v2[j]]);
}
}
return valid;
}
double calc_good_q(apf::Mesh2* m, double ref_len, double m_len) {
std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0));
apf::Downward d_v;
apf::Downward d_e;
apf::Downward d_s;
v.at(0) = apf::Vector3(0,0,0);
v.at(1) = apf::Vector3(m_len,0,0);
v.at(2) = apf::Vector3(0,ref_len,0);
v.at(3) = apf::Vector3(0,0,ref_len);
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m);
double qual = measureTetQuality(m, ref_0c, elem);
delete ref_0c;
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return qual;
}
double calc_q(apf::Mesh2* m, std::vector<apf::Vector3> &v) {
apf::Downward d_v;
apf::Downward d_s;
apf::Downward d_e;
// Create a new entity to calculate it's quailty.
apf::MeshEntity* elem;
apf::MeshIterator* it = m->begin(3);
elem = m->iterate(it);
m->end(it);
apf::ModelEntity* mdl = m->toModel(elem);
for(int i = 0; i < 4; i++) {
d_v[i] = m->createVert(mdl);
m->setPoint(d_v[i], 0, v.at(i));
}
elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0);
m->getDownward(elem, 1, d_e);
m->getDownward(elem, 2, d_s);
ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m);
double qual = measureTetQuality(m, ref_0c, elem);
delete ref_0c;
// Destroy the entities:
m->destroy(elem);
for(int i = 0; i < 4; i++)
m->destroy(d_s[i]);
for(int i = 0; i < 6; i++)
m->destroy(d_e[i]);
for(int i = 0; i < 4; i++)
m->destroy(d_v[i]);
return qual;
}
MaSwap3Dcheck::MaSwap3Dcheck(apf::Mesh2* m): mesh(m) {
halves[0].init(m);
halves[1].init(m);
edge = 0;
}
MaSwap3Dcheck::~MaSwap3Dcheck() {}
bool MaSwap3Dcheck::run(apf::MeshEntity* e) {
if (ma::isOnModelEdge(mesh,e))
return false;
edge = e;
if (ma::isOnModelFace(mesh,edge)) {
}
else {
cavityExists[0] = halves[0].setFromEdge(edge);
if(!cavityExists[0]) {
MaLoop loop;
loop.init(mesh);
loop.setEdge(edge);
std::vector<apf::MeshEntity*> tets(0);
std::vector<apf::MeshEntity*> surf(0);
vd_set_up(mesh, e, &surf);
vd_set_up(mesh, &surf, &tets);
apf::ModelEntity* mdl = mesh->toModel(edge);
std::cout << "Curl is not OK! " << edge << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
apf::Downward dv;
apf::Up up;
mesh->getDownward(edge, 0, dv);
mdl = mesh->toModel(dv[0]);
std::cout << "Verts: " << dv[0] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
mdl = mesh->toModel(dv[1]);
std::cout << dv[1] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
for(int i = 0; i < tets.size(); i++) {
mdl = mesh->toModel(tets.at(i));
std::cout << "Tet " << tets.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, tets.at(i))
<< std::endl;
vd_print_down(mesh, tets.at(i));
}
for(int i = 0; i < surf.size(); i++) {
mdl = mesh->toModel(surf.at(i));
std::cout << "Surf " << surf.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, surf.at(i))
<< std::endl;
vd_print_down(mesh, surf.at(i));
vd_set_up(mesh, surf.at(i), &tets);
apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge);
for(int j = 0; j < tets.size(); j++) {
mdl = mesh->toModel(tets.at(j));
std::cout << "Tet " << tets.at(j) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< std::endl;
std::cout << "Curl:" << loop.isCurlOk(v,tets.at(j)) << std::endl;
}
}
}
assert(cavityExists[0]);
}
return true;
}
bool MaSwap3Dcheck::run_all_surf(apf::MeshEntity* e) {
bool curl_ok = true;
if (ma::isOnModelEdge(mesh,e))
return curl_ok;
edge = e;
if (ma::isOnModelFace(mesh,edge)) {
}
else {
MaLoop loop;
loop.init(mesh);
loop.setEdge(edge);
std::vector<apf::MeshEntity*> tets(0);
std::vector<apf::MeshEntity*> surf(0);
vd_set_up(mesh, e, &surf);
vd_set_up(mesh, &surf, &tets);
apf::ModelEntity* mdl = mesh->toModel(edge);
std::cout << edge << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
apf::Downward dv;
apf::Up up;
mesh->getDownward(edge, 0, dv);
mdl = mesh->toModel(dv[0]);
std::cout << "Verts: " << dv[0] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
mdl = mesh->toModel(dv[1]);
std::cout << dv[1] << " "
<< mesh->getModelType(mdl) << "c"
<< mesh->getModelTag(mdl)
<< std::endl;
for(int i = 0; i < tets.size(); i++) {
mdl = mesh->toModel(tets.at(i));
std::cout << "Tet " << tets.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, tets.at(i))
<< std::endl;
vd_print_down(mesh, tets.at(i));
}
for(int i = 0; i < surf.size(); i++) {
mdl = mesh->toModel(surf.at(i));
std::cout << "Surf " << surf.at(i) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< " " << vd_get_pos(mesh, surf.at(i))
<< std::endl;
vd_print_down(mesh, surf.at(i));
vd_set_up(mesh, surf.at(i), &tets);
bool curls_tot = false;
apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge);
for(int j = 0; j < tets.size(); j++) {
mdl = mesh->toModel(tets.at(j));
std::cout << "Tet " << tets.at(j) << " "
<< mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl)
<< std::endl;
bool curl_curr = loop.isCurlOk(v,tets.at(j));
std::cout << "Curl:" << curl_curr << std::endl;
curls_tot = curls_tot or curl_curr;
}
curl_ok = curl_ok and curls_tot;
}
}
return curl_ok;
}
bool chk_ma_swap(apf::Mesh2* m) {
MaSwap3Dcheck swap_chk(m);
apf::MeshEntity* e;
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
apf::MeshIterator* it = m->begin(1);
while ((e = m->iterate(it))) {
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
if(!swap_chk.run(e)) {
return false;
}
}
}
m->end(it);
return true;
}
bool chk_ma_swap(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) {
MaSwap3Dcheck swap_chk(m);
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
std::vector<apf::MeshEntity*> edge(0);
vd_set_up(m, &vert_in, &edge);
apf::MeshEntity* e;
for(int i = 0; i < edge.size(); i++) {
e = edge.at(i);
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
if(!swap_chk.run(e)) {
return false;
}
}
}
return true;
}
bool chk_ma_swap_all(apf::Mesh2* m) {
MaSwap3Dcheck swap_chk(m);
apf::MeshEntity* e;
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
bool curl_ok = true;
apf::MeshIterator* it = m->begin(1);
while ((e = m->iterate(it))) {
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
bool curl_curr = swap_chk.run_all_surf(e);
curl_ok = curl_ok and curl_curr;
}
}
m->end(it);
return curl_ok;
}
bool chk_ma_swap_all(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) {
MaSwap3Dcheck swap_chk(m);
apf::ModelEntity* mdl;
std::cout << "Doing swap check for cavityexists crashes" << std::endl;
bool curl_ok = true;
std::vector<apf::MeshEntity*> edge(0);
vd_set_up(m, &vert_in, &edge);
apf::MeshEntity* e;
for(int i = 0; i < edge.size(); i++) {
e = edge.at(i);
mdl = m->toModel(e);
if(m->getModelType(mdl) == 3) {
bool curl_curr = swap_chk.run_all_surf(e);
curl_ok = curl_ok and curl_curr;
}
}
return curl_ok;
}
// Given an ma::Input, replace the old size field.
void repl_sz_field(ma::Input* in, apf::Mesh2* m, MA_SIZE_TYPE MA_T) {
if(MA_T == MA_SIZE_TYPE::EDGE_COL) {
delete in->sizeField;
ModelEdgeCollapse* ref = new ModelEdgeCollapse(m);
in->sizeField = ref;
}
else if(MA_T == MA_SIZE_TYPE::EDGE_SPLIT) {
delete in->sizeField;
ModelEdgeSplit* ref = new ModelEdgeSplit(m);
in->sizeField = ref;
}
else if(MA_T == MA_SIZE_TYPE::EDGE_REFINER) {
delete in->sizeField;
ModelEdgeRefiner* ref = new ModelEdgeRefiner(m);
in->sizeField = ref;
}
else {
assert(MA_T == MA_SIZE_TYPE::EDGE_REF_DIST);
delete in->sizeField;
ModelEdgeRefinerDist* ref = new ModelEdgeRefinerDist(m);
in->sizeField = ref;
}
}
void vd_ma_input::set_def() {
maximumIterations = 3;
shouldCoarsen = true;
shouldFixShape = true;
shouldForceAdaptation = false;
shouldPrintQuality = true;
goodQuality = 0.027;
maximumEdgeRatio = 2.0;
shouldCheckQualityForDoubleSplits = false;
validQuality = 1e-10;
maximumImbalance = 1.10;
shouldRunPreZoltan = false;
shouldRunPreZoltanRib = false;
shouldRunPreParma = false;
shouldRunMidZoltan = false;
shouldRunMidParma = false;
shouldRunPostZoltan = false;
shouldRunPostZoltanRib = false;
shouldRunPostParma = false;
shouldTurnLayerToTets = false;
shouldCleanupLayer = false;
shouldRefineLayer = false;
shouldCoarsenLayer = false;
splitAllLayerEdges = false;
}
void vd_ma_input::flip_template(INPUT_TYPE IT_IN) {
assert(IT_IN < INPUT_TYPE::END);
if(IT_IN == INPUT_TYPE::ADAPT_SPLIT) {
shouldRefineLayer = true;
}
else if(IT_IN == INPUT_TYPE::ADAPT_COL) {
shouldRunPreZoltan = false;
shouldRunMidParma = false;
shouldRunPostParma = false;
shouldRefineLayer = false;
shouldCoarsen = true;
shouldCoarsenLayer = true;
shouldFixShape = false;
}
else {
assert(IT_IN == INPUT_TYPE::ADAPT_Q);
shouldRunPreZoltan = true;
shouldRunMidParma = true;
shouldRunPostParma = true;
shouldRefineLayer = true;
shouldFixShape = true;
}
}
void vd_ma_input::set_template(INPUT_TYPE IT_IN) {
set_def();
flip_template(IT_IN);
}
// Get the input fields from ma::Input.
void vd_ma_input::get_input(ma::Input* in) {
maximumIterations = in->maximumIterations;
shouldCoarsen = in->shouldCoarsen;
shouldFixShape = in->shouldFixShape;
shouldForceAdaptation = in->shouldForceAdaptation;
shouldPrintQuality = in->shouldPrintQuality;
goodQuality = in->goodQuality;
maximumEdgeRatio = in->maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = in->shouldCheckQualityForDoubleSplits;
validQuality = in->validQuality;
maximumImbalance = in->maximumImbalance;
shouldRunPreZoltan = in->shouldRunPreZoltan;
shouldRunPreZoltanRib = in->shouldRunPreZoltanRib;
shouldRunPreParma = in->shouldRunPreParma;
shouldRunMidZoltan = in->shouldRunMidZoltan;
shouldRunMidParma = in->shouldRunMidParma;
shouldRunPostZoltan = in->shouldRunPostZoltan;
shouldRunPostZoltanRib = in->shouldRunPostZoltanRib;
shouldRunPostParma = in->shouldRunPostParma;
shouldTurnLayerToTets = in->shouldTurnLayerToTets;
shouldCleanupLayer = in->shouldCleanupLayer;
shouldRefineLayer = in->shouldRefineLayer;
shouldCoarsenLayer = in->shouldCoarsenLayer;
splitAllLayerEdges = in->splitAllLayerEdges;
}
// Transfer the input fields to ma::Input.
void vd_ma_input::set_input(ma::Input* in) {
in->maximumIterations = maximumIterations;
in->shouldCoarsen = shouldCoarsen;
in->shouldFixShape = shouldFixShape;
in->shouldForceAdaptation = shouldForceAdaptation;
in->shouldPrintQuality = shouldPrintQuality;
in->goodQuality = goodQuality;
in->maximumEdgeRatio = maximumEdgeRatio;
in->shouldCheckQualityForDoubleSplits = shouldCheckQualityForDoubleSplits;
in->validQuality = validQuality;
in->maximumImbalance = maximumImbalance;
in->shouldRunPreZoltan = shouldRunPreZoltan;
in->shouldRunPreZoltanRib = shouldRunPreZoltanRib;
in->shouldRunPreParma = shouldRunPreParma;
in->shouldRunMidZoltan = shouldRunMidZoltan;
in->shouldRunMidParma = shouldRunMidParma;
in->shouldRunPostZoltan = shouldRunPostZoltan;
in->shouldRunPostZoltanRib = shouldRunPostZoltanRib;
in->shouldRunPostParma = shouldRunPostParma;
in->shouldTurnLayerToTets = shouldTurnLayerToTets;
in->shouldCleanupLayer = shouldCleanupLayer;
in->shouldRefineLayer = shouldRefineLayer;
in->shouldCoarsenLayer = shouldCoarsenLayer;
in->splitAllLayerEdges = splitAllLayerEdges;
}
// Copy constructor
vd_ma_input::vd_ma_input(const vd_ma_input& that) {
maximumIterations = that.maximumIterations;
shouldCoarsen = that.shouldCoarsen;
shouldFixShape = that.shouldFixShape;
shouldForceAdaptation = that.shouldForceAdaptation;
shouldPrintQuality = that.shouldPrintQuality;
goodQuality = that.goodQuality;
maximumEdgeRatio = that.maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits;
validQuality = that.validQuality;
maximumImbalance = that.maximumImbalance;
shouldRunPreZoltan = that.shouldRunPreZoltan;
shouldRunPreZoltanRib = that.shouldRunPreZoltanRib;
shouldRunPreParma = that.shouldRunPreParma;
shouldRunMidZoltan = that.shouldRunMidZoltan;
shouldRunMidParma = that.shouldRunMidParma;
shouldRunPostZoltan = that.shouldRunPostZoltan;
shouldRunPostZoltanRib = that.shouldRunPostZoltanRib;
shouldRunPostParma = that.shouldRunPostParma;
shouldTurnLayerToTets = that.shouldTurnLayerToTets;
shouldCleanupLayer = that.shouldCleanupLayer;
shouldRefineLayer = that.shouldRefineLayer;
shouldCoarsenLayer = that.shouldCoarsenLayer;
splitAllLayerEdges = that.splitAllLayerEdges;
}
// Copy
vd_ma_input& vd_ma_input::operator=(const vd_ma_input& that) {
maximumIterations = that.maximumIterations;
shouldCoarsen = that.shouldCoarsen;
shouldFixShape = that.shouldFixShape;
shouldForceAdaptation = that.shouldForceAdaptation;
shouldPrintQuality = that.shouldPrintQuality;
goodQuality = that.goodQuality;
maximumEdgeRatio = that.maximumEdgeRatio;
shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits;
validQuality = that.validQuality;
maximumImbalance = that.maximumImbalance;
shouldRunPreZoltan = that.shouldRunPreZoltan;
shouldRunPreZoltanRib = that.shouldRunPreZoltanRib;
shouldRunPreParma = that.shouldRunPreParma;
shouldRunMidZoltan = that.shouldRunMidZoltan;
shouldRunMidParma = that.shouldRunMidParma;
shouldRunPostZoltan = that.shouldRunPostZoltan;
shouldRunPostZoltanRib = that.shouldRunPostZoltanRib;
shouldRunPostParma = that.shouldRunPostParma;
shouldTurnLayerToTets = that.shouldTurnLayerToTets;
shouldCleanupLayer = that.shouldCleanupLayer;
shouldRefineLayer = that.shouldRefineLayer;
shouldCoarsenLayer = that.shouldCoarsenLayer;
splitAllLayerEdges = that.splitAllLayerEdges;
}
vd_ma_input::vd_ma_input() :
maximumIterations(3),
shouldCoarsen(true),
shouldFixShape(true),
shouldForceAdaptation(false),
shouldPrintQuality(true),
goodQuality(0.027),
maximumEdgeRatio(2.0),
shouldCheckQualityForDoubleSplits(false),
validQuality(1e-10),
maximumImbalance(1.10),
shouldRunPreZoltan(false),
shouldRunPreZoltanRib(false),
shouldRunPreParma(false),
shouldRunMidZoltan(false),
shouldRunMidParma(false),
shouldRunPostZoltan(false),
shouldRunPostZoltanRib(false),
shouldRunPostParma(false),
shouldTurnLayerToTets(false),
shouldCleanupLayer(false),
shouldRefineLayer(false),
shouldCoarsenLayer(false),
splitAllLayerEdges(false) {
}
vd_ma_input::~vd_ma_input() {}
vd_input_iso::vd_input_iso() {
}
/*
// A wrapper for ma::Input object with common predefined use cases.
// Using INPUT_TYPE flags as input, the input flags can be set for a certain
// option, or the flags associated with a INPUT_TYPE can be flipped.
vd_input_iso::vd_input_iso(apf::Mesh2* m, ma::IsotropicFunction* sf,
ma::IdentitySizeField* ref) :
in(NULL) {
in = ma::configure(m, sf);
if(ref != NULL) {
delete in->sizeField;
in->sizeField = ref;
}
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
in->shouldCoarsenLayer = true;
in->shouldFixShape = true;
in->goodQuality = 0.2;
in->validQuality = 10e-5;
std::cout << "Minimum quality is " << in->validQuality
<< ", good quality is " << in->goodQuality
<< std::endl;
in->maximumEdgeRatio = 12;
in->maximumIterations = 3;
}
*/
//void vd_input_iso::set_valid(double v_in) {
// in->validQuality = v_in;
// std::cout << "Set valid quality to " << in->validQuality
// << std::endl;
//}
//void vd_input_iso::set_good(double g_in) {
// in->goodQuality = g_in;
// std::cout << "Set good quality to " << in->goodQuality
// << std::endl;
//}
vd_input_iso::~vd_input_iso() {
}
//void vd_input_iso::set_sizefield(ma::IdentitySizeField* ref) {
// assert(ref != NULL);
// delete in->sizeField;
// in->sizeField = ref;
//}
void vd_input_iso::set_input(std::vector<INPUT_TYPE> &IT_IN) {
IT = IT_IN;
}
//ma::Input* vd_input_iso::get_input() {
// return in;
//}
// Container for keeping calculations of distances of a given stratum vertices
// from its bounding strata. Calculates for bounding 2s for 3c, 1s for 2s and
// 0s for 1s.
// Set the cell for the distances to be calculated:
void DistBurner::set_cell(int d_in, int id_in, apf::Mesh2* m_in,
vd_entlist & e_list,
cell_base* c_base_in, double len) {
clear();
c_dim = d_in;
c_id = id_in;
sim_len = len;
m = m_in;
c_base = c_base_in;
collect_adj(e_list);
burn_dist();
//consider the distance to entity centers, in addition to vertices.
}
// Collect adjacencies:
void DistBurner::collect_adj(vd_entlist & e_list) {
assert(e_list.e.at(c_dim).at(c_id).at(c_dim).size() > 0);
front.reserve(e_list.e.at(c_dim).at(c_id).at(c_dim).size());
// Link the downward adjacencies of the same dimensional entities of the
// calculated stratum to it's entities of one dimension lower.
int d_lower = c_dim - 1;
apf::Downward d_e;
for(int i = 0; i < e_list.e.at(c_dim).at(c_id).at(c_dim).size(); i++) {
apf::MeshEntity* e_curr = e_list.e.at(c_dim).at(c_id).at(c_dim).at(i);
m->getDownward(e_curr, d_lower, d_e);
for(int j = 0; j < c_dim + 1; j++) {
if(e_map1[d_e[j]] == NULL) {
e_map1[d_e[j]] = e_curr;
}
else {
assert(e_map2[d_e[j]] == NULL);
e_map2[d_e[j]] = e_curr;
}
}
}
ent_conn* edown = new ent_conn();
c_base->get_conn(c_dim, c_id, edown);
// TODO for now, assume no ring-like strata. In future, consider the distance
// from the weighted center.
assert(edown->conn.size() > 0);
// Collect the geometric information about boundary entities.
int lookup_tet_x_surf [4] = {3, 2, 0, 1};
int lookup_v_tri_x_e [3] = {2,0,1};
apf::Vector3 temp(0,0,0);
apf::Downward d_v;
apf::Up up;
for(int c_down = 0; c_down < e_list.e.at(d_lower).size(); c_down++) {
if(e_list.e.at(d_lower).at(c_down).at(d_lower).size() > 0) {
// Walk over downward adjancency lists:
for(int i = 0; i < e_list.e.at(d_lower).at(c_down).at(d_lower).size();
i++) {
apf::MeshEntity* e_curr = e_list.e.at(d_lower).at(c_down)
.at(d_lower).at(i);
m->getUp(e_curr, up);
// The geometric information is assigned. Used in lower dim boundary
// entities to prevent spurious assignment.
std::map<apf::MeshEntity*, bool> asgn{};
bool found = false;
for(int j = 0; j < up.n; j++) {
apf::ModelEntity* mdl = m->toModel(up.e[j]);
int d_up = m->getModelType(mdl);
int id_up = m->getModelTag(mdl) - 1;
if(d_up == c_dim and id_up == c_id) {
assert(!found);
found = true;
front.push_back(up.e[j]);
m->getDownward(up.e[j], d_lower, d_e);
int e1 = findIn(d_e, c_dim+1, e_curr);
// Collecting entities bounding a 1cell:
if(d_lower == 0) {
// The information about the bounding vertex is collected:
m->getPoint(e_curr, 0, temp);
v_pos[e_curr] = temp;
asgn[e_curr] = true;
// The vertex of the front entity is collected:
int v1 = (e1 + 1) % 2;
v_map[up.e[j]] = d_e[v1];
v_id[up.e[j]] = v1;
m->getPoint(d_e[v1], 0, temp);
v_pos[d_e[v1]] = temp;
}
// Collecting entities bounding a 2cell:
else if(d_lower == 1) {
// The vertex of the front entity is collected:
m->getDownward(up.e[j], 0, d_v);
int v1 = lookup_v_tri_x_e[e1];
v_map[up.e[j]] = d_v[v1];
v_id[up.e[j]] = v1;
// Position of the interior vertex.
m->getPoint(d_v[v1], 0, temp);
v_pos[d_v[v1]] = temp;
// The information about the bounding entities are collected:
apf::Vector3 temp2(0,0,0);
int v2 = (v1+1)%3;
m->getPoint(d_v[v2], 0, temp);
v_pos[d_v[v2]] = temp;
asgn[d_v[v2]] = true;
v2 = (v1+2)%3;
m->getPoint(d_v[v2], 0, temp2);
v_pos[d_v[v2]] = temp2;
asgn[d_v[v2]] = true;
e_pos[e_curr] = temp;
e_dir[e_curr] = norm_0(temp2 - temp);
asgn[e_curr] = true;
}
else {
// The vertex of the front entity is collected:
m->getDownward(up.e[j], 0, d_v);
int v1 = lookup_tet_x_surf[e1];
v_map[up.e[j]] = d_v[v1];
v_id[up.e[j]] = v1;
// Position of the interior vertex.
m->getPoint(d_v[v1], 0, temp);
v_pos[d_v[v1]] = temp;
// The information about the bounding entities are collected:
t_pos[e_curr] = apf::Vector3(0,0,0);
for(int k = 0; k < 3; k++) {
int v2 = (v1+k+1)%4;
m->getPoint(d_v[v2], 0, temp);
v_pos[d_v[v2]] = temp;
asgn[d_v[v2]] = true;
t_pos[e_curr] = t_pos[e_curr] + temp;
}
m->getPoint(d_v[v1], 0, temp);
t_dir[e_curr] = vd_area_out_n(m, e_curr);
if((temp - t_pos[e_curr])*t_dir[e_curr] <
- std::numeric_limits<double>::min())
t_dir[e_curr] = t_dir[e_curr]*(-1);
m->getDownward(e_curr, 1, d_e);
for(int k = 0; k < 3; k++) {
m->getDownward(d_e[k], 0, d_v);
assert(asgn[d_v[0]]);
assert(asgn[d_v[1]]);
m->getPoint(d_v[0], 0, temp);
e_pos[d_e[k]] = temp;
m->getPoint(d_v[1], 0, temp);
e_dir[d_e[k]] = norm_0(temp - e_pos[d_e[k]]);
asgn[d_e[k]] = true;
}
}
}
}
assert(found);
}
}
}
delete edown;
}
// Starting from the current entity on the front and moving over the
// adjacent entities, find the smallest distance boundary element
// reachable from the starting element for the vertex associated
// with the starting entity.
void DistBurner::calc_v_3c(apf::MeshEntity* tet) {
apf::Downward d_v;
/*
apf::Vector3 int_pt(0,0,0);
apf::MeshEntity* last;
apf::MeshEntity* next;
next = tri_proj_v(v_map[tet], last, int_pt);
if(last == next)
*/
}
void DistBurner::calc_v_2c(apf::MeshEntity* tri) {
}
void DistBurner::calc_v_1c(apf::MeshEntity* edge) {
}
// Starting from given triangle, return the entity the closest projection of
// the vertex onto the boundary lies on. If the projection is on the triangle,
// return the intersection point.
apf::MeshEntity* DistBurner::tri_proj_v(apf::MeshEntity* v, apf::MeshEntity* tri, apf::Vector3& int_pt) {
apf::MeshEntity* ent = tri;
apf::Vector3 temp1(0,0,0);
apf::Vector3 temp2(0,0,0);
apf::Vector3 edir(0,0,0);
apf::Vector3 epos(0,0,0);
int_pt = v_pos[v] - t_pos[tri];
int_pt = int_pt - t_dir[tri]*(int_pt*t_dir[tri]) + t_pos[tri];
for(int i = 0; i < 3; i++) {
edir = e_dir[e_d[tri].at(i)];
epos = e_pos[e_d[tri].at(i)];
temp1 = (int_pt - epos);
temp1 = temp1 - edir*(temp1*edir);
temp2 = (t_pos[tri] - epos);
temp2 = temp2 - edir*(temp2*edir);
// If outside get the first edge that the projection lies outside of.
if( temp1*temp2 < - std::numeric_limits<double>::min()) {
//std::cout << "v1v2 - t_pos[tri]" << temp1*temp2 << std::endl;
if(e_map1[e_d[tri].at(i)] == tri)
ent = e_map2[e_d[tri].at(i)];
else {
assert(e_map2[e_d[tri].at(i)] == tri);
ent = e_map1[e_d[tri].at(i)];
}
i = 3;
}
}
return ent;
}
// Calculate the distance from the vertex to a given entity.
double DistBurner::calc_d_tri(apf::MeshEntity* v, apf::MeshEntity* tri) {
}
double DistBurner::calc_d_edge(apf::MeshEntity* v, apf::MeshEntity* edge) {
}
double DistBurner::calc_d_vert(apf::MeshEntity* v, apf::MeshEntity* vert) {
apf::Downward d_v;
}
// Burn the vertices below (1+dist_tol)*dist_min distance from the boundary
// remove the burnt entities in the front and add new ones.
void DistBurner::step_front() {
}
// Run step_front until the front is empty.
void DistBurner::burn_dist() {
/*
dist_max = sim_len;
while(front.size() > 0) {
// The end burnt number of tets are burnt and not to be considered.
int burnt = 0;
double dist_min = sim_len;
for(int i = 0; i < front.size() - burnt; i++) {
apf::MeshEntity* t_curr = front.at(i);
assert(!t_burn[t_curr]);
m->getDownward(t_curr, 0, d_v);
bool found = false;
for(int j = 0; j < 4; j++) {
if(!v_burn[d_v[j]]) {
assert(!found);
found = true;
v_map[t_curr] = d_v[j];
v_id[t_curr] = j;
}
}
assert(found);
t_dist[t_curr] = approx_dist(m, v_dist, d_v, v_map[t_curr]);
if(t_dist[t_curr] < v_dist[v_map[t_curr]]) {
v_dist[v_map[t_curr]] = t_dist[t_curr];
if(v_dist[v_map[t_curr]] < dist_min)
dist_min = v_dist[v_map[t_curr]];
}
}
int added = 0;
double dist_th = dist_min*(1+dist_tol);
for(int i = 0; i < front.size() - burnt - added; i++) {
apf::MeshEntity* t_curr = front.at(i);
if(v_dist[v_map[t_curr]] < dist_th) {
v_burn[v_map[t_curr]] = true;
}
}
for(int i = 0; i < front.size() - burnt - added; i++) {
apf::MeshEntity* t_curr = front.at(i);
assert(tv_id[t_curr] > -1);
assert(v_map[t_curr] != NULL);
if(v_dist[v_map[t_curr]] < dist_th) {
m->getDownward(t_curr, 2, d_t);
int v_id = tv_id[t_curr];
for(int j = 0; j < 3; j++) {
int t_id = lookup_tet_surf[v_id][j];
apf::MeshEntity* tri_curr = d_t[t_id];
m->getUp(tri_curr, up);
if(up.n == 2) {
apf::MeshEntity* t_next;
if(up.e[0] == t_curr)
t_next = up.e[1];
else
t_next = up.e[0];
if(!t_burn[t_next]) {
int t1 = findIn(&front, front.size(), t_next);
if(t1 == -1) {
m->getDownward(t_next, 0, d_v);
bool found1 = false;
bool found2 = false;
for(int j = 0; j < 4; j++) {
if(!v_burn[d_v[j]]) {
if(found1)
found2 = true;
else
found1 = true;
}
}
assert(!found2);
if(found1) {
if(burnt > 0) {
int i_b = front.size() - burnt;
assert(!t_burn[front.at(i_b-1)]);
assert(t_burn[front.at(i_b)]);
front.push_back(front.at(i_b));
front.at(i_b) = t_next;
//m->getDownward(t_next, 2, d_t2);
//int t2 = findIn(d_t2, 4, tri_curr);
//assert(t2 > -1);
//v_map[t_next] = d_v[lookup_tet_surf_x[t2]];
//t_dist[t_next] = approx_dist(m, v_dist, d_v,
// v_map[t_curr]);
}
else
front.push_back(t_next);
tv_id[t_next] = -1;
v_map[t_next] = NULL;
added = added + 1;
}
else {
t_burn[t_next] = true;
}
}
}
}
}
t_burn[t_curr] = true;
int i_ub = front.size() - burnt - added - 1;
int i_ad = front.size() - burnt - 1;
if(i_ub != i)
assert(!t_burn[front.at(i_ub)]);
if(added > 0)
assert(!t_burn[front.at(i_ub+1)]);
if(burnt > 0)
assert(t_burn[front.at(i_ub+added+1)]);
front.at(i) = front.at(i_ub);
front.at(i_ub) = front.at(i_ad);
front.at(i_ad) = t_curr;
burnt = burnt + 1;
i = i-1;
}
}
front.resize(front.size() - burnt);
}
*/
}
void DistBurner::clear() {
v_pos.clear();
e_pos.clear();
t_pos.clear();
e_dir.clear();
t_dir.clear();
v_dist.clear();
front.clear();
burn_curr.clear();
e_d.clear();
e_v.clear();
v_map.clear();
v_id.clear();
e_map1.clear();
e_map2.clear();
b_map.clear();
}
DistBurner::DistBurner() :
m(NULL), v_pos{}, e_pos{}, t_pos{}, e_dir{}, t_dir{}, v_dist{},
burn_curr{},
front(0), e_d{}, e_v{}, v_map{}, v_id{}, e_map1{}, e_map2{}, b_map{} {
}
DistBurner::~DistBurner() {
clear();
}
ModelEdgeRefiner::ModelEdgeRefiner(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) {
}
bool ModelEdgeRefiner::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return false;
}
bool ModelEdgeRefiner::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return false;
}
ModelEdgeRefiner::~ModelEdgeRefiner() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
ModelEdgeRefinerDist::ModelEdgeRefinerDist(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false),
split_target(1.5), coarse_target(0.5) {
field_step = m->findField("adapt_step");
assert(field_step != NULL);
}
double ModelEdgeRefinerDist::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
double dist = apf::getScalar(field_step, d_v[0], 0);
dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2;
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return len*dist;
}
bool ModelEdgeRefinerDist::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return this->measure_dist(edge) < coarse_target;
}
bool ModelEdgeRefinerDist::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
//else if(dim_e == 1 and dim_e > dim_v0 and dim_e > dim_v1)
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return this->measure_dist(edge) > split_target;
//else if
}
void ModelEdgeRefinerDist::set_target_th(double coarse_in, double split_in) {
split_target = split_in;
coarse_target = coarse_in;
}
ModelEdgeRefinerDist::~ModelEdgeRefinerDist() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
ModelEdgeCollapse::ModelEdgeCollapse(ma::Mesh* m) : coarse_map{},
IdentitySizeField(m) {
}
bool ModelEdgeCollapse::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map[edge])
return true;
return false;
}
bool ModelEdgeCollapse::shouldSplit(ma::Entity* edge) {
return false;
}
ModelEdgeCollapse::~ModelEdgeCollapse() {
coarse_map.clear();
}
ModelEdgeSplit::ModelEdgeSplit(ma::Mesh* m) : split_map{},
IdentitySizeField(m) {
}
bool ModelEdgeSplit::shouldCollapse(ma::Entity* edge) {
return false;
}
bool ModelEdgeSplit::shouldSplit(ma::Entity* edge) {
if(split_map[edge])
return true;
return false;
}
ModelEdgeSplit::~ModelEdgeSplit() {
split_map.clear();
}
/////////////////////////////////////
// ModelEdgeRefinerGrain
/////////////////////////////////////
ModelEdgeRefinerGrain::ModelEdgeRefinerGrain(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) {
field_step = m->findField("adapt_step");
assert(field_step != NULL);
}
double ModelEdgeRefinerGrain::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
double dist = apf::getScalar(field_step, d_v[0], 0);
dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2;
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return len*dist;
}
bool ModelEdgeRefinerGrain::shouldCollapse(ma::Entity* edge) {
int dim_e = mesh->getModelType(mesh->toModel(edge));
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return true;
return this->measure_dist(edge) < 0.5;
}
bool ModelEdgeRefinerGrain::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))])
return false;
else if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
else if(split_all)
return true;
}
return this->measure_dist(edge) > 1.5;
//else if
}
ModelEdgeRefinerGrain::~ModelEdgeRefinerGrain() {
for(int i = 0; i < 3; i++) {
coarse_map.at(i).clear();
}
coarse_map.clear();
}
/////////////////////////////////////
// ModelEdgeRefinerVarying
/////////////////////////////////////
ModelEdgeRefinerVarying::ModelEdgeRefinerVarying(ma::Mesh* m) : len_map(3, std::map<int, double> {}), rat_map(3, std::map<int, double> {}), IdentitySizeField(m), split_target(1.5), coarse_target(0.5) {
gmi_model* mdl = m->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
apf::MeshEntity* e;
for(int dim = 1; dim < 4; dim++) {
apf::MeshIterator* it = m->begin(dim);
while ((e = m->iterate(it))) {
apf::ModelEntity* mdl_curr = m->toModel(e);
int c_type = m->getModelType(mdl_curr);
int c_tag = m->getModelTag(mdl_curr);
double meas_curr = vd_meas_ent(m, e);
len_map.at(c_type - 1)[c_tag] = len_map.at(c_type - 1)[c_tag] + meas_curr;
}
m->end(it);
}
double pow[3] = {1., 0.5, 1.0/3};
double coef[3] = {1./2, 1./8, 1./16};
for(int dim = 1; dim < 4; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
len_map.at(dim - 1)[c_tag] = std::pow(len_map.at(dim - 1)[c_tag]*coef[dim-1], pow[dim-1]);
rat_map.at(dim - 1)[c_tag] = 1;
}
gmi_end(mdl, it_gmi);
}
}
// Set the rat_map for boundary cells such that they are refined to yield edge
// length len.
void ModelEdgeRefinerVarying::set_all_cell(double len) {
gmi_model* mdl = mesh->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
for(int dim = 1; dim < 4; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
gmi_end(mdl, it_gmi);
}
}
// Set the rat_map for boundary cells such that they are refined to yield edge
// length len.
void ModelEdgeRefinerVarying::set_bound_cell(double len,
std::vector<std::pair<int,int> >* cells) {
if(cells != NULL) {
for(int i = 0; i < cells->size(); i++) {
int dim = cells->at(i).first;
int c_tag = cells->at(i).second;
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
}
else {
gmi_model* mdl = mesh->getModel();
struct gmi_iter* it_gmi;
struct gmi_ent* e_gmi;
struct gmi_set* s_gmi;
for(int dim = 1; dim < 3; dim++) {
it_gmi = gmi_begin(mdl, dim);
while ((e_gmi = gmi_next(mdl, it_gmi))) {
int c_tag = gmi_tag(mdl,e_gmi);
rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len;
}
gmi_end(mdl, it_gmi);
}
}
}
double ModelEdgeRefinerVarying::measure_dist(ma::Entity* edge) {
// TODO Use integrators of apf to integrate the field directly. For linear
// elements and for isotropic metrics, it is equivalent.
apf::MeshElement* me = apf::createMeshElement(mesh, edge);
double len = measure(edge);
apf::destroyMeshElement(me);
apf::ModelEntity* mdl = mesh->toModel(edge);
int dim_e = mesh->getModelType(mdl);
int tag_e = mesh->getModelTag(mdl);
if(len_map.at(dim_e - 1)[tag_e] < std::numeric_limits<double>::min())
return len;
return len/len_map.at(dim_e - 1)[tag_e]*rat_map.at(dim_e - 1)[tag_e];
}
bool ModelEdgeRefinerVarying::shouldCollapse(ma::Entity* edge) {
return this->measure_dist(edge) < coarse_target;
}
bool ModelEdgeRefinerVarying::shouldSplit(ma::Entity* edge) {
apf::Downward d_v;
mesh->getDownward(edge, 0, d_v);
int dim_e = mesh->getModelType(mesh->toModel(edge));
int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0]));
int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1]));
//double v0 = apf::getScalar(field_step, d_v[0], 0);
//double v1 = apf::getScalar(field_step, d_v[1], 0);
//double len = vd_meas_ent(mesh, edge);
//return (1 > v0) or (1 > v1);
//return (2*len > v0) or (2*len > v1);
//return (len > v0/4+v1/4);
if(dim_e > dim_v0 and dim_e > dim_v1) {
if(dim_e == 1)
return true;
}
return this->measure_dist(edge) > split_target;
}
void ModelEdgeRefinerVarying::set_target_th(double coarse_in, double split_in) {
split_target = split_in;
coarse_target = coarse_in;
}
ModelEdgeRefinerVarying::~ModelEdgeRefinerVarying() {
for(int i = 0; i < 3; i++) {
len_map.at(i).clear();
}
len_map.clear();
}
////////////////////////////
// STEP
////////////////////////////
Step::Step(ma::Mesh* m, double sz) {
if(sz > std::numeric_limits<double>::min())
sizing = sz;
else
sizing = 1;
mesh = m;
average = ma::getAverageEdgeLength(m);
field_step = m->findField("adapt_step");
assert(field_step);
}
double Step::getValue(ma::Entity* v) {
double dist = apf::getScalar(field_step, v, 0);
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return dist/sizing;
}
Step_ns::Step_ns(ma::Mesh* m, double sz) {
if(sz > std::numeric_limits<double>::min())
sizing = sz;
else
sizing = 1;
mesh = m;
average = ma::getAverageEdgeLength(m);
field_step = m->findField("adapt_step");
assert(field_step);
}
double Step_ns::getValue(ma::Entity* v) {
double dist = apf::getScalar(field_step, v, 0);
assert(dist > std::numeric_limits<double>::min());
//return average*dist*sizing;
return dist;
}
void vd_adapt_0cell(apf::Mesh2* m, struct cell_base* c) {
std::vector<double> avg_cell(0);
avg_cell = upd_cell_rad(m);
Linear_0cell sf(m, c, &avg_cell);
ma::Input* in = ma::configure(m, &sf);
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
ma::adapt(in);
}
void vd_adapt(apf::Mesh2* m) {
Linear sf(m, 1.1);
ma::Input* in = ma::configure(m, &sf);
in->shouldRunPreZoltan = true;
in->shouldRunMidParma = true;
in->shouldRunPostParma = true;
in->shouldRefineLayer = true;
ma::adapt(in);
}
Linear_0cell::Linear_0cell(ma::Mesh* m, struct cell_base* c,
std::vector<double>* avg_cell_in) :
mesh(NULL), average(0), avg_cell(0), cell0(0),
cell0_pos(0, apf::Vector3(0, 0, 0)),
cnc0(0, std::vector<std::vector<int > > (0, std::vector<int >(0) ) ) {
avg_cell = *avg_cell_in;
mesh = m;
c_base = c;
refresh();
}
void Linear_0cell::reload(ma::Mesh* m, struct cell_base* c,
std::vector<double>* avg_cell_in) {
avg_cell = *avg_cell_in;
mesh = m;
c_base = c;
refresh();
}
double Linear_0cell::getValue(ma::Entity* v) {
return getDistance(v);
//return getDistance(v)*sizing;
}
double Linear_0cell::getDistance(ma::Entity* v) {
double distance = average+1;
double temp_len;
apf::Vector3 e_pos;
apf::Vector3 temp;
mesh->getPoint(v, 0, e_pos);
int ent_type = mesh->getType(v);
int d = mesh->typeDimension[ent_type];
apf::ModelEntity* mdl = mesh->toModel(v);
int c_type = mesh->getModelType(mdl);
int c_tag = mesh->getModelTag(mdl);
//std::cout << c_type << "c" << c_tag << " "
// << d << "-ent" << v << std::endl;
for(int i = 0; i < cnc0.at(c_type).at(c_tag-1).size(); i++) {
int c_id = cnc0.at(c_type).at(c_tag-1).at(i);
if(cell0.at(c_id) != NULL) {
//std::cout << "v " << cell0.at(c_id)
// << " pos " << cell0_pos.at(c_id) << std::endl;
temp = e_pos - cell0_pos.at(c_id);
temp_len = temp.getLength();
if(distance > temp_len);
distance = temp_len;
}
}
if(distance < average) {
//if(c_type == 0)
return distance*0.7;
//else
// return distance;
//return distance*3;
//return average*3;
//return average*exp(-average/distance);
}
else
//return avg_cell.at(c_type-1);
return avg_cell.at(0)*0.7;
//return average;
}
Linear_0cell::~Linear_0cell() {
clear();
}
void Linear_0cell::refresh() {
clear();
load_0cell();
average = ma::getAverageEdgeLength(mesh);
}
void Linear_0cell::load_0cell_ent() {
cell0_pos.resize(c_base->get_sz(0));
cell0.resize(c_base->get_sz(0));
double z[3] = {0,0,0};
for(int i = 0; i < cell0_pos.size(); i++) {
cell0_pos.at(i).fromArray(z);
}
for(int i = 0; i < cell0.size(); i++) {
cell0.at(i) = NULL;
}
apf::MeshIterator* it_e = mesh->begin(0);
//std::cout << "Iterator." << std::endl;
apf::MeshEntity* v;
while (v = mesh->iterate(it_e)) {
apf::ModelEntity* mdl = mesh->toModel(v);
int type = mesh->getModelType(mdl);
int tag = mesh->getModelTag(mdl);
if(type == 0) {
assert(cell0.at(tag-1) == NULL);
cell0.at(tag-1) = v;
}
}
mesh->end(it_e);
}
void Linear_0cell::load_0cell_pos() {
apf::Vector3 vert_pos;
for(int i = 0; i < cell0.size(); i++) {
if(cell0.at(i) != NULL) {
mesh->getPoint(cell0.at(i), 0, vert_pos);
cell0_pos.at(i) = vert_pos;
}
}
}
// TODO very ugly notation.
void Linear_0cell::load_0cell() {
load_0cell_ent();
load_0cell_pos();
cnc0.at(3).resize(c_base->get_sz(3));
cnc0.at(2).resize(c_base->get_sz(2));
cnc0.at(1).resize(c_base->get_sz(1));
cnc0.at(0).resize(c_base->get_sz(0));
struct ent_conn e_cover;
int max_sz = 1;
for(int i = 0; i < cnc0.at(3).size(); i++) {
c_base->get_conn_lower(0, 3, i, &e_cover);
cnc0.at(3).at(i).reserve(e_cover.conn.size());
for(int j = 0; j < e_cover.conn.size(); j++) {
cnc0.at(3).at(i).push_back(e_cover.conn.at(j));
}
if(max_sz < e_cover.conn.size())
max_sz = e_cover.conn.size();
}
for(int i = 0; i < cnc0.at(2).size(); i++) {
cnc0.at(2).at(i).reserve(2*max_sz);
}
for(int i = 0; i < cnc0.at(1).size(); i++) {
cnc0.at(1).at(i).reserve(7*max_sz);
}
for(int i = 0; i < cnc0.at(0).size(); i++) {
c_base->get_conn_dim(0, 0, i, &e_cover);
cnc0.at(0).at(i).reserve(e_cover.conn.size());
for(int j = 0; j < e_cover.conn.size(); j++) {
if(i != e_cover.conn.at(j))
cnc0.at(0).at(i).push_back(e_cover.conn.at(j));
}
}
// Go over 2cell adj. of 3cell, check for 0cell adj of the 3cell in the 0cell
// list of the 2cell.
for(int i = 0; i < cnc0.at(3).size(); i++) {
//std::cout << "3c-" << i + 1 << std::endl;
c_base->get_conn_lower(2, 3, i, &e_cover);
for(int j = 0; j < e_cover.conn.size(); j++) {
//std::cout << "2c-" << e_cover.conn.at(j) + 1 << std::endl;
for(int k = 0; k < cnc0.at(3).at(i).size(); k++) {
std::vector<int>::iterator c_st;
std::vector<int>::iterator c_end;
c_st = cnc0.at(2).at(e_cover.conn.at(j)).begin();
c_end = cnc0.at(2).at(e_cover.conn.at(j)).end();
int c0 = cnc0.at(3).at(i).at(k);
//std::cout << "0c-" << c0 + 1 << ", "
// << (std::find(c_st, c_end, c0) != c_end) << ", ";
if(std::find(c_st, c_end, c0) == c_end) {
cnc0.at(2).at(e_cover.conn.at(j)).push_back(c0);
}
}
//std::cout << std::endl;
}
//std::cout << std::endl;
c_base->get_conn_lower(1, 3, i, &e_cover);
for(int j = 0; j < e_cover.conn.size(); j++) {
for(int k = 0; k < cnc0.at(3).at(i).size(); k++) {
std::vector<int>::iterator c_st;
std::vector<int>::iterator c_end;
c_st = cnc0.at(1).at(e_cover.conn.at(j)).begin();
c_end = cnc0.at(1).at(e_cover.conn.at(j)).end();
int c0 = cnc0.at(3).at(i).at(k);
if(std::find(c_st, c_end, c0) == c_end) {
cnc0.at(1).at(e_cover.conn.at(j)).push_back(c0);
}
}
}
}
for(int i = 0; i < cnc0.size(); i++) {
for(int j = 0; j < cnc0.at(i).size(); j++) {
//std::cout << i << "c" << j+1 << std::endl;
for(int k = 0; k < cnc0.at(i).at(j).size(); k++) {
//std::cout << "0" << "c" << cnc0.at(i).at(j).at(k) + 1 << ", ";
}
//std::cout << std::endl;
}
}
}
void Linear_0cell::clear() {
dummy_clear_stop();
cell0_pos.clear();
for(int i = 0; i < cnc0.size(); i++) {
for(int j = 0; j < cnc0.at(i).size(); j++) {
cnc0.at(i).at(j).clear();
}
cnc0.at(i).clear();
}
cnc0.clear();
cnc0.resize(4);
}
| 29.662752 | 201 | 0.593623 | erdemeren |
91825db1e52c5f3d5b3aa48752a882d39450bd28 | 28,923 | cpp | C++ | Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 1 | 2021-12-10T19:15:25.000Z | 2021-12-10T19:15:25.000Z | Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 41 | 2021-08-18T21:32:14.000Z | 2022-02-20T11:44:06.000Z | Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | null | null | null | #include "egpch.h"
#include "ScriptEngineRegistry.h"
#include "ScriptEngine.h"
#include "ScriptWrappers.h"
#include "Eagle/Components/Components.h"
#include "Eagle/Core/Entity.h"
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
namespace Eagle
{
std::unordered_map<MonoType*, std::function<void(Entity&)>> m_AddComponentFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_HasComponentFunctions;
//SceneComponents
std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetWorldTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetRelativeTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetWorldTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetRelativeTransformFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetForwardVectorFunctions;
//Light Component
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetLightColorFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetLightColorFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetAmbientFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetAmbientFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetSpecularFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetSpecularFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetAffectsWorldFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_GetAffectsWorldFunctions;
//BaseColliderComponent
std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetIsTriggerFunctions;
std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_IsTriggerFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetStaticFrictionFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetDynamicFrictionFunctions;
std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetBouncinessFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetStaticFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetDynamicFrictionFunctions;
std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetBouncinessFunctions;
extern MonoImage* s_CoreAssemblyImage;
#define REGISTER_COMPONENT_TYPE(Type)\
{\
MonoType* type = mono_reflection_type_from_name("Eagle." #Type, s_CoreAssemblyImage);\
if (type)\
{\
m_HasComponentFunctions[type] = [](Entity& entity) { return entity.HasComponent<Type>(); };\
m_AddComponentFunctions[type] = [](Entity& entity) { entity.AddComponent<Type>(); };\
\
if (std::is_base_of<SceneComponent, Type>::value)\
{\
m_SetWorldTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetWorldTransform(*transform); };\
m_SetRelativeTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetRelativeTransform(*transform); };\
\
m_GetWorldTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetWorldTransform(); };\
m_GetRelativeTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetRelativeTransform(); };\
m_GetForwardVectorFunctions[type] = [](Entity& entity, glm::vec3* outVector) { *outVector = ((SceneComponent&)entity.GetComponent<Type>()).GetForwardVector(); };\
}\
\
if (std::is_base_of<LightComponent, Type>::value)\
{\
m_SetLightColorFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).LightColor = *value; };\
m_GetLightColorFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).LightColor; };\
\
m_SetAmbientFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Ambient = *value; };\
m_GetAmbientFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Ambient; };\
\
m_SetSpecularFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Specular = *value; };\
m_GetSpecularFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Specular; };\
\
m_SetAffectsWorldFunctions[type] = [](Entity& entity, bool value) { ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld = value; };\
m_GetAffectsWorldFunctions[type] = [](Entity& entity) { return ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld; };\
}\
if (std::is_base_of<BaseColliderComponent, Type>::value)\
{\
m_SetIsTriggerFunctions[type] = [](Entity& entity, bool bTrigger) { ((BaseColliderComponent&)entity.GetComponent<Type>()).SetIsTrigger(bTrigger); };\
m_IsTriggerFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).IsTrigger(); };\
m_SetStaticFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->StaticFriction = value; comp.SetPhysicsMaterial(mat); };\
m_SetDynamicFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->DynamicFriction = value; comp.SetPhysicsMaterial(mat); };\
m_SetBouncinessFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->Bounciness = value; comp.SetPhysicsMaterial(mat); };\
m_GetStaticFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->StaticFriction; };\
m_GetDynamicFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->DynamicFriction; };\
m_GetBouncinessFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->Bounciness; };\
}\
}\
else\
EG_CORE_ERROR("No C# Component found for " #Type "!");\
}
static void InitComponentTypes()
{
REGISTER_COMPONENT_TYPE(TransformComponent);
REGISTER_COMPONENT_TYPE(SceneComponent);
REGISTER_COMPONENT_TYPE(PointLightComponent);
REGISTER_COMPONENT_TYPE(DirectionalLightComponent);
REGISTER_COMPONENT_TYPE(SpotLightComponent);
REGISTER_COMPONENT_TYPE(StaticMeshComponent);
REGISTER_COMPONENT_TYPE(AudioComponent);
REGISTER_COMPONENT_TYPE(RigidBodyComponent);
REGISTER_COMPONENT_TYPE(BoxColliderComponent);
REGISTER_COMPONENT_TYPE(SphereColliderComponent);
REGISTER_COMPONENT_TYPE(CapsuleColliderComponent);
REGISTER_COMPONENT_TYPE(MeshColliderComponent);
}
void ScriptEngineRegistry::RegisterAll()
{
InitComponentTypes();
//Entity
mono_add_internal_call("Eagle.Entity::GetParent_Native", Eagle::Script::Eagle_Entity_GetParent);
mono_add_internal_call("Eagle.Entity::SetParent_Native", Eagle::Script::Eagle_Entity_SetParent);
mono_add_internal_call("Eagle.Entity::GetChildren_Native", Eagle::Script::Eagle_Entity_GetChildren);
mono_add_internal_call("Eagle.Entity::CreateEntity_Native", Eagle::Script::Eagle_Entity_CreateEntity);
mono_add_internal_call("Eagle.Entity::DestroyEntity_Native", Eagle::Script::Eagle_Entity_DestroyEntity);
mono_add_internal_call("Eagle.Entity::AddComponent_Native", Eagle::Script::Eagle_Entity_AddComponent);
mono_add_internal_call("Eagle.Entity::HasComponent_Native", Eagle::Script::Eagle_Entity_HasComponent);
mono_add_internal_call("Eagle.Entity::GetEntityName_Native", Eagle::Script::Eagle_Entity_GetEntityName);
mono_add_internal_call("Eagle.Entity::GetForwardVector_Native", Eagle::Script::Eagle_Entity_GetForwardVector);
mono_add_internal_call("Eagle.Entity::GetRightVector_Native", Eagle::Script::Eagle_Entity_GetRightVector);
mono_add_internal_call("Eagle.Entity::GetUpVector_Native", Eagle::Script::Eagle_Entity_GetUpVector);
//Entity-Physics
mono_add_internal_call("Eagle.Entity::WakeUp_Native", Eagle::Script::Eagle_Entity_WakeUp);
mono_add_internal_call("Eagle.Entity::PutToSleep_Native", Eagle::Script::Eagle_Entity_PutToSleep);
mono_add_internal_call("Eagle.Entity::GetMass_Native", Eagle::Script::Eagle_Entity_GetMass);
mono_add_internal_call("Eagle.Entity::SetMass_Native", Eagle::Script::Eagle_Entity_SetMass);
mono_add_internal_call("Eagle.Entity::AddForce_Native", Eagle::Script::Eagle_Entity_AddForce);
mono_add_internal_call("Eagle.Entity::AddTorque_Native", Eagle::Script::Eagle_Entity_AddTorque);
mono_add_internal_call("Eagle.Entity::GetLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetLinearVelocity);
mono_add_internal_call("Eagle.Entity::SetLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetLinearVelocity);
mono_add_internal_call("Eagle.Entity::GetAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetAngularVelocity);
mono_add_internal_call("Eagle.Entity::GetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxLinearVelocity);
mono_add_internal_call("Eagle.Entity::SetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxLinearVelocity);
mono_add_internal_call("Eagle.Entity::GetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxAngularVelocity);
mono_add_internal_call("Eagle.Entity::SetLinearDamping_Native", Eagle::Script::Eagle_Entity_SetLinearDamping);
mono_add_internal_call("Eagle.Entity::SetAngularDamping_Native", Eagle::Script::Eagle_Entity_SetAngularDamping);
mono_add_internal_call("Eagle.Entity::IsDynamic_Native", Eagle::Script::Eagle_Entity_IsDynamic);
mono_add_internal_call("Eagle.Entity::IsKinematic_Native", Eagle::Script::Eagle_Entity_IsKinematic);
mono_add_internal_call("Eagle.Entity::IsGravityEnabled_Native", Eagle::Script::Eagle_Entity_IsGravityEnabled);
mono_add_internal_call("Eagle.Entity::IsLockFlagSet_Native", Eagle::Script::Eagle_Entity_IsLockFlagSet);
mono_add_internal_call("Eagle.Entity::GetLockFlags_Native", Eagle::Script::Eagle_Entity_GetLockFlags);
mono_add_internal_call("Eagle.Entity::SetKinematic_Native", Eagle::Script::Eagle_Entity_SetKinematic);
mono_add_internal_call("Eagle.Entity::SetGravityEnabled_Native", Eagle::Script::Eagle_Entity_SetGravityEnabled);
mono_add_internal_call("Eagle.Entity::SetLockFlag_Native", Eagle::Script::Eagle_Entity_SetLockFlag);
//Input
mono_add_internal_call("Eagle.Input::IsMouseButtonPressed_Native", Eagle::Script::Eagle_Input_IsMouseButtonPressed);
mono_add_internal_call("Eagle.Input::IsKeyPressed_Native", Eagle::Script::Eagle_Input_IsKeyPressed);
mono_add_internal_call("Eagle.Input::GetMousePosition_Native", Eagle::Script::Eagle_Input_GetMousePosition);
mono_add_internal_call("Eagle.Input::SetCursorMode_Native", Eagle::Script::Eagle_Input_SetCursorMode);
mono_add_internal_call("Eagle.Input::GetCursorMode_Native", Eagle::Script::Eagle_Input_GetCursorMode);
//TransformComponent
mono_add_internal_call("Eagle.TransformComponent::GetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_GetWorldTransform);
mono_add_internal_call("Eagle.TransformComponent::GetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldLocation);
mono_add_internal_call("Eagle.TransformComponent::GetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldRotation);
mono_add_internal_call("Eagle.TransformComponent::GetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_GetWorldScale);
mono_add_internal_call("Eagle.TransformComponent::SetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_SetWorldTransform);
mono_add_internal_call("Eagle.TransformComponent::SetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldLocation);
mono_add_internal_call("Eagle.TransformComponent::SetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldRotation);
mono_add_internal_call("Eagle.TransformComponent::SetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_SetWorldScale);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeTransform);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeLocation);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeRotation);
mono_add_internal_call("Eagle.TransformComponent::GetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeScale);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeTransform);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeLocation);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeRotation);
mono_add_internal_call("Eagle.TransformComponent::SetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeScale);
//Scene Component
mono_add_internal_call("Eagle.SceneComponent::GetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_GetWorldTransform);
mono_add_internal_call("Eagle.SceneComponent::GetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldLocation);
mono_add_internal_call("Eagle.SceneComponent::GetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldRotation);
mono_add_internal_call("Eagle.SceneComponent::GetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_GetWorldScale);
mono_add_internal_call("Eagle.SceneComponent::SetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_SetWorldTransform);
mono_add_internal_call("Eagle.SceneComponent::SetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldLocation);
mono_add_internal_call("Eagle.SceneComponent::SetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldRotation);
mono_add_internal_call("Eagle.SceneComponent::SetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_SetWorldScale);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeTransform);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeLocation);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeRotation);
mono_add_internal_call("Eagle.SceneComponent::GetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeScale);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeTransform);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeLocation);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeRotation);
mono_add_internal_call("Eagle.SceneComponent::SetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeScale);
mono_add_internal_call("Eagle.SceneComponent::GetForwardVector_Native", Eagle::Script::Eagle_SceneComponent_GetForwardVector);
//Light Component
mono_add_internal_call("Eagle.LightComponent::GetLightColor_Native", Eagle::Script::Eagle_LightComponent_GetLightColor);
mono_add_internal_call("Eagle.LightComponent::GetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_GetAmbientColor);
mono_add_internal_call("Eagle.LightComponent::GetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_GetSpecularColor);
mono_add_internal_call("Eagle.LightComponent::GetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_GetAffectsWorld);
mono_add_internal_call("Eagle.LightComponent::SetLightColor_Native", Eagle::Script::Eagle_LightComponent_SetLightColor);
mono_add_internal_call("Eagle.LightComponent::SetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_SetAmbientColor);
mono_add_internal_call("Eagle.LightComponent::SetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_SetSpecularColor);
mono_add_internal_call("Eagle.LightComponent::SetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_SetAffectsWorld);
//PointLight Component
mono_add_internal_call("Eagle.PointLightComponent::GetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_GetIntensity);
mono_add_internal_call("Eagle.PointLightComponent::SetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_SetIntensity);
//DirectionalLight Component
//SpotLight Component
mono_add_internal_call("Eagle.SpotLightComponent::GetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetInnerCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::GetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetOuterCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetInnerCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetOuterCutoffAngle);
mono_add_internal_call("Eagle.SpotLightComponent::SetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_SetIntensity);
mono_add_internal_call("Eagle.SpotLightComponent::GetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_GetIntensity);
//Texture
mono_add_internal_call("Eagle.Texture::IsValid_Native", Eagle::Script::Eagle_Texture_IsValid);
//Texture2D
mono_add_internal_call("Eagle.Texture2D::Create_Native", Eagle::Script::Eagle_Texture2D_Create);
//Static Mesh
mono_add_internal_call("Eagle.StaticMesh::Create_Native", Eagle::Script::Eagle_StaticMesh_Create);
mono_add_internal_call("Eagle.StaticMesh::IsValid_Native", Eagle::Script::Eagle_StaticMesh_IsValid);
mono_add_internal_call("Eagle.StaticMesh::SetDiffuseTexture_Native", Eagle::Script::Eagle_StaticMesh_SetDiffuseTexture);
mono_add_internal_call("Eagle.StaticMesh::SetSpecularTexture_Native", Eagle::Script::Eagle_StaticMesh_SetSpecularTexture);
mono_add_internal_call("Eagle.StaticMesh::SetNormalTexture_Native", Eagle::Script::Eagle_StaticMesh_SetNormalTexture);
mono_add_internal_call("Eagle.StaticMesh::SetScalarMaterialParams_Native", Eagle::Script::Eagle_StaticMesh_SetScalarMaterialParams);
mono_add_internal_call("Eagle.StaticMesh::GetMaterial_Native", Eagle::Script::Eagle_StaticMesh_GetMaterial);
//StaticMeshComponent
mono_add_internal_call("Eagle.StaticMeshComponent::SetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_SetMesh);
mono_add_internal_call("Eagle.StaticMeshComponent::GetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_GetMesh);
//Sound
mono_add_internal_call("Eagle.Sound2D::Play_Native", Eagle::Script::Eagle_Sound2D_Play);
mono_add_internal_call("Eagle.Sound3D::Play_Native", Eagle::Script::Eagle_Sound3D_Play);
//AudioComponent
mono_add_internal_call("Eagle.AudioComponent::SetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinDistance);
mono_add_internal_call("Eagle.AudioComponent::SetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::SetMinMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::SetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_SetRollOffModel);
mono_add_internal_call("Eagle.AudioComponent::SetVolume_Native", Eagle::Script::Eagle_AudioComponent_SetVolume);
mono_add_internal_call("Eagle.AudioComponent::SetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_SetLoopCount);
mono_add_internal_call("Eagle.AudioComponent::SetLooping_Native", Eagle::Script::Eagle_AudioComponent_SetLooping);
mono_add_internal_call("Eagle.AudioComponent::SetMuted_Native", Eagle::Script::Eagle_AudioComponent_SetMuted);
mono_add_internal_call("Eagle.AudioComponent::SetSound_Native", Eagle::Script::Eagle_AudioComponent_SetSound);
mono_add_internal_call("Eagle.AudioComponent::SetStreaming_Native", Eagle::Script::Eagle_AudioComponent_SetStreaming);
mono_add_internal_call("Eagle.AudioComponent::Play_Native", Eagle::Script::Eagle_AudioComponent_Play);
mono_add_internal_call("Eagle.AudioComponent::Stop_Native", Eagle::Script::Eagle_AudioComponent_Stop);
mono_add_internal_call("Eagle.AudioComponent::SetPaused_Native", Eagle::Script::Eagle_AudioComponent_SetPaused);
mono_add_internal_call("Eagle.AudioComponent::GetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMinDistance);
mono_add_internal_call("Eagle.AudioComponent::GetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMaxDistance);
mono_add_internal_call("Eagle.AudioComponent::GetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_GetRollOffModel);
mono_add_internal_call("Eagle.AudioComponent::GetVolume_Native", Eagle::Script::Eagle_AudioComponent_GetVolume);
mono_add_internal_call("Eagle.AudioComponent::GetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_GetLoopCount);
mono_add_internal_call("Eagle.AudioComponent::IsLooping_Native", Eagle::Script::Eagle_AudioComponent_IsLooping);
mono_add_internal_call("Eagle.AudioComponent::IsMuted_Native", Eagle::Script::Eagle_AudioComponent_IsMuted);
mono_add_internal_call("Eagle.AudioComponent::IsStreaming_Native", Eagle::Script::Eagle_AudioComponent_IsStreaming);
mono_add_internal_call("Eagle.AudioComponent::IsPlaying_Native", Eagle::Script::Eagle_AudioComponent_IsPlaying);
//RigidBodyComponent
mono_add_internal_call("Eagle.RigidBodyComponent::SetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_SetMass);
mono_add_internal_call("Eagle.RigidBodyComponent::GetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_GetMass);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLinearDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::GetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetLinearDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::SetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetAngularDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::GetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetAngularDamping);
mono_add_internal_call("Eagle.RigidBodyComponent::SetEnableGravity_Native", Eagle::Script::Eagle_RigidBodyComponent_SetEnableGravity);
mono_add_internal_call("Eagle.RigidBodyComponent::IsGravityEnabled_Native", Eagle::Script::Eagle_RigidBodyComponent_IsGravityEnabled);
mono_add_internal_call("Eagle.RigidBodyComponent::SetIsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_SetIsKinematic);
mono_add_internal_call("Eagle.RigidBodyComponent::IsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_IsKinematic);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPosition_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPosition);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionX);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionY);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionZ);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotation_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotation);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationX);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationY);
mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationZ);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionXLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionYLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionZLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationXLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationYLocked);
mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationZLocked);
//BaseColliderComponent
mono_add_internal_call("Eagle.BaseColliderComponent::SetIsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_SetIsTrigger);
mono_add_internal_call("Eagle.BaseColliderComponent::IsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_IsTrigger);
mono_add_internal_call("Eagle.BaseColliderComponent::SetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetStaticFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::SetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetDynamicFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::SetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_SetBounciness);
mono_add_internal_call("Eagle.BaseColliderComponent::GetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetStaticFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::GetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetDynamicFriction);
mono_add_internal_call("Eagle.BaseColliderComponent::GetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_GetBounciness);
//BoxColliderComponent
mono_add_internal_call("Eagle.BoxColliderComponent::SetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_SetSize);
mono_add_internal_call("Eagle.BoxColliderComponent::GetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_GetSize);
//SphereColliderComponent
mono_add_internal_call("Eagle.SphereColliderComponent::SetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_SetRadius);
mono_add_internal_call("Eagle.SphereColliderComponent::GetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_GetRadius);
//CapsuleColliderComponent
mono_add_internal_call("Eagle.CapsuleColliderComponent::SetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetRadius);
mono_add_internal_call("Eagle.CapsuleColliderComponent::GetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetRadius);
mono_add_internal_call("Eagle.CapsuleColliderComponent::SetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetHeight);
mono_add_internal_call("Eagle.CapsuleColliderComponent::GetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetHeight);
//MeshColliderComponent
mono_add_internal_call("Eagle.MeshColliderComponent::SetIsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_SetIsConvex);
mono_add_internal_call("Eagle.MeshColliderComponent::IsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_IsConvex);
mono_add_internal_call("Eagle.MeshColliderComponent::SetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_SetCollisionMesh);
mono_add_internal_call("Eagle.MeshColliderComponent::GetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_GetCollisionMesh);
}
}
| 88.449541 | 271 | 0.831 | IceLuna |
91834e8215c7c0af05dc6635277eee55d53d54e4 | 1,790 | cpp | C++ | src/RESTAPI_oauth2Handler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | src/RESTAPI_oauth2Handler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | src/RESTAPI_oauth2Handler.cpp | shimmy568/wlan-cloud-ucentralgw | 806e24e1e666c31175c059373440ae029d9fff67 | [
"BSD-3-Clause"
] | null | null | null | //
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "Poco/JSON/Parser.h"
#include "RESTAPI_oauth2Handler.h"
#include "uAuthService.h"
void RESTAPI_oauth2Handler::handleRequest(Poco::Net::HTTPServerRequest & Request, Poco::Net::HTTPServerResponse & Response)
{
if(!ContinueProcessing(Request,Response))
return;
try {
if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_POST) {
// Extract the info for login...
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr Obj = parser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
Poco::DynamicStruct ds = *Obj;
auto userId = ds["userId"].toString();
auto password = ds["password"].toString();
uCentral::Objects::WebToken Token;
if (uCentral::Auth::Authorize(userId, password, Token)) {
Poco::JSON::Object ReturnObj;
Token.to_json(ReturnObj);
ReturnObject(ReturnObj, Response);
} else {
UnAuthorized(Response);
}
} else if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_DELETE) {
if (!IsAuthorized(Request, Response))
return;
auto Token = GetBinding("token", "...");
if (Token == SessionToken_)
uCentral::Auth::Logout(Token);
OK(Response);
}
return;
}
catch (const Poco::Exception &E) {
Logger_.warning(Poco::format( "%s: Failed with: %s" , std::string(__func__), E.displayText()));
}
BadRequest(Response);
} | 31.403509 | 123 | 0.594413 | shimmy568 |
91860598057b479f935047626faa8fe8337d007a | 810 | cpp | C++ | src/blinkit/blink/renderer/core/layout/ViewFragmentationContext.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 13 | 2020-04-21T13:14:00.000Z | 2021-11-13T14:55:12.000Z | third_party/WebKit/Source/core/layout/ViewFragmentationContext.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/layout/ViewFragmentationContext.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 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 "core/layout/ViewFragmentationContext.h"
#include "core/layout/LayoutView.h"
namespace blink {
bool ViewFragmentationContext::isFragmentainerLogicalHeightKnown()
{
ASSERT(m_view.pageLogicalHeight());
return true;
}
LayoutUnit ViewFragmentationContext::fragmentainerLogicalHeightAt(LayoutUnit)
{
ASSERT(m_view.pageLogicalHeight());
return m_view.pageLogicalHeight();
}
LayoutUnit ViewFragmentationContext::remainingLogicalHeightAt(LayoutUnit blockOffset)
{
LayoutUnit pageLogicalHeight = m_view.pageLogicalHeight();
return pageLogicalHeight - intMod(blockOffset, pageLogicalHeight);
}
} // namespace blink
| 27 | 85 | 0.788889 | titilima |
9262f0f0afd214758b8e18e6dacf30a35ca5d0dd | 188 | cpp | C++ | library/src/ProgressBar.cpp | StratifyLabs/UxAPI | 4dc043b132452896ed9626038d53439b0def786a | [
"MIT"
] | null | null | null | library/src/ProgressBar.cpp | StratifyLabs/UxAPI | 4dc043b132452896ed9626038d53439b0def786a | [
"MIT"
] | null | null | null | library/src/ProgressBar.cpp | StratifyLabs/UxAPI | 4dc043b132452896ed9626038d53439b0def786a | [
"MIT"
] | null | null | null | // Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md
#include "ux/ProgressBar.hpp"
#include "ux/draw/Rectangle.hpp"
using namespace ux::sgfx;
using namespace ux;
| 20.888889 | 75 | 0.760638 | StratifyLabs |
9262f30414ebd6153de123175ac857de8ebf8c87 | 382 | hpp | C++ | include/Defines.hpp | Aargonian/JLMG | 18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7 | [
"MIT"
] | null | null | null | include/Defines.hpp | Aargonian/JLMG | 18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7 | [
"MIT"
] | null | null | null | include/Defines.hpp | Aargonian/JLMG | 18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7 | [
"MIT"
] | null | null | null | //
// Created by Aaron Helton on 1/16/2020.
//
#ifndef JLMG_DEFINES_HPP
#define JLMG_DEFINES_HPP
#include <cstdint>
typedef uint_least8_t uint8;
typedef uint_least16_t uint16;
typedef uint_least32_t uint32;
typedef uint_least64_t uint64;
typedef int_least8_t int8;
typedef int_least16_t int16;
typedef int_least32_t int32;
typedef int_least64_t int64;
#endif //JLMG_DEFINES_HPP
| 19.1 | 40 | 0.816754 | Aargonian |
9267740308a459caa4270a25b0bd9fcad4df2114 | 909 | hpp | C++ | vnix/bit-range.hpp | tevaughan/units | 75e5cfa76a44225983ca55f2a54e0869ff7b3715 | [
"BSD-3-Clause"
] | null | null | null | vnix/bit-range.hpp | tevaughan/units | 75e5cfa76a44225983ca55f2a54e0869ff7b3715 | [
"BSD-3-Clause"
] | 4 | 2019-04-17T21:36:00.000Z | 2019-04-30T22:06:31.000Z | vnix/bit-range.hpp | tevaughan/units | 75e5cfa76a44225983ca55f2a54e0869ff7b3715 | [
"BSD-3-Clause"
] | null | null | null | /// @file vnix/bit-range.hpp
/// @brief Definition of vnix::bit, vnix::bit_range.
/// @copyright 2019 Thomas E. Vaughan; all rights reserved.
/// @license BSD Three-Clause; see LICENSE.
#ifndef VNIX_BIT_HPP
#define VNIX_BIT_HPP
namespace vnix {
/// Word with specified bit set.
/// @tparam I Type of integer word.
/// @param n Offset of bit in word.
template <typename I> constexpr I bit(unsigned n) { return I(1) << n; }
/// Word with specified range of bits set.
/// @tparam I Type of integer word.
/// @param n1 Offset of bit at one end of range.
/// @param n2 Offset of bit at other end of range.
template <typename I> constexpr I bit_range(unsigned n1, unsigned n2) {
if (n1 < n2) { return bit<I>(n1) | bit_range<I>(n1 + 1, n2); }
if (n2 < n1) { return bit<I>(n2) | bit_range<I>(n2 + 1, n1); }
return bit<I>(n1);
}
} // namespace vnix
#endif // ndef VNIX_BIT_HPP
| 28.40625 | 71 | 0.647965 | tevaughan |
9271323e52f133fcecca87a1821b7f8ddec1a8b2 | 358 | cpp | C++ | test/unit/src/alloy/source/model.cpp | brunocodutra/alloy | e05e30a40b1b04c09819b8b968829ba4f62dc221 | [
"MIT"
] | 16 | 2017-06-15T18:37:05.000Z | 2022-02-20T09:17:38.000Z | test/unit/src/alloy/source/model.cpp | brunocodutra/alloy | e05e30a40b1b04c09819b8b968829ba4f62dc221 | [
"MIT"
] | 3 | 2017-06-15T18:26:02.000Z | 2017-07-29T15:29:16.000Z | test/unit/src/alloy/source/model.cpp | brunocodutra/alloy | e05e30a40b1b04c09819b8b968829ba4f62dc221 | [
"MIT"
] | 1 | 2018-06-05T20:39:14.000Z | 2018-06-05T20:39:14.000Z | #include <alloy.hpp>
#include "test.hpp"
template<auto X, auto Y, auto Z>
struct matrix {
constexpr matrix() {
auto f = [](auto&& sink) {
return values<X, Y, Z>()(FWD(sink));
};
static_assert(qualify<X>(alloy::source{callable<X>(f)}) >> expect(values<X, Y, Z>()));
}
};
int main() {
return test<matrix>;
}
| 18.842105 | 94 | 0.541899 | brunocodutra |
92744e2ec5f824ed15a53b13adbfd9f970556322 | 740 | cpp | C++ | snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2020-03-12T19:26:36.000Z | 2022-01-10T21:45:33.000Z | snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 555 | 2019-09-23T22:22:58.000Z | 2021-07-15T18:51:12.000Z | snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 3 | 2020-01-29T16:31:15.000Z | 2021-08-24T07:00:15.000Z |
// <Snippet1>
using namespace System;
using namespace System::Runtime::InteropServices;
public ref class LibWrap
{
public:
// CallingConvention.Cdecl must be used since the stack is
// cleaned up by the caller.
// int printf( const char *format [, argument]... )
[DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)]
static int printf( String^ format, int i, double d );
[DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)]
static int printf( String^ format, int i, String^ s );
};
int main()
{
LibWrap::printf( "\nPrint params: %i %f", 99, 99.99 );
LibWrap::printf( "\nPrint params: %i %s", 99, "abcd" );
}
// </Snippet1>
| 27.407407 | 97 | 0.687838 | BohdanMosiyuk |
927874510225c5fb5aa53d0a5b089bc99afc57bd | 326 | cpp | C++ | alex/chapter4/4.3_functional_addition.cpp | Alexhhhc/gay-school-cpp-homework | fa864ce1632367ef0fa269c25030e60d3a0aafac | [
"BSD-3-Clause"
] | null | null | null | alex/chapter4/4.3_functional_addition.cpp | Alexhhhc/gay-school-cpp-homework | fa864ce1632367ef0fa269c25030e60d3a0aafac | [
"BSD-3-Clause"
] | null | null | null | alex/chapter4/4.3_functional_addition.cpp | Alexhhhc/gay-school-cpp-homework | fa864ce1632367ef0fa269c25030e60d3a0aafac | [
"BSD-3-Clause"
] | null | null | null | #include<iostream>
using namespace std;
int main(){
float add(float x,float y);//声明add函数
float a,b,c;
cout<<"Please enter a&b:";//输出语句
cin>>a>>b; //输入语句
c=add(a,b); //调用add函数
cout<<"sum="<<c<<endl; //输出语句
return 0;
}
float add(float x,float y){ //定义add函数
float z;
z=x+y;
return(z);
} | 20.375 | 40 | 0.56135 | Alexhhhc |
927e4f75c55a804c83b0033ede86cba10772b177 | 1,403 | cc | C++ | source/Detectors/MeshModels.cc | vetlewi/AFRODITE | 4aa42184c0f94613e7e2b219bc8aca371094143e | [
"MIT"
] | null | null | null | source/Detectors/MeshModels.cc | vetlewi/AFRODITE | 4aa42184c0f94613e7e2b219bc8aca371094143e | [
"MIT"
] | 1 | 2021-05-04T10:52:08.000Z | 2021-05-04T10:52:08.000Z | source/Detectors/MeshModels.cc | vetlewi/AFRODITE | 4aa42184c0f94613e7e2b219bc8aca371094143e | [
"MIT"
] | null | null | null | //
// Created by Vetle Wegner Ingeberg on 30/04/2021.
//
#include "meshreader/incbin.h"
#ifndef SRC_PATH
#define SRC_PATH "../"
#endif // SRC_PATH
#ifndef PLY_PATH
#define PLY_PATH SRC_PATH"Mesh-Models"
#endif // PLY_PATH
#ifndef DETECTOR_PATH
#define DETECTOR_PATH PLY_PATH"/DETECTORS"
#endif // DETECTOR_PATH
#ifndef CLOVER_PATH
#define CLOVER_PATH DETECTOR_PATH"/CLOVER"
#endif // CLOVER_PATH
// Including all the CLOVER HPGe mesh models
INCBIN(CLOVER_VACCUM, CLOVER_PATH"/CLOVER-InternalVacuum/CloverInternalVacuum_approx.ply");
INCBIN(CLOVER_ENCASEMENT, CLOVER_PATH"/CloverEncasement/CloverEncasement_new_approx.ply");
INCBIN(HPGeCrystalA, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal1_10umTolerance.ply");
INCBIN(HPGeCrystalB, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal2_10umTolerance.ply");
INCBIN(HPGeCrystalC, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal3_10umTolerance.ply");
INCBIN(HPGeCrystalD, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal4_10umTolerance.ply");
INCBIN(HPGeContactA, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact1_10um.ply");
INCBIN(HPGeContactB, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact2_10um.ply");
INCBIN(HPGeContactC, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact3_10um.ply");
INCBIN(HPGeContactD, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact4_10um.ply");
| 40.085714 | 103 | 0.840342 | vetlewi |
927e8a6f4a1a295f15b212626ccc771a4f6f0576 | 1,913 | cpp | C++ | cpp/graphs/shortestpaths/dijkstra.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 1,727 | 2015-01-01T18:32:37.000Z | 2022-03-28T05:56:03.000Z | cpp/graphs/shortestpaths/dijkstra.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 110 | 2015-05-03T10:23:18.000Z | 2021-07-31T22:44:39.000Z | cpp/graphs/shortestpaths/dijkstra.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 570 | 2015-01-01T10:17:11.000Z | 2022-03-31T22:23:46.000Z | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> edge;
typedef pair<int, int> item;
// https://cp-algorithms.com/graph/dijkstra_sparse.html
// O(E*log(V)) time and O(E) memory
tuple<vector<int>, vector<int>> dijkstra_heap(const vector<vector<edge>> &g, int s) {
size_t n = g.size();
vector<int> prio(n, numeric_limits<int>::max());
vector<int> pred(n, -1);
priority_queue<item, vector<item>, greater<>> q;
q.emplace(prio[s] = 0, s);
while (!q.empty()) {
auto [d, u] = q.top();
q.pop();
if (d != prio[u])
continue;
for (auto [v, len] : g[u]) {
int nprio = prio[u] + len;
if (prio[v] > nprio) {
prio[v] = nprio;
pred[v] = u;
q.emplace(nprio, v);
}
}
}
return {prio, pred};
}
// O(E*log(V)) time and O(V) memory
tuple<vector<int>, vector<int>> dijkstra_set(const vector<vector<edge>> &g, int s) {
size_t n = g.size();
vector<int> prio(n, numeric_limits<int>::max());
vector<int> pred(n, -1);
set<item> q;
q.emplace(prio[s] = 0, s);
while (!q.empty()) {
int u = q.begin()->second;
q.erase(q.begin());
for (auto [v, len] : g[u]) {
int nprio = prio[u] + len;
if (prio[v] > nprio) {
q.erase({prio[v], v});
prio[v] = nprio;
pred[v] = u;
q.emplace(prio[v], v);
}
}
}
return {prio, pred};
}
int main() {
vector<vector<edge>> g(3);
g[0].emplace_back(1, 10);
g[1].emplace_back(2, -5);
g[0].emplace_back(2, 8);
auto [prio1, pred1] = dijkstra_heap(g, 0);
auto [prio2, pred2] = dijkstra_set(g, 0);
for (int x : prio1)
cout << x << " ";
cout << endl;
for (int x : prio2)
cout << x << " ";
cout << endl;
}
| 23.617284 | 85 | 0.482488 | ayushbhatt2000 |
927feb418c31d63018cf81ffc516680a7b3d707a | 2,613 | cpp | C++ | src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "specialguildquestion.hpp"
#include "scene/activityshadow/activityshadow.hpp"
#include "obj/character/role.h"
#include "obj/otherobj/gatherobj.h"
#include "servercommon/activitydef.hpp"
#include "config/logicconfigmanager.hpp"
#include "servercommon/string/gameworldstr.h"
#include "scene/scenemanager.h"
#include "other/event/eventhandler.hpp"
#include "global/guild/guild.hpp"
#include "global/guild/guildmanager.hpp"
#include "protocal/msgchatmsg.h"
#include "config/activityconfig/guildquestionconfig.hpp"
SpecialGuildQuestion::SpecialGuildQuestion(Scene *scene)
: SpecialLogic(scene), m_is_init(false), m_is_open(true), m_is_first(false)
{
}
SpecialGuildQuestion::~SpecialGuildQuestion()
{
}
void SpecialGuildQuestion::Update(unsigned long interval, time_t now_second)
{
SpecialLogic::Update(interval, now_second);
if (!m_is_open)
{
this->DelayKickOutAllRole();
}
}
void SpecialGuildQuestion::OnRoleEnterScene(Role *role)
{
if (NULL == role || !m_is_open)
{
return;
}
if (!m_is_first && ActivityShadow::Instance().IsActivtyOpen(ACTIVITY_TYPE_GUILD_QUESTION))
{
m_is_first = true;
this->RefreshGatherItem();
}
ActivityShadow::Instance().OnJoinGuildQuestionActivity(role);
}
void SpecialGuildQuestion::OnRoleLeaveScene(Role *role, bool is_logout)
{
}
void SpecialGuildQuestion::NotifySystemMsg(char *str_buff, int str_len)
{
}
void SpecialGuildQuestion::OnActivityStart()
{
if (!m_is_first)
{
m_is_first = true;
this->RefreshGatherItem();
}
}
void SpecialGuildQuestion::OnActivityClose()
{
m_is_open = false;
}
void SpecialGuildQuestion::RefreshGatherItem()
{
const GuildQuestionOtherConfig &other_cfg = LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg();
int pos_count = LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPosCount();
for (int i = 0; i < pos_count; i ++)
{
Posi gather_pos(0, 0);
if (!LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPos(i, &gather_pos))
{
continue;
}
if (m_scene->GetMap()->Validate(Obj::OBJ_TYPE_ROLE, gather_pos.x, gather_pos.y))
{
GatherObj *gather_obj = new GatherObj();
gather_obj->SetPos(gather_pos);
gather_obj->Init(NULL, other_cfg.gather_id, other_cfg.gather_time_s * 1000, 0, false);
m_scene->AddObj(gather_obj);
}
}
}
bool SpecialGuildQuestion::SpecialCanGather(Role *role, GatherObj *gather)
{
if (NULL == role || NULL == gather)
{
return false;
}
if (gather->GatherId() != LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg().gather_id)
{
return false;
}
if (!ActivityShadow::Instance().IsCanGatherGuildQuestion(role))
{
return false;
}
return true;
}
| 21.775 | 98 | 0.745886 | mage-game |
928569bb6b8d4e4dd3aa3ba56dc744b2e81b2734 | 349 | cpp | C++ | Engine/Application/ClientApplication.cpp | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 16 | 2018-12-22T02:09:05.000Z | 2022-03-09T20:38:59.000Z | Engine/Application/ClientApplication.cpp | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 46 | 2018-04-02T11:06:01.000Z | 2019-12-14T11:16:04.000Z | Engine/Application/ClientApplication.cpp | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 14 | 2018-04-09T02:26:15.000Z | 2021-09-11T03:12:15.000Z | // ------------------------------------ //
#include "ClientApplication.h"
using namespace Leviathan;
// ------------------------------------ //
DLLEXPORT ClientApplication::ClientApplication() {}
DLLEXPORT ClientApplication::ClientApplication(Engine* engine) : LeviathanApplication(engine)
{}
DLLEXPORT ClientApplication::~ClientApplication() {}
| 29.083333 | 93 | 0.616046 | hhyyrylainen |
928721107e2c12801e71dbdca664b7c9fd173c72 | 356 | cpp | C++ | Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | 1 | 2021-12-18T13:50:51.000Z | 2021-12-18T13:50:51.000Z | Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | 1 | 2021-11-30T08:09:46.000Z | 2021-11-30T08:09:46.000Z | Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | null | null | null | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "Pixel2DLayerCommands.h"
#define LOCTEXT_NAMESPACE "FPixel2DLayerModule"
void FPixel2DLayerCommands::RegisterCommands()
{
UI_COMMAND(OpenPluginWindow, "Pixel2DLayers", "Bring up Pixel2D Layers window", EUserInterfaceActionType::Button, FInputGesture());
}
#undef LOCTEXT_NAMESPACE
| 27.384615 | 132 | 0.80618 | UnderGround-orchestra-band |
92886a7939396c808f0ed681d65c74420a805bbc | 2,062 | cpp | C++ | code/SoulVania/ItemRenderingSystem.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | 1 | 2021-06-30T06:29:54.000Z | 2021-06-30T06:29:54.000Z | code/SoulVania/ItemRenderingSystem.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | null | null | null | code/SoulVania/ItemRenderingSystem.cpp | warzes/Soulvania | 83733b6a6aa38f8024109193893eb5b65b0e6294 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ItemRenderingSystem.h"
#include "GameObject.h"
ItemRenderingSystem::ItemRenderingSystem(
GameObject& parent,
std::string spritePath,
std::unique_ptr<IEffect> deadEffect,
std::unique_ptr<IEffect> hitEffect)
:
parent{ parent }
{
this->spritePath = spritePath;
this->deadEffect = std::move(deadEffect);
this->hitEffect = std::move(hitEffect);
}
ItemRenderingSystem::ItemRenderingSystem(
GameObject& parent,
TextureRegion textureRegion,
std::unique_ptr<IEffect> deadEffect,
std::unique_ptr<IEffect> hitEffect)
:
parent{ parent }
{
this->sprite = std::make_unique<Sprite>(textureRegion);
this->deadEffect = std::move(deadEffect);
this->hitEffect = std::move(hitEffect);
}
Sprite& ItemRenderingSystem::GetSprite()
{
return *sprite;
}
GameObject& ItemRenderingSystem::GetParent()
{
return parent;
}
void ItemRenderingSystem::LoadContent(ContentManager& content)
{
RenderingSystem::LoadContent(content);
if (sprite != nullptr)
return;
auto texture = content.Load<Texture>(spritePath);
sprite = std::make_unique<Sprite>(texture);
}
void ItemRenderingSystem::Update(GameTime gameTime)
{
if (GetParent().GetState() == ObjectState::DYING)
{
deadEffect->Update(gameTime);
if (deadEffect->IsFinished())
GetParent().Destroy();
}
if (hitEffect != nullptr)
hitEffect->Update(gameTime);
}
void ItemRenderingSystem::Draw(SpriteExtensions& spriteBatch)
{
switch (GetParent().GetState())
{
case ObjectState::NORMAL:
spriteBatch.Draw(*sprite, GetParent().GetPosition());
RenderingSystem::Draw(spriteBatch);
break;
case ObjectState::DYING:
deadEffect->Draw(spriteBatch);
break;
}
if (hitEffect != nullptr)
hitEffect->Draw(spriteBatch);
}
void ItemRenderingSystem::OnStateChanged()
{
if (GetParent().GetState() == ObjectState::DYING)
{
if (deadEffect != nullptr)
deadEffect->Show(GetParent().GetOriginPosition());
else
GetParent().Destroy();
}
}
void ItemRenderingSystem::OnTakingDamage()
{
if (hitEffect != nullptr)
hitEffect->Show(GetParent().GetOriginPosition());
} | 20.828283 | 62 | 0.733269 | warzes |
928ff6427e75f750af4d841ed2de785f10a04b9e | 2,641 | inl | C++ | repos/plywood/src/build/Instantiators.inl | lambdatastic/plywood | 1a5688e0cdd03471a17f3a628752a5734cbd0d07 | [
"MIT"
] | null | null | null | repos/plywood/src/build/Instantiators.inl | lambdatastic/plywood | 1a5688e0cdd03471a17f3a628752a5734cbd0d07 | [
"MIT"
] | null | null | null | repos/plywood/src/build/Instantiators.inl | lambdatastic/plywood | 1a5688e0cdd03471a17f3a628752a5734cbd0d07 | [
"MIT"
] | null | null | null | // ply instantiate build-common PLY_BUILD
void inst_ply_build_common(TargetInstantiatorArgs* args) {
args->addSourceFiles("common/ply-build-common");
args->addIncludeDir(Visibility::Public, "common");
args->addTarget(Visibility::Public, "reflect");
}
// ply instantiate build-target PLY_BUILD
void inst_ply_build_target(TargetInstantiatorArgs* args) {
args->addSourceFiles("target/ply-build-target");
args->addIncludeDir(Visibility::Public, "target");
args->addIncludeDir(Visibility::Private, NativePath::join(args->projInst->env->buildFolderPath,
"codegen/ply-build-target"));
args->addTarget(Visibility::Public, "build-common");
// Write codegen/ply-build-target/ply-build-target/NativeToolchain.inl
// Note: If we ever cross-compile this module, the NativeToolchain will have to be different
const CMakeGeneratorOptions* cmakeOptions = args->projInst->env->cmakeOptions;
PLY_ASSERT(cmakeOptions);
String nativeToolchainFile = String::format(
R"(CMakeGeneratorOptions NativeToolchain = {{
"{}",
"{}",
"{}",
"{}",
}};
)",
cmakeOptions->generator, cmakeOptions->platform, cmakeOptions->toolset,
cmakeOptions->buildType);
FileSystem::native()->makeDirsAndSaveTextIfDifferent(
NativePath::join(args->projInst->env->buildFolderPath,
"codegen/ply-build-target/ply-build-target/NativeToolchain.inl"),
nativeToolchainFile, TextFormat::platformPreference());
}
// ply instantiate build-provider PLY_BUILD
void inst_ply_build_provider(TargetInstantiatorArgs* args) {
args->addSourceFiles("provider/ply-build-provider");
args->addIncludeDir(Visibility::Public, "provider");
args->addTarget(Visibility::Public, "build-common");
args->addTarget(Visibility::Private, "pylon-reflect");
}
// ply instantiate build-repo PLY_BUILD
void inst_ply_build_repo(TargetInstantiatorArgs* args) {
args->addSourceFiles("repo/ply-build-repo");
args->addIncludeDir(Visibility::Public, "repo");
args->addTarget(Visibility::Public, "build-target");
args->addTarget(Visibility::Public, "build-provider");
args->addTarget(Visibility::Private, "pylon-reflect");
args->addTarget(Visibility::Private, "cpp");
}
// ply instantiate build-folder PLY_BUILD
void inst_ply_build_folder(TargetInstantiatorArgs* args) {
args->addSourceFiles("folder/ply-build-folder");
args->addIncludeDir(Visibility::Public, "folder");
args->addTarget(Visibility::Public, "build-repo");
args->addTarget(Visibility::Private, "pylon-reflect");
}
| 43.295082 | 99 | 0.706929 | lambdatastic |
92922d321b2e9ab0af0973ddf5fc489078167e7c | 740 | cpp | C++ | Codeforces/918B/map.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Codeforces/918B/map.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/918B/map.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <iomanip>
#include <climits>
#include <vector>
#include <set>
#include <queue>
#include <map>
using namespace std;
map <string, string> mp;
int main()
{
ios::sync_with_stdio(false);
int serverNum, commandNum;
cin >> serverNum >> commandNum;
for (int i = 0; i < serverNum; i++)
{
string name, ip;
cin >> name >> ip;
mp[ip] = name;
}
for (int i = 0; i < commandNum; i++)
{
string command, ip;
cin >> command >> ip;
ip = ip.substr(0, ip.length() - 1);
cout << command << " " << ip << "; #" << mp[ip] << endl;
}
return 0;
}
| 20 | 64 | 0.55 | codgician |
92938214ecf428d006b075c336428d30b84ba127 | 9,478 | cc | C++ | simulation/astrobee_gazebo/src/astrobee_gazebo.cc | linorobot/astrobee | e74a241ddea4e2088923891f8173fdcfea4afd2b | [
"Apache-2.0"
] | 3 | 2018-01-04T02:00:49.000Z | 2020-09-29T20:32:07.000Z | simulation/astrobee_gazebo/src/astrobee_gazebo.cc | nicedone/astrobee | e74a241ddea4e2088923891f8173fdcfea4afd2b | [
"Apache-2.0"
] | null | null | null | simulation/astrobee_gazebo/src/astrobee_gazebo.cc | nicedone/astrobee | e74a241ddea4e2088923891f8173fdcfea4afd2b | [
"Apache-2.0"
] | 2 | 2020-02-20T06:02:33.000Z | 2020-07-21T11:45:47.000Z | /* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is 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 <astrobee_gazebo/astrobee_gazebo.h>
// Transformation helper code
#include <Eigen/Eigen>
#include <Eigen/Geometry>
// TF2 eigen bindings
#include <tf2_eigen/tf2_eigen.h>
namespace gazebo {
// Model plugin
FreeFlyerModelPlugin::FreeFlyerModelPlugin(std::string const& name, bool heartbeats) :
ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {}
FreeFlyerModelPlugin::~FreeFlyerModelPlugin() {
thread_.join();
}
void FreeFlyerModelPlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) {
gzmsg << "[FF] Loading plugin for model with name " << name_ << "\n";
// Get usefule properties
sdf_ = sdf;
link_ = model->GetLink();
world_ = model->GetWorld();
model_ = model;
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized())
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized");
// Get a nodehandle based on the model name and use a different default queue
// We have to do this to avoid gazebo main thread blocking the ROS queue.
nh_ = ros::NodeHandle(model_->GetName());
nh_.setCallbackQueue(&queue_);
// Start a custom queue thread for messages
thread_ = boost::thread(
boost::bind(&FreeFlyerModelPlugin::QueueThread, this));
// Call initialize on the freeflyer nodelet to start heartbeat and faults
Setup(nh_);
// Pass the new callback queue
LoadCallback(&nh_, model_, sdf_);
}
// Get the model link
physics::LinkPtr FreeFlyerModelPlugin::GetLink() {
return link_;
}
// Get the model world
physics::WorldPtr FreeFlyerModelPlugin::GetWorld() {
return world_;
}
// Get the model
physics::ModelPtr FreeFlyerModelPlugin::GetModel() {
return model_;
}
// Get the extrinsics frame
std::string FreeFlyerModelPlugin::GetFrame(std::string target) {
std::string frame = (target.empty() ? "body" : target);
if (GetModel()->GetName() == "/")
return frame;
return GetModel()->GetName() + "/" + frame;
}
// Put laser data to the interface
void FreeFlyerModelPlugin::QueueThread() {
while (nh_.ok())
queue_.callAvailable(ros::WallDuration(0.1));
}
// Sensor plugin
FreeFlyerSensorPlugin::FreeFlyerSensorPlugin(std::string const& name, bool heartbeats) :
ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {}
FreeFlyerSensorPlugin::~FreeFlyerSensorPlugin() {
thread_.join();
}
void FreeFlyerSensorPlugin::Load(sensors::SensorPtr sensor, sdf::ElementPtr sdf) {
gzmsg << "[FF] Loading plugin for sensor with name " << name_ << "\n";
// Get the world in which this sensor exists, and the link it is attached to
sensor_ = sensor;
sdf_ = sdf;
world_ = gazebo::physics::get_world(sensor->WorldName());
model_ = boost::static_pointer_cast < physics::Link > (
world_->GetEntity(sensor->ParentName()))->GetModel();
// If we specify a frame name different to our sensor tag name
if (sdf->HasElement("frame"))
frame_ = sdf->Get<std::string>("frame");
else
frame_ = sensor_->Name();
// If we specify a different sensor type
if (sdf->HasElement("rotation_type"))
rotation_type_ = sdf->Get<std::string>("rotation_type");
else
rotation_type_ = sensor_->Type();
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized())
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized");
// Get a nodehandle based on the model name and use a different default queue
// We have to do this to avoid gazebo main thread blocking the ROS queue.
nh_ = ros::NodeHandle(model_->GetName());
nh_.setCallbackQueue(&queue_);
// Start a custom queue thread for messages
thread_ = boost::thread(
boost::bind(&FreeFlyerSensorPlugin::QueueThread, this));
// Call initialize on the freeflyer nodelet to start heartbeat and faults
Setup(nh_);
// Pass the new callback queue
LoadCallback(&nh_, sensor_, sdf_);
// Defer the extrinsics setup to allow plugins to load
timer_ = nh_.createTimer(ros::Duration(1.0),
&FreeFlyerSensorPlugin::SetupExtrinsics, this, true, true);
}
// Get the sensor world
physics::WorldPtr FreeFlyerSensorPlugin::GetWorld() {
return world_;
}
// Get the sensor model
physics::ModelPtr FreeFlyerSensorPlugin::GetModel() {
return model_;
}
// Get the extrinsics frame
std::string FreeFlyerSensorPlugin::GetFrame(std::string target) {
std::string frame = (target.empty() ? frame_ : target);
if (GetModel()->GetName() == "/")
return frame;
return GetModel()->GetName() + "/" + frame;
}
// Get the type of the sensor
std::string FreeFlyerSensorPlugin::GetRotationType() {
return rotation_type_;
}
// Put laser data to the interface
void FreeFlyerSensorPlugin::QueueThread() {
while (nh_.ok())
queue_.callAvailable(ros::WallDuration(0.1));
}
// Manage the extrinsics based on the sensor type
void FreeFlyerSensorPlugin::SetupExtrinsics(const ros::TimerEvent&) {
// Create a buffer and listener for TF2 transforms
tf2_ros::Buffer buffer;
tf2_ros::TransformListener listener(buffer);
// Get extrinsics from framestore
try {
// Lookup the transform for this sensor
geometry_msgs::TransformStamped tf = buffer.lookupTransform(
GetFrame("body"), GetFrame(), ros::Time(0), ros::Duration(60.0));
// Handle the transform for all sensor types
ignition::math::Pose3d pose(
tf.transform.translation.x,
tf.transform.translation.y,
tf.transform.translation.z,
tf.transform.rotation.w,
tf.transform.rotation.x,
tf.transform.rotation.y,
tf.transform.rotation.z);
sensor_->SetPose(pose);
gzmsg << "Extrinsics set for sensor " << name_ << "\n";
// Get the pose as an Eigen type
Eigen::Quaterniond pose_temp = Eigen::Quaterniond(tf.transform.rotation.w,
tf.transform.rotation.x,
tf.transform.rotation.y,
tf.transform.rotation.z);
// define the two rotations needed to transform from the flight software camera pose to the
// gazebo camera pose
Eigen::Quaterniond rot_90_x = Eigen::Quaterniond(0.70710678, 0.70710678, 0, 0);
Eigen::Quaterniond rot_90_z = Eigen::Quaterniond(0.70710678, 0, 0, 0.70710678);
pose_temp = pose_temp * rot_90_x;
pose_temp = pose_temp * rot_90_z;
pose = ignition::math::Pose3d(
tf.transform.translation.x,
tf.transform.translation.y,
tf.transform.translation.z,
pose_temp.w(), pose_temp.x(), pose_temp.y(), pose_temp.z());
// transform the pose into the world frame and set the camera world pose
math::Pose tf_bs = pose;
math::Pose tf_wb = model_->GetWorldPose();
math::Pose tf_ws = tf_bs + tf_wb;
ignition::math::Pose3d world_pose = ignition::math::Pose3d(tf_ws.pos.x, tf_ws.pos.y,
tf_ws.pos.z, tf_ws.rot.w, tf_ws.rot.x, tf_ws.rot.y, tf_ws.rot.z);
////////////////////////////
// SPECIAL CASE 1: CAMERA //
////////////////////////////
if (sensor_->Type() == "camera") {
// Dynamically cast to the correct sensor
sensors::CameraSensorPtr sensor
= std::dynamic_pointer_cast < sensors::CameraSensor > (sensor_);
if (!sensor)
gzerr << "Extrinsics requires a camera sensor as a parent.\n";
// set the sensor pose to the pose from tf2 static
sensor_->SetPose(pose);
sensor->Camera()->SetWorldPose(world_pose);
gzmsg << "Extrinsics update for camera " << name_ << "\n";
}
//////////////////////////////////////
// SPECIAL CASE 2: WIDEANGLE CAMERA //
//////////////////////////////////////
if (sensor_->Type() == "wideanglecamera") {
// Dynamically cast to the correct sensor
sensors::WideAngleCameraSensorPtr sensor =
std::dynamic_pointer_cast < sensors::WideAngleCameraSensor > (sensor_);
if (!sensor)
gzerr << "Extrinsics requires a wideanglecamera sensor as a parent.\n";
// set the sensor pose to the pose from tf2 static
sensor_->SetPose(pose);
sensor->Camera()->SetWorldPose(world_pose);
gzmsg << "Extrinsics update for wideanglecamera " << name_ << "\n";
}
//////////////////////////////////
// SPECIAL CASE 3: DEPTH CAMERA //
//////////////////////////////////
if (sensor_->Type() == "depth") {
// Dynamically cast to the correct sensor
sensors::DepthCameraSensorPtr sensor =
std::dynamic_pointer_cast < sensors::DepthCameraSensor > (sensor_);
if (!sensor)
gzerr << "Extrinsics requires a depth camera sensor as a parent.\n";
sensor->DepthCamera()->SetWorldPose(world_pose);
gzmsg << "Extrinsics update for depth camera " << name_ << "\n";
}
} catch (tf2::TransformException &ex) {
gzmsg << "[FF] No extrinsics for sensor " << name_ << "\n";
}
}
} // namespace gazebo
| 33.491166 | 95 | 0.675986 | linorobot |
9295ce21dcffbbc90049cad2b6d7fcb6ba7dd7a9 | 13,233 | hpp | C++ | src/3rd party/components/AlexMX/multi_edit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/components/AlexMX/multi_edit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/components/AlexMX/multi_edit.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'multi_edit.pas' rev: 6.00
#ifndef multi_editHPP
#define multi_editHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <CommCtrl.hpp> // Pascal unit
#include <ComCtrls.hpp> // Pascal unit
#include <ExtCtrls.hpp> // Pascal unit
#include <StdCtrls.hpp> // Pascal unit
#include <Graphics.hpp> // Pascal unit
#include <Menus.hpp> // Pascal unit
#include <Forms.hpp> // Pascal unit
#include <Controls.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Multi_edit
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TSpinButtonState { sbNotDown, sbTopDown, sbBottomDown };
#pragma option pop
#pragma option push -b-
enum TValueType { vtInt, vtFloat, vtHex };
#pragma option pop
#pragma option push -b-
enum TSpinButtonKind { bkStandard, bkDiagonal, bkLightWave };
#pragma option pop
#pragma option push -b-
enum TLWButtonState { sbLWNotDown, sbLWDown };
#pragma option pop
class DELPHICLASS TMultiObjSpinButton;
class PASCALIMPLEMENTATION TMultiObjSpinButton : public Controls::TGraphicControl
{
typedef Controls::TGraphicControl inherited;
private:
TSpinButtonState FDown;
Graphics::TBitmap* FUpBitmap;
Graphics::TBitmap* FDownBitmap;
bool FDragging;
bool FInvalidate;
Graphics::TBitmap* FTopDownBtn;
Graphics::TBitmap* FBottomDownBtn;
Extctrls::TTimer* FRepeatTimer;
Graphics::TBitmap* FNotDownBtn;
TSpinButtonState FLastDown;
Controls::TWinControl* FFocusControl;
Classes::TNotifyEvent FOnTopClick;
Classes::TNotifyEvent FOnBottomClick;
void __fastcall TopClick(void);
void __fastcall BottomClick(void);
void __fastcall GlyphChanged(System::TObject* Sender);
Graphics::TBitmap* __fastcall GetUpGlyph(void);
Graphics::TBitmap* __fastcall GetDownGlyph(void);
void __fastcall SetUpGlyph(Graphics::TBitmap* Value);
void __fastcall SetDownGlyph(Graphics::TBitmap* Value);
void __fastcall SetDown(TSpinButtonState Value);
void __fastcall SetFocusControl(Controls::TWinControl* Value);
void __fastcall DrawAllBitmap(void);
void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TSpinButtonState ADownState);
void __fastcall TimerExpired(System::TObject* Sender);
HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message);
protected:
virtual void __fastcall Paint(void);
DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
public:
__fastcall virtual TMultiObjSpinButton(Classes::TComponent* AOwner);
__fastcall virtual ~TMultiObjSpinButton(void);
__property TSpinButtonState Down = {read=FDown, write=SetDown, default=0};
__published:
__property DragCursor = {default=-12};
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Visible = {default=1};
__property Graphics::TBitmap* DownGlyph = {read=GetDownGlyph, write=SetDownGlyph};
__property Graphics::TBitmap* UpGlyph = {read=GetUpGlyph, write=SetUpGlyph};
__property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl};
__property ShowHint ;
__property ParentShowHint = {default=1};
__property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick};
__property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick};
__property OnDragDrop ;
__property OnDragOver ;
__property OnEndDrag ;
__property OnStartDrag ;
};
typedef void __fastcall (__closure *TLWNotifyEvent)(System::TObject* Sender, int Val);
class DELPHICLASS TMultiObjLWButton;
class PASCALIMPLEMENTATION TMultiObjLWButton : public Controls::TGraphicControl
{
typedef Controls::TGraphicControl inherited;
private:
TLWButtonState FDown;
Graphics::TBitmap* FLWBitmap;
bool FDragging;
bool FInvalidate;
Graphics::TBitmap* FLWDownBtn;
Graphics::TBitmap* FLWNotDownBtn;
Controls::TWinControl* FFocusControl;
TLWNotifyEvent FOnLWChange;
double FSens;
double FAccum;
void __fastcall LWChange(System::TObject* Sender, int Val);
void __fastcall GlyphChanged(System::TObject* Sender);
Graphics::TBitmap* __fastcall GetGlyph(void);
void __fastcall SetGlyph(Graphics::TBitmap* Value);
void __fastcall SetDown(TLWButtonState Value);
void __fastcall SetFocusControl(Controls::TWinControl* Value);
void __fastcall DrawAllBitmap(void);
void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TLWButtonState ADownState);
HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message);
protected:
virtual void __fastcall Paint(void);
DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y);
DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y);
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
void __fastcall SetSens(double Value);
public:
__fastcall virtual TMultiObjLWButton(Classes::TComponent* AOwner);
__fastcall virtual ~TMultiObjLWButton(void);
__property TLWButtonState Down = {read=FDown, write=SetDown, default=0};
virtual void __fastcall Invalidate(void);
__published:
__property double LWSensitivity = {read=FSens, write=SetSens};
__property DragCursor = {default=-12};
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Visible = {default=1};
__property Graphics::TBitmap* LWGlyph = {read=GetGlyph, write=SetGlyph};
__property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl};
__property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange};
__property ShowHint ;
__property ParentShowHint = {default=1};
__property OnDragDrop ;
__property OnDragOver ;
__property OnEndDrag ;
__property OnStartDrag ;
};
class DELPHICLASS TMultiObjSpinEdit;
class PASCALIMPLEMENTATION TMultiObjSpinEdit : public Stdctrls::TCustomEdit
{
typedef Stdctrls::TCustomEdit inherited;
private:
bool bIsMulti;
bool bChanged;
Extended BeforeValue;
Graphics::TColor StartColor;
Graphics::TColor FBtnColor;
Classes::TAlignment FAlignment;
Extended FMinValue;
Extended FMaxValue;
Extended FIncrement;
int FButtonWidth;
Byte FDecimal;
bool FChanging;
bool FEditorEnabled;
TValueType FValueType;
TMultiObjSpinButton* FButton;
Controls::TWinControl* FBtnWindow;
bool FArrowKeys;
Classes::TNotifyEvent FOnTopClick;
Classes::TNotifyEvent FOnBottomClick;
TSpinButtonKind FButtonKind;
Comctrls::TCustomUpDown* FUpDown;
TMultiObjLWButton* FLWButton;
TLWNotifyEvent FOnLWChange;
double FSens;
TSpinButtonKind __fastcall GetButtonKind(void);
void __fastcall SetButtonKind(TSpinButtonKind Value);
void __fastcall UpDownClick(System::TObject* Sender, Comctrls::TUDBtnType Button);
void __fastcall LWChange(System::TObject* Sender, int Val);
Extended __fastcall GetValue(void);
Extended __fastcall CheckValue(Extended NewValue);
int __fastcall GetAsInteger(void);
bool __fastcall IsIncrementStored(void);
bool __fastcall IsMaxStored(void);
bool __fastcall IsMinStored(void);
bool __fastcall IsValueStored(void);
void __fastcall SetArrowKeys(bool Value);
void __fastcall SetAsInteger(int NewValue);
void __fastcall SetValue(Extended NewValue);
void __fastcall SetValueType(TValueType NewType);
void __fastcall SetButtonWidth(int NewValue);
void __fastcall SetDecimal(Byte NewValue);
int __fastcall GetButtonWidth(void);
void __fastcall RecreateButton(void);
void __fastcall ResizeButton(void);
void __fastcall SetEditRect(void);
void __fastcall SetAlignment(Classes::TAlignment Value);
HIDESBASE MESSAGE void __fastcall WMSize(Messages::TWMSize &Message);
HIDESBASE MESSAGE void __fastcall CMEnter(Messages::TMessage &Message);
HIDESBASE MESSAGE void __fastcall CMExit(Messages::TWMNoParams &Message);
MESSAGE void __fastcall WMPaste(Messages::TWMNoParams &Message);
MESSAGE void __fastcall WMCut(Messages::TWMNoParams &Message);
HIDESBASE MESSAGE void __fastcall CMCtl3DChanged(Messages::TMessage &Message);
HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message);
HIDESBASE MESSAGE void __fastcall CMFontChanged(Messages::TMessage &Message);
void __fastcall SetBtnColor(Graphics::TColor Value);
protected:
DYNAMIC void __fastcall Change(void);
virtual bool __fastcall IsValidChar(char Key);
virtual void __fastcall UpClick(System::TObject* Sender);
virtual void __fastcall DownClick(System::TObject* Sender);
DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift);
DYNAMIC void __fastcall KeyPress(char &Key);
virtual void __fastcall CreateParams(Controls::TCreateParams &Params);
virtual void __fastcall CreateWnd(void);
void __fastcall SetSens(double Val);
double __fastcall GetSens(void);
public:
__fastcall virtual TMultiObjSpinEdit(Classes::TComponent* AOwner);
__fastcall virtual ~TMultiObjSpinEdit(void);
__property int AsInteger = {read=GetAsInteger, write=SetAsInteger, default=0};
__property Text ;
void __fastcall ObjFirstInit(float v);
void __fastcall ObjNextInit(float v);
void __fastcall ObjApplyFloat(float &_to);
void __fastcall ObjApplyInt(int &_to);
__published:
__property double LWSensitivity = {read=GetSens, write=SetSens};
__property Classes::TAlignment Alignment = {read=FAlignment, write=SetAlignment, default=0};
__property bool ArrowKeys = {read=FArrowKeys, write=SetArrowKeys, default=1};
__property Graphics::TColor BtnColor = {read=FBtnColor, write=SetBtnColor, default=-2147483633};
__property TSpinButtonKind ButtonKind = {read=FButtonKind, write=SetButtonKind, default=0};
__property Byte Decimal = {read=FDecimal, write=SetDecimal, default=2};
__property int ButtonWidth = {read=FButtonWidth, write=SetButtonWidth, default=14};
__property bool EditorEnabled = {read=FEditorEnabled, write=FEditorEnabled, default=1};
__property Extended Increment = {read=FIncrement, write=FIncrement, stored=IsIncrementStored};
__property Extended MaxValue = {read=FMaxValue, write=FMaxValue, stored=IsMaxStored};
__property Extended MinValue = {read=FMinValue, write=FMinValue, stored=IsMinStored};
__property TValueType ValueType = {read=FValueType, write=SetValueType, default=0};
__property Extended Value = {read=GetValue, write=SetValue, stored=IsValueStored};
__property AutoSelect = {default=1};
__property AutoSize = {default=1};
__property BorderStyle = {default=1};
__property Color = {default=-2147483643};
__property Ctl3D ;
__property DragCursor = {default=-12};
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Font ;
__property Anchors = {default=3};
__property BiDiMode ;
__property Constraints ;
__property DragKind = {default=0};
__property ParentBiDiMode = {default=1};
__property ImeMode = {default=3};
__property ImeName ;
__property MaxLength = {default=0};
__property ParentColor = {default=0};
__property ParentCtl3D = {default=1};
__property ParentFont = {default=1};
__property ParentShowHint = {default=1};
__property PopupMenu ;
__property ReadOnly = {default=0};
__property ShowHint ;
__property TabOrder = {default=-1};
__property TabStop = {default=1};
__property Visible = {default=1};
__property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange};
__property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick};
__property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick};
__property OnChange ;
__property OnClick ;
__property OnDblClick ;
__property OnDragDrop ;
__property OnDragOver ;
__property OnEndDrag ;
__property OnEnter ;
__property OnExit ;
__property OnKeyDown ;
__property OnKeyPress ;
__property OnKeyUp ;
__property OnMouseDown ;
__property OnMouseMove ;
__property OnMouseUp ;
__property OnStartDrag ;
__property OnContextPopup ;
__property OnMouseWheelDown ;
__property OnMouseWheelUp ;
__property OnEndDock ;
__property OnStartDock ;
public:
#pragma option push -w-inl
/* TWinControl.CreateParented */ inline __fastcall TMultiObjSpinEdit(HWND ParentWindow) : Stdctrls::TCustomEdit(ParentWindow) { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Multi_edit */
using namespace Multi_edit;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // multi_edit
| 39.035398 | 130 | 0.775712 | OLR-xray |
9298a61340db9fd60a9c5603815e935dcdeec3d5 | 1,389 | cpp | C++ | src/gui/window_taborder.cpp | ShigotoShoujin/shigoto.shoujin | 165bac0703ffdec544ab275af25dd3504529a565 | [
"MIT"
] | 1 | 2021-10-31T04:29:16.000Z | 2021-10-31T04:29:16.000Z | src/gui/window_taborder.cpp | ShigotoShoujin/shigoto.shoujin | 165bac0703ffdec544ab275af25dd3504529a565 | [
"MIT"
] | null | null | null | src/gui/window_taborder.cpp | ShigotoShoujin/shigoto.shoujin | 165bac0703ffdec544ab275af25dd3504529a565 | [
"MIT"
] | null | null | null | //#include "../assert/assert.hpp"
#include "../assert/assert.hpp"
#include "window.hpp"
#include "window_taborder.hpp"
namespace shoujin::gui {
void WindowTabOrder::AddWindow(Window* window, int& out_taborder)
{
SHOUJIN_ASSERT(window);
if(window->tabstop()) {
_taborder_map.emplace(++_taborder_max, window);
out_taborder = _taborder_max;
}
else
out_taborder = 0;
}
void WindowTabOrder::CycleTab(bool cycle_up)
{
HWND focus_hwnd = GetFocus();
if(!focus_hwnd) {
SetFocusToFirstWindow();
return;
}
auto window = Window::FindWindowByHandle(focus_hwnd);
if(!window) {
SetFocusToFirstWindow();
return;
}
window = FindNextWindowInTabOrder(window, cycle_up);
if(window)
window->SetFocus();
}
Window* WindowTabOrder::FindNextWindowInTabOrder(Window* window, bool cycle_up) const
{
if(_taborder_map.size() == 1)
return window;
auto current = _taborder_map.find(window->taborder());
if(current == _taborder_map.end())
return nullptr;
if(cycle_up) {
if(current == _taborder_map.begin())
return _taborder_map.rbegin()->second;
return std::prev(current)->second;
}
auto next = std::next(current);
if(next == _taborder_map.end())
return _taborder_map.begin()->second;
return next->second;
}
void WindowTabOrder::SetFocusToFirstWindow()
{
const auto it = _taborder_map.cbegin();
if(it != _taborder_map.cend())
it->second->SetFocus();
}
}
| 19.842857 | 85 | 0.714903 | ShigotoShoujin |
929b975bdfe46c0afc7e916b74dc9b1e3dd5e2bd | 608 | cpp | C++ | C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp | m-payal/AlgorithmsAndDataStructure | db53da00cefa3b681b4fcebfc0d22ee91cd489f9 | [
"MIT"
] | 195 | 2020-05-09T02:26:13.000Z | 2022-03-30T06:12:07.000Z | C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp | m-payal/AlgorithmsAndDataStructure | db53da00cefa3b681b4fcebfc0d22ee91cd489f9 | [
"MIT"
] | 31 | 2021-06-15T19:00:57.000Z | 2022-02-02T15:51:25.000Z | C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp | m-payal/AlgorithmsAndDataStructure | db53da00cefa3b681b4fcebfc0d22ee91cd489f9 | [
"MIT"
] | 64 | 2020-05-09T02:26:15.000Z | 2022-02-23T16:02:01.000Z | /*
Title - Recusive Sum
Description- A Program to recursively calculate sum of N natural numbers.
*/
#include<bits/stdc++.h>
using namespace std;
// A recursive function to calculate the sum of N natural numbers
int recursiveSum(int num)
{
if(num == 0)
return 0;
return (recursiveSum(num - 1) + num);
}
int main()
{
int num;
cout<<"\n Enter a number N to find sum of first N natural numbers: ";
cin>>num;
cout<<"\n Sum of first "<<num<<" natural numbers is = "<<recursiveSum(num);
return 0;
}
/*
Time complexity - O(n)
Sample Input - 5
Sample Output - 15
*/
| 19.612903 | 80 | 0.636513 | m-payal |
929c1561b2ff5533ede9ff300b9fbd2f63160531 | 24,627 | cpp | C++ | ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
/**
@file ntv2capture8k.cpp
@brief Implementation of NTV2Capture class.
@copyright (C) 2012-2021 AJA Video Systems, Inc. All rights reserved.
**/
#include "ntv2capture8k.h"
#include "ntv2utils.h"
#include "ntv2devicefeatures.h"
#include "ajabase/system/process.h"
#include "ajabase/system/systemtime.h"
#include "ajabase/system/memory.h"
using namespace std;
/**
@brief The alignment of the video and audio buffers has a big impact on the efficiency of
DMA transfers. When aligned to the page size of the architecture, only one DMA
descriptor is needed per page. Misalignment will double the number of descriptors
that need to be fetched and processed, thus reducing bandwidth.
**/
static const uint32_t BUFFER_ALIGNMENT (4096); // The correct size for many systems
NTV2Capture8K::NTV2Capture8K (const string inDeviceSpecifier,
const bool withAudio,
const NTV2Channel channel,
const NTV2FrameBufferFormat pixelFormat,
const bool inLevelConversion,
const bool inDoMultiFormat,
const bool inWithAnc,
const bool inDoTsiRouting)
: mConsumerThread (AJAThread()),
mProducerThread (AJAThread()),
mDeviceID (DEVICE_ID_NOTFOUND),
mDeviceSpecifier (inDeviceSpecifier),
mWithAudio (withAudio),
mInputChannel (channel),
mInputSource (::NTV2ChannelToInputSource (mInputChannel)),
mVideoFormat (NTV2_FORMAT_UNKNOWN),
mPixelFormat (pixelFormat),
mSavedTaskMode (NTV2_DISABLE_TASKS),
mAudioSystem (NTV2_AUDIOSYSTEM_1),
mDoLevelConversion (inLevelConversion),
mDoMultiFormat (inDoMultiFormat),
mGlobalQuit (false),
mWithAnc (inWithAnc),
mVideoBufferSize (0),
mAudioBufferSize (0),
mDoTsiRouting (inDoTsiRouting)
{
::memset (mAVHostBuffer, 0x0, sizeof (mAVHostBuffer));
} // constructor
NTV2Capture8K::~NTV2Capture8K ()
{
// Stop my capture and consumer threads, then destroy them...
Quit ();
// Unsubscribe from input vertical event...
mDevice.UnsubscribeInputVerticalEvent (mInputChannel);
// Unsubscribe from output vertical
mDevice.UnsubscribeOutputVerticalEvent(NTV2_CHANNEL1);
// Free all my buffers...
for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++)
{
if (mAVHostBuffer[bufferNdx].fVideoBuffer)
{
delete mAVHostBuffer[bufferNdx].fVideoBuffer;
mAVHostBuffer[bufferNdx].fVideoBuffer = AJA_NULL;
}
if (mAVHostBuffer[bufferNdx].fAudioBuffer)
{
delete mAVHostBuffer[bufferNdx].fAudioBuffer;
mAVHostBuffer[bufferNdx].fAudioBuffer = AJA_NULL;
}
if (mAVHostBuffer[bufferNdx].fAncBuffer)
{
delete mAVHostBuffer[bufferNdx].fAncBuffer;
mAVHostBuffer[bufferNdx].fAncBuffer = AJA_NULL;
}
} // for each buffer in the ring
if (!mDoMultiFormat)
{
mDevice.ReleaseStreamForApplication(kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid()));
mDevice.SetEveryFrameServices(mSavedTaskMode); // Restore prior task mode
}
} // destructor
void NTV2Capture8K::Quit (void)
{
// Set the global 'quit' flag, and wait for the threads to go inactive...
mGlobalQuit = true;
while (mConsumerThread.Active())
AJATime::Sleep(10);
while (mProducerThread.Active())
AJATime::Sleep(10);
mDevice.DMABufferUnlockAll();
} // Quit
AJAStatus NTV2Capture8K::Init (void)
{
AJAStatus status (AJA_STATUS_SUCCESS);
// Open the device...
if (!CNTV2DeviceScanner::GetFirstDeviceFromArgument (mDeviceSpecifier, mDevice))
{cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not found" << endl; return AJA_STATUS_OPEN;}
if (!mDevice.IsDeviceReady ())
{cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not ready" << endl; return AJA_STATUS_INITIALIZE;}
if (!mDoMultiFormat)
{
if (!mDevice.AcquireStreamForApplication (kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid())))
return AJA_STATUS_BUSY; // Another app is using the device
mDevice.GetEveryFrameServices (mSavedTaskMode); // Save the current state before we change it
}
mDevice.SetEveryFrameServices (NTV2_OEM_TASKS); // Since this is an OEM demo, use the OEM service level
mDeviceID = mDevice.GetDeviceID (); // Keep the device ID handy, as it's used frequently
// Sometimes other applications disable some or all of the frame buffers, so turn them all on here...
mDevice.EnableChannel(NTV2_CHANNEL4);
mDevice.EnableChannel(NTV2_CHANNEL3);
mDevice.EnableChannel(NTV2_CHANNEL2);
mDevice.EnableChannel(NTV2_CHANNEL1);
if (::NTV2DeviceCanDoMultiFormat (mDeviceID))
{
mDevice.SetMultiFormatMode (mDoMultiFormat);
}
else
{
mDoMultiFormat = false;
}
// Set up the video and audio...
status = SetupVideo ();
if (AJA_FAILURE (status))
return status;
status = SetupAudio ();
if (AJA_FAILURE (status))
return status;
// Set up the circular buffers, the device signal routing, and both playout and capture AutoCirculate...
SetupHostBuffers ();
RouteInputSignal ();
SetupInputAutoCirculate ();
return AJA_STATUS_SUCCESS;
} // Init
AJAStatus NTV2Capture8K::SetupVideo (void)
{
// Enable and subscribe to the interrupts for the channel to be used...
mDevice.EnableInputInterrupt(mInputChannel);
mDevice.SubscribeInputVerticalEvent(mInputChannel);
// The input vertical is not always available so we like to use the output for timing - sometimes
mDevice.SubscribeOutputVerticalEvent(mInputChannel);
// disable SDI transmitter
mDevice.SetSDITransmitEnable(mInputChannel, false);
// Wait for four verticals to let the reciever lock...
mDevice.WaitForOutputVerticalInterrupt(mInputChannel, 10);
// Set the video format to match the incomming video format.
// Does the device support the desired input source?
// Determine the input video signal format...
mVideoFormat = mDevice.GetInputVideoFormat (mInputSource);
if (mVideoFormat == NTV2_FORMAT_UNKNOWN)
{
cerr << "## ERROR: No input signal or unknown format" << endl;
return AJA_STATUS_NOINPUT; // Sorry, can't handle this format
}
// Convert the signal wire format to a 8k format
CNTV2DemoCommon::Get8KInputFormat(mVideoFormat);
mDevice.SetVideoFormat(mVideoFormat, false, false, mInputChannel);
mDevice.SetQuadQuadFrameEnable(true, mInputChannel);
mDevice.SetQuadQuadSquaresEnable(!mDoTsiRouting, mInputChannel);
// Set the device video format to whatever we detected at the input...
// The user has an option here. If doing multi-format, we are, lock to the board.
// If the user wants to E-E the signal then lock to input.
mDevice.SetReference(NTV2_REFERENCE_FREERUN);
// Set the frame buffer pixel format for all the channels on the device
// (assuming it supports that pixel format -- otherwise default to 8-bit YCbCr)...
if (!::NTV2DeviceCanDoFrameBufferFormat (mDeviceID, mPixelFormat))
mPixelFormat = NTV2_FBF_8BIT_YCBCR;
// ...and set all buffers pixel format...
if (mDoTsiRouting)
{
if (mInputChannel < NTV2_CHANNEL3)
{
mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat);
mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2);
mDevice.EnableChannel(NTV2_CHANNEL1);
mDevice.EnableChannel(NTV2_CHANNEL2);
if (!mDoMultiFormat)
{
mDevice.DisableChannel(NTV2_CHANNEL3);
mDevice.DisableChannel(NTV2_CHANNEL4);
}
}
else
{
mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat);
mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4);
mDevice.EnableChannel(NTV2_CHANNEL3);
mDevice.EnableChannel(NTV2_CHANNEL4);
if (!mDoMultiFormat)
{
mDevice.DisableChannel(NTV2_CHANNEL1);
mDevice.DisableChannel(NTV2_CHANNEL2);
}
}
}
else
{
mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat);
mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat);
mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat);
mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3);
mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4);
mDevice.EnableChannel(NTV2_CHANNEL1);
mDevice.EnableChannel(NTV2_CHANNEL2);
mDevice.EnableChannel(NTV2_CHANNEL3);
mDevice.EnableChannel(NTV2_CHANNEL4);
}
return AJA_STATUS_SUCCESS;
} // SetupVideo
AJAStatus NTV2Capture8K::SetupAudio (void)
{
// In multiformat mode, base the audio system on the channel...
if (mDoMultiFormat && ::NTV2DeviceGetNumAudioSystems (mDeviceID) > 1 && UWord (mInputChannel) < ::NTV2DeviceGetNumAudioSystems (mDeviceID))
mAudioSystem = ::NTV2ChannelToAudioSystem (mInputChannel);
// Have the audio system capture audio from the designated device input (i.e., ch1 uses SDIIn1, ch2 uses SDIIn2, etc.)...
mDevice.SetAudioSystemInputSource (mAudioSystem, NTV2_AUDIO_EMBEDDED, ::NTV2InputSourceToEmbeddedAudioInput (mInputSource));
mDevice.SetNumberAudioChannels (::NTV2DeviceGetMaxAudioChannels (mDeviceID), mAudioSystem);
mDevice.SetAudioRate (NTV2_AUDIO_48K, mAudioSystem);
// The on-device audio buffer should be 4MB to work best across all devices & platforms...
mDevice.SetAudioBufferSize (NTV2_AUDIO_BUFFER_BIG, mAudioSystem);
mDevice.SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, mAudioSystem);
return AJA_STATUS_SUCCESS;
} // SetupAudio
void NTV2Capture8K::SetupHostBuffers (void)
{
// Let my circular buffer know when it's time to quit...
mAVCircularBuffer.SetAbortFlag (&mGlobalQuit);
mVideoBufferSize = ::GetVideoWriteSize (mVideoFormat, mPixelFormat);
printf("video size = %d\n", mVideoBufferSize);
mAudioBufferSize = NTV2_AUDIOSIZE_MAX;
mAncBufferSize = NTV2_ANCSIZE_MAX;
// Allocate and add each in-host AVDataBuffer to my circular buffer member variable...
for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++ )
{
mAVHostBuffer [bufferNdx].fVideoBuffer = reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mVideoBufferSize, BUFFER_ALIGNMENT));
mAVHostBuffer [bufferNdx].fVideoBufferSize = mVideoBufferSize;
mAVHostBuffer [bufferNdx].fAudioBuffer = mWithAudio ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAudioBufferSize, BUFFER_ALIGNMENT)) : 0;
mAVHostBuffer [bufferNdx].fAudioBufferSize = mWithAudio ? mAudioBufferSize : 0;
mAVHostBuffer [bufferNdx].fAncBuffer = mWithAnc ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAncBufferSize, BUFFER_ALIGNMENT)) : 0;
mAVHostBuffer [bufferNdx].fAncBufferSize = mAncBufferSize;
mAVCircularBuffer.Add (& mAVHostBuffer [bufferNdx]);
// Page lock the memory
if (mAVHostBuffer [bufferNdx].fVideoBuffer != AJA_NULL)
mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fVideoBuffer, mVideoBufferSize, true);
if (mAVHostBuffer [bufferNdx].fAudioBuffer)
mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAudioBuffer, mAudioBufferSize, true);
if (mAVHostBuffer [bufferNdx].fAncBuffer)
mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAncBuffer, mAncBufferSize, true);
} // for each AVDataBuffer
} // SetupHostBuffers
void NTV2Capture8K::RouteInputSignal(void)
{
if (mDoTsiRouting)
{
if (::IsRGBFormat (mPixelFormat))
{
if (mInputChannel < NTV2_CHANNEL3)
{
mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2);
mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2);
mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2);
mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4);
mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2);
mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1);
mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptDuallinkIn2);
mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn3);
mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptDuallinkIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
else
{
mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2);
mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2);
mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2);
mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4);
mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2);
mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn1);
mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptDuallinkIn2);
mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn3);
mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptDuallinkIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
}
else
{
if (mInputChannel < NTV2_CHANNEL3)
{
if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat))
{
mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
else
{
mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn1DS2);
mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn2DS2);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
}
}
else
{
if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat))
{
mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
else
{
mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn3DS2);
mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4);
mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4DS2);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
}
}
}
else
{
if (::IsRGBFormat (mPixelFormat))
{
mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2);
mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2);
mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2);
mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4);
mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2);
mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1);
mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn2);
mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn3);
mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
else
{
mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1);
mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2);
mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3);
mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false);
mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false);
}
}
} // RouteInputSignal
void NTV2Capture8K::SetupInputAutoCirculate (void)
{
// Tell capture AutoCirculate to use 7 frame buffers on the device...
ULWord startFrame = 0, endFrame = 7;
mDevice.AutoCirculateStop(NTV2_CHANNEL1);
mDevice.AutoCirculateStop(NTV2_CHANNEL2);
mDevice.AutoCirculateStop(NTV2_CHANNEL3);
mDevice.AutoCirculateStop(NTV2_CHANNEL4);
mDevice.AutoCirculateInitForInput (mInputChannel, 0, // 0 frames == explicitly set start & end frames
mWithAudio ? mAudioSystem : NTV2_AUDIOSYSTEM_INVALID, // Which audio system (if any)?
AUTOCIRCULATE_WITH_RP188 | AUTOCIRCULATE_WITH_ANC, // Include timecode & custom Anc
1, startFrame, endFrame);
} // SetupInputAutoCirculate
AJAStatus NTV2Capture8K::Run ()
{
// Start the playout and capture threads...
StartConsumerThread ();
StartProducerThread ();
return AJA_STATUS_SUCCESS;
} // Run
//////////////////////////////////////////////
// This is where we will start the consumer thread
void NTV2Capture8K::StartConsumerThread (void)
{
// Create and start the consumer thread...
mConsumerThread.Attach(ConsumerThreadStatic, this);
mConsumerThread.SetPriority(AJA_ThreadPriority_High);
mConsumerThread.Start();
} // StartConsumerThread
// The consumer thread function
void NTV2Capture8K::ConsumerThreadStatic (AJAThread * pThread, void * pContext) // static
{
(void) pThread;
// Grab the NTV2Capture instance pointer from the pContext parameter,
// then call its ConsumeFrames method...
NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext));
pApp->ConsumeFrames ();
} // ConsumerThreadStatic
void NTV2Capture8K::ConsumeFrames (void)
{
CAPNOTE("Thread started");
while (!mGlobalQuit)
{
// Wait for the next frame to become ready to "consume"...
AVDataBuffer * pFrameData (mAVCircularBuffer.StartConsumeNextBuffer ());
if (pFrameData)
{
// Do something useful with the frame data...
// . . . . . . . . . . . .
// . . . . . . . . . . . .
// . . . . . . . . . . . .
// Now release and recycle the buffer...
mAVCircularBuffer.EndConsumeNextBuffer ();
}
} // loop til quit signaled
CAPNOTE("Thread completed, will exit");
} // ConsumeFrames
//////////////////////////////////////////////
//////////////////////////////////////////////
// This is where we start the capture thread
void NTV2Capture8K::StartProducerThread (void)
{
// Create and start the capture thread...
mProducerThread.Attach(ProducerThreadStatic, this);
mProducerThread.SetPriority(AJA_ThreadPriority_High);
mProducerThread.Start();
} // StartProducerThread
// The capture thread function
void NTV2Capture8K::ProducerThreadStatic (AJAThread * pThread, void * pContext) // static
{
(void) pThread;
// Grab the NTV2Capture instance pointer from the pContext parameter,
// then call its CaptureFrames method...
NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext));
pApp->CaptureFrames ();
} // ProducerThreadStatic
void NTV2Capture8K::CaptureFrames (void)
{
NTV2AudioChannelPairs nonPcmPairs, oldNonPcmPairs;
CAPNOTE("Thread started");
// Start AutoCirculate running...
mDevice.AutoCirculateStart (mInputChannel);
while (!mGlobalQuit)
{
AUTOCIRCULATE_STATUS acStatus;
mDevice.AutoCirculateGetStatus (mInputChannel, acStatus);
if (acStatus.IsRunning () && acStatus.HasAvailableInputFrame ())
{
// At this point, there's at least one fully-formed frame available in the device's
// frame buffer to transfer to the host. Reserve an AVDataBuffer to "produce", and
// use it in the next transfer from the device...
AVDataBuffer * captureData (mAVCircularBuffer.StartProduceNextBuffer ());
mInputTransfer.SetBuffers (captureData->fVideoBuffer, captureData->fVideoBufferSize,
captureData->fAudioBuffer, captureData->fAudioBufferSize,
captureData->fAncBuffer, captureData->fAncBufferSize);
// Do the transfer from the device into our host AVDataBuffer...
mDevice.AutoCirculateTransfer (mInputChannel, mInputTransfer);
// mInputTransfer.acTransferStatus.acAudioTransferSize; // this is the amount of audio captured
NTV2SDIInStatistics sdiStats;
mDevice.ReadSDIStatistics (sdiStats);
// "Capture" timecode into the host AVDataBuffer while we have full access to it...
NTV2_RP188 timecode;
mInputTransfer.GetInputTimeCode (timecode);
captureData->fRP188Data = timecode;
// Signal that we're done "producing" the frame, making it available for future "consumption"...
mAVCircularBuffer.EndProduceNextBuffer ();
} // if A/C running and frame(s) are available for transfer
else
{
// Either AutoCirculate is not running, or there were no frames available on the device to transfer.
// Rather than waste CPU cycles spinning, waiting until a frame becomes available, it's far more
// efficient to wait for the next input vertical interrupt event to get signaled...
mDevice.WaitForInputVerticalInterrupt (mInputChannel);
}
} // loop til quit signaled
// Stop AutoCirculate...
mDevice.AutoCirculateStop (mInputChannel);
CAPNOTE("Thread completed, will exit");
} // CaptureFrames
//////////////////////////////////////////////
void NTV2Capture8K::GetACStatus (ULWord & outGoodFrames, ULWord & outDroppedFrames, ULWord & outBufferLevel)
{
AUTOCIRCULATE_STATUS status;
mDevice.AutoCirculateGetStatus (mInputChannel, status);
outGoodFrames = status.acFramesProcessed;
outDroppedFrames = status.acFramesDropped;
outBufferLevel = status.acBufferLevel;
}
| 39.593248 | 157 | 0.697811 | ibstewart |
929d530fe906177786471f26757b646ba7848678 | 2,832 | cpp | C++ | Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp | bLandais/txRobotic | bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03 | [
"CC0-1.0"
] | 2 | 2018-04-04T18:59:50.000Z | 2021-06-13T01:07:38.000Z | Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp | bLandais/txRobotic | bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03 | [
"CC0-1.0"
] | 9 | 2017-03-22T17:26:25.000Z | 2017-06-25T13:35:34.000Z | Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp | bLandais/txRobotic | bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03 | [
"CC0-1.0"
] | 3 | 2017-03-22T15:09:12.000Z | 2018-04-04T18:59:51.000Z |
/*
File: ControlPanel.cpp
Author: Mathilde
Created on 18 octobre 2016, 11:37
*/
#include <map>
#include "vector"
#include <math.h>
#include <iostream>
#include "Arduino.h"
#include "ControlPanel.h"
#include "Button.h"
// constructors
ControlPanel::ControlPanel() {
}
ControlPanel::ControlPanel(int newBtnNumberMax) {
this->btnList.reserve(newBtnNumberMax);
}
//getter
/*
std::vector::size_type ControlPanel::getBtnNumber(){
return this->btnList.size;
}*/
int ControlPanel::getBtnNumberMax() {
return this->btnList.capacity();
}
std::vector<Button> ControlPanel::getBtnList() {
return this->btnList;
}
//setters
void ControlPanel::setBtnNumberMax(int newBtnNumberMax) {
this->btnList.reserve(newBtnNumberMax);
}
//************************************************************************
// Add button in the control panel button list
// Arguments : the button you want to add in the list
// Return : nothing
//************************************************************************
void ControlPanel::addButton(Button newBtn) {
this->btnList.push_back(newBtn);
}
//************************************************************************
// Memory reservation for buttons
// Arguments : the number of buttons you want to rreserve memory for
// Return : nothing
//************************************************************************
void ControlPanel::reserve(int newBtnNumberMax) {
this->btnList.reserve(newBtnNumberMax);
}
//************************************************************************
// Control panel read: read all buttons stocked in the button vector
// Arguments : none
// Return : none
//************************************************************************
void ControlPanel::controlRead() {
for (auto &btn : this->btnList) {
btn.readValue();
}
}
//int ControlPanel::toBinary(){
// int count=0;
// int binary=0;
//
// controlRead();
// for (auto &btn: this->btnList){
// if(btn.getValue() == LOW){
// binary = binary + pow(10,count);
// }
// count++;
// }
// return binary;
//}
//************************************************************************
// Control panel analyse: analyse the values stored in memory from read
// Arguments : none
// Return : 1 right; 2 left; 3 down; 4 up; 5 validate
//************************************************************************
int ControlPanel::analyze() {
controlRead();
// Serial.println("Analyse button");
if (this->btnList[0].value == LOW) {
return 1;
}
else if (this->btnList[1].value == LOW) {
return 2;
}
else if (this->btnList[2].value == LOW) {
return 3;
}
else if (this->btnList[3].value == LOW) {
return 4;
}
else if (this->btnList[4].value == LOW) {
return 5;
} else {
return 0;
}
}
| 23.6 | 74 | 0.513771 | bLandais |
929f720a94a4ebbc040a014231c03521e5eccb7c | 11,055 | cpp | C++ | src/GameCardProcess.cpp | jakcron/NXTools | 04662e529f2be92f590ca0754e780c7716b8c077 | [
"MIT"
] | 40 | 2017-07-18T18:21:00.000Z | 2018-08-05T12:30:05.000Z | src/GameCardProcess.cpp | PMArkive/NNTools | 276db64e45471a77345a87abb5c10a54ed8cc71e | [
"MIT"
] | 9 | 2018-04-05T07:44:54.000Z | 2018-08-07T09:11:22.000Z | src/GameCardProcess.cpp | PMArkive/NNTools | 276db64e45471a77345a87abb5c10a54ed8cc71e | [
"MIT"
] | 13 | 2018-01-22T09:10:13.000Z | 2018-08-05T12:30:06.000Z | #include "GameCardProcess.h"
#include <tc/crypto.h>
#include <tc/io/IOUtil.h>
#include <nn/hac/GameCardUtil.h>
#include <nn/hac/ContentMetaUtil.h>
#include <nn/hac/ContentArchiveUtil.h>
#include <nn/hac/GameCardFsMetaGenerator.h>
#include "FsProcess.h"
nstool::GameCardProcess::GameCardProcess() :
mModuleName("nstool::GameCardProcess"),
mFile(),
mCliOutputMode(true, false, false, false),
mVerify(false),
mListFs(false),
mProccessExtendedHeader(false),
mRootPfs(),
mExtractJobs()
{
}
void nstool::GameCardProcess::process()
{
importHeader();
// validate header signature
if (mVerify)
validateXciSignature();
// display header
if (mCliOutputMode.show_basic_info)
displayHeader();
// process nested HFS0
processRootPfs();
}
void nstool::GameCardProcess::setInputFile(const std::shared_ptr<tc::io::IStream>& file)
{
mFile = file;
}
void nstool::GameCardProcess::setKeyCfg(const KeyBag& keycfg)
{
mKeyCfg = keycfg;
}
void nstool::GameCardProcess::setCliOutputMode(CliOutputMode type)
{
mCliOutputMode = type;
}
void nstool::GameCardProcess::setVerifyMode(bool verify)
{
mVerify = verify;
}
void nstool::GameCardProcess::setExtractJobs(const std::vector<nstool::ExtractJob> extract_jobs)
{
mExtractJobs = extract_jobs;
}
void nstool::GameCardProcess::setShowFsTree(bool show_fs_tree)
{
mListFs = show_fs_tree;
}
void nstool::GameCardProcess::importHeader()
{
if (mFile == nullptr)
{
throw tc::Exception(mModuleName, "No file reader set.");
}
if (mFile->canRead() == false || mFile->canSeek() == false)
{
throw tc::NotSupportedException(mModuleName, "Input stream requires read/seek permissions.");
}
// check stream is large enough for header
if (mFile->length() < tc::io::IOUtil::castSizeToInt64(sizeof(nn::hac::sSdkGcHeader)))
{
throw tc::Exception(mModuleName, "Corrupt GameCard Image: File too small.");
}
// allocate memory for header
tc::ByteData scratch = tc::ByteData(sizeof(nn::hac::sSdkGcHeader));
// read header region
mFile->seek(0, tc::io::SeekOrigin::Begin);
mFile->read(scratch.data(), scratch.size());
// determine if this is a SDK XCI or a "Community" XCI
if (((nn::hac::sSdkGcHeader*)scratch.data())->signed_header.header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic)
{
mIsTrueSdkXci = true;
mGcHeaderOffset = sizeof(nn::hac::sGcKeyDataRegion);
}
else if (((nn::hac::sGcHeader_Rsa2048Signed*)scratch.data())->header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic)
{
mIsTrueSdkXci = false;
mGcHeaderOffset = 0;
}
else
{
throw tc::Exception(mModuleName, "Corrupt GameCard Image: Unexpected magic bytes.");
}
nn::hac::sGcHeader_Rsa2048Signed* hdr_ptr = (nn::hac::sGcHeader_Rsa2048Signed*)(scratch.data() + mGcHeaderOffset);
// generate hash of raw header
tc::crypto::GenerateSha256Hash(mHdrHash.data(), (byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader));
// save the signature
memcpy(mHdrSignature.data(), hdr_ptr->signature.data(), mHdrSignature.size());
// decrypt extended header
byte_t xci_header_key_index = hdr_ptr->header.key_flag & 7;
if (mKeyCfg.xci_header_key.find(xci_header_key_index) != mKeyCfg.xci_header_key.end())
{
nn::hac::GameCardUtil::decryptXciHeader(&hdr_ptr->header, mKeyCfg.xci_header_key[xci_header_key_index].data());
mProccessExtendedHeader = true;
}
// deserialise header
mHdr.fromBytes((byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader));
}
void nstool::GameCardProcess::displayHeader()
{
const nn::hac::sGcHeader* raw_hdr = (const nn::hac::sGcHeader*)mHdr.getBytes().data();
fmt::print("[GameCard/Header]\n");
fmt::print(" CardHeaderVersion: {:d}\n", mHdr.getCardHeaderVersion());
fmt::print(" RomSize: {:s}", nn::hac::GameCardUtil::getRomSizeAsString((nn::hac::gc::RomSize)mHdr.getRomSizeType()));
if (mCliOutputMode.show_extended_info)
fmt::print(" (0x{:x})", mHdr.getRomSizeType());
fmt::print("\n");
fmt::print(" PackageId: 0x{:016x}\n", mHdr.getPackageId());
fmt::print(" Flags: 0x{:02x}\n", *((byte_t*)&raw_hdr->flags));
for (auto itr = mHdr.getFlags().begin(); itr != mHdr.getFlags().end(); itr++)
{
fmt::print(" {:s}\n", nn::hac::GameCardUtil::getHeaderFlagsAsString((nn::hac::gc::HeaderFlags)*itr));
}
if (mCliOutputMode.show_extended_info)
{
fmt::print(" KekIndex: {:s} ({:d})\n", nn::hac::GameCardUtil::getKekIndexAsString((nn::hac::gc::KekIndex)mHdr.getKekIndex()), mHdr.getKekIndex());
fmt::print(" TitleKeyDecIndex: {:d}\n", mHdr.getTitleKeyDecIndex());
fmt::print(" InitialData:\n");
fmt::print(" Hash:\n");
fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getInitialDataHash().data(), mHdr.getInitialDataHash().size(), true, "", 0x10, 6, false));
}
if (mCliOutputMode.show_extended_info)
{
fmt::print(" Extended Header AesCbc IV:\n");
fmt::print(" {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getAesCbcIv().data(), mHdr.getAesCbcIv().size(), true, ""));
}
fmt::print(" SelSec: 0x{:x}\n", mHdr.getSelSec());
fmt::print(" SelT1Key: 0x{:x}\n", mHdr.getSelT1Key());
fmt::print(" SelKey: 0x{:x}\n", mHdr.getSelKey());
if (mCliOutputMode.show_layout)
{
fmt::print(" RomAreaStartPage: 0x{:x}", mHdr.getRomAreaStartPage());
if (mHdr.getRomAreaStartPage() != (uint32_t)(-1))
fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getRomAreaStartPage()));
fmt::print("\n");
fmt::print(" BackupAreaStartPage: 0x{:x}", mHdr.getBackupAreaStartPage());
if (mHdr.getBackupAreaStartPage() != (uint32_t)(-1))
fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getBackupAreaStartPage()));
fmt::print("\n");
fmt::print(" ValidDataEndPage: 0x{:x}", mHdr.getValidDataEndPage());
if (mHdr.getValidDataEndPage() != (uint32_t)(-1))
fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage()));
fmt::print("\n");
fmt::print(" LimArea: 0x{:x}", mHdr.getLimAreaPage());
if (mHdr.getLimAreaPage() != (uint32_t)(-1))
fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getLimAreaPage()));
fmt::print("\n");
fmt::print(" PartitionFs Header:\n");
fmt::print(" Offset: 0x{:x}\n", mHdr.getPartitionFsAddress());
fmt::print(" Size: 0x{:x}\n", mHdr.getPartitionFsSize());
if (mCliOutputMode.show_extended_info)
{
fmt::print(" Hash:\n");
fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getPartitionFsHash().data(), mHdr.getPartitionFsHash().size(), true, "", 0x10, 6, false));
}
}
if (mProccessExtendedHeader)
{
fmt::print("[GameCard/ExtendedHeader]\n");
fmt::print(" FwVersion: v{:d} ({:s})\n", mHdr.getFwVersion(), nn::hac::GameCardUtil::getCardFwVersionDescriptionAsString((nn::hac::gc::FwVersion)mHdr.getFwVersion()));
fmt::print(" AccCtrl1: 0x{:x}\n", mHdr.getAccCtrl1());
fmt::print(" CardClockRate: {:s}\n", nn::hac::GameCardUtil::getCardClockRateAsString((nn::hac::gc::CardClockRate)mHdr.getAccCtrl1()));
fmt::print(" Wait1TimeRead: 0x{:x}\n", mHdr.getWait1TimeRead());
fmt::print(" Wait2TimeRead: 0x{:x}\n", mHdr.getWait2TimeRead());
fmt::print(" Wait1TimeWrite: 0x{:x}\n", mHdr.getWait1TimeWrite());
fmt::print(" Wait2TimeWrite: 0x{:x}\n", mHdr.getWait2TimeWrite());
fmt::print(" SdkAddon Version: {:s} (v{:d})\n", nn::hac::ContentArchiveUtil::getSdkAddonVersionAsString(mHdr.getFwMode()), mHdr.getFwMode());
fmt::print(" CompatibilityType: {:s} ({:d})\n", nn::hac::GameCardUtil::getCompatibilityTypeAsString((nn::hac::gc::CompatibilityType)mHdr.getCompatibilityType()), mHdr.getCompatibilityType());
fmt::print(" Update Partition Info:\n");
fmt::print(" CUP Version: {:s} (v{:d})\n", nn::hac::ContentMetaUtil::getVersionAsString(mHdr.getUppVersion()), mHdr.getUppVersion());
fmt::print(" CUP TitleId: 0x{:016x}\n", mHdr.getUppId());
fmt::print(" CUP Digest: {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getUppHash().data(), mHdr.getUppHash().size(), true, ""));
}
}
bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash, bool use_salt, byte_t salt)
{
// read region into memory
tc::ByteData scratch = tc::ByteData(tc::io::IOUtil::castInt64ToSize(len));
mFile->seek(offset, tc::io::SeekOrigin::Begin);
mFile->read(scratch.data(), scratch.size());
// update hash
tc::crypto::Sha256Generator sha256_gen;
sha256_gen.initialize();
sha256_gen.update(scratch.data(), scratch.size());
if (use_salt)
sha256_gen.update(&salt, sizeof(salt));
// calculate hash
nn::hac::detail::sha256_hash_t calc_hash;
sha256_gen.getHash(calc_hash.data());
return memcmp(calc_hash.data(), test_hash, calc_hash.size()) == 0;
}
bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash)
{
return validateRegionOfFile(offset, len, test_hash, false, 0);
}
void nstool::GameCardProcess::validateXciSignature()
{
if (mKeyCfg.xci_header_sign_key.isSet())
{
if (tc::crypto::VerifyRsa2048Pkcs1Sha256(mHdrSignature.data(), mHdrHash.data(), mKeyCfg.xci_header_sign_key.get()) == false)
{
fmt::print("[WARNING] GameCard Header Signature: FAIL\n");
}
}
else
{
fmt::print("[WARNING] GameCard Header Signature: FAIL (Failed to load rsa public key.)\n");
}
}
void nstool::GameCardProcess::processRootPfs()
{
if (mVerify && validateRegionOfFile(mHdr.getPartitionFsAddress(), mHdr.getPartitionFsSize(), mHdr.getPartitionFsHash().data(), mHdr.getCompatibilityType() != nn::hac::gc::COMPAT_GLOBAL, mHdr.getCompatibilityType()) == false)
{
fmt::print("[WARNING] GameCard Root HFS0: FAIL (bad hash)\n");
}
std::shared_ptr<tc::io::IStream> gc_fs_raw = std::make_shared<tc::io::SubStream>(tc::io::SubStream(mFile, mHdr.getPartitionFsAddress(), nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage()+1) - mHdr.getPartitionFsAddress()));
auto gc_vfs_meta = nn::hac::GameCardFsMetaGenerator(gc_fs_raw, mHdr.getPartitionFsSize(), mVerify ? nn::hac::GameCardFsMetaGenerator::ValidationMode_Warn : nn::hac::GameCardFsMetaGenerator::ValidationMode_None);
std::shared_ptr<tc::io::IStorage> gc_vfs = std::make_shared<tc::io::VirtualFileSystem>(tc::io::VirtualFileSystem(gc_vfs_meta) );
FsProcess fs_proc;
fs_proc.setInputFileSystem(gc_vfs);
fs_proc.setFsFormatName("PartitionFs");
fs_proc.setFsProperties({
fmt::format("Type: Nested HFS0"),
fmt::format("DirNum: {:d}", gc_vfs_meta.dir_entries.empty() ? 0 : gc_vfs_meta.dir_entries.size() - 1), // -1 to not include root directory
fmt::format("FileNum: {:d}", gc_vfs_meta.file_entries.size())
});
fs_proc.setShowFsInfo(mCliOutputMode.show_basic_info);
fs_proc.setShowFsTree(mListFs);
fs_proc.setFsRootLabel(kXciMountPointName);
fs_proc.setExtractJobs(mExtractJobs);
fs_proc.process();
} | 38.653846 | 235 | 0.686839 | jakcron |
92a57ef5e759d6605d43b995e30da1833c5f2339 | 734 | cpp | C++ | lib/src/Flag.cpp | Kylerchrdsn/OOP-Strategoo | da182252ed37eca4c30d7aefa513434abb4a2ff2 | [
"MIT"
] | null | null | null | lib/src/Flag.cpp | Kylerchrdsn/OOP-Strategoo | da182252ed37eca4c30d7aefa513434abb4a2ff2 | [
"MIT"
] | null | null | null | lib/src/Flag.cpp | Kylerchrdsn/OOP-Strategoo | da182252ed37eca4c30d7aefa513434abb4a2ff2 | [
"MIT"
] | null | null | null | /******************************************************
Flag.cpp
This is the implementation file for the Flag
class.
******************************************************/
#include "headers/Flag.h"
//*****************************************************
Flag::Flag(Player* owner, int xPos, int yPos, int boardSpace) : Piece(owner, xPos, yPos, "lib/images/flag.png"){
setBoardSpace(boardSpace);
setRank(12);
}
//*****************************************************
Flag::Flag(Player* owner, std::string filename) : Piece(owner, 0, 0, filename.c_str()){
setBoardSpace(-1);
setRank(12);
}
//*****************************************************
Piece* Flag::move(Piece* const destination){ return 0; }
| 31.913043 | 113 | 0.415531 | Kylerchrdsn |
92ac653f1ffe2d4ef4b60de2ad61758cf81572e8 | 1,018 | cpp | C++ | ABC/ABC123/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | ABC/ABC123/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | ABC/ABC123/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#define FOR(idx, begin, end) for(int idx = (int)(begin); idx < (int)(end); ++idx)
#ifdef _DEBUG
#define DMP(x) cerr << #x << ": " << x << "\n"
#else
#define DMP(x) ((void)0)
#endif
using namespace std;
typedef long long lint;
const int MOD = 100000007;
const int INF = 1 << 29;
const double EPS = 1e-9;
int main() {
cin.tie(0);
lint X, Y, Z, K;
cin >> X >> Y >> Z >> K;
vector<lint> A(X), B(Y), C(Z), ans(K);
FOR(i, 0, X)cin >> A[i];
FOR(i, 0, Y)cin >> B[i];
FOR(i, 0, Z)cin >> C[i];
sort(A.begin(), A.end(), greater<lint>());
sort(B.begin(), B.end(), greater<lint>());
sort(C.begin(), C.end(), greater<lint>());
FOR(a,0,X)FOR(b,0,Y)FOR(c,0,Z){
if ((a + 1)*(b + 1)*(c+1)<=K) ans.emplace_back(A[a] + B[b] + C[c]);
}
sort(ans.begin(), ans.end(), greater<lint>());
FOR(i, 0, K) cout << ans[i] << "\n";
return 0;
} | 19.576923 | 81 | 0.561886 | rajyan |
92b1144443ce18ad5f19b27b82200db1b051780f | 7,191 | cpp | C++ | src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp | samdauwe/BabylonCpp | eea9f761a49bb460ff1324c20e4674ef120e94f1 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/gizmos/plane_drag_gizmo.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/engines/scene.h>
#include <babylon/gizmos/position_gizmo.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/builders/plane_builder.h>
#include <babylon/meshes/instanced_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/transform_node.h>
namespace BABYLON {
TransformNodePtr PlaneDragGizmo::_CreatePlane(Scene* scene, const StandardMaterialPtr& material)
{
auto plane = TransformNode::New("plane", scene);
// make sure plane is double sided
PlaneOptions options;
options.width = 0.1375f;
options.height = 0.1375f;
options.sideOrientation = 2u;
auto dragPlane = PlaneBuilder::CreatePlane("dragPlane", options, scene);
dragPlane->material = material;
dragPlane->parent = plane.get();
return plane;
}
PlaneDragGizmo::PlaneDragGizmo(const Vector3& dragPlaneNormal, const Color3& color,
const UtilityLayerRendererPtr& iGizmoLayer, PositionGizmo* parent)
: Gizmo{iGizmoLayer}
, snapDistance{0.f}
, isEnabled{this, &PlaneDragGizmo::get_isEnabled, &PlaneDragGizmo::set_isEnabled}
, _pointerObserver{nullptr}
, _gizmoMesh{nullptr}
, _coloredMaterial{nullptr}
, _hoverMaterial{nullptr}
, _disableMaterial{nullptr}
, _isEnabled{false}
, _parent{nullptr}
, _dragging{false}
, tmpSnapEvent{SnapEvent{0.f}}
{
_parent = parent;
// Create Material
_coloredMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get());
_coloredMaterial->diffuseColor = color;
_coloredMaterial->specularColor = color.subtract(Color3(0.1f, 0.1f, 0.1f));
_hoverMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get());
_hoverMaterial->diffuseColor = Color3::Yellow();
_disableMaterial = StandardMaterial::New("", gizmoLayer->utilityLayerScene.get());
_disableMaterial->diffuseColor = Color3::Gray();
_disableMaterial->alpha = 0.4f;
// Build plane mesh on root node
_gizmoMesh = PlaneDragGizmo::_CreatePlane(gizmoLayer->utilityLayerScene.get(), _coloredMaterial);
_gizmoMesh->lookAt(_rootMesh->position().add(dragPlaneNormal));
_gizmoMesh->scaling().scaleInPlace(1.f / 3.f);
_gizmoMesh->parent = _rootMesh.get();
currentSnapDragDistance = 0.f;
// Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged
PointerDragBehaviorOptions options;
options.dragPlaneNormal = dragPlaneNormal;
dragBehavior = std::make_shared<PointerDragBehavior>(options);
dragBehavior->moveAttached = false;
// _rootMesh->addBehavior(dragBehavior);
dragBehavior->onDragObservable.add([this](DragMoveEvent* event, EventState& /*es*/) -> void {
if (attachedNode()) {
_handlePivot();
// Keep world translation and use it to update world transform
// if the node has parent, the local transform properties (position, rotation, scale)
// will be recomputed in _matrixChanged function
// Snapping logic
if (snapDistance == 0.f) {
attachedNode()->getWorldMatrix().addTranslationFromFloats(event->delta.x, event->delta.y,
event->delta.z);
}
else {
currentSnapDragDistance += event->dragDistance;
if (std::abs(currentSnapDragDistance) > snapDistance) {
auto dragSteps = std::floor(std::abs(currentSnapDragDistance) / snapDistance);
currentSnapDragDistance = std::fmod(currentSnapDragDistance, snapDistance);
event->delta.normalizeToRef(tmpVector);
tmpVector.scaleInPlace(snapDistance * dragSteps);
attachedNode()->getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y,
tmpVector.z);
tmpSnapEvent.snapDistance = snapDistance * dragSteps;
onSnapObservable.notifyObservers(&tmpSnapEvent);
}
}
_matrixChanged();
}
});
dragBehavior->onDragStartObservable.add(
[this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = true; });
dragBehavior->onDragEndObservable.add(
[this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = false; });
auto light = gizmoLayer->_getSharedGizmoLight();
light->includedOnlyMeshes
= stl_util::concat(light->includedOnlyMeshes(), _rootMesh->getChildMeshes(false));
const auto toMeshArray = [](const std::vector<AbstractMeshPtr>& meshes) -> std::vector<MeshPtr> {
std::vector<MeshPtr> meshArray;
meshArray.reserve(meshes.size());
for (const auto& mesh : meshes) {
meshArray.emplace_back(std::static_pointer_cast<Mesh>(mesh));
}
return meshArray;
};
_cache.gizmoMeshes = toMeshArray(_gizmoMesh->getChildMeshes());
_cache.colliderMeshes = toMeshArray(_gizmoMesh->getChildMeshes());
_cache.material = _coloredMaterial;
_cache.hoverMaterial = _hoverMaterial;
_cache.disableMaterial = _disableMaterial;
_cache.active = false;
_cache.dragBehavior = dragBehavior;
if (_parent) {
_parent->addToAxisCache(static_cast<Mesh*>(_gizmoMesh.get()), _cache);
}
_pointerObserver = gizmoLayer->utilityLayerScene->onPointerObservable.add(
[this](PointerInfo* pointerInfo, EventState& /*es*/) -> void {
if (_customMeshSet) {
return;
}
auto pickedMesh = std::static_pointer_cast<Mesh>(pointerInfo->pickInfo.pickedMesh);
_isHovered = stl_util::contains(_cache.colliderMeshes, pickedMesh);
if (!_parent) {
const auto material = _cache.dragBehavior->enabled ?
(_isHovered || _dragging ? _hoverMaterial : _coloredMaterial) :
_disableMaterial;
_setGizmoMeshMaterial(_cache.gizmoMeshes, material);
}
});
dragBehavior->onEnabledObservable.add([this](bool* newState, EventState& /*es*/) -> void {
_setGizmoMeshMaterial(_cache.gizmoMeshes, *newState ? _coloredMaterial : _disableMaterial);
});
}
PlaneDragGizmo::~PlaneDragGizmo() = default;
void PlaneDragGizmo::_attachedNodeChanged(const NodePtr& value)
{
dragBehavior->enabled = value ? true : false;
}
void PlaneDragGizmo::set_isEnabled(bool value)
{
_isEnabled = value;
if (!value) {
attachedNode = nullptr;
}
else {
if (_parent) {
attachedNode = _parent->attachedNode();
}
}
}
bool PlaneDragGizmo::get_isEnabled() const
{
return _isEnabled;
}
void PlaneDragGizmo::dispose(bool /*doNotRecurse*/, bool /*disposeMaterialAndTextures*/)
{
onSnapObservable.clear();
gizmoLayer->utilityLayerScene->onPointerObservable.remove(_pointerObserver);
dragBehavior->detach();
Gizmo::dispose();
if (_gizmoMesh) {
_gizmoMesh->dispose();
}
for (const auto& matl : {_coloredMaterial, _hoverMaterial, _disableMaterial}) {
if (matl) {
matl->dispose();
}
}
}
} // namespace BABYLON
| 36.688776 | 100 | 0.681129 | samdauwe |
92b27659ae0fc9884ea551f525dc787337b01179 | 534 | hpp | C++ | table/include/item_set.hpp | TheAspiringHacker/Asparserations | 2962c685f5aa36fde966a1ea2a4549401c39ba37 | [
"MIT"
] | 12 | 2017-08-27T21:12:30.000Z | 2018-09-17T05:42:42.000Z | table/include/item_set.hpp | TheAspiringHacker/Asparserations | 2962c685f5aa36fde966a1ea2a4549401c39ba37 | [
"MIT"
] | 1 | 2021-06-16T20:44:33.000Z | 2021-06-16T20:44:33.000Z | table/include/item_set.hpp | TheAspiringHacker/Asparserations | 2962c685f5aa36fde966a1ea2a4549401c39ba37 | [
"MIT"
] | 1 | 2021-07-27T07:42:26.000Z | 2021-07-27T07:42:26.000Z | #ifndef ASPARSERATIONS_TABLE_ITEM_SET_H_
#define ASPARSERATIONS_TABLE_ITEM_SET_H_
#include "item.hpp"
#include <set>
namespace asparserations {
namespace table {
class Item_Set
{
friend bool operator<(const Item_Set&, const Item_Set&);
public:
Item_Set(const std::set<Item>&);
const std::set<Item>& items() const;
void insert(const Item&);
bool merge(const Item_Set&);
private:
std::set<Item> m_items;
};
bool operator<(const Item_Set&, const Item_Set&);
}
}
#endif
| 20.538462 | 62 | 0.666667 | TheAspiringHacker |
92b39c56d4725cc5af4999bb319eda82e936e79c | 32,603 | cpp | C++ | src/OpenGL/frontend/gl_formats.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 114 | 2018-08-05T16:26:53.000Z | 2021-12-30T07:28:35.000Z | src/OpenGL/frontend/gl_formats.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 5 | 2018-08-18T21:16:58.000Z | 2018-11-22T21:50:48.000Z | src/OpenGL/frontend/gl_formats.cpp | kbiElude/VKGL | fffabf412723a3612ba1c5bfeafe1da38062bd18 | [
"MIT"
] | 6 | 2018-08-05T22:32:28.000Z | 2021-10-04T15:39:53.000Z | /* VKGL (c) 2018 Dominik Witczak
*
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
#include "Common/macros.h"
#include "OpenGL/frontend/gl_formats.h"
typedef struct InternalFormatData
{
OpenGL::FormatDataType data_type;
uint32_t n_components;
/* For base and compressed internal formats, "1" indicates the component is used.
* For sized internal formats, non-zero value indicates the component is used and describes the component size in bits.
*/
uint32_t component_size_r;
uint32_t component_size_g;
uint32_t component_size_b;
uint32_t component_size_a;
uint32_t component_size_depth;
uint32_t component_size_stencil;
uint32_t component_size_shared;
bool is_base_internal_format;
bool is_compressed_internal_format;
bool is_sized_internal_format;
InternalFormatData()
{
memset(this,
0,
sizeof(*this) );
}
InternalFormatData(const OpenGL::FormatDataType& in_data_type,
const uint32_t& in_n_components,
const uint32_t& in_component_size_r,
const uint32_t& in_component_size_g,
const uint32_t& in_component_size_b,
const uint32_t& in_component_size_a,
const uint32_t& in_component_size_depth,
const uint32_t& in_component_size_stencil,
const uint32_t& in_component_size_shared,
const bool& in_is_base_internal_format,
const bool& in_is_compressed_internal_format,
const bool& in_is_sized_internal_format)
:data_type (in_data_type),
n_components (in_n_components),
component_size_r (in_component_size_r),
component_size_g (in_component_size_g),
component_size_b (in_component_size_b),
component_size_a (in_component_size_a),
component_size_depth (in_component_size_depth),
component_size_stencil (in_component_size_stencil),
component_size_shared (in_component_size_shared),
is_base_internal_format (in_is_base_internal_format),
is_compressed_internal_format(in_is_compressed_internal_format),
is_sized_internal_format (in_is_sized_internal_format)
{
/* Stub */
}
} InternalFormatData;
OpenGL::PixelFormat;
static const std::unordered_map<OpenGL::InternalFormat, InternalFormatData> g_gl_internalformat_data =
{
/* Base internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Depth_Component, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 0, 0, 0, 0, 1, 0, 0, true, false, false)},
{OpenGL::InternalFormat::Depth_Stencil, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 0, 0, 0, 0, 1, 1, 0, true, false, false)},
{OpenGL::InternalFormat::Red, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 1, 0, 0, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RG, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 1, 1, 0, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RGB, InternalFormatData(OpenGL::FormatDataType::Unknown, 3, 1, 1, 1, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RGBA, InternalFormatData(OpenGL::FormatDataType::Unknown, 4, 1, 1, 1, 1, 0, 0, 0, true, false, false)},
/* Sized internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::R11F_G11F_B10F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 11, 11, 10, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R3_G3_B2, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 3, 3, 2, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 10, 10, 10, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10_A2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10_A2UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB12, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 12, 12, 12, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB4, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 4, 4, 4, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB5, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 5, 5, 5, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB5_A1, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 5, 5, 5, 1, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB9_E5, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 9, 9, 9, 0, 0, 0, 5, false, false, true)},
{OpenGL::InternalFormat::RGBA12, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 12, 12, 12, 12, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 2, 2, 2, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA4, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 4, 4, 4, 4, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::SRGB8, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::SRGB8_Alpha8, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Depth_Component16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 16, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component24, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 24, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component32, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component32_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth24_Stencil8, InternalFormatData(OpenGL::FormatDataType::UNorm_UInt, 2, 0, 0, 0, 0, 24, 8, 0, false, false, true) },
{OpenGL::InternalFormat::Depth32_Float_Stencil8, InternalFormatData(OpenGL::FormatDataType::UFloat_UInt, 2, 0, 0, 0, 0, 32, 8, 0, false, false, true) },
/* Compressed internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Compressed_Red, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RG, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB_BPTC_Signed_Float, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB_BPTC_Unsigned_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGBA, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGBA_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Signed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Signed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB_Alpha, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB_Alpha_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
};
static const std::vector<OpenGL::InternalFormat> g_color_sized_internalformats =
{
OpenGL::InternalFormat::R11F_G11F_B10F,
OpenGL::InternalFormat::R16,
OpenGL::InternalFormat::R16_SNorm,
OpenGL::InternalFormat::R16F,
OpenGL::InternalFormat::R16I,
OpenGL::InternalFormat::R16UI,
OpenGL::InternalFormat::R3_G3_B2,
OpenGL::InternalFormat::R32F,
OpenGL::InternalFormat::R32I,
OpenGL::InternalFormat::R32UI,
OpenGL::InternalFormat::R8,
OpenGL::InternalFormat::R8_SNorm,
OpenGL::InternalFormat::R8I,
OpenGL::InternalFormat::R8UI,
OpenGL::InternalFormat::RG16,
OpenGL::InternalFormat::RG16_SNorm,
OpenGL::InternalFormat::RG16F,
OpenGL::InternalFormat::RG16I,
OpenGL::InternalFormat::RG16UI,
OpenGL::InternalFormat::RG32F,
OpenGL::InternalFormat::RG32I,
OpenGL::InternalFormat::RG32UI,
OpenGL::InternalFormat::RG8,
OpenGL::InternalFormat::RG8_SNorm,
OpenGL::InternalFormat::RG8I,
OpenGL::InternalFormat::RG8UI,
OpenGL::InternalFormat::RGB10,
OpenGL::InternalFormat::RGB10_A2,
OpenGL::InternalFormat::RGB10_A2UI,
OpenGL::InternalFormat::RGB12,
OpenGL::InternalFormat::RGB16_SNorm,
OpenGL::InternalFormat::RGB16F,
OpenGL::InternalFormat::RGB16I,
OpenGL::InternalFormat::RGB16UI,
OpenGL::InternalFormat::RGB32F,
OpenGL::InternalFormat::RGB32I,
OpenGL::InternalFormat::RGB32UI,
OpenGL::InternalFormat::RGB4,
OpenGL::InternalFormat::RGB5,
OpenGL::InternalFormat::RGB5_A1,
OpenGL::InternalFormat::RGB8,
OpenGL::InternalFormat::RGB8_SNorm,
OpenGL::InternalFormat::RGB8I,
OpenGL::InternalFormat::RGB8UI,
OpenGL::InternalFormat::RGB9_E5,
OpenGL::InternalFormat::RGBA12,
OpenGL::InternalFormat::RGBA16,
OpenGL::InternalFormat::RGBA16F,
OpenGL::InternalFormat::RGBA16I,
OpenGL::InternalFormat::RGBA16UI,
OpenGL::InternalFormat::RGBA2,
OpenGL::InternalFormat::RGBA32F,
OpenGL::InternalFormat::RGBA32I,
OpenGL::InternalFormat::RGBA32UI,
OpenGL::InternalFormat::RGBA4,
OpenGL::InternalFormat::RGBA8,
OpenGL::InternalFormat::RGBA8_SNorm,
OpenGL::InternalFormat::RGBA8I,
OpenGL::InternalFormat::RGBA8UI,
OpenGL::InternalFormat::SRGB8,
OpenGL::InternalFormat::SRGB8_Alpha8,
};
static const std::vector<OpenGL::InternalFormat> g_ds_sized_internalformats =
{
OpenGL::InternalFormat::Depth_Component16,
OpenGL::InternalFormat::Depth_Component24,
OpenGL::InternalFormat::Depth_Component32,
OpenGL::InternalFormat::Depth_Component32_Float,
OpenGL::InternalFormat::Depth24_Stencil8,
OpenGL::InternalFormat::Depth32_Float_Stencil8,
};
OpenGL::InternalFormat OpenGL::GLFormats::get_best_fit_ds_internal_format(const uint32_t& in_depth_bits,
const uint32_t& in_stencil_bits)
{
OpenGL::InternalFormat result = OpenGL::InternalFormat::Unknown;
uint32_t result_n_depth_bits = 0;
uint32_t result_n_stencil_bits = 0;
vkgl_assert(in_depth_bits != 0 ||
in_stencil_bits != 0);
for (const auto& current_internalformat : g_ds_sized_internalformats)
{
const auto& internalformat_data_iterator = g_gl_internalformat_data.find(current_internalformat);
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
const auto& internalformat_data = internalformat_data_iterator->second;
if ((in_depth_bits == 0 && internalformat_data.component_size_depth != 0) ||
(in_stencil_bits == 0 && internalformat_data.component_size_stencil != 0) )
{
continue;
}
if ((in_depth_bits != 0 && internalformat_data.component_size_depth == 0) ||
(in_stencil_bits != 0 && internalformat_data.component_size_stencil == 0) )
{
continue;
}
if (result == OpenGL::InternalFormat::Unknown)
{
result = current_internalformat;
result_n_depth_bits = internalformat_data.component_size_depth;
result_n_stencil_bits = internalformat_data.component_size_stencil;
}
else
{
const auto current_depth_diff = abs(static_cast<int32_t>(internalformat_data.component_size_depth) - static_cast<int32_t>(in_depth_bits) );
const auto current_stencil_diff = abs(static_cast<int32_t>(internalformat_data.component_size_stencil) - static_cast<int32_t>(in_stencil_bits) );
const auto result_depth_diff = abs(static_cast<int32_t>(result_n_depth_bits) - static_cast<int32_t>(in_depth_bits) );
const auto result_stencil_diff = abs(static_cast<int32_t>(result_n_stencil_bits) - static_cast<int32_t>(in_stencil_bits) );
if (current_depth_diff + current_stencil_diff < result_depth_diff + result_stencil_diff)
{
result = current_internalformat;
result_n_depth_bits = internalformat_data.component_size_depth;
result_n_stencil_bits = internalformat_data.component_size_stencil;
}
}
}
vkgl_assert(result != OpenGL::InternalFormat::Unknown);
return result;
}
OpenGL::FormatDataType OpenGL::GLFormats::get_format_data_type_for_non_base_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
OpenGL::FormatDataType result = OpenGL::FormatDataType::Unknown;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.data_type;
}
return result;
}
uint32_t OpenGL::GLFormats::get_n_components_for_sized_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
uint32_t result = 0;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.n_components;
}
return result;
}
bool OpenGL::GLFormats::get_per_component_bit_size_for_sized_internal_format(const OpenGL::InternalFormat& in_format,
uint32_t* out_rgba_bit_size_ptr,
uint32_t* out_ds_size_ptr,
uint32_t* out_shared_size_ptr)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
out_rgba_bit_size_ptr[0] = internalformat_data_iterator->second.component_size_r;
out_rgba_bit_size_ptr[1] = internalformat_data_iterator->second.component_size_g;
out_rgba_bit_size_ptr[2] = internalformat_data_iterator->second.component_size_b;
out_rgba_bit_size_ptr[3] = internalformat_data_iterator->second.component_size_a;
out_ds_size_ptr [0] = internalformat_data_iterator->second.component_size_depth;
out_ds_size_ptr [1] = internalformat_data_iterator->second.component_size_stencil;
*out_shared_size_ptr = internalformat_data_iterator->second.component_size_shared;
result = true;
}
return result;
}
bool OpenGL::GLFormats::is_base_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_base_internal_format;
}
return result;
}
bool OpenGL::GLFormats::is_compressed_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_compressed_internal_format;
}
return result;
}
bool OpenGL::GLFormats::is_sized_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_sized_internal_format;
}
return result;
}
| 83.170918 | 240 | 0.52121 | kbiElude |
92b5fdc2de86dc8bea366b6becd7a3a38690d844 | 175 | cpp | C++ | ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp | sowrov/ChronicleLogger | 50678be7e2987211ab976d105fcd8549e5b8744b | [
"Apache-2.0"
] | 1 | 2020-03-05T10:36:48.000Z | 2020-03-05T10:36:48.000Z | ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp | sowrov/ChronicleLogger | 50678be7e2987211ab976d105fcd8549e5b8744b | [
"Apache-2.0"
] | null | null | null | ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp | sowrov/ChronicleLogger | 50678be7e2987211ab976d105fcd8549e5b8744b | [
"Apache-2.0"
] | null | null | null | #include "ThreadLocker.h"
#ifdef _P_THREAD
pthread_mutex_t Global_Mutex_Lock = PTHREAD_MUTEX_INITIALIZER;
#elif defined(_BOOST_THREAD)
boost::mutex Global_Mutex_Lock;
#endif
| 21.875 | 62 | 0.84 | sowrov |
92c1746c8d3a8d16fb209eedc62b2e190decd3cf | 1,142 | cpp | C++ | src/Utils/mpcdiUtils.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 3 | 2021-03-09T01:57:37.000Z | 2021-05-07T08:40:41.000Z | src/Utils/mpcdiUtils.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 1 | 2021-06-01T07:52:36.000Z | 2021-06-03T00:54:49.000Z | src/Utils/mpcdiUtils.cpp | scaredyfish/MPCDI | 1ddbc9abf99d39d4464afa2005934c325443cf28 | [
"BSD-3-Clause"
] | 4 | 2020-06-22T14:14:15.000Z | 2021-11-11T14:34:42.000Z | /* =========================================================================
Program: MPCDI Library
Language: C++
Date: $Date: 2012-08-22 20:19:58 -0400 (Wed, 22 Aug 2012) $
Version: $Revision: 19513 $
Copyright (c) 2013 Scalable Display Technologies, Inc.
All Rights Reserved.
The MPCDI Library is distributed under the BSD license.
Please see License.txt distributed with this package.
===================================================================auto== */
#include "mpcdiUtils.h"
using namespace mpcdi;
std::string Utils::ProfileVersionToString(const ProfileVersion& pv)
{
std::stringstream ss;
ss << pv.MajorVersion << "." << pv.MinorVersion;
return ss.str();
}
MPCDI_Error Utils::StringToProfileVersion(const std::string &text, ProfileVersion& pv)
{
pv = ProfileVersion();
size_t pos = text.find_first_of(".");
if (pos==std::string::npos)
return MPCDI_FAILURE;
pv.MajorVersion = StringToNumber<int>(text.substr(0,pos));
pv.MinorVersion = 0;
if (text.size() >= pos+1)
pv.MinorVersion = StringToNumber<int>(text.substr(pos+1,text.length()));
return MPCDI_SUCCESS;
}
| 27.853659 | 86 | 0.60683 | scaredyfish |
92c2194c831fa6102456e80f868b6c6f385ccb51 | 1,508 | cpp | C++ | ex03/main.cpp | Gundul42/CPP_mod03 | 822c83ebca93e9a519bc8629c58ac39ef02365d6 | [
"MIT"
] | null | null | null | ex03/main.cpp | Gundul42/CPP_mod03 | 822c83ebca93e9a519bc8629c58ac39ef02365d6 | [
"MIT"
] | null | null | null | ex03/main.cpp | Gundul42/CPP_mod03 | 822c83ebca93e9a519bc8629c58ac39ef02365d6 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: graja <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/12 14:02:52 by graja #+# #+# */
/* Updated: 2022/02/17 10:05:47 by graja ### ########.fr */
/* */
/* ************************************************************************** */
#include "DiamondTrap.hpp"
int main(void)
{
DiamondTrap test;
DiamondTrap lala("LaLa");
DiamondTrap kuemmel(test);
//attack method overloaded by ScavTrap
lala.attack("LOLO");
test.attack("TestTrapper");
//methods from ClapTrap
lala.beRepaired(20);
kuemmel.takeDamage(10);
//method ScavTrap
test.guardGate();
//method FragTrap
test.highFivesGuys();
//method DiamondTrap
test.whoAmI();
lala.whoAmI();
//operator overload for =
test = lala;
//check if it works
test.whoAmI();
std::cout << "--------------------------------------------";
std::cout << std::endl << std::endl;
return (0);
}
| 31.416667 | 80 | 0.322944 | Gundul42 |
92c35370d69641889736865a3d06ccea318d9824 | 8,562 | inl | C++ | src/core/containers/internal/hash_map.inl | JakubLukas/NewEngine | 38ea585a37347ec0630673b9d4a7f948e4dc1477 | [
"MIT"
] | 4 | 2017-10-04T11:38:48.000Z | 2021-11-16T20:35:37.000Z | src/core/containers/internal/hash_map.inl | JakubLukas/NewEngine | 38ea585a37347ec0630673b9d4a7f948e4dc1477 | [
"MIT"
] | 4 | 2018-06-07T23:27:02.000Z | 2018-10-18T12:19:57.000Z | src/core/containers/internal/hash_map.inl | JakubLukas/NewEngine | 38ea585a37347ec0630673b9d4a7f948e4dc1477 | [
"MIT"
] | null | null | null |
namespace Veng
{
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value)
: key(key)
, value(value)
, next(INVALID_INDEX)
{}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value, int next)
: key(key)
, value(value)
, next(next)
{}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(HashNode&& other)
: key(other.key)
, value(other.value)
, next(other.next)
{
other.next = INVALID_INDEX;
}
template<class KeyType, class ValueType, class Hasher>
typename HashMap<KeyType, ValueType, Hasher>::HashNode& HashMap<KeyType, ValueType, Hasher>::HashNode::operator=(typename HashMap<KeyType, ValueType, Hasher>::HashNode&& other)
{
KeyType k = key;
ValueType v = value;
key = other.key;
value = other.value;
next = other.next;
other.key = k;
other.value = v;
other.next = INVALID_INDEX;
return *this;
}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::HashMap(Allocator& allocator)
: m_allocator(allocator)
{}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::HashMap(HashMap<KeyType, ValueType, Hasher>&& other)
: m_allocator(other.m_allocator)
, m_buckets(other.m_buckets)
, m_bucketSize(other.m_bucketSize)
, m_table(other.m_table)
, m_size(other.m_size)
{
other.m_buckets = nullptr;
other.m_bucketSize = 0;
other.m_table = nullptr;
other.m_size = 0;
}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>& HashMap<KeyType, ValueType, Hasher>::operator=(HashMap<KeyType, ValueType, Hasher>&& other)
{
int* buckets = m_buckets;
unsigned bucketSize = m_bucketSize;
HashNode* table = m_table;
unsigned size = m_size;
m_allocator = other.m_allocator;
m_buckets = other.m_buckets;
m_bucketSize = other.m_bucketSize;
m_table = other.m_table;
m_size = other.m_size;
other.m_buckets = buckets;
other.m_bucketSize = bucketSize;
other.m_table = table;
other.m_size = size;
return *this;
}
template<class KeyType, class ValueType, class Hasher>
HashMap<KeyType, ValueType, Hasher>::~HashMap()
{
for (unsigned i = 0; i < m_size; ++i)
{
DELETE_PLACEMENT(m_table + i);
}
if (m_buckets != nullptr)
m_allocator.Deallocate(m_buckets);
}
template<class KeyType, class ValueType, class Hasher>
void HashMap<KeyType, ValueType, Hasher>::Clear()
{
for (unsigned i = 0; i < m_bucketSize; ++i)
{
m_buckets[i] = INVALID_INDEX;
}
for (unsigned i = 0; i < m_size; ++i)
{
DELETE_PLACEMENT(m_table + i);
}
m_size = 0;
}
template<class KeyType, class ValueType, class Hasher>
typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() { return m_table; }
template<class KeyType, class ValueType, class Hasher>
typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() { return m_table + m_size; }
template<class KeyType, class ValueType, class Hasher>
typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() const { return m_table; }
template<class KeyType, class ValueType, class Hasher>
typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() const { return m_table + m_size; }
template<class KeyType, class ValueType, class Hasher>
bool HashMap<KeyType, ValueType, Hasher>::Find(const KeyType& key, ValueType*& value) const
{
if (m_size == 0)
return false;
unsigned bucketIdx = GetIndex(key);
if (m_buckets[bucketIdx] == INVALID_INDEX)
return false;
HashNode* node = &m_table[m_buckets[bucketIdx]];
while (node->next != INVALID_INDEX && node->key != key)
{
node = &m_table[node->next];
}
if (node->key == key)
{
value = &node->value;
return true;
}
else
{
return false;
}
}
template<class KeyType, class ValueType, class Hasher>
ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(const KeyType& key, const ValueType& value)
{
if (m_bucketSize == 0)
Rehash(INITIAL_SIZE);
if ((m_size / (float)m_bucketSize) * 100 > MAX_FACTOR)
Rehash(m_bucketSize * ENLARGE_MULTIPLIER);
unsigned bucketIdx = GetIndex(key);
return Insert(bucketIdx, key, value);
}
template<class KeyType, class ValueType, class Hasher>
bool HashMap<KeyType, ValueType, Hasher>::Erase(const KeyType& key)
{
unsigned bucketIdx = GetIndex(key);
if (m_buckets[bucketIdx] == INVALID_INDEX)
return false;
int* pointingIdx = &m_buckets[bucketIdx];
HashNode* node = &m_table[*pointingIdx];
while (node->next != INVALID_INDEX && node->key != key)
{
pointingIdx = &node->next;
node = &m_table[node->next];
}
if (node->key != key)
return false;
int freeNodeIdx = *pointingIdx;
*pointingIdx = node->next;
DELETE_PLACEMENT(node);
m_size--;
if(m_size > 0 && freeNodeIdx != m_size)
{
//fill up hole in m_table
HashNode& lastNode = m_table[m_size];
unsigned lastNodeBucketIdx = GetIndex(lastNode.key);
pointingIdx = &m_buckets[lastNodeBucketIdx];
while(m_table[*pointingIdx].key != lastNode.key)
{
pointingIdx = &(m_table[*pointingIdx].next);
}
*pointingIdx = freeNodeIdx;
NEW_PLACEMENT(node, HashNode)(Utils::Move(lastNode));
//DELETE_PLACEMENT(&lastNode);
}
return true;
}
template<class KeyType, class ValueType, class Hasher>
void HashMap<KeyType, ValueType, Hasher>::Rehash(unsigned bucketSize)
{
ASSERT(bucketSize > m_bucketSize);
int* oldBuckets = m_buckets;
unsigned oldBucketSize = m_bucketSize;
HashNode* oldTable = m_table;
unsigned oldSize = m_size;
m_bucketSize = bucketSize;
m_size = 0;
void* data = m_allocator.Allocate(bucketSize * (sizeof(int) + sizeof(HashNode)) + alignof(HashNode), alignof(int));
m_buckets = static_cast<int*>(data);
m_table = static_cast<HashNode*>(AlignPointer(m_buckets + bucketSize, alignof(HashNode)));
for (unsigned i = 0; i < m_bucketSize; ++i)
{
m_buckets[i] = INVALID_INDEX;
}
for (unsigned i = 0; i < oldSize; ++i)
{
HashNode& node = oldTable[i];
unsigned idx = GetIndex(node.key);
Insert(idx, node.key, node.value);
}
if (oldBuckets != nullptr)
m_allocator.Deallocate(oldBuckets);
}
template<class KeyType, class ValueType, class Hasher>
size_t HashMap<KeyType, ValueType, Hasher>::GetBucketsSize() const { return m_bucketSize; }
template<class KeyType, class ValueType, class Hasher>
size_t HashMap<KeyType, ValueType, Hasher>::GetSize() const { return m_size; }
template<class KeyType, class ValueType, class Hasher>
ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(unsigned bucketIdx, const KeyType& key, const ValueType& value)
{
ASSERT(m_size < m_bucketSize);
if (m_buckets[bucketIdx] == INVALID_INDEX)
{
HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value);
m_buckets[bucketIdx] = m_size++;
return &newNode->value;
}
HashNode* node = &m_table[m_buckets[bucketIdx]];
while (node->key != key && node->next != INVALID_INDEX)
{
node = &m_table[node->next];
}
if (node->key == key)
{
return nullptr;
}
else
{
HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value);
node->next = m_size++;
return &newNode->value;
}
}
template<class KeyType, class ValueType, class Hasher>
unsigned HashMap<KeyType, ValueType, Hasher>::GetIndex(const KeyType& key) const
{
auto hash = Hasher::get(key);
return hash % m_bucketSize;
}
template<class KeyType, class ValueType, class Hasher>
typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::GetNode(unsigned index)
{
ASSERT(index < m_bucketSize);
return &m_table[index];
}
template<class KeyType, class ValueType, class Hasher>
inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* begin(HashMap<KeyType, ValueType, Hasher>& a)
{
return a.Begin();
}
template<class KeyType, class ValueType, class Hasher>
inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* end(HashMap<KeyType, ValueType, Hasher>& a)
{
return a.End();
}
template<class KeyType, class ValueType, class Hasher>
inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* begin(const HashMap<KeyType, ValueType, Hasher>& a)
{
return a.Begin();
}
template<class KeyType, class ValueType, class Hasher>
inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* end(const HashMap<KeyType, ValueType, Hasher>& a)
{
return a.End();
}
} | 26.103659 | 176 | 0.726583 | JakubLukas |
92c3decbf871b019c6694afd8c9bea1858e7186f | 968 | cpp | C++ | PlacementQuestions/OYO/decodingbottomup.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | PlacementQuestions/OYO/decodingbottomup.cpp | UltraProton/Placement-Prepration | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | 3 | 2020-05-08T18:02:51.000Z | 2020-05-09T08:37:35.000Z | PlacementQuestions/OYO/decodingbottomup.cpp | UltraProton/PlacementPrep | cc70f174c4410c254ce0469737a884fffdc81164 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int decodings(string &str);
int main(){
string str="";
cin>>str;
cout<<decodings(str)<<endl;
return 0;
}
int decodings(string &str){
int n=str.size();
/*
Here just do the reverse process of memoization and get the ans in the bottom up manner. Compare it with the memoized version and you
will get more clarity.
*/
vector<int> dp(n+1,0);
//base case
dp[0]=1;
dp[1]=1;
//Here we are going to fill the table bottomup both the conditions are same here also just the order is different and even if you look
//closely then you will see that the order of filling the table is same in both the cases it's just difference in methodology
for(int i=2;i<=n;i++){
if(str[i-1]>'0'){
dp[i]+=dp[i-1];
}
if(str[i-2]=='1' || (str[i-2]=='2' && str[i-1]<'7')){
dp[i]+=dp[i-2];
}
}
return dp[n];
} | 24.2 | 138 | 0.578512 | UltraProton |
92c4de0efac80a39026d318d969880de4dc60da2 | 4,966 | cpp | C++ | aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/inspector2/model/Ec2InstanceAggregation.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Inspector2
{
namespace Model
{
Ec2InstanceAggregation::Ec2InstanceAggregation() :
m_amisHasBeenSet(false),
m_instanceIdsHasBeenSet(false),
m_instanceTagsHasBeenSet(false),
m_operatingSystemsHasBeenSet(false),
m_sortBy(Ec2InstanceSortBy::NOT_SET),
m_sortByHasBeenSet(false),
m_sortOrder(SortOrder::NOT_SET),
m_sortOrderHasBeenSet(false)
{
}
Ec2InstanceAggregation::Ec2InstanceAggregation(JsonView jsonValue) :
m_amisHasBeenSet(false),
m_instanceIdsHasBeenSet(false),
m_instanceTagsHasBeenSet(false),
m_operatingSystemsHasBeenSet(false),
m_sortBy(Ec2InstanceSortBy::NOT_SET),
m_sortByHasBeenSet(false),
m_sortOrder(SortOrder::NOT_SET),
m_sortOrderHasBeenSet(false)
{
*this = jsonValue;
}
Ec2InstanceAggregation& Ec2InstanceAggregation::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("amis"))
{
Array<JsonView> amisJsonList = jsonValue.GetArray("amis");
for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex)
{
m_amis.push_back(amisJsonList[amisIndex].AsObject());
}
m_amisHasBeenSet = true;
}
if(jsonValue.ValueExists("instanceIds"))
{
Array<JsonView> instanceIdsJsonList = jsonValue.GetArray("instanceIds");
for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex)
{
m_instanceIds.push_back(instanceIdsJsonList[instanceIdsIndex].AsObject());
}
m_instanceIdsHasBeenSet = true;
}
if(jsonValue.ValueExists("instanceTags"))
{
Array<JsonView> instanceTagsJsonList = jsonValue.GetArray("instanceTags");
for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex)
{
m_instanceTags.push_back(instanceTagsJsonList[instanceTagsIndex].AsObject());
}
m_instanceTagsHasBeenSet = true;
}
if(jsonValue.ValueExists("operatingSystems"))
{
Array<JsonView> operatingSystemsJsonList = jsonValue.GetArray("operatingSystems");
for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex)
{
m_operatingSystems.push_back(operatingSystemsJsonList[operatingSystemsIndex].AsObject());
}
m_operatingSystemsHasBeenSet = true;
}
if(jsonValue.ValueExists("sortBy"))
{
m_sortBy = Ec2InstanceSortByMapper::GetEc2InstanceSortByForName(jsonValue.GetString("sortBy"));
m_sortByHasBeenSet = true;
}
if(jsonValue.ValueExists("sortOrder"))
{
m_sortOrder = SortOrderMapper::GetSortOrderForName(jsonValue.GetString("sortOrder"));
m_sortOrderHasBeenSet = true;
}
return *this;
}
JsonValue Ec2InstanceAggregation::Jsonize() const
{
JsonValue payload;
if(m_amisHasBeenSet)
{
Array<JsonValue> amisJsonList(m_amis.size());
for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex)
{
amisJsonList[amisIndex].AsObject(m_amis[amisIndex].Jsonize());
}
payload.WithArray("amis", std::move(amisJsonList));
}
if(m_instanceIdsHasBeenSet)
{
Array<JsonValue> instanceIdsJsonList(m_instanceIds.size());
for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex)
{
instanceIdsJsonList[instanceIdsIndex].AsObject(m_instanceIds[instanceIdsIndex].Jsonize());
}
payload.WithArray("instanceIds", std::move(instanceIdsJsonList));
}
if(m_instanceTagsHasBeenSet)
{
Array<JsonValue> instanceTagsJsonList(m_instanceTags.size());
for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex)
{
instanceTagsJsonList[instanceTagsIndex].AsObject(m_instanceTags[instanceTagsIndex].Jsonize());
}
payload.WithArray("instanceTags", std::move(instanceTagsJsonList));
}
if(m_operatingSystemsHasBeenSet)
{
Array<JsonValue> operatingSystemsJsonList(m_operatingSystems.size());
for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex)
{
operatingSystemsJsonList[operatingSystemsIndex].AsObject(m_operatingSystems[operatingSystemsIndex].Jsonize());
}
payload.WithArray("operatingSystems", std::move(operatingSystemsJsonList));
}
if(m_sortByHasBeenSet)
{
payload.WithString("sortBy", Ec2InstanceSortByMapper::GetNameForEc2InstanceSortBy(m_sortBy));
}
if(m_sortOrderHasBeenSet)
{
payload.WithString("sortOrder", SortOrderMapper::GetNameForSortOrder(m_sortOrder));
}
return payload;
}
} // namespace Model
} // namespace Inspector2
} // namespace Aws
| 29.384615 | 130 | 0.751108 | perfectrecall |
92c53c9df52cadbe122e3624411e3485c05c45f3 | 1,587 | hpp | C++ | include/nifty/meta/tuple.hpp | DerThorsten/nifty_meta | d31d35f54b8bf252518bee18eacaa696fee82e9b | [
"MIT"
] | null | null | null | include/nifty/meta/tuple.hpp | DerThorsten/nifty_meta | d31d35f54b8bf252518bee18eacaa696fee82e9b | [
"MIT"
] | null | null | null | include/nifty/meta/tuple.hpp | DerThorsten/nifty_meta | d31d35f54b8bf252518bee18eacaa696fee82e9b | [
"MIT"
] | null | null | null | #pragma once
#include <utility>
#include <tuple>
#include <type_traits>
#include "nifty/meta/integral_constant.hpp"
namespace nifty{
namespace meta{
// find the position of a type in a tuple
template <class T, class Tuple>
struct TupleTypeIndex;
template <class T, class... Types>
struct TupleTypeIndex<T, std::tuple<T, Types...>>
: SizeT<0>{
};
template <class T, class U, class... Types>
struct TupleTypeIndex<T, std::tuple<U, Types...>>
: SizeT<1 + TupleTypeIndex<T, std::tuple<Types...>>::value>{
};
template<class TUPLE, template<typename ...> typename C>
struct TransformTuple;
template<class ... TUPLE_ARGS , template< typename ... ARGS> class C>
struct TransformTuple<std::tuple<TUPLE_ARGS ...>, C >{
typedef std::tuple< C<TUPLE_ARGS> ...> type;
};
///\cond
namespace detail{
template<class INDEX_SEQUENCE, template<std::size_t I> typename C>
struct GenerateTupleImpl;
template<std::size_t... Ints, template<std::size_t I> typename C>
struct GenerateTupleImpl<std::index_sequence<Ints ... >, C>{
typedef std::tuple<C<Ints> ...> type;
};
}
///\endcond
template<std::size_t N, template<std::size_t I> typename C>
struct GenerateTuple : detail::GenerateTupleImpl<std::make_index_sequence<N>, C>{
};
template<std::size_t N, class T>
struct GenerateUniformTuple{
template<std::size_t I>
using Helper = T;
typedef typename GenerateTuple<N, Helper>::type type;
};
}
} | 24.415385 | 90 | 0.626969 | DerThorsten |
92c886868c9ee688b61549cd38d011f4d4e9cc10 | 4,506 | cpp | C++ | src/mongo/dbtests/counttests.cpp | corefan/mongo | c949cad1fa6e4cb26693748b1751f4fd2e6113b8 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/counttests.cpp | corefan/mongo | c949cad1fa6e4cb26693748b1751f4fd2e6113b8 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/counttests.cpp | corefan/mongo | c949cad1fa6e4cb26693748b1751f4fd2e6113b8 | [
"Apache-2.0"
] | 1 | 2021-02-28T12:03:02.000Z | 2021-02-28T12:03:02.000Z | // counttests.cpp : count.{h,cpp} unit tests.
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../db/ops/count.h"
#include "../db/cursor.h"
#include "../db/pdfile.h"
#include "dbtests.h"
namespace CountTests {
class Base {
Lock::DBWrite lk;
Client::Context _context;
public:
Base() : lk(ns()), _context( ns() ) {
addIndex( fromjson( "{\"a\":1}" ) );
}
~Base() {
try {
boost::shared_ptr<Cursor> c = theDataFileMgr.findAll( ns() );
vector< DiskLoc > toDelete;
for(; c->ok(); c->advance() )
toDelete.push_back( c->currLoc() );
for( vector< DiskLoc >::iterator i = toDelete.begin(); i != toDelete.end(); ++i )
theDataFileMgr.deleteRecord( ns(), i->rec(), *i, false );
DBDirectClient cl;
cl.dropIndexes( ns() );
}
catch ( ... ) {
FAIL( "Exception while cleaning up collection" );
}
}
protected:
static const char *ns() {
return "unittests.counttests";
}
static void addIndex( const BSONObj &key ) {
BSONObjBuilder b;
b.append( "name", key.firstElementFieldName() );
b.append( "ns", ns() );
b.append( "key", key );
BSONObj o = b.done();
stringstream indexNs;
indexNs << "unittests.system.indexes";
theDataFileMgr.insert( indexNs.str().c_str(), o.objdata(), o.objsize() );
}
static void insert( const char *s ) {
insert( fromjson( s ) );
}
static void insert( const BSONObj &o ) {
theDataFileMgr.insert( ns(), o.objdata(), o.objsize() );
}
};
class CountBasic : public Base {
public:
void run() {
insert( "{\"a\":\"b\"}" );
BSONObj cmd = fromjson( "{\"query\":{}}" );
string err;
ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) );
}
};
class CountQuery : public Base {
public:
void run() {
insert( "{\"a\":\"b\"}" );
insert( "{\"a\":\"b\",\"x\":\"y\"}" );
insert( "{\"a\":\"c\"}" );
BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"}}" );
string err;
ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) );
}
};
class CountFields : public Base {
public:
void run() {
insert( "{\"a\":\"b\"}" );
insert( "{\"c\":\"d\"}" );
BSONObj cmd = fromjson( "{\"query\":{},\"fields\":{\"a\":1}}" );
string err;
ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) );
}
};
class CountQueryFields : public Base {
public:
void run() {
insert( "{\"a\":\"b\"}" );
insert( "{\"a\":\"c\"}" );
insert( "{\"d\":\"e\"}" );
BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"},\"fields\":{\"a\":1}}" );
string err;
ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) );
}
};
class CountIndexedRegex : public Base {
public:
void run() {
insert( "{\"a\":\"b\"}" );
insert( "{\"a\":\"c\"}" );
BSONObj cmd = fromjson( "{\"query\":{\"a\":/^b/}}" );
string err;
ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) );
}
};
class All : public Suite {
public:
All() : Suite( "count" ) {
}
void setupTests() {
add< CountBasic >();
add< CountQuery >();
add< CountFields >();
add< CountQueryFields >();
add< CountIndexedRegex >();
}
} myall;
} // namespace CountTests
| 31.51049 | 97 | 0.46893 | corefan |
92c8fb05fa571187ba977c80c16b54df073d7bc5 | 771 | cc | C++ | src/InsetOp.cc | pbrier/Mandoline | bb517e7e5ba531d4e20c2474a53ee521dd1d1642 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2017-01-05T06:40:55.000Z | 2017-01-05T06:40:55.000Z | src/InsetOp.cc | pbrier/Mandoline | bb517e7e5ba531d4e20c2474a53ee521dd1d1642 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/InsetOp.cc | pbrier/Mandoline | bb517e7e5ba531d4e20c2474a53ee521dd1d1642 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | //
// InsetOp.cc
// Mandoline
//
// Created by GM on 11/24/10.
// Copyright 2010 Belfry DevWorks. All rights reserved.
//
#include "InsetOp.h"
#include "BGL/BGL.h"
#include "SlicingContext.h"
#include "CarvedSlice.h"
InsetOp::~InsetOp()
{
}
void InsetOp::main()
{
if ( isCancelled ) return;
if ( NULL == context ) return;
if ( NULL == slice ) return;
double extWidth = context->standardExtrusionWidth();
int shells = context->perimeterShells;
slice->perimeter.inset(shells*extWidth, slice->infillMask);
for (int i = 0; i < shells; i++) {
BGL::CompoundRegion compReg;
slice->perimeter.inset((i+0.5)*extWidth, compReg);
slice->shells.push_back(compReg);
}
slice->state = INSET;
if ( isCancelled ) return;
}
| 17.930233 | 63 | 0.642023 | pbrier |
92da1c435775bc9520949451a04473e003db78f7 | 1,676 | cpp | C++ | bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp | 5reichar/bitbots_kick_engine | 0817f4f0a206de6f0f01a0cedfe201f62e677a11 | [
"BSD-3-Clause"
] | null | null | null | #include "throws/throw_curves/throw_movement_position_only.h"
namespace bitbots_throw{
ThrowMovementPositionOnly::ThrowMovementPositionOnly(std::shared_ptr<ThrowMaterial> material)
: ThrowMovement(material){
}
void ThrowMovementPositionOnly::add_movement_prepare_throw(){
throw_start_time_ = trajectory_time_;
ThrowMovement::add_movement_prepare_throw();
}
void ThrowMovementPositionOnly::add_movement_throw(){
// get Values
auto current_throw_release_time = trajectory_time_;
double duration_throw = sp_service_->get_movement_time_throw();
duration_throw -= sp_service_->get_movement_offset_move_arms_away_from_ball();
Struct3dRPY velocity = sp_service_->calculate_throw_velocity(duration_throw);
auto left_arm_throw_release = sp_service_->get_left_arm_throw_release();
auto diff = left_arm_throw_release.x_ - sp_service_->get_left_arm_ball_behind_head().x_;
trajectory_time_ = throw_start_time_ + (diff / velocity.x_);
//// Movement
////==== Release ball
add_to_left_hand( left_arm_throw_release);
add_to_right_hand(sp_service_->get_right_arm_throw_release());
////==== Move arms away from the ball
trajectory_time_ += sp_service_->get_movement_offset_move_arms_away_from_ball();
add_to_left_hand(sp_service_->get_left_arm_move_away_from_ball(velocity.x_));
add_to_right_hand(sp_service_->get_right_arm_move_away_from_ball(velocity.x_));
if(current_throw_release_time > trajectory_time_){
trajectory_time_ = current_throw_release_time;
}
}
} //bitbots_throw | 42.974359 | 97 | 0.73389 | 5reichar |
92ddce5f43a5131e26d6b3cb705efcb8c1bfe597 | 82 | cpp | C++ | 1-15/thefunction.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | 1-15/thefunction.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | 1-15/thefunction.cpp | domijin/ComPhy | 0dea6d7b09eb4880b7f2d8f55c321c827e713488 | [
"MIT"
] | null | null | null | #include<math.h>
double cubeandmult(double u, double v)
{
return(pow(u,3)*v);
}
| 13.666667 | 38 | 0.670732 | domijin |
92e010291c2ea4a5cc83c09327e575f3bde61fe4 | 627 | cpp | C++ | 1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp | Iluvata/PAT-Advanced-Level-Practice | 08a02e82eef30c81ed9ef8e4f327f7b2a9535582 | [
"MIT"
] | 2 | 2020-10-17T12:26:42.000Z | 2021-11-12T08:47:10.000Z | 1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp | Iluvata/PAT-Advanced-Level-Practice | 08a02e82eef30c81ed9ef8e4f327f7b2a9535582 | [
"MIT"
] | 1 | 2020-10-19T11:31:55.000Z | 2020-10-19T11:31:55.000Z | 1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp | Iluvata/PAT-Advanced-Level-Practice | 08a02e82eef30c81ed9ef8e4f327f7b2a9535582 | [
"MIT"
] | 1 | 2020-10-18T01:08:34.000Z | 2020-10-18T01:08:34.000Z | // 1128_N_Queens_Puzzle.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
int main()
{
int k, n;
cin >> k;
for (int i = 0; i < k; ++i) {
cin >> n;
vector<bool> row(n + 1, false);
map<int, bool> diagsum;
map<int, bool> diagdel;
int p;
bool flag = true;
for (int j = 1; j <= n; ++j) {
cin >> p;
if (row[p] || diagsum[j + p] || diagdel[j - p])
flag = false;
row[p] = diagsum[j + p] = diagdel[j - p] = true;
}
if (flag) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
}
| 16.945946 | 61 | 0.527911 | Iluvata |
2baf016f451c314c8757506b9861d33fd0efd790 | 34,785 | cpp | C++ | aoiduino/esp-esp8266.cpp | gunjouinc/Aoiduino | f2b954010672d60bec69d6019cd1e77a14d21046 | [
"MIT"
] | null | null | null | aoiduino/esp-esp8266.cpp | gunjouinc/Aoiduino | f2b954010672d60bec69d6019cd1e77a14d21046 | [
"MIT"
] | null | null | null | aoiduino/esp-esp8266.cpp | gunjouinc/Aoiduino | f2b954010672d60bec69d6019cd1e77a14d21046 | [
"MIT"
] | null | null | null | /******************************************************************************
**
** Copyright 2009-2020 Gunjou Inc. All rights reserved.
** Contact: Gunjou Inc. ([email protected])
**
** This software is released under the MIT License.
** https://github.com/gunjouinc/Aoiduino/blob/master/LICENSE
**
******************************************************************************/
#ifdef ESP8266
/** Esp WiFi timeout */
#define ESP_WIFI_TIMEOUT 30000
#include "esp-esp8266.h"
/* Flash */
#include <FS.h>
FS *EspStorage = &SPIFFS;
/* RTC */
#include <time.h>
/* Servo */
#include <Servo.h>
/* Ticker */
#include <Ticker.h>
Ticker ticker;
Ticker watchdog;
uint32_t watchdogSecond = 0;
uint32_t watchdogMills = 0;
/* WiFi */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
WiFiClient wifiClient;
WiFiClientSecure wifiClientSecure;
/** File mode - append */
#define _FILE_APPEND_ "a"
/** File mode - read */
#define _FILE_READ_ "r"
/** File mode - write */
#define _FILE_WRITE_ "w"
/** Flash root path */
#define _FLASH_ "/mnt/spif"
/**
* @namespace AoiEsp
* @brief Aoi esp classes.
*/
namespace AoiEsp
{
// Static variables.
AoiBase::FunctionTable *Esp8266::m_functionTable = 0;
Servo *Esp8266::m_servo = 0;
int Esp8266::m_servoCount = 0;
/**
* @fn Esp8266::Esp8266( void )
*
* Constructor. Member variables are initialized.
*/
Esp8266::Esp8266( void )
{
if( m_functionTable )
return;
// Sets function table, If there is no instance.
AoiBase::FunctionTable ftl[] =
{
// ^ Please set your function to use.
/* Arduino Core */
{ "analogRead", &Arduino::analogRead },
{ "analogWrite", &Arduino::analogWrite },
{ "delay", &Arduino::delay },
{ "delayMicroseconds", &Arduino::delayMicroseconds },
{ "digitalRead", &Arduino::digitalRead },
{ "digitalWrite", &Arduino::digitalWrite },
{ "echo", &Arduino::echo },
{ "micros", &Arduino::micros },
{ "millis", &Arduino::millis },
{ "noTone", &Arduino::noTone },
{ "pinMode", &Arduino::pinMode },
{ "tone", &Arduino::tone },
{ "yield", &Arduino::yield },
/* File */
{ ">", &Esp8266::create },
{ ">>", &Esp8266::append },
{ "cat", &Esp8266::read },
{ "cd", &Esp8266::cd },
{ "format", &Esp8266::format },
{ "ll", &Esp8266::ll },
{ "mkdir", &Esp8266::mkdir },
{ "pwd", &Esp8266::pwd },
{ "rm", &Esp8266::remove },
{ "rmdir", &Esp8266::rmdir },
{ "touch", &Esp8266::touch },
/* LowPower */
{ "deepSleep", &Esp8266::deepSleep },
{ "dmesg", &Esp8266::dmesg },
{ "reboot", &Esp8266::restart },
/* HTTP */
{ "httpBegin", &Esp8266::httpBegin },
{ "httpGet", &AoiUtil::Http::httpGet },
{ "httpPost", &Esp8266::httpPost },
/* RTC */
{ "date", &Esp8266::date },
/* Servo */
{ "servoAttach", &Esp8266::servoAttach },
{ "servoBegin", &Esp8266::servoBegin },
{ "servoEnd", &Esp8266::servoEnd },
{ "servoWriteMicroseconds", &Esp8266::servoWriteMicroseconds },
/* Watchdog */
{ "watchdogBegin", &Esp8266::watchdogBegin },
{ "watchdogEnd", &Esp8266::watchdogEnd },
{ "watchdogKick", &Esp8266::watchdogKick },
{ "watchdogTimeleft", &Esp8266::watchdogTimeleft },
/* WiFi */
{ "ifconfig", &Esp8266::ifConfig },
{ "iwlist", &Esp8266::wifiScanNetworks },
{ "wifiBegin", &Esp8266::wifiBegin },
{ "wifiEnd", &Esp8266::wifiEnd },
{ "wifiRtc", &Esp8266::wifiRtc },
// $ Please set your function to use.
{ "", 0 }
};
// Creates function table to avoid kernel panic.
uint8_t c = sizeof(ftl) / sizeof(AoiBase::FunctionTable);
m_functionTable = Arduino::functionTable( ftl, c );
// Initalize library
/* File */
SPIFFS.begin();
/* HTTP */
http = &wifiClient;
}
/**
* @fn Esp8266::~Esp8266( void )
*
* Destructor. Member variables are deleted.
*/
Esp8266::~Esp8266( void )
{
}
/**
* @fn String Esp8266::className( void )
*
* @see bool AbstractBase::className( void )
*/
String Esp8266::className( void )
{
return String( "Esp8266" );
}
/**
* @fn bool Esp8266::isExist( const String &function )
*
* @see bool AbstractBase::isExist( const String &function )
*/
bool Esp8266::isExist( const String &function )
{
return Arduino::isExist( function, m_functionTable );
}
/**
* @fn String Esp8266::practice( StringList *args )
*
* @see String AbstractBase::practice( StringList *args )
*/
String Esp8266::practice( StringList *args )
{
return Arduino::practice( args, m_functionTable );
}
/**
* @fn String Esp8266::usages( void )
*
* @see String AbstractBase::usages( void )
*/
String Esp8266::usages( void )
{
return Arduino::usages( m_functionTable );
}
/**
* @fn StringList* Esp8266::rcScript( const String &index )
*
* @see StringList* AbstractBase::rcScript( const String &index )
*/
StringList* Esp8266::rcScript( const String &index )
{
StringList *sl = 0;
String s = appendRootPath( index );
if( !EspStorage->exists(s) )
return sl;
File f = EspStorage->open( s, _FILE_READ_ );
if( f )
{
String s = f.readString();
f.close();
sl = split( s, String(_lf) );
}
return sl;
}
/**
* @fn String Esp8266::append( StringList *args )
*
* Append value on current device.
*
* @param[in] args Reference to arguments.
* @return value string.
*/
String Esp8266::append( StringList *args )
{
String s, t;
int c = count( args );
if( c<2 )
s = usage( ">> file .+" );
else
{
t = appendRootPath( _a(0) );
// Create file if need
if( !EspStorage->exists(t) )
{
File w = EspStorage->open( t, _FILE_WRITE_ );
w.close();
}
File f = EspStorage->open( t, _FILE_APPEND_ );
if( 0<f.size() )
f.print( _lf );
for( int i=1; i<c; i++ )
{
if( 1<i )
f.print( STR_SPACE );
f.print( _a(i) );
}
f.close();
// Re-open, Can't practice f.seek( 0 )
f = EspStorage->open( t, _FILE_READ_ );
s = prettyPrintTo( "value", f.readString() );
f.close();
}
return s;
}
/**
* @fn String Esp8266::cd( StringList *args )
*
* Change device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::cd( StringList *args )
{
String s;
String path;
switch( count(args) )
{
case 1:
path = _a( 0 );
if( (path==_FLASH_) || (path=="/") )
EspStorage = &SPIFFS;
else
s = cd( 0 );
break;
default:
s = usage( "cd ("+String(_FLASH_)+")" );
break;
}
return s;
}
/**
* @fn String Esp8266::create( StringList *args )
*
* Create value on current device.
*
* @param[in] args Reference to arguments.
* @return value string.
*/
String Esp8266::create( StringList *args )
{
String s, t;
int c = count( args );
if( c<2 )
s = usage( "> file .+" );
else
{
t = appendRootPath( _a(0) );
if( EspStorage->exists(t) )
EspStorage->remove( t );
s = append( args );
}
return s;
}
/**
* @fn String Esp8266::format( StringList *args )
*
* Format file device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::format( StringList *args )
{
String s;
String path;
switch( count(args) )
{
case 1:
path = _a( 0 );
if( path==_FLASH_ )
SPIFFS.format();
else
s = format( 0 );
break;
default:
s = usage( "format ("+String(_FLASH_)+")" );
break;
}
return s;
}
/**
* @fn String Esp8266::ll( StringList *args )
*
* Return file detail list in current device.
*
* @param[in] args Reference to arguments.
* @return Current device.
*/
String Esp8266::ll( StringList *args )
{
String s, p, root;
DynamicJsonBuffer json;
JsonArray &r = json.createArray();
Dir d;
File f;
switch( count(args) )
{
case 1:
root = _a( 0 );
case 0:
// Root path
root = appendRootPath( root );
d = EspStorage->openDir( root );
p = root;
// File info to JSON
while( d.next() )
{
File f = d.openFile( "r" );
JsonObject &o = r.createNestedObject();
o[ "type" ] = f.isDirectory() ? "d" : "-";
o[ "name" ] = String(f.name()).substring( p.length() );
o[ "size" ] = f.size();
f.close();
}
s = "";
r.prettyPrintTo( s );
break;
default:
s = usage( "ll (path)?" );
break;
}
return s;
}
/**
* @fn String Esp8266::mkdir( StringList *args )
*
* Make directory on current device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::mkdir( StringList *args )
{
String s, t;
switch( count(args) )
{
case 1:
t = appendRootPath( _a(0) );
if( EspStorage->exists(t) )
s = mkdir( 0 );
else
EspStorage->mkdir( t );
break;
default:
s = usage( "mkdir path" );
break;
}
return s;
}
/**
* @fn String Esp8266::pwd( StringList *args )
*
* Return current device.
*
* @param[in] args Reference to arguments.
* @return Current device.
*/
String Esp8266::pwd( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
s = prettyPrintTo( "value" , _FLASH_ );
break;
default:
s = usage( "pwd" );
break;
}
return s;
}
/**
* @fn String Esp8266::read( StringList *args )
*
* Return file content on current device.
*
* @param[in] args Reference to arguments.
* @return File content.
*/
String Esp8266::read( StringList *args )
{
String s, t;
File f;
switch( count(args) )
{
case 1:
t = appendRootPath( _a(0) );
if( !EspStorage->exists(t) )
s = read( 0 );
else
{
f = EspStorage->open( t, _FILE_READ_ );
if( f )
{
s = prettyPrintTo( "value" , f.readString() );
f.close();
}
}
break;
default:
s = usage( "cat file" );
break;
}
return s;
}
/**
* @fn String Esp8266::remove( StringList *args )
*
* Remove file on current device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::remove( StringList *args )
{
String s, t;
switch( count(args) )
{
case 1:
t = appendRootPath( _a(0) );
if( !EspStorage->exists(t) )
s = remove( 0 );
else
EspStorage->remove( t );
break;
default:
s = usage( "rm file" );
break;
}
return s;
}
/**
* @fn String Esp8266::rmdir( StringList *args )
*
* Remove directory on current device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::rmdir( StringList *args )
{
String s, t;
switch( count(args) )
{
case 1:
t = appendRootPath( _a(0) );
if( !EspStorage->exists(t) )
s = rmdir( 0 );
else
EspStorage->rmdir( t );
break;
default:
s = usage( "rmdir path" );
break;
}
return s;
}
/**
* @fn String Esp8266::httpBegin( StringList *args )
*
* Initalize https certs.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::httpBegin( StringList *args )
{
String s, t;
File rc, cc, pk;
switch( count(args) )
{
case 0:
http = &wifiClient;
break;
case 3:
http = &wifiClientSecure;
// RootCA
rc = EspStorage->open( appendRootPath(_a(0)), _FILE_READ_ );
t = rc.readString();
wifiClientSecure.setCACert( (uint8_t*)t.c_str(), t.length() );
rc.close();
// Client certificate
cc = EspStorage->open( appendRootPath(_a(1)), _FILE_READ_ );
t = cc.readString();
wifiClientSecure.setCertificate( (uint8_t*)t.c_str(), t.length() );
cc.close();
// Client private key
pk = EspStorage->open( appendRootPath(_a(2)), _FILE_READ_ );
t = pk.readString();
wifiClientSecure.setPrivateKey( (uint8_t*)t.c_str(), t.length() );
pk.close();
break;
default:
s = usage( "httpBegin CACert Certificate PrivateKey" );
break;
}
return s;
}
/**
* @fn String Esp8266::httpPost( StringList *args )
*
* Send HTTP POST to server.
*
* @param[in] args Reference to arguments.
* @return Recieved content.
*/
String Esp8266::httpPost( StringList *args )
{
String s, t, header, footer;
File f;
int size = 0;
String host;
int port = 80;
int timeout = 30 * 1000;
uint8_t *buf = 0;
switch( count(args) )
{
case 5:
timeout = _atoi( 4 ) * 1000;
case 4:
port = _atoi( 3 );
case 3:
t = appendRootPath( _a(2) );
if( !EspStorage->exists(t) )
return AoiUtil::Http::httpPost( args );
// Request body
header = requestBodyHeaderInPut( STR_BOUNDARY, STR_AOIDUINO, t,
&size );
footer = requestBodyFooterInPut( STR_BOUNDARY );
size += header.length() + footer.length();
// POST
host = _a( 0 );
if( !http->connect(host.c_str(),port) )
return httpPost( 0 );
http->println( "POST "+_a(1)+" HTTP/1.0" );
http->println( "Host: " + host );
http->println( "User-Agent: " + String(STR_USER_AGENT) );
http->print( "Content-Type: multipart/form-data; " );
http->println( "boundary=\""+String(STR_BOUNDARY)+"\"" );
http->println( "Content-Length: "+String(size) );
http->println( "Connection: close" );
http->println();
http->print( header );
// Upload file
f = EspStorage->open( t, _FILE_READ_ );
buf = new uint8_t[ _AOIUTIL_HTTP_BUFFER_SIZE_ ];
while( f.available() )
{
size = f.read( buf, _AOIUTIL_HTTP_BUFFER_SIZE_ );
http->write( buf, size );
}
delete [] buf;
f.close();
http->print( footer );
// Response
s = response( timeout );
s = prettyPrintTo( "value", s );
break;
default:
s = usage( "httpPost host path (file|text) (port timeout)?" );
break;
}
return s;
}
/**
* @fn String Esp8266::touch( StringList *args )
*
* Create empty file on current device.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::touch( StringList *args )
{
String s, t;
File f;
switch( count(args) )
{
case 1:
t = appendRootPath( _a(0) );
f = EspStorage->open( t, _FILE_WRITE_ );
if( f )
f.close();
break;
default:
s = usage( "touch file" );
break;
}
return s;
}
/**
* @fn String Esp8266::deepSleep( StringList *args )
*
* Enter the deep sleep state.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::deepSleep( StringList *args )
{
String s;
RFMode mode;
switch( count(args) )
{
case 0:
ESP.deepSleep( 0 );
break;
case 1:
// Micro second.
mode = WAKE_RF_DEFAULT;
ESP.deepSleep( _atoi(0) * 1000 * 1000, mode );
break;
default:
s = usage( "deepSleep [0-9]*" );
break;
}
return s;
}
/**
* @fn String Esp8266::dmesg( StringList *args )
*
* Returns system information.
*
* @param[in] args Reference to arguments.
* @return System information.
*/
String Esp8266::dmesg( StringList *args )
{
String s;
DynamicJsonBuffer json;
JsonObject &r = json.createObject();
switch( count(args) )
{
case 0:
r[ "chipId" ] = String( ESP.getChipId(), HEX );
r[ "coreVersion" ] = ESP.getCoreVersion();
r[ "cpuFreqMHz" ] = ESP.getCpuFreqMHz();
r[ "flashChipId" ] = String( ESP.getFlashChipId(), HEX );
r[ "flashChipSize" ] = ESP.getFlashChipSize();
r[ "freeHeap" ] = ESP.getFreeHeap();
r[ "freeSketchSpace" ] = ESP.getFreeSketchSpace();
r[ "resetReason" ] = ESP.getResetReason();
r[ "sdkVersion" ] = ESP.getSdkVersion();
r[ "sketchSize" ] = ESP.getSketchSize();
r.prettyPrintTo( s );
break;
default:
s = usage( "dmesg" );
break;
}
return s;
}
/**
* @fn String Esp8266::restart( StringList *args )
*
* Reboot the system.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::restart( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
ESP.restart();
break;
case 1:
ticker.once_ms( _atoi(0), reboot );
break;
default:
s = usage( "reboot ([0-9]+)" );
break;
}
return s;
}
/**
* @fn String Esp8266::date( StringList *args )
*
* Print date.
*
* @param[in] args Reference to arguments.
* @return date string.
*/
String Esp8266::date( StringList *args )
{
String s;
uint8_t size = 20;
char *buf = NULL;
time_t t;
struct tm *rtc;
struct timeval tv;
switch( count(args) )
{
case 0:
t = time( NULL );
rtc = localtime( &t );
buf = new char[ size ];
snprintf( buf, size,
"%04d-%02d-%02dT%02d:%02d:%02d",
rtc->tm_year+1900, rtc->tm_mon+1, rtc->tm_mday,
rtc->tm_hour, rtc->tm_min, rtc->tm_sec );
s = prettyPrintTo( "value", buf );
delete [] buf;
break;
case 1:
tv.tv_sec = _atoul( 0 );
settimeofday( &tv, NULL );
break;
default:
s = usage( "date (unixtime)?" );
break;
}
return s;
}
/**
* @fn String Esp8266::servoAttach( StringList *args )
*
* Attach the Servo variable to a pin.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::servoAttach( StringList *args )
{
String s;
switch( count(args) )
{
case 1:
( m_servo+0 )->attach( _atoi(0) );
break;
case 2:
( m_servo+_atoi(1) )->attach( _atoi(0) );
break;
default:
s = usage( "servoAttach pin ([0-(count-1)])" );
break;
}
return s;
}
/**
* @fn String Esp8266::servoBegin( StringList *args )
*
* Initialize the servo using count.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::servoBegin( StringList *args )
{
String s;
StringList sl;
switch( count(args) )
{
case 1:
servoEnd( &sl );
m_servoCount = _atoi( 0 );
m_servo = new Servo[ m_servoCount ];
break;
default:
s = usage( "servoBegin count" );
break;
}
return s;
}
/**
* @fn String Esp8266::servoEnd( StringList *args )
*
* Detach the all Servo variable from its pin.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::servoEnd( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
if( m_servo )
{
for( int i=0; i<m_servoCount; i++ )
(m_servo+i)->detach();
delete [] m_servo;
}
m_servo = 0;
m_servoCount = 0;
break;
default:
s = usage( "servoEnd" );
break;
}
return s;
}
/**
* @fn String Esp8266::servoWriteMicroseconds( StringList *args )
*
* Set microseconds to servo using pin number.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::servoWriteMicroseconds( StringList *args )
{
String s;
switch( count(args) )
{
case 1:
( m_servo+0 )->writeMicroseconds( _atoi(0) );
break;
case 2:
( m_servo+_atoi(1) )->writeMicroseconds( _atoi(0) );
break;
default:
s = usage( "servoWriteMicroseconds micros ([0-(count-1)])" );
break;
}
return s;
}
/**
* @fn String Esp8266::watchdogBegin( StringList *args )
*
* Initialize the Watchdog and start to check timer(mesc).
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::watchdogBegin( StringList *args )
{
String s;
switch( count(args) )
{
case 1:
watchdog.once_ms( _atoi(0), reboot );
watchdogSecond = _atoi(0);
watchdogMills = ::millis();
break;
default:
s = usage( "watchdogBegin [0-9]+" );
break;
}
return s;
}
/**
* @fn String Esp8266::watchdogEnd( StringList *args )
*
* Stop to check timer for avoid bite watchdog.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::watchdogEnd( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
watchdog.detach();
watchdogSecond = 0;
watchdogMills = 0;
break;
default:
s = usage( "watchdogEnd" );
break;
}
return s;
}
/**
* @fn String Ast::watchdogKick( StringList *args )
*
* Kick to watchdog for notify keep alive.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::watchdogKick( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
watchdog.detach();
watchdog.once_ms( watchdogSecond, reboot );
watchdogMills = ::millis();
break;
default:
s = usage( "watchdogKick" );
break;
}
return s;
}
/**
* @fn String Esp8266::watchdogTimeleft( StringList *args )
*
* Get a remain time for bite watchdog.
*
* @param[in] args Reference to arguments.
* @return Remain time to expire timeout(mesc).
*/
String Esp8266::watchdogTimeleft( StringList *args )
{
String s;
uint32_t i = 0;
switch( count(args) )
{
case 0:
i = watchdogSecond - (::millis()-watchdogMills);
s = prettyPrintTo( "value" , i );
break;
default:
s = usage( "watchdogTimeleft" );
break;
}
return s;
}
/**
* @fn String Esp8266::ifConfig( StringList *args )
*
* Show network information.
*
* @param[in] args Reference to arguments.
* @return Network information.
*/
String Esp8266::ifConfig( StringList *args )
{
String s;
DynamicJsonBuffer json;
JsonObject &r = json.createObject();
switch( count(args) )
{
case 0:
r[ "ipAddress" ] = WiFi.localIP().toString();
r[ "subnetMask" ] = WiFi.subnetMask().toString();
r[ "gatewayIp" ] = WiFi.gatewayIP().toString();
r[ "macAddress" ] = WiFi.macAddress();
r[ "dnsIP1" ] = WiFi.dnsIP( 0 ).toString();
r[ "dnsIP2" ] = WiFi.dnsIP( 1 ).toString();
r[ "softAP" ] = WiFi.softAPIP().toString();
r.prettyPrintTo( s );
break;
default:
s = usage( "ifconfig" );
break;
}
return s;
}
/**
* @fn String Esp8266::wifiScanNetworks( StringList *args )
*
* Scan wifi networks.
*
* @param[in] args Reference to arguments.
* @return Returns SSID, RSSI and Encryption type.
*/
String Esp8266::wifiScanNetworks( StringList *args )
{
String s;
int i = 0;
DynamicJsonBuffer json;
JsonArray &r = json.createArray();
switch( count(args) )
{
case 0:
i = WiFi.scanNetworks();
if( !i )
s = STR_NO_NETWORKS_FOUND;
else
{
for( int j=0; j<i; j++ )
{
JsonObject &o = r.createNestedObject();
o[ "ssid" ] = WiFi.SSID( j );
o[ "rssi" ] = WiFi.RSSI( j );
// Sets encription type.
String t = "";
switch( WiFi.encryptionType(j) )
{
case 2:
t = "TKIP(WPA)";
break;
case 5:
t = "WEP";
break;
case 4:
t = "CCMP(WPA)";
break;
case 7:
t = "None";
break;
case 8:
t = "Auto";
break;
default:
t = "Other";
break;
}
o[ "type" ] = t;
}
r.prettyPrintTo( s );
}
break;
default:
s = usage( "iwlist" );
break;
}
return s;
}
/**
* @fn String Esp8266::wifiBegin( StringList *args )
*
* Connect to wireless network.
*
* @param[in] args Reference to arguments.
* @return Wireless ip address, Otherwise error string.
*/
String Esp8266::wifiBegin( StringList *args )
{
String s;
unsigned long i = 0;
switch( count(args) )
{
case 2:
// Start
WiFi.disconnect();
WiFi.mode( WIFI_STA );
WiFi.begin( _a(0).c_str(), _a(1).c_str() );
// Waiting
i = ::millis();
while( WiFi.status()!=WL_CONNECTED && (::millis()-i)<ESP_WIFI_TIMEOUT )
::delay( 500 );
// Result
if( WiFi.status()!=WL_CONNECTED )
s = STR_CANT_CONNECT_TO_WIRELESS_NETWORK;
else
{
StringList sl;
s = ifConfig( &sl );
}
break;
default:
s = usage( "wifiBegin ssid password" );
break;
}
return s;
}
/**
* @fn String Esp8266::wifiEnd( StringList *args )
*
* Detach from wireless network.
*
* @param[in] args Reference to arguments.
* @return Empty string.
*/
String Esp8266::wifiEnd( StringList *args )
{
String s;
switch( count(args) )
{
case 0:
if( WiFi.status()!=WL_CONNECTED )
s = wifiEnd( 0 );
else
WiFi.disconnect();
break;
default:
s = usage( "wifiEnd" );
break;
}
return s;
}
/**
* @fn String Esp8266::wifiRtc( StringList *args )
*
* Get rtc from the WiFi network.
*
* @param[in] args Reference to arguments.
* @return unixtime string.
*/
String Esp8266::wifiRtc( StringList *args )
{
String s;
time_t now;
switch( count(args) )
{
case 0:
if( WiFi.status()!=WL_CONNECTED )
s = wifiRtc( 0 );
else
{
configTzTime( "JST-9", "ntp.nict.jp", "time.google.com", "ntp.jst.mfeed.ad.jp" );
time( &now );
s = String( now );
s = prettyPrintTo( "value", s );
}
break;
default:
s = usage( "wifiRtc" );
break;
}
return s;
}
/**
* @fn String Esp8266::appendRootPath( const String &path )
*
* Append root path ("/") if need.
*
* @return Path include root.
*/
String Esp8266::appendRootPath( const String &path )
{
String s = path;
String r = "/";
if( s.indexOf(r) )
s = r + s;
return s;
}
/**
* @fn void Esp8266::reboot( void )
*
* Reboot the system.
*/
void Esp8266::reboot( void )
{
ESP.restart();
}
/**
* @fn String Esp8266::requestBodyHeaderInPut( const String &value )
*
* Return request body header in HTTP PUT.
*
* @param[in] boundary Boundary string.
* @param[in] name Content-Disposition: name attribute string.
* @param[in] value Putted value.
* @param[in/out] size Putted value size. If value is file, File size is used.
* @return Request body header string in HTTP PUT.
*/
String Esp8266::requestBodyHeaderInPut( const String &boundary, const String &name, const String &value, int *size )
{
String s;
String t = appendRootPath( value );
// If file is exitst, use file size
if( !EspStorage->exists(t) )
s = AoiUtil::Http::requestBodyHeaderInPut( boundary, name, value, size );
else
{
s += "--" + boundary + "\r\n";
s += "Content-Disposition: form-data; name=\"" + name + "\";";
s += " filename=\"" + value + "\"\r\n";
s += "Content-Type: application/octet-stream\r\n";
s += "Content-Transfer-Encoding: binary\r\n";
File f = EspStorage->open( t, _FILE_READ_ );
*size = f.size();
f.close();
s += "\r\n";
}
return s;
}
}
#endif
| 27.629071 | 120 | 0.43812 | gunjouinc |
2bb0e4b01eb05a6a8ba1ded0a5f2b6258a848804 | 2,487 | cpp | C++ | hw4/src/lib/sema/SymbolTable.cpp | idoleat/P-Language-Compiler-CourseProject | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | 7 | 2020-09-10T16:54:49.000Z | 2022-03-15T12:39:23.000Z | hw4/src/lib/sema/SymbolTable.cpp | idoleat/simple-P-compiler | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | null | null | null | hw4/src/lib/sema/SymbolTable.cpp | idoleat/simple-P-compiler | 57db735b349a0a3a30d78b927953e2d44b7c7d53 | [
"MIT"
] | null | null | null | #include "sema/SemanticAnalyzer.hpp"
/*
std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, int attribute){
dumpList.push_back(name);
return insert(name, new SymbolEntry(name, kind, level, type, attribute));
}
std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, float attribute){
dumpList.push_back(name);
return insert(name, new SymbolEntry(name, kind, level, type, attribute));
}
std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, bool attribute){
dumpList.push_back(name);
return insert(name, new SymbolEntry(name, kind, level, type, attribute));
}*/
std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, const char *attribute){
dumpList.push_back(name);
return insert(name, new SymbolEntry(name, kind, level, type, attribute));
}
std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::insert(const char *name, SymbolEntry *symbol){
return entries.insert(std::pair<std::string, SymbolEntry *>(std::string(name), symbol)).first;
}
void SemanticAnalyzer::SymbolTable::SetLevel(uint32_t lv){
level = lv;
}
uint32_t SemanticAnalyzer::SymbolTable::GetLevel(){
return level;
}
std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListBegin(){
return dumpList.begin();
}
std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListEnd(){
return dumpList.end();
}
int SemanticAnalyzer::SymbolTable::GetDumpListSize(){
return (int)dumpList.size();
}
SemanticAnalyzer::SymbolEntry *SemanticAnalyzer::SymbolTable::lookup(const char *name){
std::unordered_map<std::string, SymbolEntry *>::iterator got = entries.find(std::string(name));
if(got != entries.end()) return (got->second);
else return NULL;
}
bool SemanticAnalyzer::SymbolTable::EraseSymbol(const char *name){
int result = entries.erase(std::string(name));
dumpList.remove(std::string(name).c_str());
if(result > 0) return true;
else return false;
} | 42.87931 | 201 | 0.741053 | idoleat |
2bb38f193fc366ae90906435b71efe731f765443 | 7,249 | cpp | C++ | Benchmarks/lud/lud_1_tiling/src/lud.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | 16 | 2020-12-28T15:07:53.000Z | 2022-02-16T08:55:40.000Z | Benchmarks/lud/lud_1_tiling/src/lud.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | null | null | null | Benchmarks/lud/lud_1_tiling/src/lud.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | 6 | 2020-12-28T07:33:08.000Z | 2022-01-13T16:31:22.000Z | #include"lud.h"
#include <iostream>
//Elment with the block BSIZE, diagonal
#define AA(i,j) result[(offset + i) * matrix_dim + j + offset]
//Elment with global index
#define BB(i,j) result[i * matrix_dim + j]
using namespace std;
extern "C"{
void diagonal_load(float* result, float* buffer, int offset){
int i, j;
for(i = 0; i < BSIZE; i++){
for (j = 0; j < BSIZE; j++){
buffer[i * BSIZE + j] = AA(i, j);
}
}
}
void diagonal_store(float* result, float* buffer, int offset){
int i, j;
for(i = 0; i < BSIZE; i++){
for (j = 0; j < BSIZE; j++){
AA(i, j) = buffer[i * BSIZE + j];
}
}
}
void lud_diagonal(float* result,
int offset)
{
int i, j, k;
float buffer[BSIZE * BSIZE];
diagonal_load(result, buffer, offset);
for (i = 0; i < BSIZE; i++){
top:for (j = i; j < BSIZE; j++){
for (k = 0; k < i; k++){
buffer[i * BSIZE + j] = buffer[i * BSIZE + j] -
buffer[i * BSIZE + k]* buffer[k * BSIZE + j];
}
}
float temp = 1.f / buffer[i * BSIZE + i];
left:for (j = i + 1; j < BSIZE; j++){
for (k = 0; k < i; k++){
buffer[j * BSIZE + i]= buffer[j * BSIZE + i]- buffer[j * BSIZE + k] * buffer[k * BSIZE + i];
}
buffer[j * BSIZE + i] = buffer[j * BSIZE + i] * temp;
}
}
diagonal_store(result, buffer, offset);
}
void perimeter_load(float* result, float* top, float* left, int offset, int chunk_idx){
int i, j;
int i_top = offset;
int j_top = offset + BSIZE * (chunk_idx + 1);
int i_left = offset + BSIZE * (chunk_idx + 1);
int j_left = offset;
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
top[i * BSIZE + j] = BB((i_top + i), (j_top + j));
}
}
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
left[i * BSIZE + j] = BB((i_left + i), (j_left + j));
}
}
}
void perimeter_store(float* result, float* top, float* left, int offset, int chunk_idx){
int i, j;
int i_top = offset;
int j_top = offset + BSIZE * (chunk_idx + 1);
int i_left = offset + BSIZE * (chunk_idx + 1);
int j_left = offset;
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
BB((i_top + i), (j_top + j)) = top[i * BSIZE + j];
}
}
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
BB((i_left + i), (j_left + j)) = left[i * BSIZE + j];
}
}
}
//99327
void lud_perimeter(float* result,
int offset) {
float diagonal_buffer[BSIZE * BSIZE];
float top_buffer[BSIZE * BSIZE];
float left_buffer[BSIZE * BSIZE];
int i, j, k;
diagonal:for (i = 0; i < BSIZE; i++){
for (j = 0; j < BSIZE; j++){
diagonal_buffer[i * BSIZE + j] = AA(i, j);
}
}
int chunk_idx, chunk_num;
chunk_num = ((matrix_dim - offset) / BSIZE) - 1;
for (chunk_idx = 0; chunk_idx < chunk_num; chunk_idx++){
perimeter_load(result, top_buffer, left_buffer, offset, chunk_idx);
float sum;
// processing top perimeter
for (j = 0; j < BSIZE; j++){
for (i = 0; i < BSIZE; i++){
sum = 0.0f;
for (k = 0; k < i; k++){
sum += diagonal_buffer[BSIZE * i + k] * top_buffer[k * BSIZE + j];
}
top_buffer[i * BSIZE + j] = top_buffer[i * BSIZE + j] - sum;
}
}
// processing left perimeter
for (i = 0; i < BSIZE; i++){
for (j = 0; j < BSIZE; j++){
sum = 0.0f;
for (k = 0; k < j; k++){
sum += left_buffer[i * BSIZE + k] * diagonal_buffer[BSIZE * k + j];
}
left_buffer[i * BSIZE + j] = (left_buffer[i * BSIZE + j] - sum) / diagonal_buffer[j * BSIZE + j];
}
}
perimeter_store(result, top_buffer, left_buffer, offset, chunk_idx);
}
cout << "success here perimeter" << endl;
}
void internal_load(float* result, float* top, float* left, float* inner, int offset, int chunk_idx, int chunk_num){
int i, j;
int i_global, j_global;
i_global = offset + BSIZE * (1 + chunk_idx / chunk_num);
j_global = offset + BSIZE * (1 + chunk_idx % chunk_num);
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
top[i * BSIZE + j] = result[matrix_dim * (i + offset) + j + j_global];
}
}
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
left[i * BSIZE + j] = result[matrix_dim * (i + i_global) + offset + j];
}
}
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
inner[i * BSIZE + j] = result[matrix_dim * (i + i_global) + j + j_global];
}
}
}
void internal_store(float* result, float* inner, int offset, int chunk_idx, int chunk_num){
int i, j;
int i_global, j_global;
i_global = offset + BSIZE * (1 + chunk_idx / chunk_num);
j_global = offset + BSIZE * (1 + chunk_idx % chunk_num);
for(i = 0; i < BSIZE; i++){
for(j = 0; j < BSIZE; j++){
result[matrix_dim * (i + i_global) + j + j_global] = inner[i * BSIZE + j];
}
}
}
void lud_internal( float* result,
int offset) {
int chunk_idx, chunk_num;
chunk_num = ((matrix_dim - offset) / BSIZE) - 1;
float top_buffer[BSIZE * BSIZE];
float left_buffer[BSIZE * BSIZE];
float inner_buffer[BSIZE * BSIZE];
int i, j, k, i_global, j_global;
for (chunk_idx = 0; chunk_idx < chunk_num * chunk_num; chunk_idx++){
internal_load(result, top_buffer, left_buffer, inner_buffer, offset, chunk_idx, chunk_num);
for (i = 0; i < BSIZE; i++){
for (j = 0; j < BSIZE; j++){
float sum = 0.0f;
//#pragma HLS unsafemath
for (k = 0; k < BSIZE; k++){
sum += left_buffer[BSIZE * i + k] * top_buffer[BSIZE * k + j];
}
inner_buffer[i * BSIZE + j] -= sum;
}
}
internal_store(result, inner_buffer, offset, chunk_idx, chunk_num);
}
cout << "success internal" << endl;
}
void workload(float result[GRID_ROWS * GRID_COLS]){
#pragma HLS INTERFACE m_axi port=result offset=slave bundle=gmem
#pragma HLS INTERFACE s_axilite port=result bundle=control
#pragma HLS INTERFACE s_axilite port=return bundle=control
for(int i = 0; i < matrix_dim - BSIZE; i += BSIZE){
lud_diagonal(result, i);
lud_perimeter(result, i);
lud_internal(result, i);
}
int i = matrix_dim - BSIZE;
lud_diagonal(result, i);
return;
}
}
| 29.831276 | 130 | 0.473445 | LemonAndRabbit |
2bb78be9e19739ee70cd0fd08d20d3b9cb48b7e1 | 1,287 | cc | C++ | GeneralUtilities/src/VMInfo.cc | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 1 | 2021-06-23T22:09:28.000Z | 2021-06-23T22:09:28.000Z | GeneralUtilities/src/VMInfo.cc | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 125 | 2020-04-03T13:44:30.000Z | 2021-10-15T21:29:57.000Z | GeneralUtilities/src/VMInfo.cc | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | null | null | null | #include "GeneralUtilities/inc/VMInfo.hh"
#include <array>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <unistd.h>
namespace {
// Helper function to check the units and return the value.
long parseLine ( std::string const& line,
std::string const& unitExpected ){
std::istringstream is(line);
std::string key, unit;
long val;
is >> key >> val >> unit;
if ( unit!=unitExpected ){
throw std::runtime_error( "ProcStatus: cannot parse: " + line );
}
return val;
}
} // end anonymous namespace
// The c'tor does all of the work.
mu2e::VMInfo::VMInfo(){
// The information we want.
std::array<std::string,4> wanted{ "VmPeak", "VmSize", "VmHWM", "VmRSS"};
// Parse the information to get what we need.
std::ifstream proc("/proc/self/status");
std::map<std::string,long> values;
while ( proc ){
std::string line;
getline( proc, line);
if ( !proc ) break;
for ( auto const& name: wanted ){
if ( line.find(name) != std::string::npos ){
long val = parseLine( line, "kB");
values[name] = val;
break;
}
}
}
vmPeak = values["VmPeak"];
vmSize = values["VmSize"];
vmHWM = values["VmHWM"];
vmRSS = values["VmRSS"];
}
| 23.833333 | 74 | 0.602176 | lborrel |
2bb9375679e453bbb52cceb696885b9fe5125bd0 | 3,125 | ipp | C++ | libember/Headers/ember/glow/impl/GlowParameter.ipp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 78 | 2015-07-31T14:46:38.000Z | 2022-03-28T09:28:28.000Z | libember/Headers/ember/glow/impl/GlowParameter.ipp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 81 | 2015-08-03T07:58:19.000Z | 2022-02-28T16:21:19.000Z | libember/Headers/ember/glow/impl/GlowParameter.ipp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 49 | 2015-08-03T12:53:10.000Z | 2022-03-17T17:25:49.000Z | /*
libember -- C++ 03 implementation of the Ember+ Protocol
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com).
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef __LIBEMBER_GLOW_GLOWPARAMETER_IPP
#define __LIBEMBER_GLOW_GLOWPARAMETER_IPP
#include "../../util/Inline.hpp"
#include "../util/ValueConverter.hpp"
#include "../GlowStringIntegerPair.hpp"
#include "../GlowTags.hpp"
#include "../GlowNodeBase.hpp"
namespace libember { namespace glow
{
LIBEMBER_INLINE
GlowParameter::GlowParameter(int number)
: GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children())
, m_cachedNumber(-1)
{
insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number));
}
LIBEMBER_INLINE
GlowParameter::GlowParameter(GlowNodeBase* parent, int number)
: GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children())
, m_cachedNumber(-1)
{
insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number));
if (parent)
{
GlowElementCollection* children = parent->children();
GlowElementCollection::iterator const where = children->end();
children->insert(where, this);
}
}
LIBEMBER_INLINE
GlowParameter::GlowParameter(int number, ber::Tag const& tag)
: GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children())
, m_cachedNumber(-1)
{
insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number));
}
LIBEMBER_INLINE
GlowParameter::GlowParameter(ber::Tag const& tag)
: GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children())
, m_cachedNumber(-1)
{}
LIBEMBER_INLINE
int GlowParameter::number() const
{
if (m_cachedNumber == -1)
{
ber::Tag const tag = GlowTags::Parameter::Number();
const_iterator const first = begin();
const_iterator const last = end();
const_iterator const result = util::find_tag(first, last, tag);
if (result != last)
{
m_cachedNumber = util::ValueConverter::valueOf(&*result, -1);
}
else
{
m_cachedNumber = -1;
}
}
return m_cachedNumber;
}
LIBEMBER_INLINE
GlowParameter::iterator GlowParameter::insertImpl(iterator const& where, Node* child)
{
m_cachedNumber = -1;
return GlowContainer::insertImpl(where, child);
}
LIBEMBER_INLINE
void GlowParameter::eraseImpl(iterator const& first, iterator const& last)
{
m_cachedNumber = -1;
GlowContainer::eraseImpl(first, last);
}
}
}
#endif // __LIBEMBER_GLOW_GLOWPARAMETER_IPP
| 32.894737 | 142 | 0.64096 | purefunsolutions |
2bbc823dacc872e579598f40345eddda0492ea26 | 1,095 | cpp | C++ | codeforces/A - Edit Distance/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/A - Edit Distance/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/A - Edit Distance/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Nov/29/2019 12:50
* solution_verdict: Accepted language: GNU C++14
* run_time: 31 ms memory_used: 0 KB
* problem: https://codeforces.com/gym/102001/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
string s;cin>>s;int one=0,zero=0;
for(auto x:s)x=='1'?one++:zero++;
char c='0';if(zero>=one)c='1';
string p;
for(int i=1;i<=s.size();i++)p.push_back(c);
if(one!=zero)cout<<p<<endl,exit(0);
if(s[0]=='0')
{
cout<<'1';
for(int i=2;i<=s.size();i++)cout<<'0';
}
else
{
cout<<'0';
for(int i=2;i<=s.size();i++)cout<<'1';
}
return 0;
} | 35.322581 | 111 | 0.389954 | kzvd4729 |
2bbf29d7d690776f16f91246827260af76486411 | 2,333 | hxx | C++ | opencascade/HLRTopoBRep_OutLiner.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/HLRTopoBRep_OutLiner.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/HLRTopoBRep_OutLiner.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-08-03
// Created by: Christophe MARION
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// 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, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _HLRTopoBRep_OutLiner_HeaderFile
#define _HLRTopoBRep_OutLiner_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TopoDS_Shape.hxx>
#include <HLRTopoBRep_Data.hxx>
#include <Standard_Transient.hxx>
#include <BRepTopAdaptor_MapOfShapeTool.hxx>
#include <Standard_Integer.hxx>
class HLRAlgo_Projector;
class TopoDS_Face;
class HLRTopoBRep_OutLiner;
DEFINE_STANDARD_HANDLE(HLRTopoBRep_OutLiner, Standard_Transient)
class HLRTopoBRep_OutLiner : public Standard_Transient
{
public:
Standard_EXPORT HLRTopoBRep_OutLiner();
Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriSh);
Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriS, const TopoDS_Shape& OutS);
void OriginalShape (const TopoDS_Shape& OriS);
TopoDS_Shape& OriginalShape();
void OutLinedShape (const TopoDS_Shape& OutS);
TopoDS_Shape& OutLinedShape();
HLRTopoBRep_Data& DataStructure();
Standard_EXPORT void Fill (const HLRAlgo_Projector& P, BRepTopAdaptor_MapOfShapeTool& MST, const Standard_Integer nbIso);
DEFINE_STANDARD_RTTIEXT(HLRTopoBRep_OutLiner,Standard_Transient)
protected:
private:
//! Builds faces from F and add them to S.
Standard_EXPORT void ProcessFace (const TopoDS_Face& F, TopoDS_Shape& S, BRepTopAdaptor_MapOfShapeTool& M);
Standard_EXPORT void BuildShape (BRepTopAdaptor_MapOfShapeTool& M);
TopoDS_Shape myOriginalShape;
TopoDS_Shape myOutLinedShape;
HLRTopoBRep_Data myDS;
};
#include <HLRTopoBRep_OutLiner.lxx>
#endif // _HLRTopoBRep_OutLiner_HeaderFile
| 25.086022 | 123 | 0.786541 | mgreminger |
2bc41f310b986fe7940cfe2ab64e3fefd9973fed | 1,017 | hpp | C++ | src/service/MoleculeService.hpp | MichelML/chempp | cba27b910e7cbf626bcd4e1c25e394311e5f74e9 | [
"Apache-2.0"
] | 5 | 2021-05-21T17:15:32.000Z | 2021-07-26T17:38:52.000Z | src/service/MoleculeService.hpp | MichelML/chempp | cba27b910e7cbf626bcd4e1c25e394311e5f74e9 | [
"Apache-2.0"
] | 15 | 2021-05-17T14:24:15.000Z | 2021-08-12T15:30:11.000Z | src/service/MoleculeService.hpp | MichelML/chempp | cba27b910e7cbf626bcd4e1c25e394311e5f74e9 | [
"Apache-2.0"
] | 1 | 2021-06-26T01:07:18.000Z | 2021-06-26T01:07:18.000Z |
#ifndef EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP
#define EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP
#include "db/MoleculeDb.hpp"
#include "dto/StatusDto.hpp"
#include "dto/MoleculeDto.hpp"
#include "dto/MoleculesListDto.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/macro/component.hpp"
class MoleculeService {
private:
typedef oatpp::web::protocol::http::Status Status;
private:
OATPP_COMPONENT(std::shared_ptr<MoleculeDb>, m_database); // Inject database component
public:
oatpp::Object<MoleculeDto> getMoleculeById(const oatpp::Int64& id);
oatpp::Object<MoleculeDetailedDto> getExactMolecule(const oatpp::String& structure);
oatpp::Object<ListDto<oatpp::Object<MoleculeDto>>> getSubstructureMatches(const oatpp::String& structure, const oatpp::Int64& limit);
oatpp::Object<SimListDto<oatpp::Object<MoleculeDto>>> getSimilarityMatches(const oatpp::String& structure, const oatpp::Int64& limit, const oatpp::Float64& threshold);
};
#endif //EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP
| 37.666667 | 169 | 0.797443 | MichelML |
2bc42c4bafc9df7ba7729f3a502e5669e9893ba0 | 3,234 | hpp | C++ | qipython/pyguard.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 7 | 2015-08-12T01:25:11.000Z | 2021-07-15T11:08:34.000Z | qipython/pyguard.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 10 | 2015-10-01T11:33:53.000Z | 2022-03-23T10:19:33.000Z | qipython/pyguard.hpp | Maelic/libqi-python | d5e250a7ce1b6039bb1f57f750cab51412dfecca | [
"BSD-3-Clause"
] | 7 | 2015-02-24T10:38:52.000Z | 2022-03-14T10:18:26.000Z | /*
** Copyright (C) 2020 SoftBank Robotics Europe
** See COPYING for the license
*/
#pragma once
#ifndef QIPYTHON_GUARD_HPP
#define QIPYTHON_GUARD_HPP
#include <qipython/common.hpp>
#include <ka/typetraits.hpp>
#include <type_traits>
namespace qi
{
namespace py
{
/// DefaultConstructible Guard
/// Procedure<_ (Args)> F
template<typename Guard, typename F, typename... Args>
ka::ResultOf<F(Args&&...)> invokeGuarded(F&& f, Args&&... args)
{
Guard g;
return std::forward<F>(f)(std::forward<Args>(args)...);
}
namespace detail
{
// Guards the copy, construction and destruction of an object, and only when
// in case of copy construction the source object evaluates to true, and in case
// of destruction, the object itself evaluates to true.
//
// Explanation:
// pybind11::object only requires the GIL to be locked on copy and if the
// source is not null. Default construction does not require the GIL either.
template<typename Guard, typename Object>
class Guarded
{
using Storage =
typename std::aligned_storage<sizeof(Object), alignof(Object)>::type;
Storage _object;
Object& object() { return reinterpret_cast<Object&>(_object); }
const Object& object() const { return reinterpret_cast<const Object&>(_object); }
public:
template<typename Arg0, typename... Args,
ka::EnableIf<std::is_constructible<Object, Arg0&&, Args&&...>::value, int> = 0>
explicit Guarded(Arg0&& arg0, Args&&... args)
{
Guard g;
new(&_object) Object(std::forward<Arg0>(arg0), std::forward<Args>(args)...);
}
Guarded()
{
// Default construction, no GIL needed.
new(&_object) Object();
}
Guarded(Guarded& o)
{
boost::optional<Guard> optGuard;
if (o.object())
optGuard.emplace();
new(&_object) Object(o.object());
}
Guarded(const Guarded& o)
{
boost::optional<Guard> optGuard;
if (o.object())
optGuard.emplace();
new(&_object) Object(o.object());
}
Guarded(Guarded&& o)
{
new(&_object) Object(std::move(o.object()));
}
~Guarded()
{
boost::optional<Guard> optGuard;
if (object())
optGuard.emplace();
object().~Object();
}
Guarded& operator=(const Guarded& o)
{
if (this == &o)
return *this;
{
boost::optional<Guard> optGuard;
if (o.object())
optGuard.emplace();
object() = o.object();
}
return *this;
}
Guarded& operator=(Guarded&& o)
{
if (this == &o)
return *this;
object() = std::move(o.object());
return *this;
}
Object& operator*() { return object(); }
const Object& operator*() const { return object(); }
Object* operator->() { return &object(); }
const Object* operator->() const { return &object(); }
explicit operator Object&() { return object(); }
explicit operator const Object&() const { return object(); }
};
} // namespace detail
/// Wraps a pybind11::object value and locks the GIL on copy and destruction.
///
/// This is useful for instance to put pybind11 objects in lambda functions so
/// that they can be copied around safely.
using GILGuardedObject = detail::Guarded<pybind11::gil_scoped_acquire, pybind11::object>;
} // namespace py
} // namespace qi
#endif // QIPYTHON_GUARD_HPP
| 23.779412 | 90 | 0.653061 | Maelic |
2bc58ddcf7479e5d3006b54cb23426bb1db7b70d | 7,820 | cpp | C++ | src/gui/qt/qt_backend.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | src/gui/qt/qt_backend.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | src/gui/qt/qt_backend.cpp | alicemona/Smala | 6f66c3b4bb111993a6bcf148e84c229fb3fa3534 | [
"BSD-2-Clause"
] | null | null | null | /*
* djnn v2
*
* The copyright holders for the contents of this file are:
* Ecole Nationale de l'Aviation Civile, France (2018)
* See file "license.terms" for the rights and conditions
* defined by copyright holders.
*
*
* Contributors:
* Mathieu Magnaudet <[email protected]>
*
*/
#include "../backend.h"
#include "../transformation/transformations.h"
#include "qt_context.h"
#include "qt_backend.h"
#include "qt_window.h"
#include <QtWidgets/QWidget>
#include <QtGui/QPainter>
#include <QtCore/QtMath>
#include <QtCore/QFileInfo>
#include <iostream>
#include <cmath>
namespace djnn
{
QtBackend *QtBackend::_instance;
std::once_flag QtBackend::onceFlag;
QtBackend*
QtBackend::instance ()
{
std::call_once (QtBackend::onceFlag, [] () {
_instance = new QtBackend();
});
return _instance;
}
QtBackend::QtBackend () :
_painter (nullptr), _picking_view (nullptr)
{
_context_manager = new QtContextManager ();
}
QtBackend::~QtBackend ()
{
if (_context_manager) { delete _context_manager; _context_manager = nullptr;}
}
void
QtBackend::save_context ()
{
if (_painter != nullptr)
_painter->save ();
}
void
QtBackend::restore_context ()
{
if (_painter != nullptr)
_painter->restore ();
}
void
QtBackend::set_painter (QPainter* p)
{
_painter = p;
}
void
QtBackend::set_picking_view (QtPickingView* p)
{
_picking_view = p;
}
/* Qt context management is imported from djnn v1 */
void
QtBackend::load_drawing_context (AbstractGShape *s, double tx, double ty, double width, double height)
{
QtContext *cur_context = _context_manager->get_current ();
QMatrix4x4 matrix = cur_context->matrix;
QTransform transform = matrix.toTransform ();
if (s->matrix () != nullptr) {
Homography *h = dynamic_cast<Homography*> (s->matrix ());
Homography *hi = dynamic_cast<Homography*> (s->inverted_matrix ());
QMatrix4x4 loc_matrix = QMatrix4x4 (matrix);
h->_m11->set_value (loc_matrix (0, 0), false);
h->_m12->set_value (loc_matrix (0, 1), false);
h->_m13->set_value (loc_matrix (0, 2), false);
h->_m14->set_value (loc_matrix (0, 3), false);
h->_m21->set_value (loc_matrix (1, 0), false);
h->_m22->set_value (loc_matrix (1, 1), false);
h->_m23->set_value (loc_matrix (1, 2), false);
h->_m24->set_value (loc_matrix (1, 3), false);
h->_m31->set_value (loc_matrix (2, 0), false);
h->_m32->set_value (loc_matrix (2, 1), false);
h->_m33->set_value (loc_matrix (2, 2), false);
h->_m34->set_value (loc_matrix (2, 3), false);
h->_m41->set_value (loc_matrix (3, 0), false);
h->_m42->set_value (loc_matrix (3, 1), false);
h->_m43->set_value (loc_matrix (3, 2), false);
h->_m44->set_value (loc_matrix (3, 3), false);
loc_matrix = loc_matrix.inverted ();
hi->_m11->set_value (loc_matrix (0, 0), false);
hi->_m12->set_value (loc_matrix (0, 1), false);
hi->_m13->set_value (loc_matrix (0, 2), false);
hi->_m14->set_value (loc_matrix (0, 3), false);
hi->_m21->set_value (loc_matrix (1, 0), false);
hi->_m22->set_value (loc_matrix (1, 1), false);
hi->_m23->set_value (loc_matrix (1, 2), false);
hi->_m24->set_value (loc_matrix (1, 3), false);
hi->_m31->set_value (loc_matrix (2, 0), false);
hi->_m32->set_value (loc_matrix (2, 1), false);
hi->_m33->set_value (loc_matrix (2, 2), false);
hi->_m34->set_value (loc_matrix (2, 3), false);
hi->_m41->set_value (loc_matrix (3, 0), false);
hi->_m42->set_value (loc_matrix (3, 1), false);
hi->_m43->set_value (loc_matrix (3, 2), false);
hi->_m44->set_value (loc_matrix (3, 3), false);
}
/* setup the painting environment of the drawing view */
QPen tmpPen (cur_context->pen);
/*
* with Qt, dash pattern and dash offset are specified
* in stroke-width unit so we need to update the values accordingly
*/
if (cur_context->pen.style () == Qt::CustomDashLine) {
qreal w = cur_context->pen.widthF () || 1;
QVector<qreal> dashPattern = cur_context->pen.dashPattern ();
QVector<qreal> tmp (dashPattern.size ());
for (int i = 0; i < dashPattern.size (); i++)
tmp[i] = dashPattern.value (i) / w;
tmpPen.setDashPattern (tmp);
tmpPen.setDashOffset (cur_context->pen.dashOffset () / w);
}
_painter->setRenderHint (QPainter::Antialiasing, true);
_painter->setPen (tmpPen);
_painter->setTransform (transform);
/* If the brush style is gradient and the coordinate mode is ObjectBoundingMode
* then translate the rotation axis of the gradient transform and transpose
* the translation values in the global coordinate system*/
if (cur_context->brush.style () == Qt::LinearGradientPattern
|| cur_context->brush.style () == Qt::RadialGradientPattern) {
if (cur_context->brush.gradient ()->coordinateMode () == QGradient::ObjectBoundingMode) {
QTransform origin = cur_context->gradientTransform;
QTransform newT = QTransform ();
newT.translate (tx, ty);
QTransform result = origin * newT;
result.translate (-tx, -ty);
double m11 = result.m11 ();
double m12 = result.m12 ();
double m13 = result.m13 ();
double m21 = result.m21 ();
double m22 = result.m22 ();
double m23 = result.m23 ();
double m31 = result.m31 () * width;
double m32 = result.m32 () * height;
double m33 = result.m33 ();
result.setMatrix (m11, m12, m13, m21, m22, m23, m31, m32, m33);
cur_context->gradientTransform = result;
}
}
cur_context->brush.setTransform (cur_context->gradientTransform);
_painter->setBrush (cur_context->brush);
}
void
QtBackend::load_pick_context (AbstractGShape *s)
{
QtContext *cur_context = _context_manager->get_current ();
QPen pickPen;
QBrush pickBrush (_picking_view->pick_color ());
pickPen.setStyle (Qt::SolidLine);
pickPen.setColor (_picking_view->pick_color ());
pickPen.setWidth (cur_context->pen.width());
_picking_view->painter ()->setPen (pickPen);
_picking_view->painter ()->setBrush (pickBrush);
_picking_view->painter ()->setTransform (cur_context->matrix.toTransform ());
_picking_view->add_gobj (s);
}
WinImpl*
QtBackend::create_window (Window *win, const std::string& title, double x, double y, double w, double h)
{
return new QtWindow (win, title, x, y, w, h);
}
bool
QtBackend::is_in_picking_view (AbstractGShape *s)
{
return is_pickable (s);
/*return s->press ()->has_coupling () || s->x ()->has_coupling () || s->y ()->has_coupling ()
|| s->move ()->has_coupling () || s->release ()->has_coupling () || s->enter ()->has_coupling ()
|| s->leave ()->has_coupling ();*/
}
static QFont::Style fontStyleArray[3] =
{ QFont::StyleNormal, QFont::StyleItalic, QFont::StyleOblique };
void
QtBackend::update_text_geometry (Text* text, FontFamily* ff, FontSize* fsz, FontStyle* fs, FontWeight *fw)
{
QFont qfont;
if (ff) {
QString val (ff->family()->get_value ().c_str ());
qfont.setFamily (val);
}
if (fsz) {
qfont.setPixelSize (fsz->size ()->get_value ());
}
if (fs) {
int i = fs->style ()->get_value ();
if (i >= 0 && i <= 3)
qfont.setStyle (fontStyleArray [i]);
}
if (fw) {
qfont.setWeight (fw->weight ()->get_value ());
}
QString str (text->text ()->get_value().c_str ());
QFontMetrics fm (qfont);
int width = fm.width (str);
int height = fm.height ();
text->set_width (width);
text->set_height (height);
}
} /* namespace djnn */
| 32.995781 | 108 | 0.625575 | alicemona |
2bc7cc8408c2e86201c75f4a22350f032a56f075 | 979 | cpp | C++ | Source/Foundation/bsfCore/Managers/BsMeshManager.cpp | myrgy/bsf | 2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6 | [
"MIT"
] | 1 | 2018-04-16T12:14:52.000Z | 2018-04-16T12:14:52.000Z | Source/Foundation/bsfCore/Managers/BsMeshManager.cpp | myrgy/bsf | 2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6 | [
"MIT"
] | null | null | null | Source/Foundation/bsfCore/Managers/BsMeshManager.cpp | myrgy/bsf | 2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6 | [
"MIT"
] | null | null | null | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "Managers/BsMeshManager.h"
#include "BsCoreApplication.h"
#include "Math/BsVector3.h"
#include "Mesh/BsMesh.h"
#include "RenderAPI/BsVertexDataDesc.h"
namespace bs
{
MeshManager::MeshManager()
{ }
MeshManager::~MeshManager()
{ }
void MeshManager::onStartUp()
{
SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>();
vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
mDummyMeshData = bs_shared_ptr_new<MeshData>(1, 3, vertexDesc);
auto vecIter = mDummyMeshData->getVec3DataIter(VES_POSITION);
vecIter.setValue(Vector3(0, 0, 0));
auto indices = mDummyMeshData->getIndices32();
indices[0] = 0;
indices[1] = 0;
indices[2] = 0;
mDummyMesh = Mesh::create(mDummyMeshData);
}
} | 28.794118 | 124 | 0.658836 | myrgy |
2bc81063a73e18c00b73fdb550fd89f181f2c024 | 8,210 | cc | C++ | src/Formlsms/rss_expl.cc | asminer/smart | 269747c4578b670e5c3973f93a1e6ec71d95be78 | [
"Apache-2.0"
] | 6 | 2018-05-30T23:02:14.000Z | 2022-01-19T07:30:46.000Z | src/Formlsms/rss_expl.cc | asminer/smart | 269747c4578b670e5c3973f93a1e6ec71d95be78 | [
"Apache-2.0"
] | null | null | null | src/Formlsms/rss_expl.cc | asminer/smart | 269747c4578b670e5c3973f93a1e6ec71d95be78 | [
"Apache-2.0"
] | 2 | 2018-07-13T18:53:27.000Z | 2021-04-12T17:54:02.000Z |
#include <cstdio>
#include "rss_expl.h"
#include "../ExprLib/exprman.h"
#include "../ExprLib/mod_vars.h"
// For ordering states
#include "../include/heap.h"
#include "../Modules/expl_states.h"
// ******************************************************************
// * *
// * expl_reachset methods *
// * *
// ******************************************************************
expl_reachset::expl_reachset(StateLib::state_db* ss)
{
state_dictionary = ss;
state_dictionary->ConvertToStatic(true);
state_handle = 0;
state_collection = 0;
DCASSERT(state_dictionary);
natorder = new natural_db_iter(*state_dictionary);
needs_discorder = false;
discorder = 0;
lexorder = 0;
}
expl_reachset::~expl_reachset()
{
delete state_dictionary;
delete[] state_handle;
delete state_collection;
delete natorder;
delete discorder;
delete lexorder;
}
StateLib::state_db* expl_reachset::getStateDatabase() const
{
return state_dictionary;
}
void expl_reachset::getNumStates(long &ns) const
{
if (state_dictionary) {
ns = state_dictionary->Size();
} else {
DCASSERT(state_collection);
ns = state_collection->Size();
}
}
void expl_reachset::showInternal(OutputStream &os) const
{
long ns;
getNumStates(ns);
for (long i=0; i<ns; i++) {
long bytes = 0;
const unsigned char* ptr = 0;
os << "State " << i << " internal:";
if (state_dictionary) {
ptr = state_dictionary->GetRawState(i, bytes);
} else {
DCASSERT(state_collection);
DCASSERT(state_handle);
ptr = state_collection->GetRawState(state_handle[i], bytes);
}
for (long b=0; b<bytes; b++) {
os.Put(' ');
os.PutHex(ptr[b]);
}
os.Put('\n');
os.flush();
}
}
void expl_reachset::showState(OutputStream &os, const shared_state* st) const
{
st->Print(os, 0);
}
state_lldsm::reachset::iterator& expl_reachset
::iteratorForOrder(state_lldsm::display_order ord)
{
DCASSERT(state_dictionary || (state_collection && state_handle));
switch (ord) {
case state_lldsm::DISCOVERY:
if (needs_discorder) {
if (0==discorder) {
discorder = new discovery_coll_iter(*state_collection, state_handle);
}
return *discorder;
}
DCASSERT(natorder);
return *natorder;
case state_lldsm::LEXICAL:
if (0==lexorder) {
if (state_dictionary) {
lexorder = new lexical_db_iter(getGrandParent(), *state_dictionary);
} else {
lexorder = new lexical_coll_iter(getGrandParent(), *state_collection, state_handle);
}
}
return *lexorder;
case state_lldsm::NATURAL:
default:
DCASSERT(natorder);
return *natorder;
};
}
state_lldsm::reachset::iterator& expl_reachset::easiestIterator() const
{
DCASSERT(natorder);
return *natorder;
}
void expl_reachset::Finish()
{
// Compact states
state_collection = state_dictionary->TakeStateCollection();
delete state_dictionary;
state_dictionary = 0;
state_handle = state_collection->RemoveIndexHandles();
// Update iterators
DCASSERT(state_collection);
DCASSERT(state_handle);
delete natorder;
natorder = new natural_coll_iter(*state_collection, state_handle);
delete lexorder;
lexorder = 0;
delete discorder;
discorder = 0;
}
void expl_reachset::Renumber(const GraphLib::node_renumberer* Ren)
{
if (0==Ren) return;
if (!Ren->changes_something()) return;
DCASSERT(state_collection);
DCASSERT(state_handle);
// Renumber state_handle array
long* aux = new long[state_collection->Size()];
for (long i=state_collection->Size()-1; i>=0; i--) {
aux[i] = state_handle[i];
}
for (long i=state_collection->Size()-1; i>=0; i--) {
CHECK_RANGE(0, Ren->new_number(i), state_collection->Size());
state_handle[Ren->new_number(i)] = aux[i];
}
delete[] aux;
needs_discorder = true;
}
// ******************************************************************
// * *
// * expl_reachset::db_iterator methods *
// * *
// ******************************************************************
expl_reachset::db_iterator::db_iterator(const StateLib::state_db &s)
: indexed_iterator(s.Size()), states(s)
{
}
expl_reachset::db_iterator::~db_iterator()
{
}
void expl_reachset::db_iterator::copyState(shared_state* st, long o) const
{
states.GetStateKnown(ord2index(o), st->writeState(), st->getStateSize());
}
// ******************************************************************
// * *
// * expl_reachset::coll_iterator methods *
// * *
// ******************************************************************
expl_reachset::coll_iterator::coll_iterator(const StateLib::state_coll &SC,
const long* SH) : indexed_iterator(SC.Size()), states(SC), state_handle(SH)
{
DCASSERT(state_handle);
}
expl_reachset::coll_iterator::~coll_iterator()
{
}
void expl_reachset::coll_iterator::copyState(shared_state* st, long o) const
{
states.GetStateKnown(state_handle[ord2index(o)], st->writeState(), st->getStateSize());
}
// ******************************************************************
// * *
// * expl_reachset::natural_db_iter methods *
// * *
// ******************************************************************
expl_reachset::natural_db_iter::natural_db_iter(const StateLib::state_db &s)
: db_iterator(s)
{
// nothing!
}
// ******************************************************************
// * *
// * expl_reachset::natural_coll_iter methods *
// * *
// ******************************************************************
expl_reachset::natural_coll_iter::natural_coll_iter(const StateLib::state_coll &SC,
const long* SH) : coll_iterator(SC, SH)
{
// nothing!
}
// ******************************************************************
// * *
// * expl_reachset::discovery_coll_iter methods *
// * *
// ******************************************************************
expl_reachset::discovery_coll_iter::discovery_coll_iter(const StateLib::state_coll &SC,
const long* SH) : coll_iterator(SC, SH)
{
long* M = new long[SC.Size()];
DCASSERT(SH);
HeapSort(SH, M, SC.Size());
setMap(M);
}
// ******************************************************************
// * *
// * expl_reachset::lexical_db_iter methods *
// * *
// ******************************************************************
expl_reachset::lexical_db_iter::lexical_db_iter(const hldsm* hm,
const StateLib::state_db &s) : db_iterator(s)
{
long* M = new long[s.Size()];
const StateLib::state_coll* coll = s.GetStateCollection();
LexicalSort(hm, coll, M);
setMap(M);
}
// ******************************************************************
// * *
// * expl_reachset::lexical_coll_iter methods *
// * *
// ******************************************************************
expl_reachset::lexical_coll_iter::lexical_coll_iter(const hldsm* hm,
const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH)
{
long* M = new long[SC.Size()];
DCASSERT(SH);
LexicalSort(hm, &SC, SH, M);
setMap(M);
}
| 29.746377 | 94 | 0.484409 | asminer |
2bce03c358b7d9221c58a8ab25166381d8f27de2 | 698 | cc | C++ | cmd/cmd_args.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | cmd/cmd_args.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | cmd/cmd_args.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | #include <system.hh>
#include <urbite.hh>
#include <process.hh>
#include <strutils.hh>
using namespace makemore;
extern "C" void mainmore(Process *);
void mainmore(
Process *process
) {
unsigned int itabn = process->itab.size();
if (itabn < 2)
return;
strvec argext;
if (!process->read(&argext, itabn - 1))
return;
process->itab[itabn - 1]->unlink_reader(process);
process->itab.resize(itabn - 1);
Command shellmore = find_command("sh");
process->cmd = "sh";
process->func = shellmore;
strvec bak_args = process->args;
catstrvec(process->args, argext);
shellmore(process);
process->cmd = "args";
process->func = mainmore;
process->args = bak_args;
}
| 19.388889 | 51 | 0.667622 | jdb19937 |
2bcef84f16db5b67460b4be9c6bec13eb5570382 | 122 | cpp | C++ | ACEXML/common/Element_Def_Builder.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | 16 | 2015-05-11T04:33:44.000Z | 2022-02-15T04:28:39.000Z | ACEXML/common/Element_Def_Builder.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | null | null | null | ACEXML/common/Element_Def_Builder.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | 7 | 2015-01-08T16:11:34.000Z | 2021-07-04T16:04:40.000Z | // $Id$
#include "ACEXML/common/Element_Def_Builder.h"
ACEXML_Element_Def_Builder::~ACEXML_Element_Def_Builder ()
{
}
| 12.2 | 58 | 0.762295 | BeiJiaan |
2bd23f8c9b1f6d6f07901780f6f8045644b96d26 | 12,695 | cpp | C++ | ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp | snazy2000/MediaBrowser.Plugins | 8c3a23fc0ce0186dd1ef048bf51a0eb7a1ee42b0 | [
"MIT"
] | 1 | 2021-05-15T16:24:07.000Z | 2021-05-15T16:24:07.000Z | ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp | bllakjakk/MediaBrowser.Plugins | 4b115a832f7f31d752ba0c135c65d570c6220bec | [
"MIT"
] | null | null | null | ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp | bllakjakk/MediaBrowser.Plugins | 4b115a832f7f31d752ba0c135c65d570c6220bec | [
"MIT"
] | null | null | null | /*****************************************************************
|
| Platinum - Synchronous Media Browser
|
| Copyright (c) 2004-2010, Plutinosoft, LLC.
| All rights reserved.
| http://www.plutinosoft.com
|
| This program is free software; you can redistribute it and/or
| modify it under the terms of the GNU General Public License
| as published by the Free Software Foundation; either version 2
| of the License, or (at your option) any later version.
|
| OEMs, ISVs, VARs and other distributors that combine and
| distribute commercially licensed software with Platinum software
| and do not wish to distribute the source code for the commercially
| licensed software under version 2, or (at your option) any later
| version, of the GNU General Public License (the "GPL") must enter
| into a commercial license agreement with Plutinosoft, LLC.
| [email protected]
|
| 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; see the file LICENSE.txt. If not, write to
| the Free Software Foundation, Inc.,
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
| http://www.gnu.org/licenses/gpl-2.0.html
|
****************************************************************/
/*----------------------------------------------------------------------
| includes
+---------------------------------------------------------------------*/
#include "PltSyncMediaBrowser.h"
NPT_SET_LOCAL_LOGGER("platinum.media.server.syncbrowser")
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::PLT_SyncMediaBrowser
+---------------------------------------------------------------------*/
PLT_SyncMediaBrowser::PLT_SyncMediaBrowser(PLT_CtrlPointReference& ctrlPoint,
bool use_cache /* = false */,
PLT_MediaContainerChangesListener* listener /* = NULL */) :
PLT_MediaBrowser(ctrlPoint),
m_ContainerListener(listener),
m_UseCache(use_cache)
{
SetDelegate(this);
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser
+---------------------------------------------------------------------*/
PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser()
{
}
/* Blocks forever waiting for a response from a request
* It is expected the request to succeed or to timeout and return an error eventually
*/
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::WaitForResponse
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::WaitForResponse(NPT_SharedVariable& shared_var)
{
return shared_var.WaitUntilEquals(1, 30000);
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::OnDeviceAdded
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::OnDeviceAdded(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
// test if it's a media server
PLT_Service* service;
if (NPT_SUCCEEDED(device->FindServiceByType("urn:schemas-upnp-org:service:ContentDirectory:*", service))) {
NPT_AutoLock lock(m_MediaServers);
m_MediaServers.Put(uuid, device);
}
return PLT_MediaBrowser::OnDeviceAdded(device);
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::OnDeviceRemoved
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::OnDeviceRemoved(PLT_DeviceDataReference& device)
{
NPT_String uuid = device->GetUUID();
// Remove from our list of servers first if found
{
NPT_AutoLock lock(m_MediaServers);
m_MediaServers.Erase(uuid);
}
// clear cache for that device
if (m_UseCache) m_Cache.Clear(device.AsPointer()->GetUUID());
return PLT_MediaBrowser::OnDeviceRemoved(device);
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::Find
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::Find(const char* ip, PLT_DeviceDataReference& device)
{
NPT_AutoLock lock(m_MediaServers);
const NPT_List<PLT_DeviceMapEntry*>::Iterator it =
m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByIp(ip));
if (it) {
device = (*it)->GetValue();
return NPT_SUCCESS;
}
return NPT_FAILURE;
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::OnBrowseResult
+---------------------------------------------------------------------*/
void
PLT_SyncMediaBrowser::OnBrowseResult(NPT_Result res,
PLT_DeviceDataReference& device,
PLT_BrowseInfo* info,
void* userdata)
{
NPT_COMPILER_UNUSED(device);
if (!userdata) return;
PLT_BrowseDataReference* data = (PLT_BrowseDataReference*) userdata;
(*data)->res = res;
if (NPT_SUCCEEDED(res) && info) {
(*data)->info = *info;
}
(*data)->shared_var.SetValue(1);
delete data;
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::OnMSStateVariablesChanged
+---------------------------------------------------------------------*/
void
PLT_SyncMediaBrowser::OnMSStateVariablesChanged(PLT_Service* service,
NPT_List<PLT_StateVariable*>* vars)
{
NPT_AutoLock lock(m_MediaServers);
PLT_DeviceDataReference device;
const NPT_List<PLT_DeviceMapEntry*>::Iterator it =
m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(service->GetDevice()->GetUUID()));
if (!it) return; // device with this service has gone away
device = (*it)->GetValue();
PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs");
if (var) {
// variable found, parse value
NPT_String value = var->GetValue();
NPT_String item_id, update_id;
int index;
while (value.GetLength()) {
// look for container id
index = value.Find(',');
if (index < 0) break;
item_id = value.Left(index);
value = value.SubString(index+1);
// look for update id
if (value.GetLength()) {
index = value.Find(',');
update_id = (index<0)?value:value.Left(index);
value = (index<0)?"":value.SubString(index+1);
// clear cache for that device
if (m_UseCache) m_Cache.Clear(device->GetUUID(), item_id);
// notify listener
if (m_ContainerListener) m_ContainerListener->OnContainerChanged(device, item_id, update_id);
}
}
}
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::BrowseSync
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::BrowseSync(PLT_BrowseDataReference& browse_data,
PLT_DeviceDataReference& device,
const char* object_id,
NPT_Int32 index,
NPT_Int32 count,
bool browse_metadata,
const char* filter,
const char* sort)
{
NPT_Result res;
browse_data->shared_var.SetValue(0);
browse_data->info.si = index;
// send off the browse packet. Note that this will
// not block. There is a call to WaitForResponse in order
// to block until the response comes back.
res = PLT_MediaBrowser::Browse(device,
(const char*)object_id,
index,
count,
browse_metadata,
filter,
sort,
new PLT_BrowseDataReference(browse_data));
NPT_CHECK_SEVERE(res);
return WaitForResponse(browse_data->shared_var);
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::BrowseSync
+---------------------------------------------------------------------*/
NPT_Result
PLT_SyncMediaBrowser::BrowseSync(PLT_DeviceDataReference& device,
const char* object_id,
PLT_MediaObjectListReference& list,
bool metadata, /* = false */
NPT_Int32 start, /* = 0 */
NPT_Cardinal max_results /* = 0 */)
{
NPT_Result res = NPT_FAILURE;
NPT_Int32 index = start;
// only cache metadata or if starting from 0 and asking for maximum
bool cache = m_UseCache && (metadata || (start == 0 && max_results == 0));
// reset output params
list = NULL;
// look into cache first
if (cache && NPT_SUCCEEDED(m_Cache.Get(device->GetUUID(), object_id, list))) return NPT_SUCCESS;
do {
PLT_BrowseDataReference browse_data(new PLT_BrowseData(), true);
// send off the browse packet. Note that this will
// not block. There is a call to WaitForResponse in order
// to block until the response comes back.
res = BrowseSync(
browse_data,
device,
(const char*)object_id,
index,
metadata?1:30, // DLNA recommendations for browsing children is no more than 30 at a time
metadata);
NPT_CHECK_LABEL_WARNING(res, done);
if (NPT_FAILED(browse_data->res)) {
res = browse_data->res;
NPT_CHECK_LABEL_WARNING(res, done);
}
// server returned no more, bail now
if (browse_data->info.items->GetItemCount() == 0)
break;
if (list.IsNull()) {
list = browse_data->info.items;
} else {
list->Add(*browse_data->info.items);
// clear the list items so that the data inside is not
// cleaned up by PLT_MediaItemList dtor since we copied
// each pointer into the new list.
browse_data->info.items->Clear();
}
// stop now if our list contains exactly what the server said it had.
// Note that the server could return 0 if it didn't know how many items were
// available. In this case we have to continue browsing until
// nothing is returned back by the server.
// Unless we were told to stop after reaching a certain amount to avoid
// length delays
// (some servers may return a total matches out of whack at some point too)
if ((browse_data->info.tm && browse_data->info.tm <= list->GetItemCount()) ||
(max_results && list->GetItemCount() >= max_results))
break;
// ask for the next chunk of entries
index = list->GetItemCount();
} while(1);
done:
// cache the result
if (cache && NPT_SUCCEEDED(res) && !list.IsNull() && list->GetItemCount()) {
m_Cache.Put(device->GetUUID(), object_id, list);
}
// clear entire cache data for device if failed, the device could be gone
if (NPT_FAILED(res) && cache) m_Cache.Clear(device->GetUUID());
return res;
}
/*----------------------------------------------------------------------
| PLT_SyncMediaBrowser::IsCached
+---------------------------------------------------------------------*/
bool
PLT_SyncMediaBrowser::IsCached(const char* uuid, const char* object_id)
{
NPT_AutoLock lock(m_MediaServers);
const NPT_List<PLT_DeviceMapEntry*>::Iterator it =
m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(uuid));
if (!it) {
m_Cache.Clear(uuid);
return false; // device with this service has gone away
}
PLT_MediaObjectListReference list;
return NPT_SUCCEEDED(m_Cache.Get(uuid, object_id, list))?true:false;
}
| 38.353474 | 111 | 0.525876 | snazy2000 |
2bda52c3a52f8cc9f8c5e5d7d2099af28122dee2 | 20,268 | hh | C++ | graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | // graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <[email protected]>
//
// 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 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef GRAPH_BLOCKMODEL_PARTITION_HH
#define GRAPH_BLOCKMODEL_PARTITION_HH
#include "../support/util.hh"
#include "../support/int_part.hh"
namespace graph_tool
{
// ===============
// Partition stats
// ===============
constexpr size_t null_group = std::numeric_limits<size_t>::max();
typedef vprop_map_t<std::vector<std::tuple<size_t, size_t, size_t>>>::type
degs_map_t;
struct simple_degs_t {};
template <class Graph, class Vprop, class Eprop, class F>
__attribute__((always_inline)) __attribute__((flatten)) inline
void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const simple_degs_t&,
Graph& g, F&& f)
{
f(in_degreeS()(v, g, eweight), out_degreeS()(v, g, eweight), vweight[v]);
}
template <class Graph, class Vprop, class Eprop, class F>
__attribute__((always_inline)) __attribute__((flatten)) inline
void degs_op(size_t v, Vprop& vweight, Eprop& eweight,
const typename degs_map_t::unchecked_t& degs, Graph& g, F&& f)
{
auto& ks = degs[v];
if (ks.empty())
{
degs_op(v, vweight, eweight, simple_degs_t(), g, std::forward<F>(f));
}
else
{
for (auto& k : ks)
f(get<0>(k), get<1>(k), get<2>(k));
}
}
template <bool use_rmap>
class partition_stats
{
public:
typedef gt_hash_map<pair<size_t,size_t>, int> map_t;
template <class Graph, class Vprop, class VWprop, class Eprop, class Degs,
class Mprop, class Vlist>
partition_stats(Graph& g, Vprop& b, Vlist& vlist, size_t E, size_t B,
VWprop& vweight, Eprop& eweight, Degs& degs,
const Mprop& ignore_degree, std::vector<size_t>& bmap,
bool allow_empty)
: _bmap(bmap), _N(0), _E(E), _total_B(B), _allow_empty(allow_empty)
{
if (!use_rmap)
{
_hist.resize(num_vertices(g));
_total.resize(num_vertices(g));
_ep.resize(num_vertices(g));
_em.resize(num_vertices(g));
}
for (auto v : vlist)
{
if (vweight[v] == 0)
continue;
auto r = get_r(b[v]);
if (v >= _ignore_degree.size())
_ignore_degree.resize(v + 1, 0);
_ignore_degree[v] = ignore_degree[v];
degs_op(v, vweight, eweight, degs, g,
[&](auto kin, auto kout, auto n)
{
if (_ignore_degree[v] == 2)
kout = 0;
if (_ignore_degree[v] != 1)
{
_hist[r][make_pair(kin, kout)] += n;
_em[r] += kin * n;
_ep[r] += kout * n;
}
_total[r] += n;
_N += n;
});
}
_actual_B = 0;
for (auto n : _total)
{
if (n > 0)
_actual_B++;
}
}
size_t get_r(size_t r)
{
if (use_rmap)
{
constexpr size_t null =
std::numeric_limits<size_t>::max();
if (r >= _bmap.size())
_bmap.resize(r + 1, null);
size_t nr = _bmap[r];
if (nr == null)
nr = _bmap[r] = _hist.size();
r = nr;
}
if (r >= _hist.size())
{
_hist.resize(r + 1);
_total.resize(r + 1);
_ep.resize(r + 1);
_em.resize(r + 1);
}
return r;
}
double get_partition_dl()
{
double S = 0;
if (_allow_empty)
S += lbinom(_total_B + _N - 1, _N);
else
S += lbinom(_N - 1, _actual_B - 1);
S += lgamma_fast(_N + 1);
for (auto nr : _total)
S -= lgamma_fast(nr + 1);
S += safelog_fast(_N);
return S;
}
template <class Rs, class Ks>
double get_deg_dl_ent(Rs&& rs, Ks&& ks)
{
double S = 0;
for (auto r : rs)
{
r = get_r(r);
size_t total = 0;
if (ks.empty())
{
for (auto& k_c : _hist[r])
{
S -= xlogx_fast(k_c.second);
total += k_c.second;
}
}
else
{
auto& h = _hist[r];
for (auto& k : ks)
{
auto iter = h.find(k);
auto k_c = (iter != h.end()) ? iter->second : 0;
S -= xlogx(k_c);
}
total = _total[r];
}
S += xlogx_fast(total);
}
return S;
}
template <class Rs, class Ks>
double get_deg_dl_uniform(Rs&& rs, Ks&&)
{
double S = 0;
for (auto r : rs)
{
r = get_r(r);
S += lbinom(_total[r] + _ep[r] - 1, _ep[r]);
S += lbinom(_total[r] + _em[r] - 1, _em[r]);
}
return S;
}
template <class Rs, class Ks>
double get_deg_dl_dist(Rs&& rs, Ks&& ks)
{
double S = 0;
for (auto r : rs)
{
r = get_r(r);
S += log_q(_ep[r], _total[r]);
S += log_q(_em[r], _total[r]);
size_t total = 0;
if (ks.empty())
{
for (auto& k_c : _hist[r])
{
S -= lgamma_fast(k_c.second + 1);
total += k_c.second;
}
}
else
{
auto& h = _hist[r];
for (auto& k : ks)
{
auto iter = h.find(k);
auto k_c = (iter != h.end()) ? iter->second : 0;
S -= lgamma_fast(k_c + 1);
}
total = _total[r];
}
S += lgamma_fast(total + 1);
}
return S;
}
template <class Rs, class Ks>
double get_deg_dl(int kind, Rs&& rs, Ks&& ks)
{
switch (kind)
{
case deg_dl_kind::ENT:
return get_deg_dl_ent(rs, ks);
case deg_dl_kind::UNIFORM:
return get_deg_dl_uniform(rs, ks);
case deg_dl_kind::DIST:
return get_deg_dl_dist(rs, ks);
default:
return numeric_limits<double>::quiet_NaN();
}
}
double get_deg_dl(int kind)
{
return get_deg_dl(kind, boost::counting_range(size_t(0), _total_B),
std::array<std::pair<size_t,size_t>,0>());
}
template <class Graph>
double get_edges_dl(size_t B, Graph& g)
{
size_t BB = (graph_tool::is_directed(g)) ? B * B : (B * (B + 1)) / 2;
return lbinom(BB + _E - 1, _E);
}
template <class VProp>
double get_delta_partition_dl(size_t v, size_t r, size_t nr, VProp& vweight)
{
if (r == nr)
return 0;
if (r != null_group)
r = get_r(r);
if (nr != null_group)
nr = get_r(nr);
int n = vweight[v];
if (n == 0)
{
if (r == null_group)
n = 1;
else
return 0;
}
double S_b = 0, S_a = 0;
if (r != null_group)
{
S_b += -lgamma_fast(_total[r] + 1);
S_a += -lgamma_fast(_total[r] - n + 1);
}
if (nr != null_group)
{
S_b += -lgamma_fast(_total[nr] + 1);
S_a += -lgamma_fast(_total[nr] + n + 1);
}
int dN = 0;
if (r == null_group)
dN += n;
if (nr == null_group)
dN -= n;
S_b += lgamma_fast(_N + 1);
S_a += lgamma_fast(_N + dN + 1);
int dB = 0;
if (r != null_group && _total[r] == n)
dB--;
if (nr != null_group && _total[nr] == 0)
dB++;
if ((dN != 0 || dB != 0) && !_allow_empty)
{
S_b += lbinom_fast(_N - 1, _actual_B - 1);
S_a += lbinom_fast(_N - 1 + dN, _actual_B + dB - 1);
}
if (dN != 0)
{
S_b += safelog_fast(_N);
S_a += safelog_fast(_N + dN);
}
return S_a - S_b;
}
template <class VProp, class Graph>
double get_delta_edges_dl(size_t v, size_t r, size_t nr, VProp& vweight,
size_t actual_B, Graph& g)
{
if (r == nr || _allow_empty)
return 0;
if (r != null_group)
r = get_r(r);
if (nr != null_group)
nr = get_r(nr);
double S_b = 0, S_a = 0;
int n = vweight[v];
if (n == 0)
{
if (r == null_group)
n = 1;
else
return 0;
}
int dB = 0;
if (r != null_group && _total[r] == n)
dB--;
if (nr != null_group && _total[nr] == 0)
dB++;
if (dB != 0)
{
S_b += get_edges_dl(actual_B, g);
S_a += get_edges_dl(actual_B + dB, g);
}
return S_a - S_b;
}
template <class Graph, class VProp, class EProp, class Degs>
double get_delta_deg_dl(size_t v, size_t r, size_t nr, VProp& vweight,
EProp& eweight, Degs& degs, Graph& g, int kind)
{
if (r == nr || _ignore_degree[v] == 1 || vweight[v] == 0)
return 0;
if (r != null_group)
r = get_r(r);
if (nr != null_group)
nr = get_r(nr);
auto dop =
[&](auto&& f)
{
if (_ignore_degree[v] == 2)
{
degs_op(v, vweight, eweight, degs, g,
[&](auto kin, auto, auto n)
{
f(kin, 0, n);
});
}
else
{
degs_op(v, vweight, eweight, degs, g,
[&](auto... k) { f(k...); });
}
};
double dS = 0;
switch (kind)
{
case deg_dl_kind::ENT:
if (r != null_group)
dS += get_delta_deg_dl_ent_change(r, dop, -1);
if (nr != null_group)
dS += get_delta_deg_dl_ent_change(nr, dop, +1);
break;
case deg_dl_kind::UNIFORM:
if (r != null_group)
dS += get_delta_deg_dl_uniform_change(v, r, dop, -1);
if (nr != null_group)
dS += get_delta_deg_dl_uniform_change(v, nr, dop, +1);
break;
case deg_dl_kind::DIST:
if (r != null_group)
dS += get_delta_deg_dl_dist_change(v, r, dop, -1);
if (nr != null_group)
dS += get_delta_deg_dl_dist_change(v, nr, dop, +1);
break;
default:
dS = numeric_limits<double>::quiet_NaN();
}
return dS;
}
template <class DegOP>
double get_delta_deg_dl_ent_change(size_t r, DegOP&& dop, int diff)
{
int nr = _total[r];
auto get_Sk = [&](size_t s, pair<size_t, size_t>& deg, int delta)
{
int nd = 0;
auto iter = _hist[s].find(deg);
if (iter != _hist[s].end())
nd = iter->second;
assert(nd + delta >= 0);
return -xlogx_fast(nd + delta);
};
double S_b = 0, S_a = 0;
int dn = 0;
dop([&](size_t kin, size_t kout, int nk)
{
dn += diff * nk;
auto deg = make_pair(kin, kout);
S_b += get_Sk(r, deg, 0);
S_a += get_Sk(r, deg, diff * nk);
});
S_b += xlogx_fast(nr);
S_a += xlogx_fast(nr + dn);
return S_a - S_b;
}
template <class DegOP>
double get_delta_deg_dl_uniform_change(size_t v, size_t r, DegOP&& dop,
int diff)
{
auto get_Se = [&](int dn, int dkin, int dkout)
{
double S = 0;
S += lbinom_fast(_total[r] + dn + _ep[r] - 1 + dkout, _ep[r] + dkout);
S += lbinom_fast(_total[r] + dn + _em[r] - 1 + dkin, _em[r] + dkin);
return S;
};
double S_b = 0, S_a = 0;
int tkin = 0, tkout = 0, n = 0;
dop([&](auto kin, auto kout, int nk)
{
tkin += kin * nk;
if (_ignore_degree[v] != 2)
tkout += kout * nk;
n += nk;
});
S_b += get_Se( 0, 0, 0);
S_a += get_Se(diff * n, diff * tkin, diff * tkout);
return S_a - S_b;
}
template <class DegOP>
double get_delta_deg_dl_dist_change(size_t v, size_t r, DegOP&& dop,
int diff)
{
auto get_Se = [&](int delta, int kin, int kout)
{
double S = 0;
assert(_total[r] + delta >= 0);
assert(_em[r] + kin >= 0);
assert(_ep[r] + kout >= 0);
S += log_q(_em[r] + kin, _total[r] + delta);
S += log_q(_ep[r] + kout, _total[r] + delta);
return S;
};
auto get_Sr = [&](int delta)
{
assert(_total[r] + delta + 1 >= 0);
return lgamma_fast(_total[r] + delta + 1);
};
auto get_Sk = [&](pair<size_t, size_t>& deg, int delta)
{
int nd = 0;
auto iter = _hist[r].find(deg);
if (iter != _hist[r].end())
nd = iter->second;
assert(nd + delta >= 0);
return -lgamma_fast(nd + delta + 1);
};
double S_b = 0, S_a = 0;
int tkin = 0, tkout = 0, n = 0;
dop([&](size_t kin, size_t kout, int nk)
{
tkin += kin * nk;
if (_ignore_degree[v] != 2)
tkout += kout * nk;
n += nk;
auto deg = make_pair(kin, kout);
S_b += get_Sk(deg, 0);
S_a += get_Sk(deg, diff * nk);
});
S_b += get_Se( 0, 0, 0);
S_a += get_Se(diff * n, diff * tkin, diff * tkout);
S_b += get_Sr( 0);
S_a += get_Sr(diff * n);
return S_a - S_b;
}
template <class Graph, class VWeight, class EWeight, class Degs>
void change_vertex(size_t v, size_t r, bool deg_corr, Graph& g,
VWeight& vweight, EWeight& eweight, Degs& degs,
int diff)
{
int vw = vweight[v];
int dv = vw * diff;
if (_total[r] == 0 && dv > 0)
_actual_B++;
if (_total[r] == vw && dv < 0)
_actual_B--;
_total[r] += dv;
_N += dv;
assert(_total[r] >= 0);
if (deg_corr && _ignore_degree[v] != 1)
{
degs_op(v, vweight, eweight, degs, g,
[&](auto kin, auto kout, auto n)
{
int dk = diff * n;
if (_ignore_degree[v] == 2)
kout = 0;
auto& h = _hist[r];
auto deg = make_pair(kin, kout);
auto iter = h.insert({deg, 0}).first;
iter->second += dk;
if (iter->second == 0)
h.erase(iter);
_em[r] += dk * deg.first;
_ep[r] += dk * deg.second;
});
}
}
template <class Graph, class VWeight, class EWeight, class Degs>
void remove_vertex(size_t v, size_t r, bool deg_corr, Graph& g,
VWeight& vweight, EWeight& eweight, Degs& degs)
{
if (r == null_group || vweight[v] == 0)
return;
r = get_r(r);
change_vertex(v, r, deg_corr, g, vweight, eweight, degs, -1);
}
template <class Graph, class VWeight, class EWeight, class Degs>
void add_vertex(size_t v, size_t nr, bool deg_corr, Graph& g,
VWeight& vweight, EWeight& eweight, Degs& degs)
{
if (nr == null_group || vweight[v] == 0)
return;
nr = get_r(nr);
change_vertex(v, nr, deg_corr, g, vweight, eweight, degs, 1);
}
void change_k(size_t v, size_t r, bool deg_corr, int vweight,
int kin, int kout, int diff)
{
if (_total[r] == 0 && diff * vweight > 0)
_actual_B++;
if (_total[r] == vweight && diff * vweight < 0)
_actual_B--;
_total[r] += diff * vweight;
_N += diff * vweight;
assert(_total[r] >= 0);
if (deg_corr && _ignore_degree[v] != 1)
{
if (_ignore_degree[v] == 2)
kout = 0;
auto deg = make_pair(kin, kout);
auto iter = _hist[r].insert({deg, 0}).first;
iter->second += diff * vweight;
if (iter->second == 0)
_hist[r].erase(iter);
_em[r] += diff * deg.first * vweight;
_ep[r] += diff * deg.second * vweight;
}
}
void change_E(int dE)
{
_E += dE;
}
size_t get_N()
{
return _N;
}
size_t get_E()
{
return _E;
}
size_t get_actual_B()
{
return _actual_B;
}
void add_block()
{
_total_B++;
}
template <class Graph, class VProp, class VWeight, class EWeight, class Degs>
bool check_degs(Graph& g, VProp& b, VWeight& vweight, EWeight& eweight, Degs& degs)
{
vector<map_t> dhist;
for (auto v : vertices_range(g))
{
degs_op(v, vweight, eweight, degs, g,
[&](auto kin, auto kout, auto n)
{
auto r = get_r(b[v]);
if (r >= dhist.size())
dhist.resize(r + 1);
dhist[r][{kin, kout}] += n;
});
}
for (size_t r = 0; r < dhist.size(); ++r)
{
for (auto& kn : dhist[r])
{
auto count = (r >= _hist.size()) ? 0 : _hist[r][kn.first];
if (kn.second != count)
{
assert(false);
return false;
}
}
}
for (size_t r = 0; r < _hist.size(); ++r)
{
for (auto& kn : _hist[r])
{
auto count = (r >= dhist.size()) ? 0 : dhist[r][kn.first];
if (kn.second != count)
{
assert(false);
return false;
}
}
}
return true;
}
private:
vector<size_t>& _bmap;
size_t _N;
size_t _E;
size_t _actual_B;
size_t _total_B;
bool _allow_empty;
vector<map_t> _hist;
vector<int> _total;
vector<int> _ep;
vector<int> _em;
vector<uint8_t> _ignore_degree;
};
} //namespace graph_tool
#endif // GRAPH_BLOCKMODEL_PARTITION_HH
| 28.506329 | 87 | 0.433886 | Znigneering |
2bdf37205f44b62d3314760437b00baa263f64ea | 5,437 | cc | C++ | deprected/tests/testUtils.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | deprected/tests/testUtils.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | deprected/tests/testUtils.cc | RobertWeber1/cli | 5cb67325610be41014403e9342dddbe942511c2b | [
"MIT"
] | null | null | null | #include "testUtils.h"
namespace CLI
{
std::ostream & operator<<( std::ostream & os, border::Element::Type type )
{
switch(type)
{
case border::Element::NONE:
return os << "NONE";
case border::Element::UNUSED_1:
return os << "UNUSED_1";
case border::Element::UNUSED_2:
return os << "UNUSED_2";
case border::Element::TOP_RIGHT:
return os << "TOP_RIGHT";
case border::Element::UNUSED_4:
return os << "UNUSED_4";
case border::Element::VERTICAL:
return os << "VERTICAL";
case border::Element::BOTTOM_RIGHT:
return os << "BOTTOM_RIGHT";
case border::Element::TEE_RIGHT:
return os << "TEE_RIGHT";
case border::Element::UNUSED_8:
return os << "UNUSED_8";
case border::Element::TOP_LEFT:
return os << "TOP_LEFT";
case border::Element::HORIZONTAL:
return os << "HORIZONTAL";
case border::Element::TEE_TOP:
return os << "TEE_TOP";
case border::Element::BOTTOM_LEFT:
return os << "BOTTOM_LEFT";
case border::Element::TEE_LEFT:
return os << "TEE_LEFT";
case border::Element::TEE_BOTTOM:
return os << "TEE_BOTTOM";
case border::Element::CROSS:
return os << "CROSS";
case border::Element::INVERT:
return os << "INVERT";
default:
return os;
}
}
std::ostream & operator<<( std::ostream & os, util::Color color )
{
switch(color)
{
case util::BLACK:
return os << "BLACK";
case util::WHITE:
return os << "WHITE";
case util::RED:
return os << "RED";
case util::GREEN:
return os << "GREEN";
case util::BLUE:
return os << "BLUE";
case util::YELLOW:
return os << "YELLOW";
case util::CYAN:
return os << "CYAN";
case util::MAGENTA:
return os << "MAGENTA";
default:
return os;
}
}
std::ostream & operator<<( std::ostream & os, util::Attribute attr )
{
switch(attr)
{
case util::NONE:
return os << "NONE";
case util::BOLD:
return os << "BOLD";
case util::DIM:
return os << "DIM";
case util::UNDERSCORE:
return os << "UNDERSCORE";
case util::BLINK:
return os << "BLINK";
case util::INVERSE:
return os << "INVERSE";
case util::HIDDEN:
return os << "HIDDEN";
default:
return os;
}
}
std::string to_string( util::Point const& point )
{
std::stringstream result;
result << "P(x: " << point.x() << ", y: " << point.y() << ")";
return result.str();
}
std::string to_string( util::Size const& size )
{
std::stringstream result;
result << "S(w: " << size.width() << ", h: " << size.height() << ")";
return result.str();
}
std::string to_string( util::Properties const& prop )
{
std::stringstream result;
result << "Prop(fg: " << prop.foreground << ", bg: " << prop.background << ", attr: " << prop.attribute << ")";
return result.str();
}
std::string to_string( util::SizeConstraint const& constraint )
{
std::stringstream result;
result << "C(min: " << constraint.min_val() << ", max: " << constraint.max_val() << ", f: " << constraint.factor() << ")";
return result.str();
}
std::string to_string( util::SizeHint const& size_hint )
{
std::stringstream result;
result << "Hwidth: " << to_string(size_hint.width()) << ", Hheight:" << to_string(size_hint.height());
return result.str();
}
std::string to_string( border::Buffer & buffer )
{
char char_map[16] = {
' ',//NONE = 0b00000,
'0',//UNUSED_1 = 0b00001,
'0',//UNUSED_2 = 0b00010,
'7',//BOTTOM_LEFT = 0b00011,
'0',//UNUSED_4 = 0b00100,
'|',//VERTICAL = 0b00101,
'1',//TOP_LEFT = 0b00110,
'8',//TEE_RIGHT = 0b00111,
'0',//UNUSED_8 = 0b01000,
'5',//BOTTOM_RIGHT = 0b01001,
'-',//HORIZONTAL = 0b01010,
'6',//TEE_TOP = 0b01011,
'3',//TOP_RIGHT = 0b01100,
'4',//TEE_LEFT = 0b01101,
'2',//TEE_BOTTOM = 0b01110,
'+' //CROSS = 0b01111,
};
char inv_map[16] = {
' ',//NONE = 0b00000,
'0',//UNUSED_1 = 0b00001,
'0',//UNUSED_2 = 0b00010,
'G',//BOTTOM_LEFT = 0b00011,
'0',//UNUSED_4 = 0b00100,
'#',//VERTICAL = 0b00101,
'A',//TOP_LEFT = 0b00110,
'H',//TEE_RIGHT = 0b00111,
'0',//UNUSED_8 = 0b01000,
'E',//BOTTOM_RIGHT = 0b01001,
'=',//HORIZONTAL = 0b01010,
'F',//TEE_TOP = 0b01011,
'C',//TOP_RIGHT = 0b01100,
'D',//TEE_LEFT = 0b01101,
'B',//TEE_BOTTOM = 0b01110,
'%' //CROSS = 0b01111,
};
std::stringstream borders;
util::Point pos;
border::Element *element;
while( element = buffer.get( pos ) )
{
while( element = buffer.get( pos ) )
{
//borders << element->to_char(char_map);
if(element->is_inverted())
{
borders << element->to_char(inv_map);
}
else
{
borders << element->to_char(char_map);
}
pos.right();
}
borders << "\n";
pos.break_line();
}
return borders.str();
}
}
| 22.654167 | 126 | 0.516093 | RobertWeber1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.