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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
80df7ac14ab2c88b706b8ac64d67c39a28147969
| 4,992
|
cpp
|
C++
|
Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp
|
serenityosrocks/serenity
|
75d0f2c7030cc3c14833510e5c25304d1f311f8b
|
[
"BSD-2-Clause"
] | null | null | null |
Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp
|
serenityosrocks/serenity
|
75d0f2c7030cc3c14833510e5c25304d1f311f8b
|
[
"BSD-2-Clause"
] | null | null | null |
Userland/Applications/SystemMonitor/MemoryStatsWidget.cpp
|
serenityosrocks/serenity
|
75d0f2c7030cc3c14833510e5c25304d1f311f8b
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2022, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "MemoryStatsWidget.h"
#include "GraphWidget.h"
#include <AK/JsonObject.h>
#include <AK/NumberFormat.h>
#include <LibCore/File.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Label.h>
#include <LibGUI/Painter.h>
#include <LibGfx/FontDatabase.h>
#include <LibGfx/StylePainter.h>
#include <stdlib.h>
static MemoryStatsWidget* s_the;
MemoryStatsWidget* MemoryStatsWidget::the()
{
return s_the;
}
MemoryStatsWidget::MemoryStatsWidget(GraphWidget& graph)
: m_graph(graph)
{
VERIFY(!s_the);
s_the = this;
set_fixed_height(110);
set_layout<GUI::VerticalBoxLayout>();
layout()->set_margins({ 8, 0, 0 });
layout()->set_spacing(3);
auto build_widgets_for_label = [this](String const& description) -> RefPtr<GUI::Label> {
auto& container = add<GUI::Widget>();
container.set_layout<GUI::HorizontalBoxLayout>();
container.set_fixed_size(275, 12);
auto& description_label = container.add<GUI::Label>(description);
description_label.set_font(Gfx::FontDatabase::default_font().bold_variant());
description_label.set_text_alignment(Gfx::TextAlignment::CenterLeft);
auto& label = container.add<GUI::Label>();
label.set_text_alignment(Gfx::TextAlignment::CenterRight);
return label;
};
m_user_physical_pages_label = build_widgets_for_label("Physical memory:");
m_user_physical_pages_committed_label = build_widgets_for_label("Committed memory:");
m_supervisor_physical_pages_label = build_widgets_for_label("Supervisor physical:");
m_kmalloc_space_label = build_widgets_for_label("Kernel heap:");
m_kmalloc_count_label = build_widgets_for_label("Calls kmalloc:");
m_kfree_count_label = build_widgets_for_label("Calls kfree:");
m_kmalloc_difference_label = build_widgets_for_label("Difference:");
refresh();
}
static inline u64 page_count_to_bytes(size_t count)
{
return count * 4096;
}
void MemoryStatsWidget::refresh()
{
auto proc_memstat = Core::File::construct("/proc/memstat");
if (!proc_memstat->open(Core::OpenMode::ReadOnly))
VERIFY_NOT_REACHED();
auto file_contents = proc_memstat->read_all();
auto json_result = JsonValue::from_string(file_contents).release_value_but_fixme_should_propagate_errors();
auto const& json = json_result.as_object();
u32 kmalloc_allocated = json.get("kmalloc_allocated").to_u32();
u32 kmalloc_available = json.get("kmalloc_available").to_u32();
u64 user_physical_allocated = json.get("user_physical_allocated").to_u64();
u64 user_physical_available = json.get("user_physical_available").to_u64();
u64 user_physical_committed = json.get("user_physical_committed").to_u64();
u64 user_physical_uncommitted = json.get("user_physical_uncommitted").to_u64();
u64 super_physical_alloc = json.get("super_physical_allocated").to_u64();
u64 super_physical_free = json.get("super_physical_available").to_u64();
u32 kmalloc_call_count = json.get("kmalloc_call_count").to_u32();
u32 kfree_call_count = json.get("kfree_call_count").to_u32();
u64 kmalloc_bytes_total = kmalloc_allocated + kmalloc_available;
u64 user_physical_pages_total = user_physical_allocated + user_physical_available;
u64 supervisor_pages_total = super_physical_alloc + super_physical_free;
u64 physical_pages_total = user_physical_pages_total + supervisor_pages_total;
u64 physical_pages_in_use = user_physical_allocated + super_physical_alloc;
u64 total_userphysical_and_swappable_pages = user_physical_allocated + user_physical_committed + user_physical_uncommitted;
m_kmalloc_space_label->set_text(String::formatted("{}/{}", human_readable_size(kmalloc_allocated), human_readable_size(kmalloc_bytes_total)));
m_user_physical_pages_label->set_text(String::formatted("{}/{}", human_readable_size(page_count_to_bytes(physical_pages_in_use)), human_readable_size(page_count_to_bytes(physical_pages_total))));
m_user_physical_pages_committed_label->set_text(String::formatted("{}", human_readable_size(page_count_to_bytes(user_physical_committed))));
m_supervisor_physical_pages_label->set_text(String::formatted("{}/{}", human_readable_size(page_count_to_bytes(super_physical_alloc)), human_readable_size(page_count_to_bytes(supervisor_pages_total))));
m_kmalloc_count_label->set_text(String::formatted("{}", kmalloc_call_count));
m_kfree_count_label->set_text(String::formatted("{}", kfree_call_count));
m_kmalloc_difference_label->set_text(String::formatted("{:+}", kmalloc_call_count - kfree_call_count));
m_graph.set_max(page_count_to_bytes(total_userphysical_and_swappable_pages) + kmalloc_bytes_total);
m_graph.add_value({ page_count_to_bytes(user_physical_committed), page_count_to_bytes(user_physical_allocated), kmalloc_bytes_total });
}
| 46.654206
| 206
| 0.765825
|
serenityosrocks
|
80e28e222c022389b78ee3fbec4ed45a0a7732e7
| 635
|
hpp
|
C++
|
include/Scene.hpp
|
KPO-2020-2021/zad5_1-iliubin7
|
0d3d3829830974863d25b8f5f91e5ace6ccbeaca
|
[
"Unlicense"
] | null | null | null |
include/Scene.hpp
|
KPO-2020-2021/zad5_1-iliubin7
|
0d3d3829830974863d25b8f5f91e5ace6ccbeaca
|
[
"Unlicense"
] | null | null | null |
include/Scene.hpp
|
KPO-2020-2021/zad5_1-iliubin7
|
0d3d3829830974863d25b8f5f91e5ace6ccbeaca
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <iostream>
#include <iomanip>
#include <fstream>
#include "Block.hpp"
#include "lacze_do_gnuplota.hpp"
#include "Dron.hpp"
#include "Surface.hpp"
#define N 2
/*!
* \file Scene.hpp
*
*/
/*! \class Scene
*
*/
class Scene
{
PzG::LaczeDoGNUPlota Lacze;
/*!
* Tablica dronow
*/
Dron *tab[N];
/*!
* Dno plaszczyzny
*/
Surface *bottom;
public:
/*!
* Konstruktor klasy Scene
*/
Scene();
/*!
* Metoda do rysowania calej Sceny
*/
void draw();
bool interface();
/*!
* Destruktor klasy Scene
* Argumenty:
Brak argumentow.
* Zwraca:
* Usuwa dynamicznie zaalokowane obiekty.
*/
~Scene();
};
| 12.45098
| 42
| 0.637795
|
KPO-2020-2021
|
80e43fe8997e8f07dc6a0cb3f95b0cc271451e29
| 15,797
|
cpp
|
C++
|
Funambol/source/common/updater/Updater.cpp
|
wbitos/funambol
|
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
|
[
"MIT"
] | null | null | null |
Funambol/source/common/updater/Updater.cpp
|
wbitos/funambol
|
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
|
[
"MIT"
] | null | null | null |
Funambol/source/common/updater/Updater.cpp
|
wbitos/funambol
|
29f76caf9cee51d51ddf5318613411cb1cfb8e4e
|
[
"MIT"
] | null | null | null |
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2008 Funambol, 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 with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include <Funambol/http/TransportAgent.h>
#include <Funambol/http/TransportAgentFactory.h>
#include <Funambol/http/URL.h>
#include <Funambol/http/Proxy.h>
#include <Funambol/base/errors.h>
#include <Funambol/base/Log.h>
#include <Funambol/updater/Updater.h>
#include <Funambol/updater/UpdaterConfig.h>
#include <Funambol/updater/UpdaterUI.h>
USE_NAMESPACE
Updater::Updater(const StringBuffer& component, const StringBuffer& version, UpdaterConfig& c)
: component(component),
version(version),
nextRemindTime(0),
config(c),
ui(NULL)
{
bool readOk = config.read();
if (!readOk || config.getRecommended().empty()) {
// Config not found or corrupted -> generate and save it
config.createDefaultConfig();
config.save();
}
// Init all times
uint32_t checkInterval = config.getIntervalCheckUpdateHttp();
uint32_t lastCheckUpdate = string2long(config.getLastCheckUpdate().c_str());
nextRemindTime = string2long(config.getNextRemindCheck().c_str());
currentTime = time(NULL);
// We want the upgrade check to be performed after the first sync on app
// startup, we don't want to wait for the reminder time to elapse
nextCheckTime = lastCheckUpdate + checkInterval;
LOG.debug("Next http check: %d", nextCheckTime);
LOG.debug("Next local Later check: %d", nextRemindTime);
}
Updater::~Updater() { }
void Updater::setUI(UpdaterUI* ui) {
this->ui = ui;
}
/**
* This method combines information and returns true if the user must be
* notified about a new version available.
* The method is responsible for querying the server if the http interval
* has expired.
*/
bool Updater::checkIsToUpdate() {
bool ret = true;
// Update current time
currentTime = time(NULL);
LOG.debug("Current time is: %d", currentTime);
LOG.debug("Next check time is: %d", nextCheckTime);
// First of all we check if it is time to query the
// server for new updates. This is done regardless of the remind time,
// as we may have a newer version to install and we want to show this
// asap, and not wait for the remind interval to expire
if (currentTime > nextCheckTime) {
LOG.info("Check on server location for update");
int32_t req = requestUpdate();
if (req != -1) {
// set the lastCheckUpdate in the config to be saved later
config.setLastCheckUpdate(long2string((uint32_t)currentTime));
config.save();
} else {
LOG.error("update check failed");
ret = false;
goto finally;
}
}
// If it is too early to notify the user, we don't do it
// (if a new version is detected, the nextRemindTime is reset
// by requestUpdate)
if (currentTime < nextRemindTime) {
LOG.debug("No time to check on local");
ret = false;
goto finally;
}
if (config.getVersion() == "0" || config.getVersion() == version) {
LOG.debug("No new version available");
ret = false;
}
finally:
return ret;
}
bool Updater::start() {
LOG.debug("Starting update check");
bool updateAvailable = checkIsToUpdate();
if (updateAvailable) {
LOG.debug("New version available");
return newVersionAvailable();
}
return false;
}
int32_t Updater::requestUpdate() {
int32_t res = 0;
URL url;
StringBuffer s;
if (config.getUrlCheck().empty() || config.getUrlCheck() == "0") {
LOG.debug("Invalid update url, cannot proceed");
return -1;
} else {
s = config.getUrlCheck().c_str();
}
// add the component and version to the url
s += "&";
s += UP_URL_COMPONENT;
s += component;
s += "&";
s += UP_URL_VERSION;
s += version;
s += "&";
s += UP_URL_FORMAT;
s += UP_PROPERTIES; // To get data in the properties format (JSON is default)
LOG.debug("Update url: %s", s.c_str());
url.setURL(s.c_str());
Proxy proxy;
TransportAgent* transportAgent = NULL;
transportAgent = TransportAgentFactory::getTransportAgent(url, proxy);
transportAgent->setUserAgent(USER_AGENT);
StringBuffer message = "";
char* response = transportAgent->sendMessage(message.c_str());
if (response) {
LOG.debug("Update server response: %s", response);
} else {
LOG.error("No response from update server");
}
StringBuffer nextVersion = config.getVersion();
if (response != NULL) {
int32_t parseRes = parseMessage(response);
if (parseRes < 0) {
LOG.error("Cannot parse update server response message");
} else {
// Update times
config.setLastCheckUpdate(long2string((uint32_t)currentTime));
uint32_t checkInterval = config.getIntervalCheckUpdateHttp();
nextCheckTime = currentTime + checkInterval;
LOG.debug("nextCheckTime=%d", nextCheckTime);
// If there is a new version available (newer then the one not
// installed yet), then we do not wait for the remind time
// to expire, but we query the user right away
if (nextVersion != "0" && nextVersion != config.getVersion()) {
nextRemindTime = 0;
config.setNextRemindCheck("0");
config.setSkipped("0");
}
}
} else {
//LOG.error("Client update: %i: %s", lastErrorCode, lastErrorMsg);
LOG.error("Client update error - uses the stored parameters");
res = -1;
}
if (config.getRecommended() != "0") {
config.setRecommended(config.getVersion());
config.setSkipped("0");
}
config.save();
delete response;
delete transportAgent;
return res;
}
StringBuffer getNewLine(const StringBuffer& s) {
StringBuffer newline;
size_t pos1 = s.find("\n");
if(pos1 == StringBuffer::npos){
LOG.error("Updater: no newlines in message?");
return newline;
}
size_t pos2 = pos1 + 1;
const char* chs = s.c_str();
while (chs[pos1-1] == '\r'){
pos1--;
}
newline = s.substr(pos1, pos2-pos1);
return newline;
}
void Updater::getListedString(ArrayList& allString, const StringBuffer& s,
const StringBuffer& separator)
{
size_t seplen = separator.length();
char *base = (char*)s.c_str();
char *p = strstr(base, separator.c_str());
while (p) {
StringBuffer token(base, p - base);
allString.add(token);
base = p + seplen;
p = strstr(base, separator.c_str());
}
StringBuffer token(base);
allString.add(token);
}
/*
* return -1: no new lines
*/
int32_t Updater::parseMessage(StringBuffer message) {
StringBuffer newline = getNewLine(message);
if (newline.empty()) {
return -1;
}
StringBuffer line;
ArrayList allString;
getListedString(allString, message, newline);
StringBuffer* it = (StringBuffer*)allString.front();
while (it) {
line = *it;
if (line.find(UP_TYPE) == 0) {
StringBuffer mand = line.substr(strlen(UP_TYPE));
if (mand == UP_TYPE_OPTIONAL) {
config.setRecommended("0");
config.setUpdateType(UP_TYPE_OPTIONAL);
} else if (mand == UP_TYPE_MANDATORY) {
config.setRecommended("1");
config.setUpdateType(UP_TYPE_MANDATORY);
} else {
// Default is "recommended".
// TODO: fix here when "mandatory" will be implemented (now mandatory = recommended)
config.setRecommended("1");
config.setUpdateType(UP_TYPE_RECOMMENDED);
}
} else if (line.find(UP_ACTIVATION_DATE) == 0) {
config.setReleaseDate(line.substr(strlen(UP_ACTIVATION_DATE)));
} else if (line.find(UP_SIZE) == 0) {
StringBuffer size = line.substr(strlen(UP_SIZE));
uint32_t s = atoi(size.c_str());
config.setSize(s);
} else if (line.find(UP_VERSION) == 0) {
config.setVersion(line.substr(strlen(UP_VERSION)));
} else if (line.find(UP_URL_UPDATE) == 0) {
config.setUrlUpdate(line.substr(strlen(UP_URL_UPDATE)));
} else if (line.find(UP_URL_COMMENT) == 0) {
config.setUrlComment(line.substr(strlen(UP_URL_COMMENT)));
}
it = (StringBuffer*)allString.next();
}
return 0;
}
StringBuffer Updater::long2string(uint32_t v) {
StringBuffer s;
s.sprintf("%d", v);
return s;
}
uint32_t Updater::string2long(const StringBuffer& v) {
return (uint32_t)atol(v.c_str());
}
void Updater::forceUpdate()
{
if (ui) {
config.setNow(config.getVersion());
ui->startUpgrade(config);
}
}
int32_t Updater::buildVersionID(const StringBuffer& version)
{
int32_t major, minor, build;
sscanf(version.c_str(), "%d.%d.%d", &major, &minor, &build);
return major*10000 + minor*100 + build;
}
bool Updater::isNewVersionAvailable()
{
StringBuffer newVersion = config.getVersion();
LOG.debug("newVersion=%s", newVersion.c_str());
LOG.debug("version=%s", version.c_str());
// At the moment the server is rather "stupid" and
// returns new version information regardless of our
// version. We (the client) must check if this is an update
// for ourselves or not
if (newVersion.empty() || newVersion == "0") {
return false;
}
// Compare the two versions
int32_t newVersionID = buildVersionID(newVersion);
int32_t versionID = buildVersionID(version);
return newVersionID > versionID;
}
bool Updater::newVersionAvailable(bool onlyMandatoryExpired) {
// Please note that at the moment the server returns a new version
// regardless of our version, so we must check if the new version
// is a true update or not
LOG.debug("A new version (%s) is available", config.getVersion().c_str());
if (!isNewVersionAvailable()) {
LOG.debug("The available version is not an upgrade, ignore it");
return false;
}
if (onlyMandatoryExpired) {
if (!isMandatoryUpdateActivationDateExceeded()) {
LOG.debug("onlyMandatoryUpdate: Not Mandatory or not exceeded");
return false;
}
}
// This flag specifies if the user accepts this upgrade. Possible values:
// -1) the upgrade is not applicable or already skipped
// 0) the user accepts the upgrade (now)
// 1) the user postpones the upgrade (later)
// 2) the user skips the upgrade (skip)
int32_t conf = -1;
if (config.getUpdateType() == UP_TYPE_OPTIONAL) {
if (config.getVersion() == config.getSkipped()) {
LOG.debug("The version required is the same just skipped");
} else {
LOG.debug("Ask the user if he wants update (optional)");
if (ui) {
conf = ui->askConfirmationForUpgrade(config);
}
}
} else if (config.getUpdateType() == UP_TYPE_MANDATORY) {
LOG.debug("Ask the user he had to update by a certain date (mandatory)");
if (ui) {
conf = ui->askConfirmationForMandatoryUpgrade(config);
}
} else {
LOG.debug("Ask the user if he wants update (recommended). The default");
if (ui) {
conf = ui->askConfirmationForRecommendedUpgrade(config);
}
}
// A long time may have elapsed between the dialog popping up and the
// user clicking on one of the option. We better update the current time
currentTime = time(NULL);
StringBuffer remTime("");
switch (conf) {
case 0:
// Upgrade now
if (ui) {
config.setNow(config.getVersion());
config.setLater("0");
config.setSkipped("0");
ui->startUpgrade(config);
}
break;
case 1:
if (isMandatoryUpdateActivationDateExceeded()) {
// Exit
LOG.debug("The user exits the upgrade.");
if (ui) {
ui->doExitAction(config);
return true;
}
} else {
// Postponed (later)
config.setLater(config.getVersion());
config.setNow("0");
config.setSkipped("0");
nextRemindTime = currentTime + config.getIntervalRemind();
remTime.append((uint32_t)nextRemindTime);
config.setNextRemindCheck(remTime);
LOG.debug("The user postponed the upgrade. Remind him at: %d", nextRemindTime);
}
break;
case 2:
// Skipped
config.setSkipped(config.getVersion());
config.setLater("0");
config.setNow("0");
break;
default:
// The question could not be prompted to the user, just ignore it
break;
}
config.save();
return true;
}
bool Updater::isMandatoryUpdateActivationDateExceeded() {
if (config.getUpdateType() != UP_TYPE_MANDATORY) {
LOG.debug("isUpdateActivationDateExceeded: the type is not Mandatory. ");
return false;
}
StringBuffer s_currentDate = unixTimeToString((uint32_t)time(NULL), false);
s_currentDate = s_currentDate.substr(0, 8);
const StringBuffer& s_storedDate = config.getReleaseDate();
long currentDate = atol(s_currentDate);
long storedDate = atol(s_storedDate);
if (currentDate >= storedDate) {
return true;
} else {
return false;
}
}
| 32.571134
| 100
| 0.611445
|
wbitos
|
80e6aaaeb9ab390119359597504ff17e10b1f299
| 2,510
|
cpp
|
C++
|
hsp3dish/gameplay/encoder/src/GPBDecoder.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | 1
|
2021-06-17T02:16:22.000Z
|
2021-06-17T02:16:22.000Z
|
hsp3dish/gameplay/encoder/src/GPBDecoder.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | null | null | null |
hsp3dish/gameplay/encoder/src/GPBDecoder.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | 1
|
2021-04-06T14:58:08.000Z
|
2021-04-06T14:58:08.000Z
|
#include "Base.h"
#include "GPBDecoder.h"
namespace gameplay
{
GPBDecoder::GPBDecoder(void) : _file(NULL), _outFile(NULL)
{
}
GPBDecoder::~GPBDecoder(void)
{
}
void GPBDecoder::readBinary(const std::string& filepath)
{
// open files
_file = fopen(filepath.c_str(), "rb");
std::string outfilePath = filepath;
outfilePath += ".xml";
_outFile = fopen(outfilePath.c_str(), "w");
// read and write files
assert(validateHeading());
fprintf(_outFile, "<root>\n");
readRefs();
fprintf(_outFile, "</root>\n");
// close files
fclose(_outFile);
_outFile = NULL;
fclose(_file);
_file = NULL;
}
bool GPBDecoder::validateHeading()
{
const size_t HEADING_SIZE = 9;
const char identifier[] = "\xABGPB\xBB\r\n\x1A\n";
char heading[HEADING_SIZE];
fread(heading, sizeof(unsigned char), HEADING_SIZE, _file);
for (size_t i = 0; i < HEADING_SIZE; ++i)
{
if (heading[i] != identifier[i])
{
return false;
}
}
// read version
unsigned char version[2];
fread(version, sizeof(unsigned char), 2, _file);
// don't care about version
return true;
}
void GPBDecoder::readRefs()
{
fprintf(_outFile, "<RefTable>\n");
// read number of refs
unsigned int refCount = 0;
assert(read(&refCount));
for (size_t i = 0; i < refCount; ++i)
{
readRef();
}
fprintf(_outFile, "</RefTable>\n");
}
void GPBDecoder::readRef()
{
std::string xref = readString(_file);
unsigned int type = 0, offset = 0;
assert(read(&type));
assert(read(&offset));
fprintf(_outFile, "<Reference>\n");
fprintfElement(_outFile, "xref", xref);
fprintfElement(_outFile, "type", type);
fprintfElement(_outFile, "offset", offset);
fprintf(_outFile, "</Reference>\n");
}
bool GPBDecoder::read(unsigned int* ptr)
{
return fread(ptr, sizeof(unsigned int), 1, _file) == 1;
}
std::string GPBDecoder::readString(FILE* fp)
{
unsigned int length;
if (fread(&length, 4, 1, fp) != 1)
{
return std::string();
}
char* str = new char[length + 1];
if (length > 0)
{
if (fread(str, 1, length, fp) != length)
{
delete[] str;
return std::string();
}
}
str[length] = '\0';
std::string result(str);
delete[] str;
return result;
}
}
| 21.092437
| 64
| 0.558566
|
sharkpp
|
80e7cc1ac825a96eea2159f5386705283d61584f
| 3,217
|
hpp
|
C++
|
include/kuafu.hpp
|
jetd1/kuafu
|
819d338682f3e889710731cf7ca16f790b54568f
|
[
"MIT"
] | 17
|
2021-09-03T03:06:48.000Z
|
2022-03-27T04:02:14.000Z
|
include/kuafu.hpp
|
jetd1/kuafu
|
819d338682f3e889710731cf7ca16f790b54568f
|
[
"MIT"
] | null | null | null |
include/kuafu.hpp
|
jetd1/kuafu
|
819d338682f3e889710731cf7ca16f790b54568f
|
[
"MIT"
] | null | null | null |
//
// Modified by Jet <i@jetd.me> based on Rayex source code.
// Original copyright notice:
//
// Copyright (c) 2021 Christian Hilpert
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the author 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
// 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.
//
#pragma once
#include "stdafx.hpp"
#include "core/context/context.hpp"
#include "core/window.hpp"
#include "core/gui.hpp"
namespace kuafu {
class Kuafu {
std::shared_ptr<Window> pWindow = nullptr;
std::shared_ptr<Gui> pGUI = nullptr;
kuafu::Context mContext;
bool mRunning = true;
void reset();
public:
explicit Kuafu(std::shared_ptr<Config> config = nullptr);
void run();
[[nodiscard]] bool isRunning() const;
[[nodiscard]] std::vector<uint8_t> downloadLatestFrame(Camera* cam);
void setWindow(std::shared_ptr<Window> other);
void setWindow(int width, int height, const char *title = "App", uint32_t flags = 0);
[[nodiscard]] auto getWindow() const { return pWindow; }
void setGui(std::shared_ptr<Gui> gui);
inline auto& getConfig() { return *mContext.pConfig; }
inline Scene* getScene() { return mContext.mCurrentScene; }
inline void setScene(Scene* scene) {
if (mContext.mCurrentScene == scene)
return;
KF_INFO("Switching scene, this is heavy...");
KF_ASSERT(scene, "Trying to set an invalid scene!");
auto ret = std::find_if(mContext.mScenes.begin(), mContext.mScenes.end(),
[scene](auto& s) { return scene == s.get(); });
KF_ASSERT(ret != mContext.mScenes.end(), "???");
scene->init();
mContext.mCurrentScene = scene;
mContext.pConfig->triggerSwapchainRefresh();
mContext.pConfig->triggerPipelineRefresh();
global::frameCount = -1;
}
inline Scene* createScene() {
mContext.mScenes.emplace_back(new Scene(mContext.pConfig));
return mContext.mScenes.back().get();
};
inline void removeScene(Scene* scene) {
KF_ASSERT(scene, "Trying to remove an invalid scene!");
auto ret = std::find_if(mContext.mScenes.begin(), mContext.mScenes.end(),
[scene](auto& s) { return scene == s.get(); });
KF_ASSERT(ret != mContext.mScenes.end(), "???");
mContext.mScenes.erase(std::remove_if(mContext.mScenes.begin(), mContext.mScenes.end(),
[scene](auto &s) { return scene == s.get(); }), mContext.mScenes.end());
}
};
}
| 33.510417
| 109
| 0.650295
|
jetd1
|
80e89101fcc04580ac2ae879e5e937c6b370b8b6
| 2,200
|
cpp
|
C++
|
binary-tree/lowest-common-ancestor.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
binary-tree/lowest-common-ancestor.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
binary-tree/lowest-common-ancestor.cpp
|
Strider-7/code
|
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int x)
{
data = x;
left = nullptr;
right = nullptr;
}
};
bool findPath(Node *root, vector<Node *> &path, int k)
{
// base case
if (root == NULL)
return false;
// Store this node in path vector. The node will be removed if
// not in path from root to k
path.push_back(root);
// See if the k is same as root's key
if (root->data == k)
return true;
// Check if k is found in left or right sub-tree
if ((root->left && findPath(root->left, path, k)) ||
(root->right && findPath(root->right, path, k)))
return true;
// If not present in subtree rooted with root, remove root from
// path[] and return false
path.pop_back();
return false;
}
Node *findLCA(Node *root, int n1, int n2)
{
// to store paths to n1 and n2 from the root
vector<Node *> path1, path2;
// Find paths from root to n1 and root to n1. If either n1 or n2
// is not present, return -1
if (!findPath(root, path1, n1) || !findPath(root, path2, n2))
return nullptr;
/* Compare the paths to get the first different value */
int i;
for (i = 0; i < path1.size() && i < path2.size(); i++)
if (path1[i] != path2[i])
break;
return path1[i - 1];
}
Node *LCA(Node *root, int x, int y)
{
if (!root)
return nullptr;
if (root->data == x || root->data == y)
return root;
Node *lca1 = LCA(root->left, x, y);
Node *lca2 = LCA(root->right, x, y);
if (lca1 && lca2)
return root;
if (lca1)
return lca1;
else
return lca2;
}
int main()
{
Node *root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->right->left = new Node(60);
root->right->right = new Node(70);
root->left->left = new Node(40);
root->left->right = new Node(50);
cout << findLCA(root, 40, 60)->data << endl;
cout << LCA(root, 40, 60)->data;
return 0;
}
| 23.157895
| 69
| 0.529545
|
Strider-7
|
80e895d6a17ec1316226e4ffe42b6f54534f6c4c
| 858
|
cpp
|
C++
|
solution_3.5.cpp
|
rodsanta/ccup5
|
059ce48e2b0b12994e8209b5d163141f5dd86639
|
[
"MIT"
] | null | null | null |
solution_3.5.cpp
|
rodsanta/ccup5
|
059ce48e2b0b12994e8209b5d163141f5dd86639
|
[
"MIT"
] | null | null | null |
solution_3.5.cpp
|
rodsanta/ccup5
|
059ce48e2b0b12994e8209b5d163141f5dd86639
|
[
"MIT"
] | null | null | null |
#include <stack>
#include <iostream>
using namespace std;
template<typename T>
class my_queue
{
stack<T> queue;
stack<T> helper;
public:
my_queue<T>& push(T);
T pop();
int size() {return queue.size();}
};
template<typename T>
my_queue<T>& my_queue<T>::push(T t)
{
int s = queue.size();
for (int i=0; i<s; ++i) {
helper.push(queue.top());
queue.pop();
}
helper.push(t);
for (int i=0; i<s+1; ++i) {
queue.push(helper.top());
helper.pop();
}
return *this;
}
template<typename T>
T my_queue<T>::pop()
{
T t = queue.top();
queue.pop();
return t;
}
int main()
{
my_queue<int> q;
q.push(1).push(2).push(3).push(4).push(5);
int s = q.size();
cout << "queue size: " << s << endl;
for (int i=0; i<s; ++i) {
cout << q.pop() << endl;
}
}
| 15.888889
| 46
| 0.517483
|
rodsanta
|
80f3e62909ad0537d8edfaefba4bb4f51c54e6cb
| 4,735
|
hpp
|
C++
|
include/MasterServer/MessageHandler_--c__DisplayClass73_0_1.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/MasterServer/MessageHandler_--c__DisplayClass73_0_1.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/MasterServer/MessageHandler_--c__DisplayClass73_0_1.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: MasterServer.MessageHandler
#include "MasterServer/MessageHandler.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Completed forward declares
// Type namespace: MasterServer
namespace MasterServer {
// WARNING Size may be invalid!
// Autogenerated type: MasterServer.MessageHandler/MasterServer.<>c__DisplayClass73_0`1
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
template<typename T>
class MessageHandler::$$c__DisplayClass73_0_1 : public ::Il2CppObject {
public:
// public System.Func`2<System.UInt32,T> obtain
// Size: 0x8
// Offset: 0x0
System::Func_2<uint, T>* obtain;
// Field size check
static_assert(sizeof(System::Func_2<uint, T>*) == 0x8);
// Creating value type constructor for type: $$c__DisplayClass73_0_1
$$c__DisplayClass73_0_1(System::Func_2<uint, T>* obtain_ = {}) noexcept : obtain{obtain_} {}
// Creating conversion operator: operator System::Func_2<uint, T>*
constexpr operator System::Func_2<uint, T>*() const noexcept {
return obtain;
}
// Autogenerated instance field getter
// Get instance field: public System.Func`2<System.UInt32,T> obtain
System::Func_2<uint, T>* _get_obtain() {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass73_0_1::_get_obtain");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "obtain"))->offset;
return *reinterpret_cast<System::Func_2<uint, T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset);
}
// Autogenerated instance field setter
// Set instance field: public System.Func`2<System.UInt32,T> obtain
void _set_obtain(System::Func_2<uint, T>* value) {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass73_0_1::_set_obtain");
auto ___internal__instance = this;
static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "obtain"))->offset;
*reinterpret_cast<System::Func_2<uint, T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset) = value;
}
// T <ObtainVersioned>b__0(MasterServer.MessageHandler/MasterServer.MessageOrigin origin)
// Offset: 0xFFFFFFFF
T $ObtainVersioned$b__0(MasterServer::MessageHandler::MessageOrigin origin) {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass73_0_1::<ObtainVersioned>b__0");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<ObtainVersioned>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(origin)})));
auto ___instance_arg = this;
return ::il2cpp_utils::RunMethodThrow<T, false>(___instance_arg, ___internal__method, origin);
}
// public System.Void .ctor()
// Offset: 0xFFFFFFFF
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MessageHandler::$$c__DisplayClass73_0_1<T>* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass73_0_1::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MessageHandler::$$c__DisplayClass73_0_1<T>*, creationType>()));
}
}; // MasterServer.MessageHandler/MasterServer.<>c__DisplayClass73_0`1
// Could not write size check! Type: MasterServer.MessageHandler/MasterServer.<>c__DisplayClass73_0`1 is generic, or has no fields that are valid for size checks!
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(MasterServer::MessageHandler::$$c__DisplayClass73_0_1, "MasterServer", "MessageHandler/<>c__DisplayClass73_0`1");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 57.743902
| 215
| 0.736431
|
marksteward
|
80f458d4b27de14166b3be906f4430c4c515a84b
| 1,838
|
cpp
|
C++
|
src/cscope.cpp
|
holdforther/pasc
|
5652a859bd638132c61d12884d49c6e0f91628f1
|
[
"MIT"
] | null | null | null |
src/cscope.cpp
|
holdforther/pasc
|
5652a859bd638132c61d12884d49c6e0f91628f1
|
[
"MIT"
] | null | null | null |
src/cscope.cpp
|
holdforther/pasc
|
5652a859bd638132c61d12884d49c6e0f91628f1
|
[
"MIT"
] | null | null | null |
#include "cscope.hpp"
#include "cvariant.hpp"
#include "standard_types.hpp"
#include <cctype>
#include <ostream>
#include <string>
#include <iostream>
namespace pasc {
CScope::CScope(scope_ptr &parent_scope) {
this->parent_scope = parent_scope;
if (this->parent_scope) {
depth = parent_scope->get_depth() + 1;
} else {
depth = 0;
}
}
standard_type CScope::get_type_by_id(const std::string &id) {
auto it = user_types.find(id);
if (it == user_types.end()) {
if (this->parent_scope) {
return this->parent_scope->get_type_by_id(id);
} else {
return est_unknown;
}
} else {
return it->second;
}
}
var_ptr CScope::get_variable_by_id(const std::string &id){
auto it = variables.find(id);
if (it == variables.end()) {
if (this->parent_scope) {
return this->parent_scope->get_variable_by_id(id);
} else {
return nullptr;
}
} else {
return it->second;
}
}
void CScope::set_type_name(const std::string &id, standard_type type) {
std::string name(id);
for (auto &c: name) { c = std::toupper(c); }
user_types[name] = type;
}
void CScope::add_variable(const std::string &name, standard_type type, bool is_const) {
//std::string variable_name = name + "_" + std::to_string(depth);
variables[name] = std::make_unique<CVariable>(name, type, is_const);
}
size_t CScope::get_depth() const {
return depth;
}
void CScope::print_variables() {
for (auto v : variables) {
std::cout << v.first << " " << v.second->get_type() << std::endl;
}
}
}
| 27.848485
| 91
| 0.541893
|
holdforther
|
80f84550677cc641f6ed2d293dd6d48028c266ec
| 12,260
|
hpp
|
C++
|
external/nvvkpp/pipeline_vkpp.hpp
|
FelixFifi/rtx-pathtracer
|
9bf5616c47880e8fa536a822b39b9661bb666352
|
[
"Zlib",
"Apache-2.0",
"MIT"
] | 5
|
2021-04-18T15:49:10.000Z
|
2021-09-15T10:23:44.000Z
|
external/nvvkpp/pipeline_vkpp.hpp
|
FelixFifi/rtx-pathtracer
|
9bf5616c47880e8fa536a822b39b9661bb666352
|
[
"Zlib",
"Apache-2.0",
"MIT"
] | 1
|
2021-12-27T12:11:53.000Z
|
2021-12-27T12:11:53.000Z
|
external/nvvkpp/pipeline_vkpp.hpp
|
FelixFifi/rtx-pathtracer
|
9bf5616c47880e8fa536a822b39b9661bb666352
|
[
"Zlib",
"Apache-2.0",
"MIT"
] | 2
|
2021-06-18T12:27:36.000Z
|
2021-12-26T22:06:44.000Z
|
/* Copyright (c) 2014-2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <vulkan/vulkan.hpp>
namespace nvvkpp {
//--------------------------------------------------------------------------------------------------
/**
Most graphic pipeline are similar, therefor the helper `GraphicsPipelineGenerator` holds all the elements and initialize the structure with the proper default, such as `eTriangleList`, `PipelineColorBlendAttachmentState` with their mask, `DynamicState` for viewport and scissor, adjust depth test if enable, line width to 1, for example. As those are all C++, setters exist for any members and deep copy for any attachments.
Example of usage :
~~~~ c++
nvvk::GraphicsPipelineGenerator pipelineGenerator(m_device, m_pipelineLayout, m_renderPass);
pipelineGenerator.loadShader(readFile("shaders/vert_shader.vert.spv"), vk::ShaderStageFlagBits::eVertex);
pipelineGenerator.loadShader(readFile("shaders/frag_shader.frag.spv"), vk::ShaderStageFlagBits::eFragment);
pipelineGenerator.depthStencilState = {true};
pipelineGenerator.rasterizationState.setCullMode(vk::CullModeFlagBits::eNone);
pipelineGenerator.vertexInputState.bindingDescriptions = {{0, sizeof(Vertex)}};
pipelineGenerator.vertexInputState.attributeDescriptions = {
{0, 0, vk::Format::eR32G32B32Sfloat, static_cast<uint32_t>(offsetof(Vertex, pos))},
{1, 0, vk::Format::eR32G32B32Sfloat, static_cast<uint32_t>(offsetof(Vertex, nrm))},
{2, 0, vk::Format::eR32G32B32Sfloat, static_cast<uint32_t>(offsetof(Vertex, col))}};
m_pipeline = pipelineGenerator.create();
~~~~
*/
struct GraphicsPipelineGenerator
{
public:
GraphicsPipelineGenerator(const vk::Device& device, const vk::PipelineLayout& layout, const vk::RenderPass& renderPass)
: device(device)
{
pipelineCreateInfo.layout = layout;
pipelineCreateInfo.renderPass = renderPass;
init();
}
GraphicsPipelineGenerator(const GraphicsPipelineGenerator& other)
: GraphicsPipelineGenerator(other.device, other.layout, other.renderPass)
{
}
GraphicsPipelineGenerator& operator=(const GraphicsPipelineGenerator& other) = delete;
~GraphicsPipelineGenerator() { destroyShaderModules(); }
vk::PipelineShaderStageCreateInfo& addShader(const std::string& code,
vk::ShaderStageFlagBits stage,
const char* entryPoint = "main")
{
std::vector<char> v;
std::copy(code.begin(), code.end(), std::back_inserter(v));
return addShader(v, stage, entryPoint);
}
template <typename T>
vk::PipelineShaderStageCreateInfo& addShader(const std::vector<T>& code,
vk::ShaderStageFlagBits stage,
const char* entryPoint = "main");
vk::Pipeline create(const vk::PipelineCache& cache)
{
update();
return device.createGraphicsPipeline(cache, pipelineCreateInfo);
}
vk::Pipeline create() { return create(pipelineCache); }
void destroyShaderModules()
{
for(const auto& shaderStage : shaderStages)
{
device.destroyShaderModule(shaderStage.module);
}
shaderStages.clear();
}
// Overriding the defaults
struct PipelineRasterizationStateCreateInfo : public vk::PipelineRasterizationStateCreateInfo
{
PipelineRasterizationStateCreateInfo()
{
lineWidth = 1.0f;
cullMode = vk::CullModeFlagBits::eBack;
}
};
struct PipelineInputAssemblyStateCreateInfo : public vk::PipelineInputAssemblyStateCreateInfo
{
PipelineInputAssemblyStateCreateInfo() { topology = vk::PrimitiveTopology::eTriangleList; }
};
struct PipelineColorBlendAttachmentState : public vk::PipelineColorBlendAttachmentState
{
PipelineColorBlendAttachmentState(vk::Bool32 blendEnable_ = 0,
vk::BlendFactor srcColorBlendFactor_ = vk::BlendFactor::eZero,
vk::BlendFactor dstColorBlendFactor_ = vk::BlendFactor::eZero,
vk::BlendOp colorBlendOp_ = vk::BlendOp::eAdd,
vk::BlendFactor srcAlphaBlendFactor_ = vk::BlendFactor::eZero,
vk::BlendFactor dstAlphaBlendFactor_ = vk::BlendFactor::eZero,
vk::BlendOp alphaBlendOp_ = vk::BlendOp::eAdd,
vk::ColorComponentFlags colorWriteMask_ = vk::ColorComponentFlagBits::eR
| vk::ColorComponentFlagBits::eG
| vk::ColorComponentFlagBits::eB
| vk::ColorComponentFlagBits::eA)
: vk::PipelineColorBlendAttachmentState(blendEnable_,
srcColorBlendFactor_,
dstColorBlendFactor_,
colorBlendOp_,
srcAlphaBlendFactor_,
dstAlphaBlendFactor_,
alphaBlendOp_,
colorWriteMask_)
{
}
};
struct PipelineColorBlendStateCreateInfo : public vk::PipelineColorBlendStateCreateInfo
{
std::vector<PipelineColorBlendAttachmentState> blendAttachmentStates{PipelineColorBlendAttachmentState()};
void update()
{
this->attachmentCount = (uint32_t)blendAttachmentStates.size();
this->pAttachments = blendAttachmentStates.data();
}
};
struct PipelineDynamicStateCreateInfo : public vk::PipelineDynamicStateCreateInfo
{
std::vector<vk::DynamicState> dynamicStateEnables;
PipelineDynamicStateCreateInfo()
{
dynamicStateEnables = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
}
void update()
{
this->dynamicStateCount = (uint32_t)dynamicStateEnables.size();
this->pDynamicStates = dynamicStateEnables.data();
}
};
struct PipelineVertexInputStateCreateInfo : public vk::PipelineVertexInputStateCreateInfo
{
std::vector<vk::VertexInputBindingDescription> bindingDescriptions;
std::vector<vk::VertexInputAttributeDescription> attributeDescriptions;
void update()
{
vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size());
pVertexBindingDescriptions = bindingDescriptions.data();
pVertexAttributeDescriptions = attributeDescriptions.data();
}
};
struct PipelineViewportStateCreateInfo : public vk::PipelineViewportStateCreateInfo
{
std::vector<vk::Viewport> viewports;
std::vector<vk::Rect2D> scissors;
void update()
{
if(viewports.empty())
{
viewportCount = 1;
pViewports = nullptr;
}
else
{
viewportCount = (uint32_t)viewports.size();
pViewports = viewports.data();
}
if(scissors.empty())
{
scissorCount = 1;
pScissors = nullptr;
}
else
{
scissorCount = (uint32_t)scissors.size();
pScissors = scissors.data();
}
}
};
struct PipelineDepthStencilStateCreateInfo : public vk::PipelineDepthStencilStateCreateInfo
{
PipelineDepthStencilStateCreateInfo(bool depthEnable = true)
{
if(depthEnable)
{
depthTestEnable = VK_TRUE;
depthWriteEnable = VK_TRUE;
depthCompareOp = vk::CompareOp::eLessOrEqual;
}
}
};
const vk::Device& device;
vk::GraphicsPipelineCreateInfo pipelineCreateInfo;
vk::PipelineCache pipelineCache;
vk::RenderPass& renderPass{pipelineCreateInfo.renderPass};
vk::PipelineLayout& layout{pipelineCreateInfo.layout};
uint32_t& subpass{pipelineCreateInfo.subpass};
PipelineInputAssemblyStateCreateInfo inputAssemblyState;
PipelineRasterizationStateCreateInfo rasterizationState;
vk::PipelineMultisampleStateCreateInfo multisampleState;
PipelineDepthStencilStateCreateInfo depthStencilState;
PipelineViewportStateCreateInfo viewportState;
PipelineDynamicStateCreateInfo dynamicState;
PipelineColorBlendStateCreateInfo colorBlendState;
PipelineVertexInputStateCreateInfo vertexInputState;
std::vector<vk::PipelineShaderStageCreateInfo> shaderStages;
void update()
{
pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
pipelineCreateInfo.pStages = shaderStages.data();
dynamicState.update();
colorBlendState.update();
vertexInputState.update();
viewportState.update();
}
private:
void init()
{
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.pVertexInputState = &vertexInputState;
}
};
template <typename T>
vk::PipelineShaderStageCreateInfo& nvvkpp::GraphicsPipelineGenerator::addShader(const std::vector<T>& code,
vk::ShaderStageFlagBits stage,
const char* entryPoint)
{
vk::ShaderModuleCreateInfo createInfo;
createInfo.codeSize = sizeof(T) * code.size();
createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
vk::ShaderModule shaderModule = device.createShaderModule(createInfo, nullptr);
vk::PipelineShaderStageCreateInfo shaderStage;
shaderStage.stage = stage;
shaderStage.module = shaderModule;
shaderStage.pName = entryPoint;
shaderStages.push_back(shaderStage);
return shaderStages.back();
}
} // namespace nvvkpp
| 42.867133
| 424
| 0.641599
|
FelixFifi
|
80f942da574a1f836f39636122c7b9cece9da5db
| 2,248
|
cc
|
C++
|
src/libxtp/molecule.cc
|
mbarbry/xtp
|
e79828209d11ec25bf1750ab75499ecf50f584ef
|
[
"Apache-2.0"
] | null | null | null |
src/libxtp/molecule.cc
|
mbarbry/xtp
|
e79828209d11ec25bf1750ab75499ecf50f584ef
|
[
"Apache-2.0"
] | null | null | null |
src/libxtp/molecule.cc
|
mbarbry/xtp
|
e79828209d11ec25bf1750ab75499ecf50f584ef
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2009-2018 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
/// For earlier commit history see ctp commit 77795ea591b29e664153f9404c8655ba28dc14e9
#include <stdio.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <votca/tools/vec.h>
#include <votca/xtp/molecule.h>
#include <votca/xtp/segment.h>
#include <votca/xtp/fragment.h>
#include <votca/xtp/atom.h>
using namespace std;
using namespace votca::tools;
namespace votca { namespace xtp {
/// Destructor
Molecule::~Molecule() {
_segments.clear();
_fragments.clear();
_atoms.clear();
}
/// Returns ID of the molecule
const int &Molecule::getId() {
return _id;
}
/// Returns the name of the molecule
const string &Molecule::getName() {
return _name;
}
void Molecule::AddSegment( Segment* segment ) {
_segments.push_back( segment );
segment->setMolecule(this);
}
void Molecule::AddFragment(Fragment* fragment ) {
_fragments.push_back( fragment );
fragment->setMolecule(this);
}
void Molecule::AddAtom(Atom *atom ) {
_atoms.push_back(atom);
atom->setMolecule(this);
}
/// Returns a pointer to the atom
Atom *Molecule::getAtom(const int &id) {
throw runtime_error( string("Not implemented") );
}
/// Returns atom type
const string &Molecule::getAtomType(const int &id) {
throw runtime_error( string("Not implemented") );
}
/// Returns atom position
const vec Molecule::getAtomPosition(const int &id) {
throw runtime_error( string("Not implemented") );
}
/// Returns number of atoms in the molecule
int Molecule::NumberOfAtoms() {
return _atoms.size();
}
}}
| 24.703297
| 86
| 0.691281
|
mbarbry
|
80fa87996d67b99d4bf784e323df3416279ca8ca
| 3,112
|
cpp
|
C++
|
Core/Src/opt_conjgrad.cpp
|
impressivemachines/ImpressiveAI
|
9e7efd242a32b87996b95bb8155ae8acd7b4c498
|
[
"Apache-2.0"
] | null | null | null |
Core/Src/opt_conjgrad.cpp
|
impressivemachines/ImpressiveAI
|
9e7efd242a32b87996b95bb8155ae8acd7b4c498
|
[
"Apache-2.0"
] | 17
|
2015-03-10T05:22:02.000Z
|
2015-03-21T22:36:14.000Z
|
Core/Src/opt_conjgrad.cpp
|
impressivemachines/Metaphor
|
9e7efd242a32b87996b95bb8155ae8acd7b4c498
|
[
"Apache-2.0"
] | null | null | null |
//
// opt_conjgrad.cpp
// Metaphor
//
// Created by SIMON WINDER on 3/12/15.
// Copyright (c) 2015 Impressive Machines LLC. All rights reserved.
//
#include "meta_core.h"
template <typename TT>
void im::ConjGradientMin<TT>::init(Vec<TT> vstate)
{
IM_CHECK_VALID(vstate);
IM_CHECK_ARGS(vstate.rows()>0);
m_vstate = vstate;
m_early_exit = false;
m_fx = (TT)0;
m_delta_fx = (TT)0;
m_delta_x = (TT)0;
m_iterations = 0;
int const d = dims();
m_vdir_x.resize(d);
m_vdir_g.resize(d);
m_vdir_h.resize(d);
m_linemin.init(this, d, m_params.line_min_eps, true);
m_startup = true;
eval_init();
}
template <typename TT>
bool im::ConjGradientMin<TT>::step()
{
if(m_early_exit)
return true;
eval_start_step();
bool complete = false;
if(m_startup)
{
m_fx = eval_fx(m_vstate);
eval_dfx(m_vdir_x, m_vstate);
core_block_neg(m_vdir_x.view(), m_vdir_x.view());
m_vdir_g.copy_from(m_vdir_x);
m_vdir_h.copy_from(m_vdir_x);
m_startup = false;
}
TT fxold = m_fx;
m_linemin.linemin(m_vstate, m_vdir_x, m_params.bracket_max);
TT fxnew = m_linemin.fxmin();
m_delta_x = std::abs(m_linemin.xmin()) * m_vdir_x.magnitude();
if((TT)2*(std::abs(fxnew - m_fx)) <= m_params.termination_ratio * (std::abs(fxnew) + std::abs(m_fx) + TypeProperties<TT>::epsilon()))
complete = true;
else
{
m_fx = fxnew;
eval_dfx(m_vdir_x, m_vstate);
// test for gradient relatively close to zero
TT scale = (TT)1 / std::max((TT)1, std::abs(m_fx));
TT tmax = (TT)0;
for(int i=0; i<dims(); i++)
{
TT t = scale * std::abs(m_vdir_x(i)) * std::max((TT)1, std::abs(m_vstate(i)));
if(t>tmax)
tmax = t;
}
if(tmax < m_params.gradient_ratio)
complete = true;
else
{
// compute gamma
TT gamma_denom = m_vdir_g.magnitude_squared();
if(gamma_denom==(TT)0)
complete = true;
else
{
TT gamma = m_vdir_x.magnitude_squared();
if(m_params.update_mode==ConjGradientUpdateModePolakRibiere)
gamma += m_vdir_g.dot_product(m_vdir_x);
gamma /= gamma_denom;
core_block_neg(m_vdir_g.view(), m_vdir_x.view()); // g = -x
m_vdir_x.copy_from(m_vdir_g); // x = g
core_block_blas_axpy(m_vdir_x.view(), m_vdir_h.view(), gamma); // x += gamma * h
m_vdir_h.copy_from(m_vdir_x); // h = x
}
}
}
m_delta_fx = m_fx - fxold;
m_early_exit = eval_end_step() || m_early_exit;
m_iterations++;
if(m_iterations > m_params.iterations_max)
complete = true;
return m_early_exit || complete;
}
template class im::ConjGradientMin<float>;
template class im::ConjGradientMin<double>;
| 26.151261
| 137
| 0.549807
|
impressivemachines
|
80fdb336b401e292b2adeaa729b219089151c0a7
| 32,060
|
cpp
|
C++
|
src/validator/MatchValidator.cpp
|
jude-zhu/nebula-graph
|
7cbeafba1031875b57c4f4822788a72f21d7d858
|
[
"Apache-2.0"
] | null | null | null |
src/validator/MatchValidator.cpp
|
jude-zhu/nebula-graph
|
7cbeafba1031875b57c4f4822788a72f21d7d858
|
[
"Apache-2.0"
] | null | null | null |
src/validator/MatchValidator.cpp
|
jude-zhu/nebula-graph
|
7cbeafba1031875b57c4f4822788a72f21d7d858
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "validator/MatchValidator.h"
#include "planner/match/MatchSolver.h"
#include "util/ExpressionUtils.h"
#include "visitor/RewriteVisitor.h"
#include "visitor/RewriteUnaryNotExprVisitor.h"
namespace nebula {
namespace graph {
MatchValidator::MatchValidator(Sentence *sentence, QueryContext *context)
: TraversalValidator(sentence, context) {
matchCtx_ = std::make_unique<MatchAstContext>();
matchCtx_->sentence = sentence;
matchCtx_->qctx = context;
}
AstContext *MatchValidator::getAstContext() {
return matchCtx_.get();
}
Status MatchValidator::validateImpl() {
auto *sentence = static_cast<MatchSentence *>(sentence_);
auto &clauses = sentence->clauses();
std::unordered_map<std::string, AliasType> *aliasesUsed = nullptr;
YieldColumns *prevYieldColumns = nullptr;
auto retClauseCtx = getContext<ReturnClauseContext>();
auto retYieldCtx = getContext<YieldClauseContext>();
retClauseCtx->yield = std::move(retYieldCtx);
for (size_t i = 0; i < clauses.size(); ++i) {
auto kind = clauses[i]->kind();
if (i > 0 && kind == ReadingClause::Kind::kMatch) {
return Status::SemanticError(
"Match clause is not supported to be followed by other cypher clauses");
}
switch (kind) {
case ReadingClause::Kind::kMatch: {
auto *matchClause = static_cast<MatchClause *>(clauses[i].get());
if (matchClause->isOptional()) {
return Status::SemanticError("OPTIONAL MATCH not supported");
}
auto matchClauseCtx = getContext<MatchClauseContext>();
matchClauseCtx->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(validatePath(matchClause->path(), *matchClauseCtx));
if (matchClause->where() != nullptr) {
auto whereClauseCtx = getContext<WhereClauseContext>();
whereClauseCtx->aliasesUsed = &matchClauseCtx->aliasesGenerated;
NG_RETURN_IF_ERROR(
validateFilter(matchClause->where()->filter(), *whereClauseCtx));
matchClauseCtx->where = std::move(whereClauseCtx);
}
if (aliasesUsed) {
NG_RETURN_IF_ERROR(
combineAliases(matchClauseCtx->aliasesGenerated, *aliasesUsed));
}
aliasesUsed = &matchClauseCtx->aliasesGenerated;
if (i == clauses.size() - 1) {
retClauseCtx->yield->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(
validateReturn(sentence->ret(), matchClauseCtx.get(), *retClauseCtx));
}
matchCtx_->clauses.emplace_back(std::move(matchClauseCtx));
break;
}
case ReadingClause::Kind::kUnwind: {
auto *unwindClause = static_cast<UnwindClause *>(clauses[i].get());
auto unwindClauseCtx = getContext<UnwindClauseContext>();
unwindClauseCtx->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(validateUnwind(unwindClause, *unwindClauseCtx));
if (aliasesUsed) {
NG_RETURN_IF_ERROR(
combineAliases(unwindClauseCtx->aliasesGenerated, *aliasesUsed));
}
aliasesUsed = &unwindClauseCtx->aliasesGenerated;
if (prevYieldColumns) {
NG_RETURN_IF_ERROR(combineYieldColumns(
const_cast<YieldColumns *>(unwindClauseCtx->yieldColumns),
prevYieldColumns));
}
prevYieldColumns = const_cast<YieldColumns *>(unwindClauseCtx->yieldColumns);
if (i == clauses.size() - 1) {
retClauseCtx->yield->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(
validateReturn(sentence->ret(), unwindClauseCtx.get(), *retClauseCtx));
}
matchCtx_->clauses.emplace_back(std::move(unwindClauseCtx));
break;
}
case ReadingClause::Kind::kWith: {
auto *withClause = static_cast<WithClause *>(clauses[i].get());
auto withClauseCtx = getContext<WithClauseContext>();
auto withYieldCtx = getContext<YieldClauseContext>();
withClauseCtx->yield = std::move(withYieldCtx);
withClauseCtx->yield->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(validateWith(withClause, *withClauseCtx));
if (withClause->where() != nullptr) {
auto whereClauseCtx = getContext<WhereClauseContext>();
whereClauseCtx->aliasesUsed = &withClauseCtx->aliasesGenerated;
NG_RETURN_IF_ERROR(
validateFilter(withClause->where()->filter(), *whereClauseCtx));
withClauseCtx->where = std::move(whereClauseCtx);
}
aliasesUsed = &withClauseCtx->aliasesGenerated;
prevYieldColumns = const_cast<YieldColumns *>(withClauseCtx->yield->yieldColumns);
if (i == clauses.size() - 1) {
retClauseCtx->yield->aliasesUsed = aliasesUsed;
NG_RETURN_IF_ERROR(
validateReturn(sentence->ret(), withClauseCtx.get(), *retClauseCtx));
}
matchCtx_->clauses.emplace_back(std::move(withClauseCtx));
break;
}
}
}
NG_RETURN_IF_ERROR(buildOutputs(retClauseCtx->yield->yieldColumns));
matchCtx_->clauses.emplace_back(std::move(retClauseCtx));
return Status::OK();
}
Status MatchValidator::validatePath(const MatchPath *path,
MatchClauseContext &matchClauseCtx) const {
NG_RETURN_IF_ERROR(
buildNodeInfo(path, matchClauseCtx.nodeInfos, matchClauseCtx.aliasesGenerated));
NG_RETURN_IF_ERROR(
buildEdgeInfo(path, matchClauseCtx.edgeInfos, matchClauseCtx.aliasesGenerated));
NG_RETURN_IF_ERROR(buildPathExpr(path, matchClauseCtx));
return Status::OK();
}
Status MatchValidator::buildPathExpr(const MatchPath *path,
MatchClauseContext &matchClauseCtx) const {
auto *pathAlias = path->alias();
if (pathAlias == nullptr) {
return Status::OK();
}
if (!matchClauseCtx.aliasesGenerated.emplace(*pathAlias, AliasType::kPath).second) {
return Status::SemanticError("`%s': Redefined alias", pathAlias->c_str());
}
auto &nodeInfos = matchClauseCtx.nodeInfos;
auto &edgeInfos = matchClauseCtx.edgeInfos;
auto pathBuild = std::make_unique<PathBuildExpression>();
for (size_t i = 0; i < edgeInfos.size(); ++i) {
pathBuild->add(std::make_unique<VariablePropertyExpression>(
new std::string(), new std::string(*nodeInfos[i].alias)));
pathBuild->add(std::make_unique<VariablePropertyExpression>(
new std::string(), new std::string(*edgeInfos[i].alias)));
}
pathBuild->add(std::make_unique<VariablePropertyExpression>(
new std::string(), new std::string(*nodeInfos.back().alias)));
matchClauseCtx.pathBuild = std::move(pathBuild);
return Status::OK();
}
Status MatchValidator::buildNodeInfo(const MatchPath *path,
std::vector<NodeInfo> &nodeInfos,
std::unordered_map<std::string, AliasType> &aliases) const {
auto *sm = qctx_->schemaMng();
auto steps = path->steps();
nodeInfos.resize(steps + 1);
for (auto i = 0u; i <= steps; i++) {
auto *node = path->node(i);
auto *alias = node->alias();
auto *props = node->props();
auto anonymous = false;
if (node->labels() != nullptr) {
auto &labels = node->labels()->labels();
for (const auto &label : labels) {
if (label != nullptr) {
auto tid = sm->toTagID(space_.id, *label->label());
if (!tid.ok()) {
return Status::SemanticError("`%s': Unknown tag", label->label()->c_str());
}
nodeInfos[i].tids.emplace_back(tid.value());
nodeInfos[i].labels.emplace_back(label->label());
nodeInfos[i].labelProps.emplace_back(label->props());
}
}
}
if (alias == nullptr) {
anonymous = true;
alias = saveObject(new std::string(vctx_->anonVarGen()->getVar()));
}
if (!aliases.emplace(*alias, AliasType::kNode).second) {
return Status::SemanticError("`%s': Redefined alias", alias->c_str());
}
Expression *filter = nullptr;
if (props != nullptr) {
auto result = makeSubFilterWithoutSave(*alias, props);
NG_RETURN_IF_ERROR(result);
filter = result.value();
} else if (node->labels() != nullptr && !node->labels()->labels().empty()) {
const auto &labels = node->labels()->labels();
for (const auto &label : labels) {
auto result = makeSubFilterWithoutSave(*alias, label->props(), *label->label());
NG_RETURN_IF_ERROR(result);
filter = andConnect(filter, result.value());
}
}
saveObject(filter);
nodeInfos[i].anonymous = anonymous;
nodeInfos[i].alias = alias;
nodeInfos[i].props = props;
nodeInfos[i].filter = filter;
}
return Status::OK();
}
Status MatchValidator::buildEdgeInfo(const MatchPath *path,
std::vector<EdgeInfo> &edgeInfos,
std::unordered_map<std::string, AliasType> &aliases) const {
auto *sm = qctx_->schemaMng();
auto steps = path->steps();
edgeInfos.resize(steps);
for (auto i = 0u; i < steps; i++) {
auto *edge = path->edge(i);
auto &types = edge->types();
auto *alias = edge->alias();
auto *props = edge->props();
auto direction = edge->direction();
auto anonymous = false;
if (!types.empty()) {
for (auto &type : types) {
auto etype = sm->toEdgeType(space_.id, *type);
if (!etype.ok()) {
return Status::SemanticError("`%s': Unknown edge type", type->c_str());
}
edgeInfos[i].edgeTypes.emplace_back(etype.value());
edgeInfos[i].types.emplace_back(*type);
}
} else {
const auto allEdgesResult =
matchCtx_->qctx->schemaMng()->getAllVerEdgeSchema(space_.id);
NG_RETURN_IF_ERROR(allEdgesResult);
const auto allEdges = std::move(allEdgesResult).value();
for (const auto &edgeSchema : allEdges) {
edgeInfos[i].edgeTypes.emplace_back(edgeSchema.first);
// TODO:
// edgeInfos[i].types.emplace_back(*type);
}
}
auto *stepRange = edge->range();
if (stepRange != nullptr) {
NG_RETURN_IF_ERROR(validateStepRange(stepRange));
edgeInfos[i].range = stepRange;
}
if (alias == nullptr) {
anonymous = true;
alias = saveObject(new std::string(vctx_->anonVarGen()->getVar()));
}
if (!aliases.emplace(*alias, AliasType::kEdge).second) {
return Status::SemanticError("`%s': Redefined alias", alias->c_str());
}
Expression *filter = nullptr;
if (props != nullptr) {
auto result = makeSubFilter(*alias, props);
NG_RETURN_IF_ERROR(result);
filter = result.value();
}
edgeInfos[i].anonymous = anonymous;
edgeInfos[i].direction = direction;
edgeInfos[i].alias = alias;
edgeInfos[i].props = props;
edgeInfos[i].filter = filter;
}
return Status::OK();
}
Status MatchValidator::validateFilter(const Expression *filter,
WhereClauseContext &whereClauseCtx) const {
// Fold constant expr
auto newFilter = ExpressionUtils::foldConstantExpr(filter);
// Reduce Unary expr
auto pool = whereClauseCtx.qctx->objPool();
whereClauseCtx.filter = ExpressionUtils::reduceUnaryNotExpr(newFilter.get(), pool);
auto typeStatus = deduceExprType(whereClauseCtx.filter);
NG_RETURN_IF_ERROR(typeStatus);
auto type = typeStatus.value();
if (type != Value::Type::BOOL && type != Value::Type::NULLVALUE &&
type != Value::Type::__EMPTY__) {
std::stringstream ss;
ss << "`" << filter->toString() << "', expected Boolean, "
<< "but was `" << type << "'";
return Status::SemanticError(ss.str());
}
NG_RETURN_IF_ERROR(validateAliases({whereClauseCtx.filter}, whereClauseCtx.aliasesUsed));
return Status::OK();
}
Status MatchValidator::validateReturn(MatchReturn *ret,
const CypherClauseContextBase *cypherClauseCtx,
ReturnClauseContext &retClauseCtx) const {
auto kind = cypherClauseCtx->kind;
if (kind != CypherClauseKind::kMatch && kind != CypherClauseKind::kUnwind &&
kind != CypherClauseKind::kWith) {
return Status::SemanticError("Must be a MATCH/UNWIND/WITH");
}
// `RETURN *': return all named nodes or edges
YieldColumns *columns = nullptr;
if (ret->isAll()) {
auto makeColumn = [](const std::string &name) {
auto *expr = new LabelExpression(name);
auto *alias = new std::string(name);
return new YieldColumn(expr, alias);
};
if (kind == CypherClauseKind::kMatch) {
auto matchClauseCtx = static_cast<const MatchClauseContext *>(cypherClauseCtx);
columns = saveObject(new YieldColumns());
auto steps = matchClauseCtx->edgeInfos.size();
if (!matchClauseCtx->nodeInfos[0].anonymous) {
columns->addColumn(makeColumn(*matchClauseCtx->nodeInfos[0].alias));
}
for (auto i = 0u; i < steps; i++) {
if (!matchClauseCtx->edgeInfos[i].anonymous) {
columns->addColumn(makeColumn(*matchClauseCtx->edgeInfos[i].alias));
}
if (!matchClauseCtx->nodeInfos[i + 1].anonymous) {
columns->addColumn(makeColumn(*matchClauseCtx->nodeInfos[i + 1].alias));
}
}
for (auto &aliasPair : matchClauseCtx->aliasesGenerated) {
if (aliasPair.second == AliasType::kPath) {
columns->addColumn(makeColumn(aliasPair.first));
}
}
} else if (kind == CypherClauseKind::kUnwind) {
auto unwindClauseCtx = static_cast<const UnwindClauseContext *>(cypherClauseCtx);
columns = saveObject(new YieldColumns());
columns->addColumn(makeColumn(unwindClauseCtx->aliasesGenerated.begin()->first));
} else {
// kWith
auto withClauseCtx = static_cast<const WithClauseContext *>(cypherClauseCtx);
columns = saveObject(new YieldColumns());
for (auto &aliasPair : withClauseCtx->aliasesGenerated) {
columns->addColumn(makeColumn(aliasPair.first));
}
}
if (columns->empty()) {
return Status::SemanticError("`RETURN *' not allowed if there is no alias");
}
}
if (columns == nullptr) {
retClauseCtx.yield->yieldColumns = ret->columns();
} else {
retClauseCtx.yield->yieldColumns = columns;
}
// Check all referencing expressions are valid
std::vector<const Expression *> exprs;
exprs.reserve(retClauseCtx.yield->yieldColumns->size());
for (auto *col : retClauseCtx.yield->yieldColumns->columns()) {
if (!retClauseCtx.yield->hasAgg_ &&
ExpressionUtils::hasAny(col->expr(), {Expression::Kind::kAggregate})) {
retClauseCtx.yield->hasAgg_ = true;
}
exprs.push_back(col->expr());
}
NG_RETURN_IF_ERROR(validateAliases(exprs, retClauseCtx.yield->aliasesUsed));
NG_RETURN_IF_ERROR(validateYield(*retClauseCtx.yield));
retClauseCtx.yield->distinct = ret->isDistinct();
auto paginationCtx = getContext<PaginationContext>();
NG_RETURN_IF_ERROR(validatePagination(ret->skip(), ret->limit(), *paginationCtx));
retClauseCtx.pagination = std::move(paginationCtx);
if (ret->orderFactors() != nullptr) {
auto orderByCtx = getContext<OrderByClauseContext>();
NG_RETURN_IF_ERROR(validateOrderBy(ret->orderFactors(), ret->columns(), *orderByCtx));
retClauseCtx.order = std::move(orderByCtx);
}
return Status::OK();
}
Status MatchValidator::validateAliases(
const std::vector<const Expression *> &exprs,
const std::unordered_map<std::string, AliasType> *aliasesUsed) const {
static const std::unordered_set<Expression::Kind> kinds = {Expression::Kind::kLabel,
Expression::Kind::kLabelAttribute};
for (auto *expr : exprs) {
auto refExprs = ExpressionUtils::collectAll(expr, kinds);
if (refExprs.empty()) {
continue;
}
for (auto *refExpr : refExprs) {
auto kind = refExpr->kind();
const std::string *name = nullptr;
if (kind == Expression::Kind::kLabel) {
name = static_cast<const LabelExpression *>(refExpr)->name();
} else {
DCHECK(kind == Expression::Kind::kLabelAttribute);
name = static_cast<const LabelAttributeExpression *>(refExpr)->left()->name();
}
DCHECK(name != nullptr);
if (!aliasesUsed || aliasesUsed->count(*name) != 1) {
return Status::SemanticError("Alias used but not defined: `%s'", name->c_str());
}
}
}
return Status::OK();
}
Status MatchValidator::validateStepRange(const MatchStepRange *range) const {
auto min = range->min();
auto max = range->max();
if (min > max) {
return Status::SemanticError(
"Max hop must be greater equal than min hop: %ld vs. %ld", max, min);
}
if (max == std::numeric_limits<int64_t>::max()) {
return Status::SemanticError("Cannot set maximum hop for variable length relationships");
}
if (min < 0) {
return Status::SemanticError(
"Cannot set negative steps minumum hop for variable length relationships");
}
return Status::OK();
}
Status MatchValidator::validateWith(const WithClause *with,
WithClauseContext &withClauseCtx) const {
// Check all referencing expressions are valid
std::vector<const Expression *> exprs;
exprs.reserve(with->columns()->size());
for (auto *col : with->columns()->columns()) {
if (col->alias() == nullptr) {
if (col->expr()->kind() == Expression::Kind::kLabel) {
col->setAlias(new std::string(col->expr()->toString()));
} else {
return Status::SemanticError("Expression in WITH must be aliased (use AS)");
}
}
if (!withClauseCtx.aliasesGenerated.emplace(*col->alias(), AliasType::kDefault).second) {
return Status::SemanticError("`%s': Redefined alias", col->alias()->c_str());
}
if (!withClauseCtx.yield->hasAgg_ &&
ExpressionUtils::hasAny(col->expr(), {Expression::Kind::kAggregate})) {
withClauseCtx.yield->hasAgg_ = true;
}
exprs.push_back(col->expr());
}
withClauseCtx.yield->yieldColumns = with->columns();
NG_RETURN_IF_ERROR(validateAliases(exprs, withClauseCtx.yield->aliasesUsed));
NG_RETURN_IF_ERROR(validateYield(*withClauseCtx.yield));
withClauseCtx.yield->distinct = with->isDistinct();
auto paginationCtx = getContext<PaginationContext>();
NG_RETURN_IF_ERROR(validatePagination(with->skip(), with->limit(), *paginationCtx));
withClauseCtx.pagination = std::move(paginationCtx);
if (with->orderFactors() != nullptr) {
auto orderByCtx = getContext<OrderByClauseContext>();
NG_RETURN_IF_ERROR(validateOrderBy(with->orderFactors(), with->columns(), *orderByCtx));
withClauseCtx.order = std::move(orderByCtx);
}
return Status::OK();
}
Status MatchValidator::validateUnwind(const UnwindClause *unwind,
UnwindClauseContext &unwindClauseCtx) const {
if (unwind->alias() == nullptr) {
return Status::SemanticError("Expression in UNWIND must be aliased (use AS)");
}
YieldColumns *columns = saveObject(new YieldColumns());
auto *expr = unwind->expr()->clone().release();
auto *alias = new std::string(*unwind->alias());
columns->addColumn(new YieldColumn(expr, alias));
NG_RETURN_IF_ERROR(
validateAliases(std::vector<const Expression *>{expr}, unwindClauseCtx.aliasesUsed));
unwindClauseCtx.yieldColumns = columns;
if (!unwindClauseCtx.aliasesGenerated.emplace(*unwind->alias(), AliasType::kDefault).second) {
return Status::SemanticError("`%s': Redefined alias", unwind->alias()->c_str());
}
return Status::OK();
}
StatusOr<Expression *> MatchValidator::makeSubFilter(const std::string &alias,
const MapExpression *map,
const std::string &label) const {
auto result = makeSubFilterWithoutSave(alias, map, label);
NG_RETURN_IF_ERROR(result);
return saveObject(result.value());
}
StatusOr<Expression *> MatchValidator::makeSubFilterWithoutSave(const std::string &alias,
const MapExpression *map,
const std::string &label) const {
// Node has tag without property
if (!label.empty() && map == nullptr) {
auto *left = new ConstantExpression(label);
auto *args = new ArgumentList();
args->addArgument(std::make_unique<LabelExpression>(alias));
auto *right = new FunctionCallExpression(new std::string("tags"), args);
Expression *root = new RelationalExpression(Expression::Kind::kRelIn, left, right);
return root;
}
DCHECK(map != nullptr);
auto &items = map->items();
DCHECK(!items.empty());
// TODO(dutor) Check if evaluable and evaluate
if (items[0].second->kind() != Expression::Kind::kConstant) {
return Status::SemanticError("Props must be constant: `%s'",
items[0].second->toString().c_str());
}
Expression *root = new RelationalExpression(
Expression::Kind::kRelEQ,
new LabelAttributeExpression(new LabelExpression(alias),
new ConstantExpression(*items[0].first)),
items[0].second->clone().release());
for (auto i = 1u; i < items.size(); i++) {
if (items[i].second->kind() != Expression::Kind::kConstant) {
return Status::SemanticError("Props must be constant: `%s'",
items[i].second->toString().c_str());
}
auto *left = root;
auto *right = new RelationalExpression(
Expression::Kind::kRelEQ,
new LabelAttributeExpression(new LabelExpression(alias),
new ConstantExpression(*items[i].first)),
items[i].second->clone().release());
root = new LogicalExpression(Expression::Kind::kLogicalAnd, left, right);
}
return root;
}
/*static*/ Expression *MatchValidator::andConnect(Expression *left, Expression *right) {
if (left == nullptr) {
return right;
}
if (right == nullptr) {
return left;
}
return new LogicalExpression(Expression::Kind::kLogicalAnd, left, right);
}
Status MatchValidator::combineAliases(
std::unordered_map<std::string, AliasType> &curAliases,
const std::unordered_map<std::string, AliasType> &lastAliases) const {
for (auto &aliasPair : lastAliases) {
if (!curAliases.emplace(aliasPair).second) {
return Status::SemanticError("`%s': Redefined alias", aliasPair.first.c_str());
}
}
return Status::OK();
}
Status MatchValidator::combineYieldColumns(YieldColumns *yieldColumns,
YieldColumns *prevYieldColumns) const {
const auto &prevColumns = prevYieldColumns->columns();
for (auto &column : prevColumns) {
DCHECK(column->alias() != nullptr);
auto *newColumn = new YieldColumn(
new VariablePropertyExpression(new std::string(), new std::string(*column->alias())),
new std::string(*column->alias()));
yieldColumns->addColumn(newColumn);
}
return Status::OK();
}
Status MatchValidator::validatePagination(const Expression *skipExpr,
const Expression *limitExpr,
PaginationContext &paginationCtx) const {
int64_t skip = 0;
int64_t limit = std::numeric_limits<int64_t>::max();
if (skipExpr != nullptr) {
if (!evaluableExpr(skipExpr)) {
return Status::SemanticError("SKIP should be instantly evaluable");
}
QueryExpressionContext ctx;
auto value = const_cast<Expression *>(skipExpr)->eval(ctx);
if (!value.isInt()) {
return Status::SemanticError("SKIP should be of type integer");
}
if (value.getInt() < 0) {
return Status::SemanticError("SKIP should not be negative");
}
skip = value.getInt();
}
if (limitExpr != nullptr) {
if (!evaluableExpr(limitExpr)) {
return Status::SemanticError("SKIP should be instantly evaluable");
}
QueryExpressionContext ctx;
auto value = const_cast<Expression *>(limitExpr)->eval(ctx);
if (!value.isInt()) {
return Status::SemanticError("LIMIT should be of type integer");
}
if (value.getInt() < 0) {
return Status::SemanticError("LIMIT should not be negative");
}
limit = value.getInt();
}
paginationCtx.skip = skip;
paginationCtx.limit = limit;
return Status::OK();
}
Status MatchValidator::validateOrderBy(const OrderFactors *factors,
const YieldColumns *yieldColumns,
OrderByClauseContext &orderByCtx) const {
if (factors != nullptr) {
std::vector<std::string> inputColList;
inputColList.reserve(yieldColumns->columns().size());
for (auto *col : yieldColumns->columns()) {
if (col->alias() != nullptr) {
inputColList.emplace_back(*col->alias());
} else {
inputColList.emplace_back(col->expr()->toString());
}
}
std::unordered_map<std::string, size_t> inputColIndices;
for (auto i = 0u; i < inputColList.size(); i++) {
if (!inputColIndices.emplace(inputColList[i], i).second) {
return Status::SemanticError("Duplicated columns not allowed: %s",
inputColList[i].c_str());
}
}
for (auto &factor : factors->factors()) {
if (factor->expr()->kind() != Expression::Kind::kLabel) {
return Status::SemanticError("Only column name can be used as sort item");
}
auto *name = static_cast<const LabelExpression *>(factor->expr())->name();
auto iter = inputColIndices.find(*name);
if (iter == inputColIndices.end()) {
return Status::SemanticError("Column `%s' not found", name->c_str());
}
orderByCtx.indexedOrderFactors.emplace_back(iter->second, factor->orderType());
}
}
return Status::OK();
}
Status MatchValidator::validateGroup(YieldClauseContext &yieldCtx) const {
auto cols = yieldCtx.yieldColumns->columns();
DCHECK(!cols.empty());
for (auto *col : cols) {
auto rewrited = false;
auto colOldName = deduceColName(col);
if (col->expr()->kind() != Expression::Kind::kAggregate) {
auto collectAggCol = col->expr()->clone();
auto aggs =
ExpressionUtils::collectAll(collectAggCol.get(), {Expression::Kind::kAggregate});
auto size = aggs.size();
if (size > 1) {
return Status::SemanticError("Aggregate function nesting is not allowed: `%s'",
collectAggCol->toString().c_str());
}
if (size == 1) {
// rewrite inner aggExpr to variablePropertyExpr
auto *rewritedExpr = ExpressionUtils::rewriteAgg2VarProp(col->expr());
rewrited = true;
yieldCtx.needGenProject_ = true;
yieldCtx.projCols_->addColumn(
new YieldColumn(rewritedExpr, new std::string(colOldName)));
col->setExpr(aggs[0]->clone().release());
}
}
auto colExpr = col->expr();
if (colExpr->kind() == Expression::Kind::kAggregate) {
auto *aggExpr = static_cast<AggregateExpression *>(colExpr);
NG_RETURN_IF_ERROR(ExpressionUtils::checkAggExpr(aggExpr));
} else if (!ExpressionUtils::isEvaluableExpr(colExpr)) {
yieldCtx.groupKeys_.emplace_back(colExpr);
}
yieldCtx.groupItems_.emplace_back(colExpr);
std::string colNewName;
if (!rewrited) {
colNewName = deduceColName(col);
yieldCtx.projCols_->addColumn(new YieldColumn(
new VariablePropertyExpression(new std::string(), new std::string(colNewName)),
new std::string(colOldName)));
} else {
colNewName = colExpr->toString();
}
yieldCtx.projOutputColumnNames_.emplace_back(colOldName);
yieldCtx.aggOutputColumnNames_.emplace_back(colNewName);
}
return Status::OK();
}
Status MatchValidator::validateYield(YieldClauseContext &yieldCtx) const {
auto cols = yieldCtx.yieldColumns->columns();
if (cols.empty()) {
return Status::SemanticError("Return yield columns is Empty.");
}
yieldCtx.projCols_ = yieldCtx.qctx->objPool()->add(new YieldColumns());
if (!yieldCtx.hasAgg_) {
for (auto &col : yieldCtx.yieldColumns->columns()) {
yieldCtx.projCols_->addColumn(col->clone().release());
if (col->alias() != nullptr) {
yieldCtx.projOutputColumnNames_.emplace_back(*col->alias());
} else {
yieldCtx.projOutputColumnNames_.emplace_back(col->expr()->toString());
}
}
return Status::OK();
} else {
return validateGroup(yieldCtx);
}
}
Status MatchValidator::buildOutputs(const YieldColumns *yields) {
for (auto *col : yields->columns()) {
auto colName = deduceColName(col);
auto typeStatus = deduceExprType(col->expr());
NG_RETURN_IF_ERROR(typeStatus);
auto type = typeStatus.value();
outputs_.emplace_back(colName, type);
}
return Status::OK();
}
} // namespace graph
} // namespace nebula
| 41.636364
| 99
| 0.582689
|
jude-zhu
|
80fff3776c8afab7cb9fe4f6052063170c8b9548
| 3,767
|
cpp
|
C++
|
src/board/arch/stm32/common/ISR.cpp
|
js-midi/OpenDeck
|
72fc7199e3ba484b87086541f27a1ccb20fbc54f
|
[
"Apache-2.0"
] | null | null | null |
src/board/arch/stm32/common/ISR.cpp
|
js-midi/OpenDeck
|
72fc7199e3ba484b87086541f27a1ccb20fbc54f
|
[
"Apache-2.0"
] | null | null | null |
src/board/arch/stm32/common/ISR.cpp
|
js-midi/OpenDeck
|
72fc7199e3ba484b87086541f27a1ccb20fbc54f
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2015-2021 Igor Petrovic
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 "board/Board.h"
#include "board/Internal.h"
#include "core/src/general/Timing.h"
#include <MCU.h>
#include <comm/usb/USB.h>
//This function handles USB On The Go FS global interrupt.
extern "C" void OTG_FS_IRQHandler(void)
{
HAL_PCD_IRQHandler(&hpcd_USB_OTG_FS);
}
//This function handles Non maskable interrupt.
extern "C" void NMI_Handler(void)
{
}
//This function handles Hard fault interrupt.
extern "C" void HardFault_Handler(void)
{
while (true)
{
}
}
//This function handles Memory management fault.
extern "C" void MemManage_Handler(void)
{
/* USER CODE END MemoryManagement_IRQn 0 */
while (true)
{
}
}
//This function handles Pre-fetch fault, memory access fault.
extern "C" void BusFault_Handler(void)
{
while (true)
{
}
}
//This function handles Undefined instruction or illegal state.
extern "C" void UsageFault_Handler(void)
{
while (true)
{
}
}
//This function handles System service call via SWI instruction.
extern "C" void SVC_Handler(void)
{
}
//This function handles Debug monitor.
extern "C" void DebugMon_Handler(void)
{
}
//This function handles Pendable request for system service.
extern "C" void PendSV_Handler(void)
{
}
//This function handles System tick timer.
extern "C" void SysTick_Handler(void)
{
HAL_IncTick();
}
#if defined(FW_APP)
//not needed in bootloader
#ifdef USE_UART
extern "C" void USART1_IRQHandler(void)
{
Board::detail::isrHandling::uart(0);
}
extern "C" void USART2_IRQHandler(void)
{
Board::detail::isrHandling::uart(1);
}
extern "C" void USART3_IRQHandler(void)
{
Board::detail::isrHandling::uart(2);
}
extern "C" void UART4_IRQHandler(void)
{
Board::detail::isrHandling::uart(3);
}
extern "C" void UART5_IRQHandler(void)
{
Board::detail::isrHandling::uart(4);
}
extern "C" void USART6_IRQHandler(void)
{
Board::detail::isrHandling::uart(5);
}
#endif
#ifdef FW_APP
#ifdef ANALOG_SUPPORTED
extern "C" void ADC_IRQHandler(void)
{
Board::detail::isrHandling::adc(ADC_INSTANCE->DR);
}
#endif
#endif
#endif
#ifdef TIM4
extern "C" void TIM4_IRQHandler(void)
{
TIM4->SR = ~TIM_IT_UPDATE;
if (TIM4 == MAIN_TIMER_INSTANCE)
{
Board::detail::isrHandling::mainTimer();
}
else if (TIM4 == PWM_TIMER_INSTANCE)
{
#ifdef FW_APP
#ifndef USB_LINK_MCU
#if MAX_NUMBER_OF_LEDS > 0
Board::detail::io::checkDigitalOutputs();
#endif
#endif
#endif
}
}
#endif
#ifdef TIM5
extern "C" void TIM5_IRQHandler(void)
{
TIM5->SR = ~TIM_IT_UPDATE;
if (TIM5 == MAIN_TIMER_INSTANCE)
{
Board::detail::isrHandling::mainTimer();
}
else if (TIM5 == PWM_TIMER_INSTANCE)
{
#ifdef FW_APP
#ifndef USB_LINK_MCU
#if MAX_NUMBER_OF_LEDS > 0
Board::detail::io::checkDigitalOutputs();
#endif
#endif
#endif
}
}
#endif
#ifdef TIM7
extern "C" void TIM7_IRQHandler(void)
{
TIM7->SR = ~TIM_IT_UPDATE;
if (TIM7 == MAIN_TIMER_INSTANCE)
{
Board::detail::isrHandling::mainTimer();
}
else if (TIM7 == PWM_TIMER_INSTANCE)
{
#ifdef FW_APP
#ifndef USB_LINK_MCU
#if MAX_NUMBER_OF_LEDS > 0
Board::detail::io::checkDigitalOutputs();
#endif
#endif
#endif
}
}
#endif
| 19.025253
| 72
| 0.701088
|
js-midi
|
44077aa82e2405c0eb62d6ce0d357535b1ec10c4
| 2,897
|
cc
|
C++
|
test/common/stats/stat_merger_fuzz_test.cc
|
CS2552F-DOSA/envoy-redis-nonfrontend-proxy-no-profix-router
|
c82450557a7806bb631d1b219daba0fc6fe3eda0
|
[
"Apache-2.0"
] | 40
|
2017-12-20T03:44:17.000Z
|
2022-01-28T02:25:24.000Z
|
test/common/stats/stat_merger_fuzz_test.cc
|
CS2552F-DOSA/envoy-redis-nonfrontend-proxy-no-profix-router
|
c82450557a7806bb631d1b219daba0fc6fe3eda0
|
[
"Apache-2.0"
] | 271
|
2018-06-20T00:18:31.000Z
|
2021-08-25T00:29:26.000Z
|
test/common/stats/stat_merger_fuzz_test.cc
|
CS2552F-DOSA/envoy-redis-nonfrontend-proxy-no-profix-router
|
c82450557a7806bb631d1b219daba0fc6fe3eda0
|
[
"Apache-2.0"
] | 66
|
2017-10-24T20:31:38.000Z
|
2022-03-28T13:20:36.000Z
|
#include <algorithm>
#include "common/stats/stat_merger.h"
#include "test/common/stats/stat_test_utility.h"
#include "test/fuzz/fuzz_runner.h"
#include "test/fuzz/utility.h"
#include "absl/strings/str_replace.h"
namespace Envoy {
namespace Stats {
namespace Fuzz {
void testDynamicEncoding(absl::string_view data, SymbolTable& symbol_table) {
StatNameDynamicPool dynamic_pool(symbol_table);
StatNamePool symbolic_pool(symbol_table);
std::vector<StatName> stat_names;
// This local string is write-only; it's used to help when debugging
// a crash. If a crash is found, you can print the unit_test_encoding
// in the debugger and then add that as a test-case in stat_merger_text.cc,
// in StatMergerDynamicTest.DynamicsWithFakeSymbolTable and
// StatMergerDynamicTest.DynamicsWithRealSymbolTable.
std::string unit_test_encoding;
for (uint32_t index = 0; index < data.size();) {
// Select component lengths between 1 and 8 bytes inclusive, and ensure it
// doesn't overrun our buffer.
//
// TODO(#10008): We should remove the "1 +" below, so we can get empty
// segments, which trigger some inconsistent handling as described in that
// bug.
uint32_t num_bytes = 1 + data[index] & 0x7;
num_bytes = std::min(static_cast<uint32_t>(data.size() - 1),
num_bytes); // restrict number up to the size of data
// Carve out the segment and use the 4th bit from the control-byte to
// determine whether to treat this segment symbolic or not.
absl::string_view segment = data.substr(index, num_bytes);
bool is_symbolic = (data[index] & 0x8) == 0x0;
if (index != 0) {
unit_test_encoding += ".";
}
index += num_bytes + 1;
if (is_symbolic) {
absl::StrAppend(&unit_test_encoding, segment);
stat_names.push_back(symbolic_pool.add(segment));
} else {
absl::StrAppend(&unit_test_encoding, "D:", absl::StrReplaceAll(segment, {{".", ","}}));
stat_names.push_back(dynamic_pool.add(segment));
}
}
SymbolTable::StoragePtr joined = symbol_table.join(stat_names);
StatName stat_name(joined.get());
StatMerger::DynamicContext dynamic_context(symbol_table);
std::string name = symbol_table.toString(stat_name);
StatMerger::DynamicsMap dynamic_map;
dynamic_map[name] = symbol_table.getDynamicSpans(stat_name);
StatName decoded = dynamic_context.makeDynamicStatName(name, dynamic_map);
FUZZ_ASSERT(name == symbol_table.toString(decoded));
FUZZ_ASSERT(stat_name == decoded);
}
// Fuzzer for symbol tables.
DEFINE_FUZZER(const uint8_t* buf, size_t len) {
FakeSymbolTableImpl fake_symbol_table;
SymbolTableImpl symbol_table;
absl::string_view data(reinterpret_cast<const char*>(buf), len);
testDynamicEncoding(data, fake_symbol_table);
testDynamicEncoding(data, symbol_table);
}
} // namespace Fuzz
} // namespace Stats
} // namespace Envoy
| 35.765432
| 93
| 0.721781
|
CS2552F-DOSA
|
440a3c98991b348982431f3c61e296a4f3abec22
| 8,407
|
hpp
|
C++
|
RealmTest/Pods/Realm/include/core/realm/array_binary.hpp
|
Legoless/Sandbox
|
2f0efc2a3ce27a4a813756825641d189e1ee66ce
|
[
"MIT"
] | 15
|
2016-06-06T09:35:13.000Z
|
2021-11-26T21:15:07.000Z
|
RealmTest/Pods/Realm/include/core/realm/array_binary.hpp
|
Legoless/Sandbox
|
2f0efc2a3ce27a4a813756825641d189e1ee66ce
|
[
"MIT"
] | 16
|
2016-02-25T02:31:04.000Z
|
2016-04-19T01:22:16.000Z
|
RealmTest/Pods/Realm/include/core/realm/array_binary.hpp
|
Legoless/Sandbox
|
2f0efc2a3ce27a4a813756825641d189e1ee66ce
|
[
"MIT"
] | 3
|
2016-07-08T04:34:34.000Z
|
2019-02-05T00:58:36.000Z
|
/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_ARRAY_BINARY_HPP
#define REALM_ARRAY_BINARY_HPP
#include <realm/binary_data.hpp>
#include <realm/array_blob.hpp>
#include <realm/array_integer.hpp>
#include <realm/exceptions.hpp>
namespace realm {
/*
STORAGE FORMAT
---------------------------------------------------------------------------------------
ArrayBinary stores binary elements using two ArrayInteger and one ArrayBlob. The ArrayBlob can only store one
single concecutive array of bytes (contrary to its 'Array' name that misleadingly indicates it could store multiple
elements).
Assume we have the strings "a", "", "abc", null, "ab". Then the three arrays will contain:
ArrayInteger m_offsets 1, 1, 5, 5, 6
ArrayBlob m_blob aabcab
ArrayInteger m_nulls 0, 0, 0, 1, 0 // 1 indicates null, 0 indicates non-null
So for each element the ArrayInteger, the ArrayInteger points into the ArrayBlob at the position of the first
byte of the next element.
m_nulls is always present (except for old database files; see below), so any ArrayBinary is always nullable!
The nullable property (such as throwing exception upon set(null) on non-nullable column, etc) is handled on
column level only.
DATABASE FILE VERSION CHANGES
---------------------------------------------------------------------------------------
Old database files do not have any m_nulls array. To be backwardscompatible, many methods will have tests like
`if(Array::size() == 3)` and have a backwards compatible code paths for these (e.g. avoid writing to m_nulls
in set(), etc). This way no file format upgrade is needed to support nulls for BinaryData.
*/
class ArrayBinary: public Array {
public:
explicit ArrayBinary(Allocator&) noexcept;
~ArrayBinary() noexcept override {}
/// Create a new empty binary array and attach this accessor to
/// it. This does not modify the parent reference information of
/// this accessor.
///
/// Note that the caller assumes ownership of the allocated
/// underlying node. It is not owned by the accessor.
void create();
// Old database files will not have the m_nulls array, so we need code paths for
// backwards compatibility for these cases.
bool legacy_array_type() const noexcept;
//@{
/// Overriding functions of Array
void init_from_ref(ref_type) noexcept;
void init_from_mem(MemRef) noexcept;
void init_from_parent() noexcept;
//@}
bool is_empty() const noexcept;
size_t size() const noexcept;
BinaryData get(size_t ndx) const noexcept;
void add(BinaryData value, bool add_zero_term = false);
void set(size_t ndx, BinaryData value, bool add_zero_term = false);
void insert(size_t ndx, BinaryData value, bool add_zero_term = false);
void erase(size_t ndx);
void truncate(size_t size);
void clear();
void destroy();
/// Get the specified element without the cost of constructing an
/// array instance. If an array instance is already available, or
/// you need to get multiple values, then this method will be
/// slower.
static BinaryData get(const char* header, size_t ndx, Allocator&) noexcept;
ref_type bptree_leaf_insert(size_t ndx, BinaryData, bool add_zero_term,
TreeInsertBase& state);
static size_t get_size_from_header(const char*, Allocator&) noexcept;
/// Construct a binary array of the specified size and return just
/// the reference to the underlying memory. All elements will be
/// initialized to the binary value `defaults`, which can be either
/// null or zero-length non-null (value with size > 0 is not allowed as
/// initialization value).
static MemRef create_array(size_t size, Allocator&, BinaryData defaults);
/// Construct a copy of the specified slice of this binary array
/// using the specified target allocator.
MemRef slice(size_t offset, size_t size, Allocator& target_alloc) const;
#ifdef REALM_DEBUG
void to_dot(std::ostream&, bool is_strings, StringData title = StringData()) const;
#endif
bool update_from_parent(size_t old_baseline) noexcept;
private:
ArrayInteger m_offsets;
ArrayBlob m_blob;
ArrayInteger m_nulls;
};
// Implementation:
inline ArrayBinary::ArrayBinary(Allocator& alloc) noexcept:
Array(alloc), m_offsets(alloc), m_blob(alloc),
m_nulls(alloc)
{
m_offsets.set_parent(this, 0);
m_blob.set_parent(this, 1);
m_nulls.set_parent(this, 2);
}
inline void ArrayBinary::create()
{
size_t size = 0;
BinaryData defaults = BinaryData(0, 0); // This init value is ignored because size = 0
MemRef mem = create_array(size, get_alloc(), defaults); // Throws
init_from_mem(mem);
}
inline void ArrayBinary::init_from_ref(ref_type ref) noexcept
{
REALM_ASSERT(ref);
char* header = get_alloc().translate(ref);
init_from_mem(MemRef(header, ref));
}
inline void ArrayBinary::init_from_parent() noexcept
{
ref_type ref = get_ref_from_parent();
init_from_ref(ref);
}
inline bool ArrayBinary::is_empty() const noexcept
{
return m_offsets.is_empty();
}
// Old database files will not have the m_nulls array, so we need code paths for
// backwards compatibility for these cases. We can test if m_nulls exists by looking
// at number of references in this ArrayBinary.
inline bool ArrayBinary::legacy_array_type() const noexcept
{
if (Array::size() == 3)
return false; // New database file
else if (Array::size() == 2)
return true; // Old database file
else
REALM_ASSERT(false); // Should never happen
return false;
}
inline size_t ArrayBinary::size() const noexcept
{
return m_offsets.size();
}
inline BinaryData ArrayBinary::get(size_t ndx) const noexcept
{
REALM_ASSERT_3(ndx, <, m_offsets.size());
if (!legacy_array_type() && m_nulls.get(ndx)) {
return BinaryData();
}
else {
size_t begin = ndx ? to_size_t(m_offsets.get(ndx - 1)) : 0;
size_t end = to_size_t(m_offsets.get(ndx));
BinaryData bd = BinaryData(m_blob.get(begin), end - begin);
// Old database file (non-nullable column should never return null)
REALM_ASSERT(!bd.is_null());
return bd;
}
}
inline void ArrayBinary::truncate(size_t size)
{
REALM_ASSERT_3(size, <, m_offsets.size());
size_t blob_size = size ? to_size_t(m_offsets.get(size-1)) : 0;
m_offsets.truncate(size);
m_blob.truncate(blob_size);
if (!legacy_array_type())
m_nulls.truncate(size);
}
inline void ArrayBinary::clear()
{
m_blob.clear();
m_offsets.clear();
if (!legacy_array_type())
m_nulls.clear();
}
inline void ArrayBinary::destroy()
{
m_blob.destroy();
m_offsets.destroy();
if (!legacy_array_type())
m_nulls.destroy();
Array::destroy();
}
inline size_t ArrayBinary::get_size_from_header(const char* header,
Allocator& alloc) noexcept
{
ref_type offsets_ref = to_ref(Array::get(header, 0));
const char* offsets_header = alloc.translate(offsets_ref);
return Array::get_size_from_header(offsets_header);
}
inline bool ArrayBinary::update_from_parent(size_t old_baseline) noexcept
{
bool res = Array::update_from_parent(old_baseline);
if (res) {
m_blob.update_from_parent(old_baseline);
m_offsets.update_from_parent(old_baseline);
if (!legacy_array_type())
m_nulls.update_from_parent(old_baseline);
}
return res;
}
} // namespace realm
#endif // REALM_ARRAY_BINARY_HPP
| 32.712062
| 115
| 0.67539
|
Legoless
|
440b840faaaf9d42bf6ccea70a918d3404cb8539
| 8,440
|
cpp
|
C++
|
unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
|
URSec/Silhouette-Compiler-Legacy
|
28b37f3617c5543a87537decc074b168f4803d87
|
[
"Apache-2.0"
] | 938
|
2015-12-03T16:45:43.000Z
|
2022-03-17T20:28:02.000Z
|
unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
|
URSec/Silhouette-Compiler-Legacy
|
28b37f3617c5543a87537decc074b168f4803d87
|
[
"Apache-2.0"
] | 127
|
2015-12-03T21:42:53.000Z
|
2019-11-21T14:34:20.000Z
|
unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
|
URSec/Silhouette-Compiler-Legacy
|
28b37f3617c5543a87537decc074b168f4803d87
|
[
"Apache-2.0"
] | 280
|
2015-12-03T16:51:35.000Z
|
2022-01-24T00:01:54.000Z
|
//===--- RTDyldObjectLinkingLayerTest.cpp - RTDyld linking layer tests ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "OrcTestCommon.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/ExecutionEngine/Orc/Legacy.h"
#include "llvm/ExecutionEngine/Orc/NullResolver.h"
#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace llvm::orc;
namespace {
class RTDyldObjectLinkingLayerExecutionTest : public testing::Test,
public OrcExecutionTest {};
// Adds an object with a debug section to RuntimeDyld and then returns whether
// the debug section was passed to the memory manager.
static bool testSetProcessAllSections(std::unique_ptr<MemoryBuffer> Obj,
bool ProcessAllSections) {
class MemoryManagerWrapper : public SectionMemoryManager {
public:
MemoryManagerWrapper(bool &DebugSeen) : DebugSeen(DebugSeen) {}
uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID, StringRef SectionName,
bool IsReadOnly) override {
if (SectionName == ".debug_str")
DebugSeen = true;
return SectionMemoryManager::allocateDataSection(
Size, Alignment, SectionID, SectionName, IsReadOnly);
}
private:
bool &DebugSeen;
};
bool DebugSectionSeen = false;
ExecutionSession ES;
auto &JD = ES.createJITDylib("main");
auto Foo = ES.intern("foo");
RTDyldObjectLinkingLayer ObjLayer(ES, [&DebugSectionSeen]() {
return llvm::make_unique<MemoryManagerWrapper>(DebugSectionSeen);
});
auto OnResolveDoNothing = [](Expected<SymbolMap> R) {
cantFail(std::move(R));
};
ObjLayer.setProcessAllSections(ProcessAllSections);
cantFail(ObjLayer.add(JD, std::move(Obj), ES.allocateVModule()));
ES.lookup(JITDylibSearchList({{&JD, false}}), {Foo}, SymbolState::Resolved,
OnResolveDoNothing, NoDependenciesToRegister);
return DebugSectionSeen;
}
TEST(RTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
LLVMContext Context;
auto M = llvm::make_unique<Module>("", Context);
M->setTargetTriple("x86_64-unknown-linux-gnu");
Type *Int32Ty = IntegerType::get(Context, 32);
GlobalVariable *GV =
new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
ConstantInt::get(Int32Ty, 42), "foo");
GV->setSection(".debug_str");
// Initialize the native target in case this is the first unit test
// to try to build a TM.
OrcNativeTarget::initialize();
std::unique_ptr<TargetMachine> TM(EngineBuilder().selectTarget(
Triple(M->getTargetTriple()), "", "", SmallVector<std::string, 1>()));
if (!TM)
return;
auto Obj = SimpleCompiler(*TM)(*M);
EXPECT_FALSE(testSetProcessAllSections(
MemoryBuffer::getMemBufferCopy(Obj->getBuffer()), false))
<< "Debug section seen despite ProcessAllSections being false";
EXPECT_TRUE(testSetProcessAllSections(std::move(Obj), true))
<< "Expected to see debug section when ProcessAllSections is true";
}
TEST(RTDyldObjectLinkingLayerTest, TestOverrideObjectFlags) {
OrcNativeTarget::initialize();
std::unique_ptr<TargetMachine> TM(
EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
SmallVector<std::string, 1>()));
if (!TM)
return;
// Our compiler is going to modify symbol visibility settings without telling
// ORC. This will test our ability to override the flags later.
class FunkySimpleCompiler : public SimpleCompiler {
public:
FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
CompileResult operator()(Module &M) {
auto *Foo = M.getFunction("foo");
assert(Foo && "Expected function Foo not found");
Foo->setVisibility(GlobalValue::HiddenVisibility);
return SimpleCompiler::operator()(M);
}
};
// Create a module with two void() functions: foo and bar.
ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
ThreadSafeModule M;
{
ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
MB.getModule()->setDataLayout(TM->createDataLayout());
Function *FooImpl = MB.createFunctionDecl(
FunctionType::get(Type::getVoidTy(*TSCtx.getContext()), {}, false),
"foo");
BasicBlock *FooEntry =
BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
IRBuilder<> B1(FooEntry);
B1.CreateRetVoid();
Function *BarImpl = MB.createFunctionDecl(
FunctionType::get(Type::getVoidTy(*TSCtx.getContext()), {}, false),
"bar");
BasicBlock *BarEntry =
BasicBlock::Create(*TSCtx.getContext(), "entry", BarImpl);
IRBuilder<> B2(BarEntry);
B2.CreateRetVoid();
M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
}
// Create a simple stack and set the override flags option.
ExecutionSession ES;
auto &JD = ES.createJITDylib("main");
auto Foo = ES.intern("foo");
RTDyldObjectLinkingLayer ObjLayer(
ES, []() { return llvm::make_unique<SectionMemoryManager>(); });
IRCompileLayer CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
ObjLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
cantFail(CompileLayer.add(JD, std::move(M), ES.allocateVModule()));
ES.lookup(
JITDylibSearchList({{&JD, false}}), {Foo}, SymbolState::Resolved,
[](Expected<SymbolMap> R) { cantFail(std::move(R)); },
NoDependenciesToRegister);
}
TEST(RTDyldObjectLinkingLayerTest, TestAutoClaimResponsibilityForSymbols) {
OrcNativeTarget::initialize();
std::unique_ptr<TargetMachine> TM(
EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
SmallVector<std::string, 1>()));
if (!TM)
return;
// Our compiler is going to add a new symbol without telling ORC.
// This will test our ability to auto-claim responsibility later.
class FunkySimpleCompiler : public SimpleCompiler {
public:
FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
CompileResult operator()(Module &M) {
Function *BarImpl = Function::Create(
FunctionType::get(Type::getVoidTy(M.getContext()), {}, false),
GlobalValue::ExternalLinkage, "bar", &M);
BasicBlock *BarEntry =
BasicBlock::Create(M.getContext(), "entry", BarImpl);
IRBuilder<> B(BarEntry);
B.CreateRetVoid();
return SimpleCompiler::operator()(M);
}
};
// Create a module with two void() functions: foo and bar.
ThreadSafeContext TSCtx(llvm::make_unique<LLVMContext>());
ThreadSafeModule M;
{
ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
MB.getModule()->setDataLayout(TM->createDataLayout());
Function *FooImpl = MB.createFunctionDecl(
FunctionType::get(Type::getVoidTy(*TSCtx.getContext()), {}, false),
"foo");
BasicBlock *FooEntry =
BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
IRBuilder<> B(FooEntry);
B.CreateRetVoid();
M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
}
// Create a simple stack and set the override flags option.
ExecutionSession ES;
auto &JD = ES.createJITDylib("main");
auto Foo = ES.intern("foo");
RTDyldObjectLinkingLayer ObjLayer(
ES, []() { return llvm::make_unique<SectionMemoryManager>(); });
IRCompileLayer CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
ObjLayer.setAutoClaimResponsibilityForObjectSymbols(true);
cantFail(CompileLayer.add(JD, std::move(M), ES.allocateVModule()));
ES.lookup(
JITDylibSearchList({{&JD, false}}), {Foo}, SymbolState::Resolved,
[](Expected<SymbolMap> R) { cantFail(std::move(R)); },
NoDependenciesToRegister);
}
} // end anonymous namespace
| 36.068376
| 80
| 0.679858
|
URSec
|
440c4d7c983d22cf81db1680cc1e8a4aafcf51ef
| 9,636
|
cpp
|
C++
|
player/src/player/engine.cpp
|
onvif/oxfplayer
|
fa76afebf7549b0b6f408e99de2f66c07dca457a
|
[
"BSD-3-Clause"
] | 17
|
2020-01-31T03:43:11.000Z
|
2022-03-11T03:55:37.000Z
|
player/src/player/engine.cpp
|
onvif/oxfplayer
|
fa76afebf7549b0b6f408e99de2f66c07dca457a
|
[
"BSD-3-Clause"
] | 1
|
2021-11-08T15:29:08.000Z
|
2021-12-09T14:26:44.000Z
|
player/src/player/engine.cpp
|
onvif/oxfplayer
|
fa76afebf7549b0b6f408e99de2f66c07dca457a
|
[
"BSD-3-Clause"
] | 4
|
2020-03-09T08:31:47.000Z
|
2021-11-04T18:32:41.000Z
|
/************************************************************************************
* Copyright (c) 2013 ONVIF.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ONVIF nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ONVIF BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************/
#include "videoFrameWidget.h"
#include "defines.h"
#include "engine.h"
#include "queuedVideoDecoder.h"
#include "queuedAudioDecoder.h"
#include <QDebug>
Engine::Engine() :
BasePlayback(),
m_video_widget(nullptr),
m_is_initialized(false),
m_player_state(Stopped),
m_playing_time(0)
{
QObject::connect(&m_video_playback, SIGNAL(played(BasePlayback*)), this, SIGNAL(played(BasePlayback*)));
QObject::connect(&m_video_playback, SIGNAL(playbackFinished()), this, SLOT(onFinished()));
//direct connection used to prevent receiving messages from previously opened file
QObject::connect(&m_audio_playback, SIGNAL(played(BasePlayback*)), &m_video_playback, SLOT(syncWithAudio(BasePlayback*)), Qt::DirectConnection);
QObject::connect(&m_audio_playback, SIGNAL(playbackFinished()), this, SLOT(onFinished()));
}
Engine::~Engine()
{
stop();
clear();
}
/*********************************************************************************************/
void Engine::setVideoWidget(VideoFrameWidget* video_widget)
{
m_video_widget = video_widget;
m_video_playback.setVideoWidget(m_video_widget);
}
bool Engine::init(const QString& file_name, SegmentInfo& fragment)
{
bool res = true;
res = res && initDecoders(file_name, fragment.getFpsFromSamples());
res = res && initPlayback();
res = res && m_video_decoder.getStreamsCount();
m_is_initialized = res;
return res;
}
void Engine::start()
{
if(!m_is_initialized ||
m_player_state != Stopped)
return;
bool have_video = m_video_decoder.getStreamsCount();
bool have_audio = m_audio_decoder.getStreamsCount();
if(!have_video)
return;
if(!have_audio)
{
//just video
m_video_decoder.start();
m_video_playback.start();
}
else
{
//video and audio - modify fps
m_video_decoder.start();
m_audio_decoder.start();
m_video_playback.start();
m_audio_playback.start();
}
m_player_state = Playing;
}
void Engine::pause()
{
if(!m_is_initialized ||
m_player_state != Playing)
return;
if(m_audio_decoder.getStreamsCount())
m_audio_playback.pause();
m_video_playback.pause();
m_player_state = Paused;
}
void Engine::resume()
{
if(!m_is_initialized ||
m_player_state != Paused)
return;
if(m_audio_decoder.getStreamsCount())
m_audio_playback.resume();
m_video_playback.resume();
m_player_state = Playing;
}
void Engine::stop()
{
if(!m_is_initialized)
return;
//do stop actions
stopPlayback();
//seek to the beginning
doSeek(0);
m_player_state = Stopped;
}
void Engine::startAndPause()
{
if(!m_is_initialized ||
m_player_state != Stopped)
return;
bool have_video = m_video_decoder.getStreamsCount();
bool have_audio = m_audio_decoder.getStreamsCount();
if(!have_video)
return;
if(!have_audio)
{
//just video
m_video_decoder.start();
m_video_playback.startAndPause();
}
else
{
//video and audio
if(m_video_decoder.m_context.getTimerDelay() > AUDIO_NOTIFY_TIMEOUT)
{
//vide fps is to low - connect video to audio by notify
//TODO
}
else
{
//video is faster then audio - modify fps
m_video_decoder.start();
m_audio_decoder.start();
m_video_playback.startAndPause();
m_audio_playback.startAndPause();
}
}
m_player_state = Paused;
}
void Engine::clear()
{
m_video_decoder.clear();
m_audio_decoder.clear();
m_video_playback.clear();
m_audio_playback.clear();
m_player_state = Stopped;
m_playing_time = 0;
}
int Engine::getPlayingTime() const
{
if(m_player_state != Stopped)
m_playing_time = m_video_playback.getPlayingTime();
return m_playing_time;
}
void Engine::seek(int time_ms)
{
if(!m_is_initialized)
return;
qDebug() << "Seek to" << time_ms;
switch(m_player_state)
{
case Stopped:
//seeking in stop state
doSeek(time_ms);
startAndPause();
break;
case Playing:
//seeking in playing state
stopPlayback();
doSeek(time_ms);
start();
break;
case Paused:
//seeking in paused state
stopPlayback();
doSeek(time_ms);
startAndPause();
break;
}
}
void Engine::setAudioStreamIndex(int index)
{
m_audio_decoder.setIndex(index);
m_audio_playback.setAudioParams(m_audio_decoder.getParams());
}
void Engine::setVolume(int volume)
{
if(!m_is_initialized)
return;
if(volume < 0)
volume = 0;
if(volume > 100)
volume = 100;
double vol = (double)volume / 100.0;
if(m_audio_decoder.getStreamsCount())
m_audio_playback.setVolume(vol);
}
#ifdef MEMORY_INFO
void Engine::memoryInfo(int& video_memory, int& audio_memory) const
{
video_memory = m_video_decoder.buffersSize();
audio_memory = m_audio_decoder.buffersSize();
}
#endif //MEMORY_INFO
/*********************************************************************************************/
bool Engine::initDecoders(const QString& file_name, double fps)
{
bool res = true;
res = res && m_video_decoder.open(file_name);
res = res && m_audio_decoder.open(file_name);
res = res && m_video_decoder.getStreamsCount();
m_video_decoder.setStream(0, fps);
m_audio_decoder.setIndex(0);
return res;
}
bool Engine::initPlayback()
{
m_video_playback.setVideoContext(&m_video_decoder.m_context);
m_video_playback.setVideoDecoder(&m_video_decoder);
m_video_playback.setVideoWidget(m_video_widget);
m_audio_playback.setAudioDecoder(&m_audio_decoder);
m_audio_playback.setAudioParams(m_audio_decoder.getParams());
return true;
}
void Engine::stopPlayback()
{
if(m_audio_decoder.getStreamsCount())
m_audio_playback.stop();
m_video_playback.stop();
m_audio_decoder.stop();
m_video_decoder.stop();
m_audio_decoder.clearBuffers();
m_video_decoder.clearBuffers();
m_playing_time = 0;
m_player_state = Stopped;
}
void Engine::doSeek(int time_ms)
{
m_playing_time = time_ms;
bool have_audio = m_audio_decoder.getStreamsCount();
//seek video
if(time_ms == 0)
{
//stop seek
m_video_decoder.seek(0);
}
else
{
//step by step seek
for(int step = 100; step <= SEEK_BACKSTEP; step *= 2)
{
int video_seek_time = time_ms - step;
if(video_seek_time < 0)
{
video_seek_time = 0;
//that's all - seek to start
m_video_decoder.seek(video_seek_time);
break;
}
m_video_decoder.seek(video_seek_time);
}
}
//skip threshold
QVector<int> pts_vector;
m_video_decoder.timeToPTS(time_ms, pts_vector);
if (pts_vector.size() > 0) {
m_video_decoder.setSkipThreshold(pts_vector[m_video_decoder.getIndex()]);
}
//audio seek
if(have_audio)
m_audio_decoder.seek(time_ms);
//clear video context fps
m_video_decoder.m_context.flushCurrentFps();
}
int Engine::showNextFrame()
{
VideoFrame video_frame;
m_video_decoder.getNextFrame(video_frame);
m_video_widget->setDrawImage(video_frame.m_image);
return video_frame.m_time;
}
void Engine::onFinished()
{
pause();
emit playbackFinished();
}
| 26.4
| 149
| 0.617061
|
onvif
|
440d607393d348561dd2a13a3bfa7b15bcd7c6ea
| 93
|
hpp
|
C++
|
example/system/thread/speca.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
example/system/thread/speca.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
example/system/thread/speca.hpp
|
joydit/solidframe
|
0539b0a1e77663ac4c701a88f56723d3e3688e8c
|
[
"BSL-1.0"
] | null | null | null |
#ifndef TEST_SPEC_A_HPP
#define TEST_SPEC_A_HPP
///\cond 0
void testa();
///\endcond
#endif
| 11.625
| 23
| 0.731183
|
joydit
|
440e82ca5d15d9c7b8a5ea5e947c513e3bd1560f
| 952
|
hpp
|
C++
|
library/ATF/_qry_case_unmandtrader_buy_get_info.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/_qry_case_unmandtrader_buy_get_info.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/_qry_case_unmandtrader_buy_get_info.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct _qry_case_unmandtrader_buy_get_info
{
struct __list
{
unsigned int dwRegistSerial;
unsigned int dwPrice;
unsigned int dwSeller;
char byRaceSexCode;
unsigned int dwDalant;
unsigned int dwGuildSerial;
char byUserGrade;
unsigned int dwAccountSerial;
char szAccountID[13];
char wszName[17];
unsigned int dwTax;
char byProcRet;
};
unsigned __int16 wInx;
unsigned int dwBuyer;
char byRace;
char byUserGrade;
char byDivision;
char byClass;
char bySubClass;
char byType;
char byNum;
__list List[10];
};
END_ATF_NAMESPACE
| 25.72973
| 108
| 0.586134
|
lemkova
|
440f4b717a3895303aaec41403f2601a715f60d9
| 6,475
|
cpp
|
C++
|
common/OCLSample.cpp
|
jholewinski/llvm-ptx-samples
|
2064b14fd900caa9546fb861c90ffcb7ab19fa24
|
[
"MIT"
] | 15
|
2015-01-30T01:08:08.000Z
|
2022-03-16T10:49:08.000Z
|
common/OCLSample.cpp
|
jholewinski/llvm-ptx-samples
|
2064b14fd900caa9546fb861c90ffcb7ab19fa24
|
[
"MIT"
] | null | null | null |
common/OCLSample.cpp
|
jholewinski/llvm-ptx-samples
|
2064b14fd900caa9546fb861c90ffcb7ab19fa24
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2011 by Justin Holewinski
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <vector>
#include <iostream>
#include <fstream>
#include <cassert>
#include "common/OCLSample.hpp"
OCLSample::OCLSample()
: numIterations_(4) {
initOpenCL();
}
OCLSample::~OCLSample() {
}
void OCLSample::initialize() {
}
void OCLSample::createMemoryBuffers() {
}
void OCLSample::setupKernel(cl::Kernel kernel) {
}
void OCLSample::finishKernel(cl::Kernel kernel) {
}
void OCLSample::runKernel(cl::Kernel kernel, cl::Event* evt) {
}
void OCLSample::run() {
double elapsed, average;
initialize();
createMemoryBuffers();
std::cout << "------------------------------\n";
std::cout << "* Source Kernel\n";
std::cout << "------------------------------\n";
setupKernel(sourceKernel_);
timeKernel(sourceKernel_, elapsed, average);
finishKernel(sourceKernel_);
std::cout << "Number of Iterations: " << numIterations_ << "\n";
std::cout << "Total Time: " << elapsed << " sec\n";
std::cout << "Average Time: " << average << " sec\n";
std::cout << "------------------------------\n";
std::cout << "* Binary Kernel\n";
std::cout << "------------------------------\n";
setupKernel(binaryKernel_);
timeKernel(binaryKernel_, elapsed, average);
finishKernel(binaryKernel_);
std::cout << "Number of Iterations: " << numIterations_ << "\n";
std::cout << "Total Time: " << elapsed << " sec\n";
std::cout << "Average Time: " << average << " sec\n";
}
void OCLSample::timeKernel(cl::Kernel kernel, double& elapsed,
double& average) {
cl::Event* events = new cl::Event[numIterations_];
cl_int result;
elapsed = 0.0;
for(unsigned i = 0; i < numIterations_; ++i) {
cl_ulong start, end;
runKernel(kernel, &events[i]);
queue_.flush();
events[i].wait();
result = events[i].getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START,
&start);
assert(result == CL_SUCCESS && "Unable to get profiling information");
result = events[i].getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END,
&end);
assert(result == CL_SUCCESS && "Unable to get profiling information");
elapsed += (double)1e-9 * (end - start);
}
average = elapsed / (double)numIterations_;
delete [] events;
}
cl::Program OCLSample::compileSource(const std::string& filename) {
cl_int result;
std::ifstream kernelStream(filename.c_str());
std::string source(std::istreambuf_iterator<char>(kernelStream),
(std::istreambuf_iterator<char>()));
kernelStream.close();
cl::Program::Sources sources(1, std::make_pair(source.c_str(),
source.size()));
cl::Program program(context_, sources, &result);
assert(result == CL_SUCCESS && "Failed to load program source");
std::vector<cl::Device> devices;
devices.push_back(device_);
result = program.build(devices);
if(result != CL_SUCCESS) {
std::cerr << "Source compilation failed.\n";
std::cerr << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device_);
assert(false && "Unable to continue");
}
return program;
}
cl::Program OCLSample::loadBinary(const std::string& filename) {
cl_int result;
std::ifstream kernelStream(filename.c_str());
std::string binary(std::istreambuf_iterator<char>(kernelStream),
(std::istreambuf_iterator<char>()));
kernelStream.close();
cl::Program::Binaries binaries(1, std::make_pair(binary.c_str(),
binary.size()));
std::vector<cl::Device> devices;
devices.push_back(device_);
cl::Program program(context_, devices, binaries, NULL, &result);
assert(result == CL_SUCCESS && "Failed to load program source");
result = program.build(devices);
if(result != CL_SUCCESS) {
std::cerr << "Source compilation failed.\n";
std::cerr << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device_);
assert(false && "Unable to continue");
}
return program;
}
void OCLSample::initOpenCL() {
cl_int result;
// First, select an OpenCL platform
typedef std::vector<cl::Platform> PlatformVector;
PlatformVector platforms;
result = cl::Platform::get(&platforms);
assert(result == CL_SUCCESS && "Failed to retrieve OpenCL platform");
assert(platforms.size() > 0 && "No OpenCL platforms found");
// For now, just blindly select the first platform.
// @TODO: Implement a check here for the NVidia OpenCL platform.
platform_ = platforms[0];
// Create an OpenCL context.
cl_context_properties cps[] = { CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform_)(), 0 };
context_ = cl::Context(CL_DEVICE_TYPE_GPU, cps, NULL, NULL, &result);
assert(result == CL_SUCCESS && "Failed to create OpenCL context");
// Retrieve the available OpenCL devices.
typedef std::vector<cl::Device> DeviceVector;
DeviceVector devices;
devices = context_.getInfo<CL_CONTEXT_DEVICES>();
assert(devices.size() > 0 && "No OpenCL devices found");
// For now, just blindly select the first device.
// @TODO: Implement some sort of device check here.
device_ = devices[0];
// Create a command queue
queue_ = cl::CommandQueue(context_, device_, CL_QUEUE_PROFILING_ENABLE, &result);
assert(result == CL_SUCCESS && "Failed to create command queue");
}
| 34.259259
| 83
| 0.656525
|
jholewinski
|
440ffb44b5d45016aa641011aba8762ecd6bf4fd
| 23,438
|
cpp
|
C++
|
tb_jun/src/underlag/path_mini (copy).cpp
|
ligatos/tords-workspace-2020
|
11eba9fec3c85600afaf515468f74274f7cb5a68
|
[
"Apache-2.0"
] | null | null | null |
tb_jun/src/underlag/path_mini (copy).cpp
|
ligatos/tords-workspace-2020
|
11eba9fec3c85600afaf515468f74274f7cb5a68
|
[
"Apache-2.0"
] | null | null | null |
tb_jun/src/underlag/path_mini (copy).cpp
|
ligatos/tords-workspace-2020
|
11eba9fec3c85600afaf515468f74274f7cb5a68
|
[
"Apache-2.0"
] | null | null | null |
#include <ros/ros.h>
#include <octomap_msgs/conversions.h>
#include <octomap_msgs/Octomap.h>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap/OcTreeBase.h>
#include <octomap/octomap_types.h>
#include <tf/transform_datatypes.h>
#include <dynamicEDT3D/dynamicEDTOctomap.h>
#include <nav_msgs/Path.h>
#include <geometry_msgs/Pose.h>
#include <iostream>
#include <string>
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <sensor_msgs/LaserScan.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Twist.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_ros/transform_listener.h>
#include "tf2_ros/message_filter.h"
#include "tf2_ros/transform_broadcaster.h"
#include "tf2_geometry_msgs/tf2_geometry_msgs.h"
#include <nav_msgs/Path.h>
#include <nav_msgs/OccupancyGrid.h>
#include <map_msgs/OccupancyGridUpdate.h>
#include <std_msgs/UInt8.h>
#include <visualization_msgs/MarkerArray.h>
#include <geometry_msgs/PolygonStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/Point32.h>
#include <eigen3/Eigen/Core>
#include <geometry_msgs/Vector3Stamped.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <image_transport/image_transport.h>
tf2_ros::Buffer tfBuffer;
using namespace octomap;
using namespace std;
shared_ptr<DynamicEDTOctomap> edf_ptr;
AbstractOcTree* abs_octree;
shared_ptr<OcTree> octree;
string par_workdir_path;
geometry_msgs::Point bbmin_custom,bbmax_custom,bbmin_octree,bbmax_octree,pos,last_pos;
int xmin,ymin,zmin,xmax,ymax,zmax,range_x,range_y,range_z,zmin_global,zmax_global;
float pos_yaw;
bool par_unknownAsOccupied,get_floor,got_map;
double par_maprad,par_maxobs,par_minobs,last_yaw,par_zjump,par_delta_hdng,par_delta_incline;
nav_msgs::Path path_candidates_sides,path_candidates,path_visited,path_candidates2d,path_floor,path_vlp;
geometry_msgs::Vector3 vlp_rpy;
geometry_msgs::PointStamped pnt_midpoint;
geometry_msgs::PoseStamped last_pose,base_pose;
float mapradtouse;
float grid_sidelength = 3;
geometry_msgs::PolygonStamped poly_vlp;
geometry_msgs::Point bbmin_vlp,bbmax_vlp;
std_msgs::Header hdr(){
std_msgs::Header header;
header.frame_id = "map";
header.stamp = ros::Time::now();
return header;
}
float get_hdng(geometry_msgs::Point p1,geometry_msgs::Point p0){
float dx = p1.x - p0.x;
float dy = p1.y - p0.y;
return atan2(dy,dx);
}
double get_shortest(double target_hdng,double actual_hdng){
double a = target_hdng - actual_hdng;
if(a > M_PI)a -= M_PI*2;
else if(a < -M_PI)a += M_PI*2;
return a;
}
bool in_poly(geometry_msgs::PolygonStamped polyin, float x, float y){
ros::Time t0 = ros::Time::now();
int cross = 0;
geometry_msgs::Point point;
point.x = x;
point.y = y;
for(int i = 0,j = polyin.polygon.points.size()-1; i < polyin.polygon.points.size(); j=i++){// for (int i = 0, j = vertices_.size() - 1; i < vertices_.size(); j = i++) {
if ( ((polyin.polygon.points[i].y > point.y) != (polyin.polygon.points[j].y > point.y))
&& (point.x < (polyin.polygon.points[j].x - polyin.polygon.points[i].x) * (point.y - polyin.polygon.points[i].y) /
(polyin.polygon.points[j].y - polyin.polygon.points[i].y) + polyin.polygon.points[i].x) )
{
cross++;
}
}
// float dt = (ros::Time::now() - t0).toSec();
// ROS_INFO("sr: %.5f",dt);
return bool(cross % 2);
}
nav_msgs::Path constrain_path_bbpoly(nav_msgs::Path pathin,geometry_msgs::PolygonStamped poly_bb){
nav_msgs::Path pathout;
pathout.header = hdr();
if(pathin.poses.size() == 0 || poly_bb.polygon.points.size() == 0)
return pathin;
for(int i = 0; i < pathin.poses.size(); i++){
if(in_poly(poly_bb,pathin.poses[i].pose.position.x,pathin.poses[i].pose.position.y)){
pathout.poses.push_back(pathin.poses[i]);
}
}
return pathout;
}
float get_dst2d(geometry_msgs::Point p1, geometry_msgs::Point p2){
return(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)));
}
float get_dst2d32(geometry_msgs::Point32 p1, geometry_msgs::Point p2){
return(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)));
}
float get_dst3d(geometry_msgs::Point p1, geometry_msgs::Point p2){
return(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)+pow(p1.z-p2.z,2)));
}
int dst_point_in_path_index(nav_msgs::Path pathin,geometry_msgs::Point pin,float lim){
float res,dst;
if(pathin.poses.size() == 0)
return res;
for(int i = 0; i < pathin.poses.size(); i++){
if(get_dst3d(pathin.poses[i].pose.position,pin) < lim)
return i;
}
return 0;
}
bool dst_point_in_path_lim(nav_msgs::Path pathin,geometry_msgs::Point pin,float lim){
float res,dst;
if(pathin.poses.size() == 0)
return res;
for(int i = 0; i < pathin.poses.size(); i++){
if(get_dst3d(pathin.poses[i].pose.position,pin) < lim)
return false;
}
return true;
}
bool dst_point_in_path_lim2d(nav_msgs::Path pathin,geometry_msgs::Point pin,float lim){
float res,dst;
if(pathin.poses.size() == 0)
return res;
for(int i = 0; i < pathin.poses.size(); i++){
if(get_dst2d(pathin.poses[i].pose.position,pin) < lim)
return false;
}
return true;
}
bool is_within_hdng_incline(geometry_msgs::Point pnt,float maxdelta_hdng, float maxdelta_pitch){
float hdng_shortest = get_shortest(get_hdng(pnt,pos),vlp_rpy.z);
if(hdng_shortest < 0)
hdng_shortest *= -1;
if(hdng_shortest < maxdelta_hdng){
float pitch_shortest = get_shortest(atan2(pnt.z-pos.z,get_dst2d(pnt,pos)),vlp_rpy.y);
if(pitch_shortest < 0)
pitch_shortest *= -1;
if(pitch_shortest < maxdelta_pitch)
return true;
else
return false;
}
else
return false;
}
float get_inclination(geometry_msgs::Point p1, geometry_msgs::Point p2){
return atan2(p2.z - p1.z,get_dst2d(p1,p2));
}
bool is_within_incline(geometry_msgs::Point pnt,float maxdelta_pitch){
float inclination = get_inclination(pos,pnt);
float delta_inclination = get_shortest(-vlp_rpy.y,inclination);
float pitch_shortest = get_shortest(atan2(pnt.z-pos.z,get_dst2d(pnt,pos)),-vlp_rpy.y);
//ROS_INFO("vlp_rpy: %.2f, inclination: %.2f, max_inclination: %.2f, pitch_shortest: %.2f,delta_inclination %.2f",vlp_rpy.y,inclination,maxdelta_pitch,pitch_shortest,delta_inclination);
if(delta_inclination < maxdelta_pitch && delta_inclination > -maxdelta_pitch)
return true;
else
return false;
}
nav_msgs::Path merge_paths(nav_msgs::Path path1,nav_msgs::Path path0){
for(int i = 0; i < path1.poses.size(); i++){
path0.poses.push_back(path1.poses[i]);
}
return path0;
}
bool update_edto_vlp(float collision_radius,float z0,float z1){
octree.get()->getMetricMin(bbmin_octree.x,bbmin_octree.y,bbmin_octree.z);
octree.get()->getMetricMax(bbmax_octree.x,bbmax_octree.y,bbmax_octree.z);
float zmin_touse = fmax(z0,bbmin_octree.z);
float zmax_touse = fmin(z1,bbmax_octree.z);
if(zmax_touse < zmin_touse){
zmax_touse = fmax(z0,bbmin_octree.z);
zmin_touse = fmin(z1,bbmax_octree.z);
}
octomap::point3d boundary_min(fmax(bbmin_vlp.x,bbmin_octree.x),fmax(bbmin_vlp.y,bbmin_octree.y),zmin_touse);
octomap::point3d boundary_max(fmin(bbmax_vlp.x,bbmax_octree.x),fmin(bbmax_vlp.y,bbmax_octree.y),zmax_touse);
edf_ptr.reset (new DynamicEDTOctomap(collision_radius,octree.get(),
boundary_min,
boundary_max,
false));
edf_ptr.get()->update();
xmin = int(round(boundary_min.x()))+1; ymin = int(round(boundary_min.y()))+1; zmin = int(round(boundary_min.z()));
xmax = int(round(boundary_max.x()))-1; ymax = int(round(boundary_max.y()))-1; zmax = int(round(boundary_max.z()));
range_x = xmax - xmin; range_y = ymax - ymin; range_z = zmax - zmin;
int vol = range_x*range_y*range_z;
if(vol <= 0){
ROS_INFO("FAILED update_edto FAILED: xmin: %i, ymin: %i, zmin: %i, xmax: %i, ymax: %i, zmax: %i, range_x: %i, range_y: %i, range_z: %i ",xmin,ymin,zmin,xmax,ymax,zmax,range_x,range_y,range_z);
return false;
}
return true;
}
void octomap_callback(const octomap_msgs::Octomap& msg){
abs_octree=octomap_msgs::fullMsgToMap(msg);
octree.reset(dynamic_cast<octomap::OcTree*>(abs_octree));
got_map = true;
}
float append_floor_to_candidates(){
ros::Time t0 = ros::Time::now();
for(int i = 0; i < path_floor.poses.size(); i++){
if(is_within_hdng_incline(path_floor.poses[i].pose.position,par_delta_hdng,par_delta_incline))
path_candidates.poses.push_back(path_floor.poses[i]);
}
float dt = (ros::Time::now() - t0).toSec();
return dt;
}
void enlarge_bbvlp(float dxy, float dz){
bbmin_vlp.x -= dxy;
bbmin_vlp.y -= dxy;
bbmax_vlp.x += dxy;
bbmax_vlp.y += dxy;
if(dz == 0 && abs(bbmin_vlp.z - bbmax_vlp.z) < 2)
dz = 1;
bbmin_vlp.z -= dz;
bbmax_vlp.z += dz;
}
float get_path_candidates(){
ros::Time t0 = ros::Time::now();
geometry_msgs::PoseStamped ps;
ps.header = hdr();
ps.pose.orientation.x = ps.pose.orientation.z = 0.0;
ps.pose.orientation.y = ps.pose.orientation.w = 0.7071;
path_candidates.poses.resize(0);
update_edto_vlp(1.1,bbmin_vlp.z,bbmax_vlp.z);
for(int z = int(round(bbmin_vlp.z)); z < int(round(bbmax_vlp.z)); z++){
for(int y = ymin; y < ymax; y++){
for(int x = xmin; x < xmax; x++){
ps.pose.position.x = x;
ps.pose.position.y = y;
ps.pose.position.z = z;
// if(is_within_incline(ps.pose.position,par_delta_incline) && in_poly(poly_vlp,ps.pose.position.x,ps.pose.position.y)){
if(is_within_incline(ps.pose.position,par_delta_incline) && in_poly(poly_vlp,ps.pose.position.x,ps.pose.position.y)){ //!dst_point_in_path_lim(path_vlp,ps.pose.position,8) &&
octomap::point3d p(x,y,z);
octomap::point3d closestObst;
float d;
edf_ptr.get()->getDistanceAndClosestObstacle(p,d,closestObst);
if(round(d) == 1 && d < 1.1 && closestObst.z() < z)
path_candidates.poses.push_back(ps);
}
}
}
}
float dt = (ros::Time::now() - t0).toSec();
return dt;
}
float get_path_candidates_sides(){
ros::Time t0 = ros::Time::now();
geometry_msgs::PoseStamped ps;
ps.header = hdr();
path_candidates_sides.poses.resize(0);
update_edto_vlp(10,bbmin_vlp.z,bbmax_vlp.z);
for(int z = int(round(bbmin_vlp.z)); z < int(round(bbmax_vlp.z)); z++){
for(int y = ymin; y < ymax; y++){
for(int x = xmin; x < xmax; x++){
ps.pose.position.x = x;
ps.pose.position.y = y;
ps.pose.position.z = z;
// if(is_within_incline(ps.pose.position,par_delta_incline) && in_poly(poly_vlp,ps.pose.position.x,ps.pose.position.y)){
if(is_within_incline(ps.pose.position,par_delta_incline) && in_poly(poly_vlp,ps.pose.position.x,ps.pose.position.y)){// !dst_point_in_path_lim(path_vlp,ps.pose.position,8) ){
octomap::point3d p(x,y,z);
octomap::point3d closestObst;
float d;
edf_ptr.get()->getDistanceAndClosestObstacle(p,d,closestObst);
float dz = abs(closestObst.z() - z);
if(round(d) == 6 && dz < 2){
ps.pose.orientation = tf::createQuaternionMsgFromYaw(atan2(closestObst.y() - p.y(),closestObst.x() - p.x()));
path_candidates_sides.poses.push_back(ps);
}
}
}
}
}
float dt = (ros::Time::now() - t0).toSec();
return dt;
}
geometry_msgs::PointStamped transformpoint(geometry_msgs::PointStamped pin,std::string frame_out){
geometry_msgs::PointStamped pout;
pin.header.stamp = ros::Time();
try
{
pout = tfBuffer.transform(pin, frame_out);
}
catch (tf2::TransformException &ex)
{
ROS_WARN("Failure %s\n", ex.what());
}
return pout;
}
void checktfvlp(){
geometry_msgs::TransformStamped transformStamped;
try{
transformStamped = tfBuffer.lookupTransform("map","velodyne_aligned",
ros::Time(0));
}
catch (tf2::TransformException &ex) {
ROS_WARN("%s",ex.what());
ros::Duration(1.0).sleep();
}
tf2::Matrix3x3 q(tf2::Quaternion(transformStamped.transform.rotation.x, transformStamped.transform.rotation.y, transformStamped.transform.rotation.z, transformStamped.transform.rotation.w));
q.getRPY(vlp_rpy.x,vlp_rpy.y,vlp_rpy.z);
base_pose.pose.position.x = transformStamped.transform.translation.x;
base_pose.pose.position.y = transformStamped.transform.translation.y;
base_pose.pose.position.z = transformStamped.transform.translation.z;
base_pose.pose.orientation.x = transformStamped.transform.rotation.x;
base_pose.pose.orientation.y = transformStamped.transform.rotation.y;
base_pose.pose.orientation.z = transformStamped.transform.rotation.z;
base_pose.pose.orientation.w = transformStamped.transform.rotation.w;
base_pose.header.stamp = transformStamped.header.stamp;
}
float get_polypath_vlp(float collision_radius,float maxdelta_hdng,int num_rays,float tot_length){
ros::Time t0 = ros::Time::now();
geometry_msgs::PoseStamped ps;
ps.header = hdr();
path_vlp.header = hdr();
path_vlp.poses.resize(0);
checktfvlp();
float rads_pr_i = maxdelta_hdng*2 / num_rays;
bbmax_vlp.x = -1000; bbmax_vlp.y = -1000; bbmax_vlp.z = -1000;
bbmin_vlp.x = 1000; bbmin_vlp.y = 1000; bbmin_vlp.z = 1000;
int k_lim1;
poly_vlp.polygon.points.resize(0);
std::vector<std::vector<geometry_msgs::Point>> points_points;
for(int k = 0; k < 3; k++){
std::vector<geometry_msgs::Point> points;
for(int i = 1; i < num_rays; i++){
geometry_msgs::PointStamped p,pout;
p.header.frame_id = "velodyne_aligned";
int kk;
if(k == 0)
kk = 1;
if(k == 1)
kk = 0;
if(k == 2)
kk = 2;
float a_k = -par_delta_incline + kk * par_delta_incline;
float a_i = -maxdelta_hdng + rads_pr_i * i;
p.point.x = tot_length*cos(a_k)*cos(a_i),
p.point.y = tot_length*cos(a_k)*sin(a_i),
p.point.z = tot_length*sin(a_k);
p.header.stamp = ros::Time();
pout = transformpoint(p,"map");
if(pout.point.x > bbmax_vlp.x)
bbmax_vlp.x = pout.point.x;
if(pout.point.y > bbmax_vlp.y)
bbmax_vlp.y = pout.point.y;
if(pout.point.z > bbmax_vlp.z)
bbmax_vlp.z = pout.point.z;
if(pout.point.x < bbmin_vlp.x)
bbmin_vlp.x = pout.point.x;
if(pout.point.y < bbmin_vlp.y)
bbmin_vlp.y = pout.point.y;
if(pout.point.z < bbmin_vlp.z)
bbmin_vlp.z = pout.point.z;
// ROS_INFO("p(a: %.2f a_k: %.2f) %.0f %.0f %.0f -> %.0f %.0f %.0f)",a_i,a_k,p.point.x,p.point.y,p.point.z,pout.point.x,pout.point.y,pout.point.z);
points.push_back(pout.point);
}
points_points.push_back(points);
}
poly_vlp.polygon.points.resize(points_points[0].size());
poly_vlp.polygon.points[0].x = pos.x;
poly_vlp.polygon.points[0].y = pos.y;
poly_vlp.polygon.points[0].z = pos.z;
enlarge_bbvlp(collision_radius,tot_length * sin(par_delta_incline));
float dx = bbmax_vlp.x - bbmin_vlp.x;
float dy = bbmax_vlp.y - bbmin_vlp.y;
float dz = bbmax_vlp.z - bbmin_vlp.z;
pnt_midpoint.point.x = (bbmin_vlp.x + bbmax_vlp.x)/2;
pnt_midpoint.point.y = (bbmin_vlp.y + bbmax_vlp.y)/2;
pnt_midpoint.point.z = (bbmin_vlp.z + bbmax_vlp.z)/2;
//mapradtouse = fmax(dx,dy)/2 + collision_radius;
// ROS_INFO("POLYVLP: points: %i dx: %.0f dy: %.0f dz: %.0f, midpoint: x: %.0f y: %.0f z: %.0f",points.size(),dx,dy,dz,pnt_midpoint.point.x,pnt_midpoint.point.y,pnt_midpoint.point.z);
// update_edto(pnt_midpoint.point,collision_radius,mapradtouse+collision_radius,bbmin_vlp.z-2,bbmax_vlp.z,false);
update_edto_vlp(collision_radius,bbmin_vlp.z,bbmax_vlp.z);
bbmax_vlp.x = -1000; bbmax_vlp.y = -1000; bbmax_vlp.z = -1000;
bbmin_vlp.x = 1000; bbmin_vlp.y = 1000; bbmin_vlp.z = 1000;
ps.pose = base_pose.pose;
path_vlp.poses.push_back(ps);
for(int k = 0; k < points_points.size(); k++){
for(int i = 0; i < points_points[k].size(); i++){
Eigen::Vector3f pnt1_vec(pos.x,pos.y,pos.z);
Eigen::Vector3f pnt2_vec(points_points[k][i].x,points_points[k][i].y,points_points[k][i].z);
Eigen::Vector3f stride_vec,cur_vec;
stride_vec = (pnt2_vec - pnt1_vec).normalized() * 1;
float distance = collision_radius-1;
float cur_ray_len = 0;
cur_vec = pnt1_vec;
while(distance > 2 && cur_ray_len < tot_length){
cur_vec = cur_vec + stride_vec;
cur_ray_len = (cur_vec - pnt1_vec).norm();
if(cur_vec.x() > float(xmin) && cur_vec.y() > float(ymin) && cur_vec.z() > float(zmin)
&& cur_vec.x() < float(xmax) && cur_vec.y() < float(ymax) && cur_vec.z() < float(zmax)){
ps.pose.position.x = cur_vec.x();
ps.pose.position.y = cur_vec.y();
ps.pose.position.z = cur_vec.z();
octomap::point3d closestObst;
point3d p(cur_vec.x(),cur_vec.y(),cur_vec.z());
edf_ptr.get()->getDistanceAndClosestObstacle(p,distance,closestObst);
if(k == 0){
if(dst_point_in_path_lim(path_vlp,ps.pose.position,grid_sidelength)){
float dz = closestObst.z()-p.z();
if(abs(dz) > 2){
ps.pose.orientation.x = 0;
ps.pose.orientation.z = 0;
ps.pose.orientation.y = 0.7071;
ps.pose.orientation.w = 0.7071;
}
else{
ps.pose.orientation = tf::createQuaternionMsgFromYaw(atan2(closestObst.y()-ps.pose.position.y,closestObst.x() - ps.pose.position.x));
}
poly_vlp.polygon.points[i].x = cur_vec.x();
poly_vlp.polygon.points[i].y = cur_vec.y();
poly_vlp.polygon.points[i].z = cur_vec.z();
path_vlp.poses.push_back(ps);
}
}
else{
geometry_msgs::Point p0;
p0.x = cur_vec.x();
p0.y = cur_vec.y();
float dst0 = get_dst2d(p0,base_pose.pose.position);
float dst = get_dst2d32(poly_vlp.polygon.points[i],base_pose.pose.position);
if(dst0 > dst){
poly_vlp.polygon.points[i].x = cur_vec.x();
poly_vlp.polygon.points[i].y = cur_vec.y();
}
}
if(cur_vec.x() > bbmax_vlp.x)
bbmax_vlp.x = cur_vec.x();
if(cur_vec.y() > bbmax_vlp.y)
bbmax_vlp.y = cur_vec.y();
if(cur_vec.z() > bbmax_vlp.z)
bbmax_vlp.z = cur_vec.z();
if(cur_vec.x() < bbmin_vlp.x)
bbmin_vlp.x = cur_vec.x();
if(cur_vec.y() < bbmin_vlp.y)
bbmin_vlp.y = cur_vec.y();
if(cur_vec.z() < bbmin_vlp.z)
bbmin_vlp.z = cur_vec.z();
}
else
break;
}
}
}
enlarge_bbvlp(collision_radius,2);
poly_vlp.polygon.points[poly_vlp.polygon.points.size()-1].x = pos.x;
poly_vlp.polygon.points[poly_vlp.polygon.points.size()-1].y = pos.y;
poly_vlp.polygon.points[poly_vlp.polygon.points.size()-1].z = pos.z;
float dt = (ros::Time::now() - t0).toSec();
return dt;
}
void checktf(){
geometry_msgs::TransformStamped transformStamped;
try{
transformStamped = tfBuffer.lookupTransform("map","base_stabilized",
ros::Time(0));
}
catch (tf2::TransformException &ex) {
ROS_WARN("%s",ex.what());
ros::Duration(1.0).sleep();
}
pos.x = transformStamped.transform.translation.x;
pos.y = transformStamped.transform.translation.y;
pos.z = transformStamped.transform.translation.z;
pos_yaw = tf::getYaw(transformStamped.transform.rotation);
if(sqrt(pow(transformStamped.transform.translation.x - last_pose.pose.position.x,2)+ pow(transformStamped.transform.translation.y - last_pose.pose.position.y,2)+
pow(transformStamped.transform.translation.z - last_pose.pose.position.z,2)) >= 1.00){
last_pose.pose.position = pos;
last_pose.pose.orientation = transformStamped.transform.rotation;
last_pose.header = transformStamped.header;
path_visited.poses.push_back(last_pose);
path_visited.header.stamp = ros::Time::now();
}
}
void getpaths_cb(const std_msgs::UInt8::ConstPtr& msg){
get_floor = true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "tb_pathmini_node");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
private_nh.param("workdir_path",par_workdir_path);//*2.0);
private_nh.param("par_maprad", par_maprad, 30.0);//*2.0);
private_nh.param("par_maxobs", par_maxobs, 20.0);//*2.0);
private_nh.param("par_zjump", par_zjump, 3.0);//*2.0);
private_nh.param("par_minobs", par_minobs, 2.0);//*2.0);
private_nh.param("delta_hdng", par_delta_hdng, M_PI/2);//*2.0);
private_nh.param("delta_incline", par_delta_incline, M_PI/24);//*2.0);
path_vlp.header = hdr();
path_floor.header = hdr();
poly_vlp.header = hdr();
path_candidates.header = hdr();
path_candidates_sides.header = hdr();
path_visited.header = hdr();
last_pose.header = hdr();
pnt_midpoint.header = hdr();
base_pose.header = hdr();
last_pose.pose.orientation.w = 1;
path_visited.poses.push_back(last_pose);
tf2_ros::TransformListener tf2_listener(tfBuffer);
ros::Publisher pub_candidates = nh.advertise<nav_msgs::Path>("/tb_path/candidates",100);
ros::Publisher pub_candidates_sides = nh.advertise<nav_msgs::Path>("/tb_path/candidates_sides",100);
ros::Publisher pub_visited = nh.advertise<nav_msgs::Path>("/tb_path/visited",10);
ros::Publisher pub_midpoint = nh.advertise<geometry_msgs::PointStamped>("/tb_path/vlp_midpoint",100);
ros::Publisher pub_base_pose = nh.advertise<geometry_msgs::PoseStamped>("/tb_path/vlp_pose",100);
ros::Publisher pub_poly = nh.advertise<geometry_msgs::PolygonStamped>("/tb_path/vlp_poly",100);
ros::Publisher pub_path_vlp = nh.advertise<nav_msgs::Path>("/tb_path/vlp_path",100);
ros::Subscriber s1 = nh.subscribe("/octomap_full",1,octomap_callback);
ros::Subscriber s2 = nh.subscribe("/tb_path/get",1,getpaths_cb);
ROS_INFO("Ready to convert octomaps.");
ros::Rate rate(5.0);
ros::Time t0 = ros::Time::now();
ros::Time last_update = ros::Time::now();
float collision_radius = 5;
int num_rays = 32;
float ray_length = 30;
float dt_polypath,dt_candidates,dt_candidates_sides;
while(ros::ok()){
checktf();
pub_visited.publish(path_visited);
if(got_map){
dt_polypath = get_polypath_vlp(par_maxobs,par_delta_hdng,num_rays,ray_length);
pub_path_vlp.publish(path_vlp);
pub_midpoint.publish(pnt_midpoint);
pub_poly.publish(poly_vlp);
if(get_floor){
dt_candidates = get_path_candidates();
dt_candidates_sides = get_path_candidates_sides();
last_update = ros::Time::now();
ROS_INFO("PATHS: vlp: %i, candidates_floor: %i, candidates_sides: %i",path_vlp.poses.size(),path_candidates.poses.size(),path_candidates_sides.poses.size());
ROS_INFO("PATHS-TIMER: dt_polypath: %.4f, dt_candidates_floor: %.4f, dt_candidates_sides: %.4f",dt_polypath,dt_candidates,dt_candidates_sides);
pub_candidates.publish(path_candidates);
pub_candidates_sides.publish(path_candidates_sides);
pub_base_pose.publish(base_pose);
get_floor = false;
}
}
rate.sleep();
ros::spinOnce();
}
return 0;
}
| 40.202401
| 196
| 0.667719
|
ligatos
|
441362a79702c3cb1f425b69d02515476f633c06
| 11,546
|
hpp
|
C++
|
include/System/Runtime/Remoting/Activation/ActivationServices.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/System/Runtime/Remoting/Activation/ActivationServices.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/System/Runtime/Remoting/Activation/ActivationServices.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Runtime::Remoting::Activation
namespace System::Runtime::Remoting::Activation {
// Forward declaring type: IActivator
class IActivator;
// Forward declaring type: IConstructionCallMessage
class IConstructionCallMessage;
}
// Forward declaring namespace: System::Runtime::Remoting::Messaging
namespace System::Runtime::Remoting::Messaging {
// Forward declaring type: IMessage
class IMessage;
// Forward declaring type: ConstructionCall
class ConstructionCall;
}
// Forward declaring namespace: System::Runtime::Remoting::Proxies
namespace System::Runtime::Remoting::Proxies {
// Forward declaring type: RemotingProxy
class RemotingProxy;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: System.Runtime.Remoting.Activation
namespace System::Runtime::Remoting::Activation {
// Forward declaring type: ActivationServices
class ActivationServices;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Runtime::Remoting::Activation::ActivationServices);
DEFINE_IL2CPP_ARG_TYPE(::System::Runtime::Remoting::Activation::ActivationServices*, "System.Runtime.Remoting.Activation", "ActivationServices");
// Type namespace: System.Runtime.Remoting.Activation
namespace System::Runtime::Remoting::Activation {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: System.Runtime.Remoting.Activation.ActivationServices
// [TokenAttribute] Offset: FFFFFFFF
class ActivationServices : public ::Il2CppObject {
public:
// Get static field: static private System.Runtime.Remoting.Activation.IActivator _constructionActivator
static ::System::Runtime::Remoting::Activation::IActivator* _get__constructionActivator();
// Set static field: static private System.Runtime.Remoting.Activation.IActivator _constructionActivator
static void _set__constructionActivator(::System::Runtime::Remoting::Activation::IActivator* value);
// static private System.Runtime.Remoting.Activation.IActivator get_ConstructionActivator()
// Offset: 0x1D4C75C
static ::System::Runtime::Remoting::Activation::IActivator* get_ConstructionActivator();
// static public System.Runtime.Remoting.Messaging.IMessage Activate(System.Runtime.Remoting.Proxies.RemotingProxy proxy, System.Runtime.Remoting.Messaging.ConstructionCall ctorCall)
// Offset: 0x1D4C7EC
static ::System::Runtime::Remoting::Messaging::IMessage* Activate(::System::Runtime::Remoting::Proxies::RemotingProxy* proxy, ::System::Runtime::Remoting::Messaging::ConstructionCall* ctorCall);
// static public System.Runtime.Remoting.Messaging.IMessage RemoteActivate(System.Runtime.Remoting.Activation.IConstructionCallMessage ctorCall)
// Offset: 0x1D4CA1C
static ::System::Runtime::Remoting::Messaging::IMessage* RemoteActivate(::System::Runtime::Remoting::Activation::IConstructionCallMessage* ctorCall);
// static public System.Runtime.Remoting.Messaging.ConstructionCall CreateConstructionCall(System.Type type, System.String activationUrl, System.Object[] activationAttributes)
// Offset: 0x1D4CBFC
static ::System::Runtime::Remoting::Messaging::ConstructionCall* CreateConstructionCall(::System::Type* type, ::StringW activationUrl, ::ArrayW<::Il2CppObject*> activationAttributes);
// static public System.Runtime.Remoting.Messaging.IMessage CreateInstanceFromMessage(System.Runtime.Remoting.Activation.IConstructionCallMessage ctorCall)
// Offset: 0x1D4D578
static ::System::Runtime::Remoting::Messaging::IMessage* CreateInstanceFromMessage(::System::Runtime::Remoting::Activation::IConstructionCallMessage* ctorCall);
// static public System.Object CreateProxyForType(System.Type type)
// Offset: 0x1D4D978
static ::Il2CppObject* CreateProxyForType(::System::Type* type);
// static public System.Object AllocateUninitializedClassInstance(System.Type type)
// Offset: 0x1D4D974
static ::Il2CppObject* AllocateUninitializedClassInstance(::System::Type* type);
// static public System.Void EnableProxyActivation(System.Type type, System.Boolean enable)
// Offset: 0x1D4DAEC
static void EnableProxyActivation(::System::Type* type, bool enable);
}; // System.Runtime.Remoting.Activation.ActivationServices
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::get_ConstructionActivator
// Il2CppName: get_ConstructionActivator
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Activation::IActivator* (*)()>(&System::Runtime::Remoting::Activation::ActivationServices::get_ConstructionActivator)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "get_ConstructionActivator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::Activate
// Il2CppName: Activate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Messaging::IMessage* (*)(::System::Runtime::Remoting::Proxies::RemotingProxy*, ::System::Runtime::Remoting::Messaging::ConstructionCall*)>(&System::Runtime::Remoting::Activation::ActivationServices::Activate)> {
static const MethodInfo* get() {
static auto* proxy = &::il2cpp_utils::GetClassFromName("System.Runtime.Remoting.Proxies", "RemotingProxy")->byval_arg;
static auto* ctorCall = &::il2cpp_utils::GetClassFromName("System.Runtime.Remoting.Messaging", "ConstructionCall")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "Activate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{proxy, ctorCall});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::RemoteActivate
// Il2CppName: RemoteActivate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Messaging::IMessage* (*)(::System::Runtime::Remoting::Activation::IConstructionCallMessage*)>(&System::Runtime::Remoting::Activation::ActivationServices::RemoteActivate)> {
static const MethodInfo* get() {
static auto* ctorCall = &::il2cpp_utils::GetClassFromName("System.Runtime.Remoting.Activation", "IConstructionCallMessage")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "RemoteActivate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ctorCall});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::CreateConstructionCall
// Il2CppName: CreateConstructionCall
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Messaging::ConstructionCall* (*)(::System::Type*, ::StringW, ::ArrayW<::Il2CppObject*>)>(&System::Runtime::Remoting::Activation::ActivationServices::CreateConstructionCall)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* activationUrl = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* activationAttributes = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "CreateConstructionCall", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, activationUrl, activationAttributes});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::CreateInstanceFromMessage
// Il2CppName: CreateInstanceFromMessage
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Remoting::Messaging::IMessage* (*)(::System::Runtime::Remoting::Activation::IConstructionCallMessage*)>(&System::Runtime::Remoting::Activation::ActivationServices::CreateInstanceFromMessage)> {
static const MethodInfo* get() {
static auto* ctorCall = &::il2cpp_utils::GetClassFromName("System.Runtime.Remoting.Activation", "IConstructionCallMessage")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "CreateInstanceFromMessage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ctorCall});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::CreateProxyForType
// Il2CppName: CreateProxyForType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (*)(::System::Type*)>(&System::Runtime::Remoting::Activation::ActivationServices::CreateProxyForType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "CreateProxyForType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::AllocateUninitializedClassInstance
// Il2CppName: AllocateUninitializedClassInstance
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (*)(::System::Type*)>(&System::Runtime::Remoting::Activation::ActivationServices::AllocateUninitializedClassInstance)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "AllocateUninitializedClassInstance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: System::Runtime::Remoting::Activation::ActivationServices::EnableProxyActivation
// Il2CppName: EnableProxyActivation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::System::Type*, bool)>(&System::Runtime::Remoting::Activation::ActivationServices::EnableProxyActivation)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* enable = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Runtime::Remoting::Activation::ActivationServices*), "EnableProxyActivation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, enable});
}
};
| 72.1625
| 310
| 0.761562
|
RedBrumbler
|
4413cf54cb13328365a6a0de2d6f593361a1b029
| 6,055
|
cpp
|
C++
|
src/joystick.cpp
|
jburks/box16
|
b024d7d2c9337f0183a6349637504fdc0b9243fe
|
[
"MIT"
] | 10
|
2021-09-11T15:49:03.000Z
|
2022-03-29T20:54:28.000Z
|
src/joystick.cpp
|
jburks/box16
|
b024d7d2c9337f0183a6349637504fdc0b9243fe
|
[
"MIT"
] | 33
|
2021-07-03T18:55:29.000Z
|
2022-03-28T17:25:53.000Z
|
src/joystick.cpp
|
jburks/box16
|
b024d7d2c9337f0183a6349637504fdc0b9243fe
|
[
"MIT"
] | 4
|
2021-07-04T15:49:28.000Z
|
2022-01-26T00:43:30.000Z
|
#include "joystick.h"
#include <SDL.h>
#include <unordered_map>
#define LOG_JOYSTICK(...) // printf(__VA_ARGS__)
struct joystick_info {
SDL_GameController *controller;
uint16_t button_mask;
uint16_t shift_mask;
int current_slot;
};
static const uint16_t button_map[SDL_CONTROLLER_BUTTON_MAX] = {
1 << 0, //SDL_CONTROLLER_BUTTON_A,
1 << 8, //SDL_CONTROLLER_BUTTON_B,
1 << 1, //SDL_CONTROLLER_BUTTON_X,
1 << 9, //SDL_CONTROLLER_BUTTON_Y,
1 << 2, //SDL_CONTROLLER_BUTTON_BACK,
0, //SDL_CONTROLLER_BUTTON_GUIDE,
1 << 3, //SDL_CONTROLLER_BUTTON_START,
0, //SDL_CONTROLLER_BUTTON_LEFTSTICK,
0, //SDL_CONTROLLER_BUTTON_RIGHTSTICK,
1 << 10, //SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
1 << 11, //SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
1 << 4, //SDL_CONTROLLER_BUTTON_DPAD_UP,
1 << 5, //SDL_CONTROLLER_BUTTON_DPAD_DOWN,
1 << 6, //SDL_CONTROLLER_BUTTON_DPAD_LEFT,
1 << 7, //SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
};
static std::unordered_map<int, joystick_info> Joystick_controllers;
static int Joystick_slots[NUM_JOYSTICKS];
static bool Joystick_latch = false;
uint8_t Joystick_data = 0;
bool joystick_init()
{
for (int i = 0; i < NUM_JOYSTICKS; ++i) {
Joystick_slots[i] = -1;
}
const int num_joysticks = SDL_NumJoysticks();
for (int i = 0; i < num_joysticks; ++i) {
joystick_add(i);
}
return true;
}
void joystick_add(int index)
{
LOG_JOYSTICK("joystick_add(%d)\n", index);
if (!SDL_IsGameController(index)) {
return;
}
SDL_GameController *controller = SDL_GameControllerOpen(index);
if (controller == nullptr) {
fprintf(stderr, "Could not open controller %d: %s\n", index, SDL_GetError());
return;
}
SDL_JoystickID instance_id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(controller));
bool exists = false;
for (int i = 0; i < NUM_JOYSTICKS; ++i) {
if (Joystick_slots[i] == instance_id) {
exists = true;
break;
}
}
if (!exists) {
int slot;
for (slot = 0; slot < NUM_JOYSTICKS; ++slot) {
if (Joystick_slots[slot] == -1) {
Joystick_slots[slot] = instance_id;
break;
}
}
Joystick_controllers.try_emplace(instance_id, joystick_info{ controller, 0xffff, 0, slot });
}
}
void joystick_remove(int instance_id)
{
LOG_JOYSTICK("joystick_remove(%d)\n", instance_id);
for (int i = 0; i < NUM_JOYSTICKS; ++i) {
if (Joystick_slots[i] == instance_id) {
Joystick_slots[i] = -1;
break;
}
}
SDL_GameController *controller = SDL_GameControllerFromInstanceID(instance_id);
if (controller == nullptr) {
fprintf(stderr, "Could not find controller from instance_id %d: %s\n", instance_id, SDL_GetError());
} else {
SDL_GameControllerClose(controller);
Joystick_controllers.erase(instance_id);
}
}
void joystick_slot_remap(int slot, int instance_id)
{
LOG_JOYSTICK("joystick_slot_remap(%d, %d)\n", slot, instance_id);
if (slot < 0 || slot >= NUM_JOYSTICKS) {
fprintf(stderr, "Error: joystick_slot_remap(%d, %d) trying to remap invalid controller port %d.\n", slot, instance_id, slot);
return;
}
int slot_old_instance_id = Joystick_slots[slot];
int instance_old_slot = NUM_JOYSTICKS;
if (instance_id < 0) {
Joystick_slots[slot] = -1;
} else {
const auto &joy = Joystick_controllers.find(instance_id);
if (joy == Joystick_controllers.end()) {
fprintf(stderr, "Error: joystick_slot_remap(%d, %d) could not find instance_id %d.\n", slot, instance_id, instance_id);
return;
}
instance_old_slot = joy->second.current_slot;
Joystick_slots[slot] = instance_id;
joy->second.current_slot = slot;
}
if (slot_old_instance_id >= 0) {
const auto &old_joy = Joystick_controllers.find(slot_old_instance_id);
if (old_joy == Joystick_controllers.end()) {
fprintf(stderr, "Error: joystick_slot_remap(%d, %d) could not find slot_old_instance_id %d.\n", slot, instance_id, slot_old_instance_id);
return;
}
old_joy->second.current_slot = instance_old_slot;
}
if (instance_old_slot != NUM_JOYSTICKS) {
Joystick_slots[instance_old_slot] = slot_old_instance_id;
}
}
void joystick_button_down(int instance_id, uint8_t button)
{
LOG_JOYSTICK("joystick_button_down(%d, %d)\n", instance_id, button);
const auto &joy = Joystick_controllers.find(instance_id);
if (joy != Joystick_controllers.end()) {
joy->second.button_mask &= ~(button_map[button]);
}
}
void joystick_button_up(int instance_id, uint8_t button)
{
LOG_JOYSTICK("joystick_button_up(%d, %d)\n", instance_id, button);
const auto &joy = Joystick_controllers.find(instance_id);
if (joy != Joystick_controllers.end()) {
joy->second.button_mask |= button_map[button];
}
}
static void do_shift()
{
for (int i = 0; i < NUM_JOYSTICKS; ++i) {
if (Joystick_slots[i] >= 0) {
const auto &joy = Joystick_controllers.find(Joystick_slots[i]);
Joystick_data |= ((joy->second.shift_mask & 1) ? (0x80 >> i) : 0);
joy->second.shift_mask >>= 1;
} else {
Joystick_data |= 0x80 >> i;
}
}
}
void joystick_set_latch(bool value)
{
Joystick_latch = value;
if (value) {
for (auto &joy : Joystick_controllers) {
joy.second.shift_mask = joy.second.button_mask | 0xF000;
}
do_shift();
}
}
void joystick_set_clock(bool value)
{
if (!Joystick_latch && value) {
Joystick_data = 0;
do_shift();
}
}
void joystick_for_each(std::function<void(int, SDL_GameController *, int current_slot)> fn)
{
for (auto& joy : Joystick_controllers) {
fn(joy.first, joy.second.controller, joy.second.current_slot);
}
}
void joystick_for_each_slot(std::function<void(int, int, SDL_GameController *)> fn)
{
for (int i = 0; i < NUM_JOYSTICKS; ++i) {
if (Joystick_slots[i] == -1) {
fn(i, -1, nullptr);
} else {
const auto &joy = Joystick_controllers.find(Joystick_slots[i]);
if (joy == Joystick_controllers.end()) {
fprintf(stderr, "joystick_for_each_slot(...) could not find Joystick_slots[%d] %d", i, Joystick_slots[i]);
fn(i, -1, nullptr);
} else {
fn(i, joy->first, joy->second.controller);
}
}
}
}
| 27.03125
| 140
| 0.689843
|
jburks
|
441607333d8c9a5fb4d56cca36760ddc9e907231
| 1,389
|
cc
|
C++
|
tests/elle/TypeInfo.cc
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 521
|
2016-02-14T00:39:01.000Z
|
2022-03-01T22:39:25.000Z
|
tests/elle/TypeInfo.cc
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 8
|
2017-02-21T11:47:33.000Z
|
2018-11-01T09:37:14.000Z
|
tests/elle/TypeInfo.cc
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 48
|
2017-02-21T10:18:13.000Z
|
2022-03-25T02:35:20.000Z
|
#include <elle/TypeInfo.hh>
#include <elle/test.hh>
#include <elle/log.hh>
// Avoid unnamed namespace qualifications.
namespace foo
{
struct Foo
{
struct Bar
{
struct Baz
{
struct Qux {};
};
};
};
}
namespace
{
void
comparison()
{
BOOST_TEST(elle::type_info<int>() == elle::type_info<int>());
BOOST_TEST(elle::type_info<int>() != elle::type_info<float>());
}
size_t
h(elle::TypeInfo const& info)
{
return std::hash<elle::TypeInfo>()(info);
}
void
hash()
{
BOOST_TEST(h(elle::type_info<int>()) == h(elle::type_info<int>()));
BOOST_TEST(h(elle::type_info<int>()) != h(elle::type_info<float>()));
}
ELLE_TYPE_INFO_ABBR("FB", "foo::Foo::Bar");
ELLE_TYPE_INFO_ABBR("FBB", "foo::Foo::Bar::Baz");
/// The abbreviated name of T.
template <typename T>
std::string
name()
{
return elle::sprintf("%f", elle::type_info<T>());
}
void
abbreviations()
{
BOOST_TEST(name<foo::Foo>() == "foo::Foo");
BOOST_TEST(name<foo::Foo::Bar>() == "FB");
BOOST_TEST(name<foo::Foo::Bar::Baz>() == "FBB");
BOOST_TEST(name<foo::Foo::Bar::Baz::Qux>() == "FBB::Qux");
}
}
ELLE_TEST_SUITE()
{
auto& suite = boost::unit_test::framework::master_test_suite();
suite.add(BOOST_TEST_CASE(comparison));
suite.add(BOOST_TEST_CASE(hash));
suite.add(BOOST_TEST_CASE(abbreviations));
}
| 19.842857
| 73
| 0.604752
|
infinitio
|
441968cb8e7a95a0bbd14634400fce2bc02a3eab
| 1,936
|
cpp
|
C++
|
src/qr_factorization.cpp
|
indianajohn/basic-matrix
|
51f0b8cf712e61010acb39687deb6dc633394563
|
[
"MIT"
] | null | null | null |
src/qr_factorization.cpp
|
indianajohn/basic-matrix
|
51f0b8cf712e61010acb39687deb6dc633394563
|
[
"MIT"
] | null | null | null |
src/qr_factorization.cpp
|
indianajohn/basic-matrix
|
51f0b8cf712e61010acb39687deb6dc633394563
|
[
"MIT"
] | null | null | null |
#include "lup_decomposition.hpp"
#include "qr_factorization.hpp"
#include "scalar.hpp"
namespace basic_matrix {
void qrFactorize(Matrix &Q, Matrix &R) {
Matrix A = R;
Q = identity(R.height());
for (size_t k = 0; k < R.width() && k < R.height(); k++) {
size_t m_k = R.height() - k;
size_t n_k = R.width() - k;
// Consider
// H_k = [ I 0 ]
// [ 0 I - 2*v_k*v_k_t ]
// H_k is a symmetric matrix, as is identity. Therefore,
// H_k*H_k = H_k*H_k_T=I
// A = H_1*H_2*...*H_max*H_max*...*H_2*H_1*A
// = (H_1*H_2*...*H_max)*R
// where R is diagonal.
// = Q * R
// Buid the reflector I - 2*v_k*v_k.transpose()
Matrix y(MatrixROI(k, k, 1, m_k, &R));
Matrix e1(y.width(), y.height());
e1(0, 0) = 1.0;
Matrix w = y + (sign(y(0, 0)) * y.norm() * e1);
double factor = 1. / w.norm();
Matrix v_k = factor * w;
Matrix A_roi(MatrixROI(k, k, n_k, m_k, &R));
// Edit R (whose input was A) in place. Subtracting
// 2*v_k*v_k.transpose() is equvalent to pre-multiplying H_k.
// We only do it in the region that would be affected
// by the multiplication to save on flops
A_roi = A_roi - (2.0 * v_k * (v_k.transposeROI() * A_roi));
Matrix H_k = identity(Q.height());
Matrix H_k_roi(MatrixROI(k, k, m_k, m_k, &H_k));
H_k_roi = H_k_roi - (2.0 * v_k * v_k.transposeROI());
// Perform the next multiplication for building Q
Q = Q * H_k;
}
}
void solveQR(const Matrix &A, Matrix &b) {
Matrix R = A;
Matrix Q;
qrFactorize(Q, R);
// If Q and R are a QR factorization of A, the least squares solution is equal
// to: x_hat = (A.transpose()*A).inverse()*A.transpose() * b =
// R.inverse()*Q.transpose() Therefore: R*x_hat = Q.transpose()*b where
// Q.transpose()*b is diagonaol. We can therefore solve it by back
// substitution.
b = Q.transposeROI() * b;
solveU(R, b);
}
}; // namespace basic_matrix
| 33.964912
| 80
| 0.588326
|
indianajohn
|
441a5f899f716fd71afb08bf1f92512917c75dcd
| 10,129
|
cpp
|
C++
|
contracts/test_api/test_action.cpp
|
TP-Lab/enumivo
|
76d81a36d2db8cea93fb54cd95a6ec5f6c407f97
|
[
"MIT"
] | null | null | null |
contracts/test_api/test_action.cpp
|
TP-Lab/enumivo
|
76d81a36d2db8cea93fb54cd95a6ec5f6c407f97
|
[
"MIT"
] | null | null | null |
contracts/test_api/test_action.cpp
|
TP-Lab/enumivo
|
76d81a36d2db8cea93fb54cd95a6ec5f6c407f97
|
[
"MIT"
] | null | null | null |
/**
* @file action_test.cpp
* @copyright defined in enumivo/LICENSE
*/
#include <enulib/action.hpp>
#include <enulib/transaction.hpp>
#include <enulib/chain.h>
#include <enulib/db.h>
#include <enulib/crypto.h>
#include <enulib/privileged.h>
#include <enulib/enu.hpp>
#include <enulib/datastream.hpp>
#include <enulib/print.hpp>
#include <enulib/compiler_builtins.h>
#include "test_api.hpp"
void test_action::read_action_normal() {
char buffer[100];
uint32_t total = 0;
enumivo_assert(action_data_size() == sizeof(dummy_action), "action_size() == sizeof(dummy_action)");
total = read_action_data(buffer, 30);
enumivo_assert(total == sizeof(dummy_action) , "read_action(30)" );
total = read_action_data(buffer, 100);
enumivo_assert(total == sizeof(dummy_action) , "read_action(100)" );
total = read_action_data(buffer, 5);
enumivo_assert(total == 5 , "read_action(5)" );
total = read_action_data(buffer, sizeof(dummy_action) );
enumivo_assert(total == sizeof(dummy_action), "read_action(sizeof(dummy_action))" );
dummy_action *dummy13 = reinterpret_cast<dummy_action *>(buffer);
enumivo_assert(dummy13->a == DUMMY_ACTION_DEFAULT_A, "dummy13->a == DUMMY_ACTION_DEFAULT_A");
enumivo_assert(dummy13->b == DUMMY_ACTION_DEFAULT_B, "dummy13->b == DUMMY_ACTION_DEFAULT_B");
enumivo_assert(dummy13->c == DUMMY_ACTION_DEFAULT_C, "dummy13->c == DUMMY_ACTION_DEFAULT_C");
}
void test_action::test_dummy_action() {
char buffer[100];
int total = 0;
// get_action
total = get_action( 1, 0, buffer, 0 );
total = get_action( 1, 0, buffer, static_cast<size_t>(total) );
enumivo_assert( total > 0, "get_action failed" );
enumivo::action act = enumivo::get_action( 1, 0 );
enumivo_assert( act.authorization.back().actor == N(testapi), "incorrect permission actor" );
enumivo_assert( act.authorization.back().permission == N(active), "incorrect permission name" );
enumivo_assert( enumivo::pack_size(act) == static_cast<size_t>(total), "pack_size does not match get_action size" );
enumivo_assert( act.account == N(testapi), "expected testapi account" );
dummy_action dum13 = act.data_as<dummy_action>();
if ( dum13.b == 200 ) {
// attempt to access context free only api
get_context_free_data( 0, nullptr, 0 );
enumivo_assert(false, "get_context_free_data() not allowed in non-context free action");
} else {
enumivo_assert(dum13.a == DUMMY_ACTION_DEFAULT_A, "dum13.a == DUMMY_ACTION_DEFAULT_A");
enumivo_assert(dum13.b == DUMMY_ACTION_DEFAULT_B, "dum13.b == DUMMY_ACTION_DEFAULT_B");
enumivo_assert(dum13.c == DUMMY_ACTION_DEFAULT_C, "dum13.c == DUMMY_ACTION_DEFAULT_C");
}
}
void test_action::read_action_to_0() {
read_action_data((void *)0, action_data_size());
}
void test_action::read_action_to_64k() {
read_action_data( (void *)((1<<16)-2), action_data_size());
}
void test_action::test_cf_action() {
enumivo::action act = enumivo::get_action( 0, 0 );
cf_action cfa = act.data_as<cf_action>();
if ( cfa.payload == 100 ) {
// verify read of get_context_free_data, also verifies system api access
int size = get_context_free_data( cfa.cfd_idx, nullptr, 0 );
enumivo_assert( size > 0, "size determination failed" );
enumivo::bytes cfd( static_cast<size_t>(size) );
size = get_context_free_data( cfa.cfd_idx, &cfd[0], static_cast<size_t>(size) );
enumivo_assert(static_cast<size_t>(size) == cfd.size(), "get_context_free_data failed" );
uint32_t v = enumivo::unpack<uint32_t>( &cfd[0], cfd.size() );
enumivo_assert( v == cfa.payload, "invalid value" );
// verify crypto api access
checksum256 hash;
char test[] = "test";
sha256( test, sizeof(test), &hash );
assert_sha256( test, sizeof(test), &hash );
// verify action api access
action_data_size();
// verify console api access
enumivo::print("test\n");
// verify memory api access
uint32_t i = 42;
memccpy(&v, &i, sizeof(i), sizeof(i));
// verify transaction api access
enumivo_assert(transaction_size() > 0, "transaction_size failed");
// verify softfloat api access
float f1 = 1.0f, f2 = 2.0f;
float f3 = f1 + f2;
enumivo_assert( f3 > 2.0f, "Unable to add float.");
// verify compiler builtin api access
__int128 ret;
__divti3(ret, 2, 2, 2, 2);
// verify context_free_system_api
enumivo_assert( true, "verify enumivo_assert can be called" );
} else if ( cfa.payload == 200 ) {
// attempt to access non context free api, privileged_api
is_privileged(act.name);
enumivo_assert( false, "privileged_api should not be allowed" );
} else if ( cfa.payload == 201 ) {
// attempt to access non context free api, producer_api
get_active_producers( nullptr, 0 );
enumivo_assert( false, "producer_api should not be allowed" );
} else if ( cfa.payload == 202 ) {
// attempt to access non context free api, db_api
db_store_i64( N(testapi), N(testapi), N(testapi), 0, "test", 4 );
enumivo_assert( false, "db_api should not be allowed" );
} else if ( cfa.payload == 203 ) {
// attempt to access non context free api, db_api
uint64_t i = 0;
db_idx64_store( N(testapi), N(testapi), N(testapi), 0, &i );
enumivo_assert( false, "db_api should not be allowed" );
} else if ( cfa.payload == 204 ) {
db_find_i64( N(testapi), N(testapi), N(testapi), 1);
enumivo_assert( false, "db_api should not be allowed" );
} else if ( cfa.payload == 205 ) {
// attempt to access non context free api, send action
enumivo::action dum_act;
dum_act.send();
enumivo_assert( false, "action send should not be allowed" );
} else if ( cfa.payload == 206 ) {
enumivo::require_auth(N(test));
enumivo_assert( false, "authorization_api should not be allowed" );
} else if ( cfa.payload == 207 ) {
now();
enumivo_assert( false, "system_api should not be allowed" );
} else if ( cfa.payload == 208 ) {
current_time();
enumivo_assert( false, "system_api should not be allowed" );
} else if ( cfa.payload == 209 ) {
publication_time();
enumivo_assert( false, "system_api should not be allowed" );
} else if ( cfa.payload == 210 ) {
send_inline( (char*)"hello", 6 );
enumivo_assert( false, "transaction_api should not be allowed" );
} else if ( cfa.payload == 211 ) {
send_deferred( N(testapi), N(testapi), "hello", 6 );
enumivo_assert( false, "transaction_api should not be allowed" );
}
}
void test_action::require_notice(uint64_t receiver, uint64_t code, uint64_t action) {
(void)code;(void)action;
if( receiver == N(testapi) ) {
enumivo::require_recipient( N(acc1) );
enumivo::require_recipient( N(acc2) );
enumivo::require_recipient( N(acc1), N(acc2) );
enumivo_assert(false, "Should've failed");
} else if ( receiver == N(acc1) || receiver == N(acc2) ) {
return;
}
enumivo_assert(false, "Should've failed");
}
void test_action::require_notice_tests(uint64_t receiver, uint64_t code, uint64_t action) {
enumivo::print( "require_notice_tests" );
if( receiver == N( testapi ) ) {
enumivo::print( "require_recipient( N(acc5) )" );
enumivo::require_recipient( N( acc5 ) );
} else if( receiver == N( acc5 ) ) {
enumivo::print( "require_recipient( N(testapi) )" );
enumivo::require_recipient( N( testapi ) );
}
}
void test_action::require_auth() {
prints("require_auth");
enumivo::require_auth( N(acc3) );
enumivo::require_auth( N(acc4) );
}
void test_action::assert_false() {
enumivo_assert(false, "test_action::assert_false");
}
void test_action::assert_true() {
enumivo_assert(true, "test_action::assert_true");
}
void test_action::assert_true_cf() {
enumivo_assert(true, "test_action::assert_true");
}
void test_action::test_abort() {
abort();
enumivo_assert( false, "should've aborted" );
}
void test_action::test_publication_time() {
uint64_t pub_time = 0;
uint32_t total = read_action_data(&pub_time, sizeof(uint64_t));
enumivo_assert( total == sizeof(uint64_t), "total == sizeof(uint64_t)");
enumivo_assert( pub_time == publication_time(), "pub_time == publication_time()" );
}
void test_action::test_current_receiver(uint64_t receiver, uint64_t code, uint64_t action) {
(void)code;(void)action;
account_name cur_rec;
read_action_data(&cur_rec, sizeof(account_name));
enumivo_assert( receiver == cur_rec, "the current receiver does not match" );
}
void test_action::test_current_time() {
uint64_t tmp = 0;
uint32_t total = read_action_data(&tmp, sizeof(uint64_t));
enumivo_assert( total == sizeof(uint64_t), "total == sizeof(uint64_t)");
enumivo_assert( tmp == current_time(), "tmp == current_time()" );
}
void test_action::test_assert_code() {
uint64_t code = 0;
uint32_t total = read_action_data(&code, sizeof(uint64_t));
enumivo_assert( total == sizeof(uint64_t), "total == sizeof(uint64_t)");
enumivo_assert_code( false, code );
}
void test_action::test_ram_billing_in_notify(uint64_t receiver, uint64_t code, uint64_t action) {
uint128_t tmp = 0;
uint32_t total = read_action_data(&tmp, sizeof(uint128_t));
enumivo_assert( total == sizeof(uint128_t), "total == sizeof(uint128_t)");
uint64_t to_notify = tmp >> 64;
uint64_t payer = tmp & 0xFFFFFFFFFFFFFFFFULL;
if( code == receiver ) {
enumivo::require_recipient( to_notify );
} else {
enumivo_assert( to_notify == receiver, "notified recipient other than the one specified in to_notify" );
// Remove main table row if it already exists.
int itr = db_find_i64( receiver, N(notifytest), N(notifytest), N(notifytest) );
if( itr >= 0 )
db_remove_i64( itr );
// Create the main table row simply for the purpose of charging code more RAM.
if( payer != 0 )
db_store_i64(N(notifytest), N(notifytest), payer, N(notifytest), &to_notify, sizeof(to_notify) );
}
}
| 38.367424
| 119
| 0.672426
|
TP-Lab
|
441cad76bff96baca1c2696c5fc40b478a7322cc
| 2,196
|
hpp
|
C++
|
FootCommander.hpp
|
SalimanDolev/warGame-partb
|
120e7fe7381619b6db455847f5a3690a6cec87f2
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
SalimanDolev/warGame-partb
|
120e7fe7381619b6db455847f5a3690a6cec87f2
|
[
"MIT"
] | null | null | null |
FootCommander.hpp
|
SalimanDolev/warGame-partb
|
120e7fe7381619b6db455847f5a3690a6cec87f2
|
[
"MIT"
] | null | null | null |
#include "Soldier.hpp"
#include <math.h>
//FootSoldier: initial health points=100, damage per activity=10
namespace WarGame{
class FootCommander : public Soldier{
private:
public:
FootCommander(uint player):Soldier(150,20,player){}
void Attacking(std::vector<std::vector<Soldier*>>& board,uint Player, std::pair<int,int> placeOfSoldier){
std::pair <int,int> placeToattack = {0,0};
double minDistance = INT16_MAX;
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board[0].size(); j++){
if(board[i][j] !=nullptr){
if (board[i][j]->getPlayer() != Player){//checks if the solfier that found is the other player soldier
if( sqrt(pow(placeOfSoldier.first - i,2) + pow(placeOfSoldier.second - j,2)) <= minDistance ){
minDistance = pow(placeOfSoldier.first - i,2) + pow(placeOfSoldier.second - j,2);
placeToattack = {i,j};//enter the place of the closest soldier
}
}
}
}
}
if (minDistance < INT16_MAX){
board[placeToattack.first][placeToattack.second]->decreaseHealth(board[placeOfSoldier.first][placeOfSoldier.second]->getDamage());
if(board[placeToattack.first][placeToattack.second]->getLife() <=0){
board[placeToattack.first][placeToattack.second] = nullptr;
}
}
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board[0].size(); j++){
if(board[i][j] != nullptr){
if(board[i][j]->getPlayer() == Player && dynamic_cast<FootSoldier*>(board[i][j]) ){
board[i][j]->Attacking(board,Player,std::pair<int,int> {i,j} );
}
}
}
}
}
};
}
| 44.816327
| 151
| 0.455829
|
SalimanDolev
|
441fc099b8d43fb85f0f238450c4eed5818a9048
| 30,184
|
cpp
|
C++
|
tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | null | null | null |
tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | 4
|
2020-10-22T05:45:37.000Z
|
2020-10-23T12:11:44.000Z
|
tests/cpp-tests/Classes/ClippingNodeTest/ClippingNodeTest.cpp
|
DelinWorks/adxe
|
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
|
[
"MIT"
] | 1
|
2020-10-22T03:17:28.000Z
|
2020-10-22T03:17:28.000Z
|
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://adxeproject.github.io/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//
// ClippingNodeTest
//
//
// by Pierre-David Bélanger
//
#include "ClippingNodeTest.h"
#include "../testResource.h"
#include "renderer/CCRenderer.h"
#include "renderer/backend/ProgramState.h"
#include "renderer/ccShaders.h"
USING_NS_CC;
enum
{
kTagTitleLabel = 1,
kTagSubtitleLabel = 2,
kTagStencilNode = 100,
kTagClipperNode = 101,
kTagContentNode = 102,
};
ClippingNodeTests::ClippingNodeTests()
{
ADD_TEST_CASE(ScrollViewDemo);
ADD_TEST_CASE(HoleDemo);
ADD_TEST_CASE(ShapeTest);
ADD_TEST_CASE(ShapeInvertedTest);
ADD_TEST_CASE(SpriteTest);
ADD_TEST_CASE(SpriteNoAlphaTest);
ADD_TEST_CASE(SpriteInvertedTest);
ADD_TEST_CASE(NestedTest);
ADD_TEST_CASE(RawStencilBufferTest);
ADD_TEST_CASE(RawStencilBufferTest2);
ADD_TEST_CASE(RawStencilBufferTest3);
ADD_TEST_CASE(RawStencilBufferTest4);
ADD_TEST_CASE(RawStencilBufferTest5);
ADD_TEST_CASE(RawStencilBufferTest6);
ADD_TEST_CASE(ClippingToRenderTextureTest);
ADD_TEST_CASE(ClippingRectangleNodeTest);
}
//// Demo examples start here
//@implementation BaseClippingNodeTest
bool BaseClippingNodeTest::init()
{
if (TestCase::init())
{
auto background = Sprite::create(s_back3);
background->setAnchorPoint(Vec2::ZERO);
background->setPosition(Vec2::ZERO);
this->addChild(background, -1);
this->setup();
return true;
}
return false;
}
BaseClippingNodeTest::~BaseClippingNodeTest()
{
Director::getInstance()->getTextureCache()->removeUnusedTextures();
}
std::string BaseClippingNodeTest::title() const
{
return "Clipping Demo";
}
void BaseClippingNodeTest::setup() {}
// BasicTest
std::string BasicTest::title() const
{
return "Basic Test";
}
std::string BasicTest::subtitle() const
{
return "";
}
void BasicTest::setup()
{
auto s = Director::getInstance()->getWinSize();
auto stencil = this->stencil();
stencil->setTag(kTagStencilNode);
stencil->setPosition(50, 50);
auto clipper = this->clipper();
clipper->setTag(kTagClipperNode);
clipper->setAnchorPoint(Vec2(0.5f, 0.5f));
clipper->setPosition(s.width / 2 - 50, s.height / 2 - 50);
clipper->setStencil(stencil);
this->addChild(clipper);
auto content = this->content();
content->setPosition(50, 50);
clipper->addChild(content);
}
Action* BasicTest::actionRotate()
{
return RepeatForever::create(RotateBy::create(1.0f, 90.0f));
}
Action* BasicTest::actionScale()
{
auto scale = ScaleBy::create(1.33f, 1.5f);
return RepeatForever::create(Sequence::create(scale, scale->reverse(), nullptr));
}
DrawNode* BasicTest::shape()
{
auto shape = DrawNode::create();
static Vec2 triangle[3];
triangle[0] = Vec2(-100, -100);
triangle[1] = Vec2(100, -100);
triangle[2] = Vec2(0, 100);
static Color4F green(0, 1, 0, 1);
shape->drawPolygon(triangle, 3, green, 0, green);
return shape;
}
Sprite* BasicTest::grossini()
{
auto grossini = Sprite::create(s_pathGrossini);
grossini->setScale(1.5);
return grossini;
}
Node* BasicTest::stencil()
{
return nullptr;
}
ClippingNode* BasicTest::clipper()
{
return ClippingNode::create();
}
Node* BasicTest::content()
{
return nullptr;
}
// ShapeTest
std::string ShapeTest::title() const
{
return "Shape Basic Test";
}
std::string ShapeTest::subtitle() const
{
return "A DrawNode as stencil and Sprite as content";
}
Node* ShapeTest::stencil()
{
auto node = this->shape();
node->runAction(this->actionRotate());
return node;
}
Node* ShapeTest::content()
{
auto node = this->grossini();
node->runAction(this->actionScale());
return node;
}
// ShapeInvertedTest
std::string ShapeInvertedTest::title() const
{
return "Shape Inverted Basic Test";
}
std::string ShapeInvertedTest::subtitle() const
{
return "A DrawNode as stencil and Sprite as content, inverted";
}
ClippingNode* ShapeInvertedTest::clipper()
{
auto clipper = ShapeTest::clipper();
clipper->setInverted(true);
return clipper;
}
// SpriteTest
std::string SpriteTest::title() const
{
return "Sprite Basic Test";
}
std::string SpriteTest::subtitle() const
{
return "A Sprite as stencil and DrawNode as content";
}
Node* SpriteTest::stencil()
{
auto node = this->grossini();
node->runAction(this->actionRotate());
return node;
}
ClippingNode* SpriteTest::clipper()
{
auto clipper = BasicTest::clipper();
clipper->setAlphaThreshold(0.05f);
return clipper;
}
Node* SpriteTest::content()
{
auto node = this->shape();
node->runAction(this->actionScale());
return node;
}
// SpriteNoAlphaTest
std::string SpriteNoAlphaTest::title() const
{
return "Sprite No Alpha Basic Test";
}
std::string SpriteNoAlphaTest::subtitle() const
{
return "A Sprite as stencil and DrawNode as content, no alpha";
}
ClippingNode* SpriteNoAlphaTest::clipper()
{
auto clipper = SpriteTest::clipper();
clipper->setAlphaThreshold(1);
return clipper;
}
// SpriteInvertedTest
std::string SpriteInvertedTest::title() const
{
return "Sprite Inverted Basic Test";
}
std::string SpriteInvertedTest::subtitle() const
{
return "A Sprite as stencil and DrawNode as content, inverted";
}
ClippingNode* SpriteInvertedTest::clipper()
{
auto clipper = SpriteTest::clipper();
clipper->setAlphaThreshold(0.05f);
clipper->setInverted(true);
return clipper;
}
// NestedTest
std::string NestedTest::title() const
{
return "Nested Test";
}
std::string NestedTest::subtitle() const
{
return "Nest 9 Clipping Nodes, max is usually 8";
}
void NestedTest::setup()
{
static int depth = 9;
Node* parent = this;
for (int i = 0; i < depth; i++)
{
int size = 225 - i * (225 / (depth * 2));
auto clipper = ClippingNode::create();
clipper->setContentSize(Size(size, size));
clipper->setAnchorPoint(Vec2(0.5f, 0.5f));
clipper->setPosition(parent->getContentSize().width / 2, parent->getContentSize().height / 2);
clipper->setAlphaThreshold(0.05f);
clipper->runAction(RepeatForever::create(RotateBy::create(i % 3 ? 1.33f : 1.66f, i % 2 ? 90.0f : -90.0f)));
parent->addChild(clipper);
auto stencil = Sprite::create(s_pathGrossini);
stencil->setScale(2.5f - (i * (2.5f / depth)));
stencil->setAnchorPoint(Vec2(0.5f, 0.5f));
stencil->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2);
stencil->setVisible(false);
stencil->runAction(Sequence::createWithTwoActions(DelayTime::create(i), Show::create()));
clipper->setStencil(stencil);
clipper->addChild(stencil);
parent = clipper;
}
}
// HoleDemo
HoleDemo::~HoleDemo()
{
CC_SAFE_RELEASE(_outerClipper);
CC_SAFE_RELEASE(_holes);
CC_SAFE_RELEASE(_holesStencil);
}
std::string HoleDemo::title() const
{
return "Hole Demo";
}
std::string HoleDemo::subtitle() const
{
return "Touch/click to poke holes";
}
void HoleDemo::setup()
{
auto target = Sprite::create(s_pathBlock);
target->setAnchorPoint(Vec2::ZERO);
target->setScale(3);
_outerClipper = ClippingNode::create();
_outerClipper->retain();
AffineTransform transform = AffineTransform::IDENTITY;
transform = AffineTransformScale(transform, target->getScale(), target->getScale());
_outerClipper->setContentSize(SizeApplyAffineTransform(target->getContentSize(), transform));
_outerClipper->setAnchorPoint(Vec2(0.5f, 0.5f));
_outerClipper->setPosition(Vec2(this->getContentSize()) * 0.5f);
_outerClipper->runAction(RepeatForever::create(RotateBy::create(1, 45)));
_outerClipper->setStencil(target);
auto holesClipper = ClippingNode::create();
holesClipper->setInverted(true);
holesClipper->setAlphaThreshold(0.05f);
holesClipper->addChild(target);
_holes = Node::create();
_holes->retain();
holesClipper->addChild(_holes);
_holesStencil = Node::create();
_holesStencil->retain();
holesClipper->setStencil(_holesStencil);
_outerClipper->addChild(holesClipper);
this->addChild(_outerClipper);
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
void HoleDemo::pokeHoleAtPoint(Vec2 point)
{
float scale = CCRANDOM_0_1() * 0.2 + 0.9;
float rotation = CCRANDOM_0_1() * 360;
auto hole = Sprite::create("Images/hole_effect.png");
hole->setPosition(point);
hole->setRotation(rotation);
hole->setScale(scale);
_holes->addChild(hole);
auto holeStencil = Sprite::create("Images/hole_stencil.png");
holeStencil->setPosition(point);
holeStencil->setRotation(rotation);
holeStencil->setScale(scale);
_holesStencil->addChild(holeStencil);
_outerClipper->runAction(Sequence::createWithTwoActions(ScaleBy::create(0.05f, 0.95f), ScaleTo::create(0.125f, 1)));
}
void HoleDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event* event)
{
Touch* touch = (Touch*)touches[0];
Vec2 point = _outerClipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
auto rect = Rect(0, 0, _outerClipper->getContentSize().width, _outerClipper->getContentSize().height);
if (!rect.containsPoint(point))
return;
this->pokeHoleAtPoint(point);
}
// ScrollViewDemo
std::string ScrollViewDemo::title() const
{
return "Scroll View Demo";
}
std::string ScrollViewDemo::subtitle() const
{
return "Move/drag to scroll the content";
}
void ScrollViewDemo::setup()
{
auto clipper = ClippingNode::create();
clipper->setTag(kTagClipperNode);
clipper->setContentSize(Size(200.0f, 200.0f));
clipper->setAnchorPoint(Vec2(0.5f, 0.5f));
clipper->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2);
clipper->runAction(RepeatForever::create(RotateBy::create(1, 45)));
this->addChild(clipper);
auto stencil = DrawNode::create();
Vec2 rectangle[4];
rectangle[0] = Vec2(0.0f, 0.0f);
rectangle[1] = Vec2(clipper->getContentSize().width, 0.0f);
rectangle[2] = Vec2(clipper->getContentSize().width, clipper->getContentSize().height);
rectangle[3] = Vec2(0.0f, clipper->getContentSize().height);
Color4F white(1, 1, 1, 1);
stencil->drawPolygon(rectangle, 4, white, 1, white);
clipper->setStencil(stencil);
auto content = Sprite::create(s_back2);
content->setTag(kTagContentNode);
content->setAnchorPoint(Vec2(0.5f, 0.5f));
content->setPosition(clipper->getContentSize().width / 2, clipper->getContentSize().height / 2);
clipper->addChild(content);
_scrolling = false;
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
void ScrollViewDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event* event)
{
Touch* touch = touches[0];
auto clipper = this->getChildByTag(kTagClipperNode);
Vec2 point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
auto rect = Rect(0, 0, clipper->getContentSize().width, clipper->getContentSize().height);
_scrolling = rect.containsPoint(point);
_lastPoint = point;
}
void ScrollViewDemo::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
if (!_scrolling)
return;
Touch* touch = touches[0];
auto clipper = this->getChildByTag(kTagClipperNode);
auto point = clipper->convertToNodeSpace(Director::getInstance()->convertToGL(touch->getLocationInView()));
Vec2 diff = point - _lastPoint;
auto content = clipper->getChildByTag(kTagContentNode);
content->setPosition(content->getPosition() + diff);
_lastPoint = point;
}
void ScrollViewDemo::onTouchesEnded(const std::vector<Touch*>& touches, Event* event)
{
if (!_scrolling)
return;
_scrolling = false;
}
// RawStencilBufferTests
//#if COCOS2D_DEBUG > 1
static const float _alphaThreshold = 0.05f;
static const int _planeCount = 8;
static const float _planeColor[][4] = {
{0, 0, 0, 0.65f}, {0.7f, 0, 0, 0.6f}, {0, 0.7f, 0, 0.55f}, {0, 0, 0.7f, 0.5f},
{0.7f, 0.7f, 0, 0.45f}, {0, 0.7f, 0.7f, 0.4f}, {0.7f, 0, 0.7f, 0.35f}, {0.7f, 0.7f, 0.7f, 0.3f},
};
RawStencilBufferTest::~RawStencilBufferTest() {}
std::string RawStencilBufferTest::title() const
{
return "Raw Stencil Tests";
}
std::string RawStencilBufferTest::subtitle() const
{
return "1:Default";
}
void RawStencilBufferTest::setup()
{
for (int i = 0; i < _planeCount; ++i)
{
Sprite* sprite = Sprite::create(s_pathGrossini);
sprite->setAnchorPoint(Vec2(0.5, 0));
sprite->setScale(2.5f);
_sprites.pushBack(sprite);
Sprite* sprite2 = Sprite::create(s_pathGrossini);
sprite2->setAnchorPoint(Vec2(0.5, 0));
sprite2->setScale(2.5f);
_spritesStencil.pushBack(sprite2);
}
initCommands();
}
void RawStencilBufferTest::initCommands()
{
auto renderer = Director::getInstance()->getRenderer();
_enableStencilCallback.func = [=]() { renderer->setStencilTest(true); };
_enableStencilCallback.init(_globalZOrder);
_disableStencilCallback.func = [=]() { renderer->setStencilTest(false); };
_disableStencilCallback.init(_globalZOrder);
auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_UCOLOR);
_programState = new backend::ProgramState(program);
_locColor = _programState->getProgram()->getUniformLocation("u_color");
_locMVPMatrix = _programState->getProgram()->getUniformLocation("u_MVPMatrix");
const auto& projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
_programState->setUniform(_locMVPMatrix, projectionMat.m, sizeof(projectionMat.m));
size_t neededCmdSize = _planeCount * 2;
_renderCmds.resize(neededCmdSize);
auto winPoint = Vec2(Director::getInstance()->getWinSize());
auto planeSize = winPoint * (1.0 / _planeCount);
BlendFunc blend;
blend.src = backend::BlendFactor::ONE;
blend.dst = backend::BlendFactor::ONE_MINUS_SRC_ALPHA;
for (int i = 0, cmdIndex = 0; i < _planeCount; i++)
{
auto stencilPoint = planeSize * (_planeCount - i);
stencilPoint.x = winPoint.x;
auto& cmd = _renderCmds[cmdIndex];
cmdIndex++;
cmd.init(_globalZOrder, blend);
cmd.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i));
Vec2 vertices[] = {Vec2::ZERO, Vec2(stencilPoint.x, 0.0f), stencilPoint, Vec2(0.0f, stencilPoint.y)};
unsigned short indices[] = {0, 2, 1, 0, 3, 2};
cmd.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC);
cmd.updateVertexBuffer(vertices, sizeof(vertices));
cmd.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC);
cmd.updateIndexBuffer(indices, sizeof(indices));
cmd.getPipelineDescriptor().programState = _programState;
auto vertexLayout = _programState->getVertexLayout();
auto& attributes = _programState->getProgram()->getActiveAttributes();
auto iter = attributes.find("a_position");
if (iter != attributes.end())
vertexLayout->setAttribute("a_position", iter->second.location, backend::VertexFormat::FLOAT2, 0, false);
vertexLayout->setLayout(sizeof(Vec2));
auto& cmd2 = _renderCmds[cmdIndex];
cmdIndex++;
cmd2.init(_globalZOrder, blend);
cmd2.setBeforeCallback(CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i));
Vec2 vertices2[] = {Vec2::ZERO, Vec2(winPoint.x, 0.0f), winPoint, Vec2(0.0f, winPoint.y)};
cmd2.createVertexBuffer(sizeof(Vec2), 4, backend::BufferUsage::STATIC);
cmd2.updateVertexBuffer(vertices2, sizeof(vertices2));
cmd2.createIndexBuffer(backend::IndexFormat::U_SHORT, 6, backend::BufferUsage::STATIC);
cmd2.updateIndexBuffer(indices, sizeof(indices));
cmd2.getPipelineDescriptor().programState = _programState;
}
}
void RawStencilBufferTest::draw(Renderer* renderer, const Mat4& transform, uint32_t flags)
{
auto winPoint = Vec2(Director::getInstance()->getWinSize());
auto planeSize = winPoint * (1.0 / _planeCount);
renderer->addCommand(&_enableStencilCallback);
for (int i = 0, cmdIndex = 0; i < _planeCount; i++)
{
auto spritePoint = planeSize * i;
spritePoint.x += planeSize.x / 2;
spritePoint.y = 0;
_sprites.at(i)->setPosition(spritePoint);
_spritesStencil.at(i)->setPosition(spritePoint);
renderer->clear(ClearFlag::STENCIL, Color4F::BLACK, 0.f, 0x0, _globalZOrder);
renderer->addCommand(&_renderCmds[cmdIndex]);
cmdIndex++;
Director* director = Director::getInstance();
CCASSERT(nullptr != director, "Director is null when setting matrix stack");
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_modelViewTransform = this->transform(transform);
_spritesStencil.at(i)->visit(renderer, _modelViewTransform, flags);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
renderer->addCommand(&_renderCmds[cmdIndex]);
cmdIndex++;
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
_modelViewTransform = this->transform(transform);
_sprites.at(i)->visit(renderer, _modelViewTransform, flags);
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
renderer->addCommand(&_disableStencilCallback);
}
void RawStencilBufferTest::onBeforeDrawClip(int planeIndex)
{
this->setupStencilForClippingOnPlane(planeIndex);
float color[4] = {1.f, 1.f, 1.f, 1.f};
_programState->setUniform(_locColor, color, sizeof(color));
}
void RawStencilBufferTest::onBeforeDrawSprite(int planeIndex)
{
this->setupStencilForDrawingOnPlane(planeIndex);
auto& color = _planeColor[planeIndex];
_programState->setUniform(_locColor, (void*)color, sizeof(color));
}
void RawStencilBufferTest::setupStencilForClippingOnPlane(int plane)
{
auto renderer = Director::getInstance()->getRenderer();
unsigned int planeMask = 0x1 << plane;
renderer->setStencilWriteMask(planeMask);
renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask);
renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP,
backend::StencilOperation::KEEP);
}
void RawStencilBufferTest::setupStencilForDrawingOnPlane(int plane)
{
auto renderer = Director::getInstance()->getRenderer();
unsigned int planeMask = 0x1 << plane;
renderer->setStencilCompareFunction(backend::CompareFunction::EQUAL, planeMask, planeMask);
renderer->setStencilOperation(backend::StencilOperation::KEEP, backend::StencilOperation::KEEP,
backend::StencilOperation::KEEP);
}
//@implementation RawStencilBufferTest2
std::string RawStencilBufferTest2::subtitle() const
{
return "2:DepthMask:FALSE";
}
void RawStencilBufferTest2::setupStencilForClippingOnPlane(int plane)
{
RawStencilBufferTest::setupStencilForClippingOnPlane(plane);
Director::getInstance()->getRenderer()->setDepthWrite(false);
}
void RawStencilBufferTest2::setupStencilForDrawingOnPlane(int plane)
{
Director::getInstance()->getRenderer()->setDepthWrite(true);
RawStencilBufferTest::setupStencilForDrawingOnPlane(plane);
}
//@implementation RawStencilBufferTest3
std::string RawStencilBufferTest3::subtitle() const
{
return "3:DepthTest:DISABLE,DepthMask:FALSE";
}
void RawStencilBufferTest3::setupStencilForClippingOnPlane(int plane)
{
RawStencilBufferTest::setupStencilForClippingOnPlane(plane);
auto renderer = Director::getInstance()->getRenderer();
renderer->setDepthTest(false);
renderer->setDepthWrite(false);
}
void RawStencilBufferTest3::setupStencilForDrawingOnPlane(int plane)
{
Director::getInstance()->getRenderer()->setDepthWrite(true);
RawStencilBufferTest::setupStencilForDrawingOnPlane(plane);
}
void RawStencilBufferTestAlphaTest::setup()
{
RawStencilBufferTest::setup();
for (int i = 0; i < _planeCount; ++i)
{
auto program = backend::Program::getBuiltinProgram(backend::ProgramType::POSITION_TEXTURE_COLOR_ALPHA_TEST);
auto programState = new backend::ProgramState(program);
programState->setUniform(programState->getUniformLocation("u_alpha_value"), &_alphaThreshold,
sizeof(_alphaThreshold));
_spritesStencil.at(i)->setProgramState(programState);
}
}
//@implementation RawStencilBufferTest4
std::string RawStencilBufferTest4::subtitle() const
{
return "4:DepthMask:FALSE,AlphaTest:ENABLE";
}
void RawStencilBufferTest4::setupStencilForClippingOnPlane(int plane)
{
RawStencilBufferTest::setupStencilForClippingOnPlane(plane);
auto renderer = Director::getInstance()->getRenderer();
renderer->setDepthWrite(false);
}
void RawStencilBufferTest4::setupStencilForDrawingOnPlane(int plane)
{
Director::getInstance()->getRenderer()->setDepthWrite(true);
RawStencilBufferTest::setupStencilForDrawingOnPlane(plane);
}
//@implementation RawStencilBufferTest5
std::string RawStencilBufferTest5::subtitle() const
{
return "5:DepthTest:DISABLE,DepthMask:FALSE,AlphaTest:ENABLE";
}
void RawStencilBufferTest5::setupStencilForClippingOnPlane(int plane)
{
RawStencilBufferTest::setupStencilForClippingOnPlane(plane);
auto renderer = Director::getInstance()->getRenderer();
renderer->setDepthWrite(false);
renderer->setDepthTest(false);
}
void RawStencilBufferTest5::setupStencilForDrawingOnPlane(int plane)
{
auto renderer = Director::getInstance()->getRenderer();
renderer->setDepthWrite(false);
RawStencilBufferTest::setupStencilForDrawingOnPlane(plane);
}
//@implementation RawStencilBufferTest6
std::string RawStencilBufferTest6::subtitle() const
{
return "6:ManualClear,AlphaTest:ENABLE";
}
void RawStencilBufferTest6::setup()
{
RawStencilBufferTestAlphaTest::setup();
Director::getInstance()->getRenderer()->setStencilWriteMask(~0);
}
void RawStencilBufferTest6::setupStencilForClippingOnPlane(int plane)
{
int planeMask = 0x1 << plane;
auto renderer = Director::getInstance()->getRenderer();
renderer->setStencilCompareFunction(backend::CompareFunction::NEVER, planeMask, planeMask);
renderer->setStencilOperation(backend::StencilOperation::REPLACE, backend::StencilOperation::KEEP,
backend::StencilOperation::KEEP);
renderer->setDepthTest(false);
renderer->setDepthWrite(false);
}
void RawStencilBufferTest6::setupStencilForDrawingOnPlane(int plane)
{
auto renderer = Director::getInstance()->getRenderer();
renderer->setDepthWrite(true);
RawStencilBufferTest::setupStencilForDrawingOnPlane(plane);
}
//#endif // COCOS2D_DEBUG > 1
// ClippingToRenderTextureTest
std::string ClippingToRenderTextureTest::title() const
{
return "Clipping to RenderTexture";
}
std::string ClippingToRenderTextureTest::subtitle() const
{
return "Both should look the same";
}
void ClippingToRenderTextureTest::setup()
{
auto button = MenuItemFont::create("Reproduce bug", [&](Ref* sender) {
std::vector<Node*> nodes;
enumerateChildren("remove me [0-9]", [&](Node* node) {
nodes.push_back(node);
return false;
});
for (auto node : nodes)
{
this->removeChild(node);
}
this->reproduceBug();
});
auto s = Director::getInstance()->getWinSize();
// create menu, it's an autorelease object
auto menu = Menu::create(button, nullptr);
menu->setPosition(Point(s.width / 2, s.height / 2));
this->addChild(menu, 1);
expectedBehaviour();
}
void ClippingToRenderTextureTest::expectedBehaviour()
{
auto director = Director::getInstance();
Size visibleSize = director->getVisibleSize();
Point origin = director->getVisibleOrigin();
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("Images/grossini.png");
// position the sprite on the center of the screen
sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
sprite->setName("remove me 0");
// container node that will contain the clippingNode
auto container = Node::create();
this->addChild(container);
container->setName("remove me 1");
auto stencil = DrawNode::create();
Point triangle[3];
triangle[0] = Point(-50, -50);
triangle[1] = Point(50, -50);
triangle[2] = Point(0, 50);
Color4F green(0, 1, 0, 1);
stencil->drawPolygon(triangle, 3, green, 0, green);
auto clipper = ClippingNode::create();
clipper->setAnchorPoint(Point(0.5f, 0.5f));
clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
clipper->setStencil(stencil);
clipper->setInverted(true);
container->addChild(clipper, 1);
auto img = DrawNode::create();
triangle[0] = Point(-200, -200);
triangle[1] = Point(200, -200);
triangle[2] = Point(0, 200);
Color4F red(1, 0, 0, 1);
img->drawPolygon(triangle, 3, red, 0, red);
clipper->addChild(img);
}
void ClippingToRenderTextureTest::reproduceBug()
{
auto director = Director::getInstance();
Size visibleSize = director->getVisibleSize();
Point origin = director->getVisibleOrigin();
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("Images/grossini.png");
// position the sprite on the center of the screen
sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
// container node that will contain the clippingNode
auto container = Node::create();
container->retain();
auto stencil = DrawNode::create();
Point triangle[3];
triangle[0] = Point(-50, -50);
triangle[1] = Point(50, -50);
triangle[2] = Point(0, 50);
Color4F green(0, 1, 0, 1);
stencil->drawPolygon(triangle, 3, green, 0, green);
auto clipper = ClippingNode::create();
clipper->setAnchorPoint(Point(0.5f, 0.5f));
clipper->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
clipper->setStencil(stencil);
clipper->setInverted(true);
container->addChild(clipper, 1);
auto img = DrawNode::create();
triangle[0] = Point(-200, -200);
triangle[1] = Point(200, -200);
triangle[2] = Point(0, 200);
Color4F red(1, 0, 0, 1);
img->drawPolygon(triangle, 3, red, 0, red);
clipper->addChild(img);
// container rendered on Texture the size of the screen and because Clipping node use stencil buffer so we need to
// create RenderTexture with depthStencil format parameter
RenderTexture* rt =
RenderTexture::create(visibleSize.width, visibleSize.height, backend::PixelFormat::RGBA8, PixelFormat::D24S8);
rt->setPosition(visibleSize.width / 2, visibleSize.height / 2);
this->addChild(rt);
rt->begin();
container->visit();
rt->end();
}
// ClippingRectangleNodeDemo
std::string ClippingRectangleNodeTest::title() const
{
return "ClippingRectangleNode Test";
}
std::string ClippingRectangleNodeTest::subtitle() const
{
return "more effectively";
}
void ClippingRectangleNodeTest::setup()
{
auto clipper = ClippingRectangleNode::create();
clipper->setClippingRegion(
Rect(this->getContentSize().width / 2 - 100, this->getContentSize().height / 2 - 100, 200.0f, 200.0f));
clipper->setTag(kTagClipperNode);
this->addChild(clipper);
auto content = Sprite::create(s_back2);
content->setTag(kTagContentNode);
content->setAnchorPoint(Vec2(0.5f, 0.5f));
content->setPosition(this->getContentSize().width / 2, this->getContentSize().height / 2);
clipper->addChild(content);
}
| 30.957949
| 120
| 0.687947
|
DelinWorks
|
4422a27288c8277a41c87b98c795f65b2f23b102
| 2,316
|
cc
|
C++
|
src/quadrature/utility/quadrature_utilities.cc
|
narang-amit/BART
|
22997c4ce6de3e97b39f4da4601edbd4cf73f9e2
|
[
"MIT"
] | 1
|
2020-06-29T20:43:25.000Z
|
2020-06-29T20:43:25.000Z
|
src/quadrature/utility/quadrature_utilities.cc
|
jsrehak/BART
|
0460dfffbcf5671a730448de7f45cce39fd4a485
|
[
"MIT"
] | null | null | null |
src/quadrature/utility/quadrature_utilities.cc
|
jsrehak/BART
|
0460dfffbcf5671a730448de7f45cce39fd4a485
|
[
"MIT"
] | null | null | null |
#include "quadrature/utility/quadrature_utilities.h"
#include "quadrature/quadrature_set_i.h"
#include <functional>
namespace bart {
namespace quadrature {
namespace utility {
template <int dim>
std::array<double, dim> ReflectAcrossOrigin(const OrdinateI<dim>& ordinate) {
auto position = ordinate.cartesian_position();
std::transform(position.begin(), position.end(),
position.begin(), [](double val){return -val;});
return position;
}
template <>
std::vector<std::pair<CartesianPosition<1>, Weight>> GenerateAllPositiveX<1>(
const std::vector<std::pair<CartesianPosition<1>, Weight>>& to_distribute) {
return to_distribute;
}
template <>
std::vector<std::pair<CartesianPosition<2>, Weight>> GenerateAllPositiveX<2>(
const std::vector<std::pair<CartesianPosition<2>, Weight>>& to_distribute) {
auto quadrature_pairs = to_distribute;
for (auto [position, weight] : to_distribute) {
auto& y = position.get().at(1);
if (y != 0) {
y *= -1;
quadrature_pairs.emplace_back(CartesianPosition<2>(position),
Weight(weight));
}
}
return quadrature_pairs;
}
template <>
std::vector<std::pair<CartesianPosition<3>, Weight>> GenerateAllPositiveX<3>(
const std::vector<std::pair<CartesianPosition<3>, Weight>>& to_distribute) {
auto quadrature_pairs = to_distribute;
for (auto [position, weight] : to_distribute) {
auto& y = position.get().at(1);
auto& z = position.get().at(2);
if (y != 0) {
y *= -1;
quadrature_pairs.emplace_back(CartesianPosition<3>(position),
Weight(weight));
}
if (z != 0) {
z *= -1;
quadrature_pairs.emplace_back(CartesianPosition<3>(position),
Weight(weight));
if (y != 0) {
y *= -1;
quadrature_pairs.emplace_back(CartesianPosition<3>(position),
Weight(weight));
}
}
}
return quadrature_pairs;
}
template std::array<double, 1> ReflectAcrossOrigin<1>(const OrdinateI<1>&);
template std::array<double, 2> ReflectAcrossOrigin<2>(const OrdinateI<2>&);
template std::array<double, 3> ReflectAcrossOrigin<3>(const OrdinateI<3>&);
} // namespace utility
} // namespace quadrature
} // namespace bart
| 29.692308
| 80
| 0.640328
|
narang-amit
|
442349d49c08b7e978546676ce3980918454ba5f
| 11,376
|
cpp
|
C++
|
src/model/WaterUseEquipment.cpp
|
muehleisen/OpenStudio
|
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
|
[
"blessing"
] | 354
|
2015-01-10T17:46:11.000Z
|
2022-03-29T10:00:00.000Z
|
src/model/WaterUseEquipment.cpp
|
muehleisen/OpenStudio
|
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
|
[
"blessing"
] | 3,243
|
2015-01-02T04:54:45.000Z
|
2022-03-31T17:22:22.000Z
|
src/model/WaterUseEquipment.cpp
|
jmarrec/OpenStudio
|
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
|
[
"blessing"
] | 157
|
2015-01-07T15:59:55.000Z
|
2022-03-30T07:46:09.000Z
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "WaterUseEquipment.hpp"
#include "WaterUseEquipment_Impl.hpp"
#include "WaterUseEquipmentDefinition.hpp"
#include "WaterUseEquipmentDefinition_Impl.hpp"
#include "Model.hpp"
#include "Model_Impl.hpp"
#include "WaterUseConnections.hpp"
#include "WaterUseConnections_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include <utilities/idd/OS_WaterUse_Equipment_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../utilities/units/Unit.hpp"
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
WaterUseEquipment_Impl::WaterUseEquipment_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: SpaceLoadInstance_Impl(idfObject, model, keepHandle) {
OS_ASSERT(idfObject.iddObject().type() == WaterUseEquipment::iddObjectType());
}
WaterUseEquipment_Impl::WaterUseEquipment_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle)
: SpaceLoadInstance_Impl(other, model, keepHandle) {
OS_ASSERT(other.iddObject().type() == WaterUseEquipment::iddObjectType());
}
WaterUseEquipment_Impl::WaterUseEquipment_Impl(const WaterUseEquipment_Impl& other, Model_Impl* model, bool keepHandle)
: SpaceLoadInstance_Impl(other, model, keepHandle) {}
const std::vector<std::string>& WaterUseEquipment_Impl::outputVariableNames() const {
static const std::vector<std::string> result{
"Water Use Equipment Hot Water Mass Flow Rate", "Water Use Equipment Cold Water Mass Flow Rate", "Water Use Equipment Total Mass Flow Rate",
"Water Use Equipment Hot Water Volume Flow Rate", "Water Use Equipment Cold Water Volume Flow Rate",
"Water Use Equipment Total Volume Flow Rate", "Water Use Equipment Hot Water Volume", "Water Use Equipment Cold Water Volume",
"Water Use Equipment Total Volume", "Water Use Equipment Mains Water Volume", "Water Use Equipment Hot Water Temperature",
"Water Use Equipment Cold Water Temperature", "Water Use Equipment Target Water Temperature", "Water Use Equipment Mixed Water Temperature",
"Water Use Equipment Drain Water Temperature", "Water Use Equipment Heating Rate", "Water Use Equipment Heating Energy",
// The Key is the name of the Water Use Equipment, not the zone,
// so it's appropriate to report it here rather than the ThermalZone
// cf EnergyPlus/WaterUse.cc
"Water Use Equipment Zone Sensible Heat Gain Rate", "Water Use Equipment Zone Sensible Heat Gain Energy",
"Water Use Equipment Zone Latent Gain Rate", "Water Use Equipment Zone Latent Gain Energy",
"Water Use Equipment Zone Moisture Gain Mass Flow Rate", "Water Use Equipment Zone Moisture Gain Mass"
};
return result;
}
IddObjectType WaterUseEquipment_Impl::iddObjectType() const {
return WaterUseEquipment::iddObjectType();
}
std::vector<ScheduleTypeKey> WaterUseEquipment_Impl::getScheduleTypeKeys(const Schedule& schedule) const {
std::vector<ScheduleTypeKey> result;
UnsignedVector fieldIndices = getSourceIndices(schedule.handle());
UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());
if (std::find(b, e, OS_WaterUse_EquipmentFields::FlowRateFractionScheduleName) != e) {
result.push_back(ScheduleTypeKey("WaterUseEquipment", "Flow Rate Fraction"));
}
return result;
}
boost::optional<Schedule> WaterUseEquipment_Impl::flowRateFractionSchedule() const {
return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_WaterUse_EquipmentFields::FlowRateFractionScheduleName);
}
bool WaterUseEquipment_Impl::setFlowRateFractionSchedule(Schedule& schedule) {
bool result = setSchedule(OS_WaterUse_EquipmentFields::FlowRateFractionScheduleName, "WaterUseEquipment", "Flow Rate Fraction", schedule);
return result;
}
void WaterUseEquipment_Impl::resetFlowRateFractionSchedule() {
bool result = setString(OS_WaterUse_EquipmentFields::FlowRateFractionScheduleName, "");
OS_ASSERT(result);
}
boost::optional<ModelObject> WaterUseEquipment_Impl::flowRateFractionScheduleAsModelObject() const {
OptionalModelObject result;
OptionalSchedule intermediate = flowRateFractionSchedule();
if (intermediate) {
result = *intermediate;
}
return result;
}
bool WaterUseEquipment_Impl::setFlowRateFractionScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalSchedule intermediate = modelObject->optionalCast<Schedule>();
if (intermediate) {
return setFlowRateFractionSchedule(*intermediate);
} else {
return false;
}
} else {
resetFlowRateFractionSchedule();
}
return true;
}
boost::optional<WaterUseConnections> WaterUseEquipment_Impl::waterUseConnections() const {
std::vector<WaterUseConnections> connections = model().getConcreteModelObjects<WaterUseConnections>();
for (const auto& connection : connections) {
std::vector<WaterUseEquipment> equipment = connection.waterUseEquipment();
for (const auto& elem : equipment) {
if (elem.handle() == handle()) {
return connection;
}
}
}
return boost::none;
}
std::vector<IdfObject> WaterUseEquipment_Impl::remove() {
if (boost::optional<WaterUseConnections> c = waterUseConnections()) {
WaterUseEquipment e = getObject<WaterUseEquipment>();
c->removeWaterUseEquipment(e);
}
return ModelObject_Impl::remove();
}
WaterUseEquipmentDefinition WaterUseEquipment_Impl::waterUseEquipmentDefinition() const {
return definition().cast<WaterUseEquipmentDefinition>();
}
bool WaterUseEquipment_Impl::setWaterUseEquipmentDefinition(const WaterUseEquipmentDefinition& definition) {
return setPointer(OS_WaterUse_EquipmentFields::WaterUseEquipmentDefinitionName, definition.handle());
}
int WaterUseEquipment_Impl::spaceIndex() const {
return OS_WaterUse_EquipmentFields::SpaceName;
}
int WaterUseEquipment_Impl::definitionIndex() const {
return OS_WaterUse_EquipmentFields::WaterUseEquipmentDefinitionName;
}
bool WaterUseEquipment_Impl::setDefinition(const SpaceLoadDefinition& definition) {
bool result = false;
boost::optional<WaterUseEquipmentDefinition> waterUseEquipmentDefinition = definition.optionalCast<WaterUseEquipmentDefinition>();
if (waterUseEquipmentDefinition) {
result = setWaterUseEquipmentDefinition(*waterUseEquipmentDefinition);
}
return result;
}
bool WaterUseEquipment_Impl::hardSize() {
return false;
}
bool WaterUseEquipment_Impl::hardApplySchedules() {
return false;
}
double WaterUseEquipment_Impl::multiplier() const {
return 1;
}
bool WaterUseEquipment_Impl::isMultiplierDefaulted() const {
return true;
}
bool WaterUseEquipment_Impl::isAbsolute() const {
return true;
}
} // namespace detail
WaterUseEquipment::WaterUseEquipment(const WaterUseEquipmentDefinition& waterUseEquipmentDefinition)
: SpaceLoadInstance(WaterUseEquipment::iddObjectType(), waterUseEquipmentDefinition) {
OS_ASSERT(getImpl<detail::WaterUseEquipment_Impl>());
Schedule sch = this->model().alwaysOnDiscreteSchedule();
bool test = this->setFlowRateFractionSchedule(sch);
OS_ASSERT(test);
}
IddObjectType WaterUseEquipment::iddObjectType() {
return IddObjectType(IddObjectType::OS_WaterUse_Equipment);
}
boost::optional<Schedule> WaterUseEquipment::flowRateFractionSchedule() const {
return getImpl<detail::WaterUseEquipment_Impl>()->flowRateFractionSchedule();
}
bool WaterUseEquipment::setFlowRateFractionSchedule(Schedule& flowRateFractionSchedule) {
return getImpl<detail::WaterUseEquipment_Impl>()->setFlowRateFractionSchedule(flowRateFractionSchedule);
}
void WaterUseEquipment::resetFlowRateFractionSchedule() {
getImpl<detail::WaterUseEquipment_Impl>()->resetFlowRateFractionSchedule();
}
boost::optional<WaterUseConnections> WaterUseEquipment::waterUseConnections() const {
return getImpl<detail::WaterUseEquipment_Impl>()->waterUseConnections();
}
WaterUseEquipmentDefinition WaterUseEquipment::waterUseEquipmentDefinition() const {
return getImpl<detail::WaterUseEquipment_Impl>()->waterUseEquipmentDefinition();
}
bool WaterUseEquipment::setWaterUseEquipmentDefinition(const WaterUseEquipmentDefinition& definition) {
return getImpl<detail::WaterUseEquipment_Impl>()->setWaterUseEquipmentDefinition(definition);
}
/// @cond
WaterUseEquipment::WaterUseEquipment(std::shared_ptr<detail::WaterUseEquipment_Impl> impl) : SpaceLoadInstance(std::move(impl)) {}
/// @endcond
} // namespace model
} // namespace openstudio
| 44.964427
| 148
| 0.730749
|
muehleisen
|
4423cb16f755cb095af78a9842b370de16adf1cb
| 3,919
|
cpp
|
C++
|
td/telegram/ConfigShared.cpp
|
ERussel/td
|
101aa73f132d5124d8da45bae11a29c423420072
|
[
"BSL-1.0"
] | 1
|
2019-03-24T01:16:18.000Z
|
2019-03-24T01:16:18.000Z
|
td/telegram/ConfigShared.cpp
|
ERussel/td
|
101aa73f132d5124d8da45bae11a29c423420072
|
[
"BSL-1.0"
] | 1
|
2019-01-18T16:03:35.000Z
|
2019-01-18T21:13:14.000Z
|
td/telegram/ConfigShared.cpp
|
ERussel/td
|
101aa73f132d5124d8da45bae11a29c423420072
|
[
"BSL-1.0"
] | 2
|
2018-12-21T08:37:59.000Z
|
2020-04-28T12:47:46.000Z
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// 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)
//
#include "td/telegram/ConfigShared.h"
#include "td/telegram/td_api.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
namespace td {
ConfigShared::ConfigShared(BinlogPmcPtr config_pmc, unique_ptr<Callback> callback)
: config_pmc_(config_pmc), callback_(std::move(callback)) {
for (auto key_value : config_pmc_->get_all()) {
on_option_updated(key_value.first);
}
}
void ConfigShared::set_option_boolean(Slice name, bool value) {
if (set_option(name, value ? Slice("Btrue") : Slice("Bfalse"))) {
on_option_updated(name);
}
}
void ConfigShared::set_option_empty(Slice name) {
if (set_option(name, Slice())) {
on_option_updated(name);
}
}
void ConfigShared::set_option_integer(Slice name, int32 value) {
if (set_option(name, PSLICE() << "I" << value)) {
on_option_updated(name);
}
}
void ConfigShared::set_option_string(Slice name, Slice value) {
if (set_option(name, PSLICE() << "S" << value)) {
on_option_updated(name);
}
}
bool ConfigShared::have_option(Slice name) const {
return config_pmc_->isset(name.str());
}
string ConfigShared::get_option(Slice name) const {
return config_pmc_->get(name.str());
}
std::unordered_map<string, string> ConfigShared::get_options(Slice prefix) const {
return config_pmc_->prefix_get(prefix);
}
std::unordered_map<string, string> ConfigShared::get_options() const {
return config_pmc_->get_all();
}
bool ConfigShared::get_option_boolean(Slice name, bool default_value) const {
auto value = get_option(name);
if (value.empty()) {
return default_value;
}
if (value == "Btrue") {
return true;
}
if (value == "Bfalse") {
return false;
}
LOG(ERROR) << "Found \"" << value << "\" instead of boolean option";
return default_value;
}
int32 ConfigShared::get_option_integer(Slice name, int32 default_value) const {
auto str_value = get_option(name);
if (str_value.empty()) {
return default_value;
}
if (str_value[0] != 'I') {
LOG(ERROR) << "Found \"" << str_value << "\" instead of integer option";
return default_value;
}
return to_integer<int32>(str_value.substr(1));
}
string ConfigShared::get_option_string(Slice name, string default_value) const {
auto str_value = get_option(name);
if (str_value.empty()) {
return default_value;
}
if (str_value[0] != 'S') {
LOG(ERROR) << "Found \"" << str_value << "\" instead of string option";
return default_value;
}
return str_value.substr(1);
}
tl_object_ptr<td_api::OptionValue> ConfigShared::get_option_value(Slice value) const {
return get_option_value_object(get_option(value));
}
bool ConfigShared::set_option(Slice name, Slice value) {
if (value.empty()) {
return config_pmc_->erase(name.str()) != 0;
} else {
return config_pmc_->set(name.str(), value.str()) != 0;
}
}
tl_object_ptr<td_api::OptionValue> ConfigShared::get_option_value_object(Slice value) {
if (value.empty()) {
return make_tl_object<td_api::optionValueEmpty>();
}
switch (value[0]) {
case 'B':
if (value == "Btrue") {
return make_tl_object<td_api::optionValueBoolean>(true);
}
if (value == "Bfalse") {
return make_tl_object<td_api::optionValueBoolean>(false);
}
break;
case 'I':
return make_tl_object<td_api::optionValueInteger>(to_integer<int32>(value.substr(1)));
case 'S':
return make_tl_object<td_api::optionValueString>(value.substr(1).str());
}
return make_tl_object<td_api::optionValueString>(value.str());
}
void ConfigShared::on_option_updated(Slice name) const {
callback_->on_option_updated(name.str(), get_option(name));
}
} // namespace td
| 27.794326
| 96
| 0.690737
|
ERussel
|
4424171a332c18b78e8a7a07fc90f869924fa65f
| 712
|
hpp
|
C++
|
interrupts/include/interrupts.hpp
|
Granahir2/Nematod
|
795aca41770c4fc1247f5170ca1a3a0ab6439363
|
[
"MIT"
] | 3
|
2018-11-05T19:49:48.000Z
|
2018-11-10T18:03:22.000Z
|
interrupts/include/interrupts.hpp
|
Granahir2/Nematod
|
795aca41770c4fc1247f5170ca1a3a0ab6439363
|
[
"MIT"
] | 1
|
2018-11-10T19:00:24.000Z
|
2018-11-11T18:49:46.000Z
|
interrupts/include/interrupts.hpp
|
Granahir2/Nematod
|
795aca41770c4fc1247f5170ca1a3a0ab6439363
|
[
"MIT"
] | 1
|
2018-11-06T00:09:57.000Z
|
2018-11-06T00:09:57.000Z
|
#pragma once
#include <vector>
#include "interface/interrupts.hpp"
// The default InterruptBus is a Common Emitter bus.
template<interrupt_kind T>
class InterruptBus_CtrlBlock {
public:
void add_slave(InterruptEmitter<T> *to_add);
void remove_slave(InterruptEmitter<T> *to_remove);
protected:
std::vector<InterruptEmitter<T> *> m_ie;
};
class NMIInterruptBus : public NMIInterruptBus_interface, public InterruptBus_CtrlBlock<NMI> {
public:
virtual bool is_asserted() override;
protected:
bool previous_state = false;
};
class IRQInterruptBus : public IRQInterruptBus_interface, public InterruptBus_CtrlBlock<IRQ> {
public:
virtual bool is_asserted() override;
};
| 23.733333
| 94
| 0.75
|
Granahir2
|
44256df394f0411da3617c29b1bf15d11e7b598e
| 26,685
|
cpp
|
C++
|
source/blood/src/dude.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
source/blood/src/dude.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
source/blood/src/dude.cpp
|
madame-rachelle/Raze
|
67c8187d620e6cf9e99543cab5c5746dd31007af
|
[
"RSA-MD"
] | null | null | null |
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT
This file is part of NBlood.
NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h" // Must come before everything else!
#include "compat.h"
#include "blood.h"
#include "dude.h"
BEGIN_BLD_NS
DUDEINFO dudeInfo[kDudeMax-kDudeBase] =
{
{
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4096, //seqStartId
40, // startHp
70, // mass
1200, // ???
48, // clipdist
41, // eye height
20, // aim height
10240, // hear dist
51200, // see dist
512, // periphery
0, // melee distance
10, // flee health
8, // hinder damage
256, // change target chance
16, // change target chance to same type
32768, // alert chance
1, // lockout
46603, // front speed
34952, // side speed
13981, // back speed
256, // ang speed
15, -1, -1, // gib type
256, 256, 96, 256, 256, 256, 192, // start damage
0, 0, 0, 0, 0, 0, 0, // real damage
0, // ???
0 // ???
},
{
11520,
40,
70,
1200,
48,
41,
20,
10240,
51200,
512,
0,
10,
5,
256,
16,
32768,
1,
34952,
34952,
13981,
256,
15, -1, -1,
256, 256, 128, 256, 256, 256, 192,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4352,
60,
70,
1200,
48,
46,
20,
10240,
51200,
512,
0,
10,
15,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
15, -1, -1,
256, 256, 112, 256, 256, 256, 160,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4608,
80,
200,
1200,
48,
128,
20,
10240,
51200,
512,
0,
10,
15,
256,
16,
32768,
1,
23301,
23301,
13981,
256,
15, -1, -1,
256, 256, 32, 128, 256, 64, 128,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4352,
60,
70,
1200,
48,
46,
20,
5120,
0,
341,
0,
10,
15,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
15, -1, -1,
256, 256, 112, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4864,
110,
120,
1200,
64,
13,
5,
10240,
51200,
512,
0,
10,
25,
256,
16,
32768,
1,
46603,
34952,
23301,
384,
30, -1, -1,
0, 128, 48, 208, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
5120,
200,
200,
1200,
84,
13,
5,
10240,
51200,
512,
0,
10,
20,
256,
16,
32768,
1,
46603,
34952,
23301,
256,
19, -1, -1,
0, 0, 10, 10, 0, 128, 64,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
11008,
100,
200,
1200,
64,
13,
5,
2048,
5120,
512,
0,
10,
15,
256,
16,
32768,
0,
0,
0,
0,
0,
-1, -1, -1,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
11264,
100,
200,
1200,
64,
13,
5,
2048,
5120,
512,
0,
10,
10,
256,
16,
32768,
0,
0,
0,
0,
0,
-1, -1, -1,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
5376,
100,
70,
1200,
64,
25,
15,
10240,
51200,
341,
0,
10,
10,
256,
0,
32768,
1,
58254,
46603,
34952,
384,
-1, -1, -1,
0, 0, 48, 0, 0, 16, 0,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
5632,
70,
120,
1200,
80,
6,
0,
10240,
51200,
682,
0,
10,
20,
256,
16,
32768,
0,
116508,
81555,
69905,
384,
29, -1, -1,
48, 0, 48, 48, 256, 128, 192,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
5888,
10,
70,
1200,
32,
0,
0,
5120,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
7, -1, -1,
64, 256, 256, 256, 0, 64, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
6144,
10,
5,
1200,
32,
-5,
-5,
5120,
51200,
682,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
64, 256, 256, 96, 256, 64, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
6400,
25,
10,
1200,
32,
-5,
-5,
5120,
51200,
682,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
64, 128, 256, 96, 256, 64, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
6656,
75,
20,
1200,
32,
-5,
-5,
5120,
51200,
682,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
128, 256, 256, 96, 256, 64, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
6912,
100,
40,
1200,
32,
-5,
-5,
5120,
51200,
682,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
32, 16, 16, 16, 32, 32, 32,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
7168,
50,
200,
1200,
64,
37,
20,
5120,
51200,
682,
0,
10,
10,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
7, -1, -1,
48, 80, 64, 128, 0, 128, 48,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
7424,
25,
30,
1200,
32,
4,
0,
5120,
51200,
512,
0,
10,
10,
256,
16,
32768,
0,
34952,
23301,
23301,
128,
7, -1, -1,
256, 256, 256, 256, 0, 256, 192,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
7680,
10,
5,
1200,
32,
2,
0,
10240,
25600,
512,
0,
10,
10,
256,
16,
32768,
0,
23301,
23301,
13981,
384,
7, -1, -1,
256, 256, 256, 256, 256, 64, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
7936,
10,
5,
1200,
32,
3,
0,
12800,
51200,
512,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
256, 256, 256, 256, 256, 128, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
8192,
50,
65535,
1200,
64,
40,
0,
2048,
11264,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
384,
7, -1, -1,
160, 160, 128, 160, 0, 0, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
8448,
10,
65535,
1200,
32,
0,
0,
2048,
5120,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
384,
7, -1, -1,
256, 256, 256, 80, 0, 0, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
8704,
100,
65535,
1200,
64,
40,
0,
2048,
15360,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
384,
7, -1, -1,
96, 0, 128, 64, 256, 64, 160,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
8960,
20,
65535,
1200,
32,
0,
0,
2048,
5120,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
384,
7, -1, -1,
128, 0, 128, 128, 0, 0, 128,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
9216,
200,
65535,
1200,
64,
40,
0,
2048,
51200,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
0,
7, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
9472,
50,
65535,
1200,
32,
0,
0,
2048,
51200,
1024,
0,
10,
10,
256,
0,
32768,
0,
0,
0,
0,
0,
7, -1, -1,
256, 256, 128, 256, 128, 128, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
9728,
200,
1000,
1200,
64,
29,
10,
40960,
102400,
682,
0,
10,
10,
256,
0,
32768,
0,
69905,
58254,
46603,
384,
7, -1, -1,
16, 0, 16, 16, 0, 96, 48,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
9984,
100,
1000,
1200,
64,
29,
10,
20480,
51200,
682,
0,
10,
10,
256,
0,
32768,
0,
58254,
34952,
25631,
384,
7, -1, -1,
16, 0, 16, 16, 0, 96, 48,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
10240,
32, // 800,
1500,
1200,
128,
0,
0,
25600,
51200,
512,
0,
10,
10,
256,
16,
32768,
1,
58254,
58254,
34952,
384,
7, -1, -1,
3, 1, 4, 4, 0, 4, 3,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4096,
25,
20,
1200,
32,
0,
0,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
15, -1, -1,
256, 256, 96, 256, 256, 256, 192,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12032,
100,
70,
1200,
48,
0,
16,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12544,
25,
70,
1200,
48,
41,
20,
10240,
51200,
341,
0,
100,
100,
0,
0,
32768,
0,
0,
0,
0,
160,
7, 5, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4096,
30,
70,
1200,
48,
41,
20,
10240,
51200,
341,
0,
100,
100,
0,
0,
32768,
0,
46603,
34952,
13981,
160,
7, 5, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4352,
12,
70,
1200,
48,
46,
20,
10240,
51200,
341,
0,
10,
15,
256,
16,
32768,
0,
58254,
46603,
34952,
160,
7, 5, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4352,
25,
120,
1200,
48,
44,
20,
10240,
51200,
341,
0,
10,
15,
256,
16,
32768,
0,
39612,
27962,
13981,
100,
7, 5, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4096,
100,
70,
1200,
64,
38,
20,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
0,
0,
0,
0,
64,
15, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
4352,
60,
70,
1200,
48,
46,
20,
5120,
0,
341,
0,
10,
15,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
15, -1, -1,
256, 256, 112, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12544,
50,
70,
1200,
48,
46,
20,
2560,
0,
341,
0,
10,
8,
256,
16,
32768,
1,
58254,
46603,
34952,
384,
15, -1, -1,
288, 288, 288, 288, 288, 288, 288,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
11520,
25,
70,
1200,
32,
-5,
0,
2048,
51200,
341,
0,
10,
10,
256,
16,
32768,
0,
0,
0,
0,
64,
7, 5, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
12800,
40,
70,
1200,
48,
41,
20,
10240,
51200,
512,
0,
10,
8,
256,
16,
32768,
1,
46603,
34952,
13981,
256,
15, -1, -1,
256, 256, 96, 160, 256, 256, 12,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
13056,
40,
70,
1200,
48,
41,
20,
10240,
51200,
512,
0,
10,
8,
256,
16,
32768,
1,
46603,
34952,
13981,
256,
15, -1, -1,
256, 160, 96, 64, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
13312,
40,
70,
1200,
48,
41,
20,
10240,
51200,
512,
0,
10,
12,
256,
16,
32768,
1,
46603,
34952,
13981,
256,
15, -1, -1,
128, 128, 16, 16, 0, 64, 48,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
13568,
10,
5,
1200,
32,
3,
0,
12800,
51200,
512,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
160, 160, 160, 160, 256, 128, 288,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
10752,
120,
70,
1200,
48,
41,
20,
12800,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
116508,
81555,
69905,
384,
7, -1, -1,
5, 5, 15, 8, 0, 15, 15,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
13568,
10,
5,
1200,
32,
3,
0,
12800,
51200,
512,
0,
10,
10,
256,
16,
32768,
0,
58254,
46603,
34952,
384,
7, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
{
10752,
25,
70,
1200,
48,
41,
20,
12800,
51200,
341,
0,
10,
10,
256,
16,
32768,
1,
116508,
81555,
69905,
384,
7, -1, -1,
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
//254 - kDudeModernCustom
{
11520, // start sequence ID
85, // start health
75, // mass
120,
48, // clip distance
48, // eye above z
20,
10240, // hear distance
51200, // seeing distance
kAng120, // vision periphery
// 0,
618, // melee distance
5, // flee health
5, // hinder damage
0x0000, // change target chance
0x0000, // change target to kin chance
0x8000, // alertChance
0, // lockout
46603, // frontSpeed
34952, // sideSpeed
13981, // backSpeed
256, // angSpeed
// 0,
7, -1, 18, // nGibType
64, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
//255 - kDudeModernCustomBurning
{
4096, // start sequence ID
25, // start health
5, // mass
120,
48, // clip distance
41, // eye above z
20,
12800, // hear distance
51200, // seeing distance
kAng60, // vision periphery
// 0,
0, // melee distance
10, // flee health
10, // hinder damage
0x0100, // change target chance
0x0010, // change target to kin chance
0x8000, // alertChance
true, // lockout
58254, // frontSpeed
46603, // sideSpeed
34952, // backSpeed
384, // angSpeed
// 0,
7, -1, -1, // nGibType
256, 256, 256, 256, 256, 256, 256,
0, 0, 0, 0, 0, 0, 0,
0,
0
}
};
DUDEINFO gPlayerTemplate[4] =
{
// normal human
{
0x2f00,
100,
70,
1200,
0x30,
0,
0x10,
0x800,
0xc800,
0x155,
0,
10,
10,
0x100,
0x10,
0x8000,
0x1,
0,
0,
0,
0x40,
15, -1, -1,
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x120,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
// normal beast
{
0x2900,
100,
70,
1200,
0x30,
0,
0x14,
0x800,
0xc800,
0x155,
0,
10,
10,
0x100,
0x10,
0x8000,
0x1,
0,
0,
0,
0x40,
7, -1, -1,
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x120,
0, 0, 0, 0, 0, 0, 0,
0,
0
},
// shrink human
{
12032,
100,
10, // mass
1200,
16, // clipdist
0,
0x10,
0x800,
0xc800,
0x155,
0,
10,
10,
0x100,
0x10,
0x8000,
0x1,
0,
0,
0,
0x40,
15, -1, -1, // gib type
1024, 1024, 1024, 1024, 256, 1024, 1024, //damage shift
0, 0, 0, 0, 0, 0, 0,
0,
0
},
// grown human
{
12032,
100,
1100, // mass
1200,
100, // clipdist
0,
0x10,
0x800,
0xc800,
0x155,
0,
10,
10,
0x100,
0x10,
0x8000,
0x1,
0,
0,
0,
0x40,
15, 7, 7, // gib type
64, 64, 64, 64, 256, 64, 64, // damage shift
0, 0, 0, 0, 0, 0, 0,
0,
0
},
};
DUDEINFO fakeDudeInfo = {};
END_BLD_NS
| 15.380403
| 79
| 0.26573
|
madame-rachelle
|
4425c5098e3f907f285331c22e49c416e626078f
| 2,680
|
cpp
|
C++
|
Practice/2018/2018.4.12/BZOJ4298.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.4.12/BZOJ4298.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.4.12/BZOJ4298.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define ull unsigned long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=5010;
const int maxId=210;
const int maxM=maxN*2*maxId;
const int Mod=100003;
const ull hashbase=213;
const int inf=2147483647;
int n,Id,m;
int UFS[maxId][maxN],Size[maxId][maxN];
ull NodeHash[maxN];
int edgecnt=0,EHead[maxId][maxN],ENext[maxM],EV[maxM];
int hashcnt=0,HHead[maxM],HNext[maxM],Cnt[maxM];
ull HVal[maxM],HPow[maxId];
int ReuseStack[maxM],restacktop=0;
ll Ans=0;
void Insert(ull key);
void Delete(ull key);
void EAdd_Edge(int u,int v,int id);
void Union(int u,int v,int id);
void dfs(int u,int fa,int id,int anc);
int main()
{
//ios::sync_with_stdio(false);
mem(EHead,-1);mem(HHead,-1);
for (int i=1;i<maxM;i++) ReuseStack[++restacktop]=i;
scanf("%d%d%d",&Id,&n,&m);//cin>>Id>>n>>m;
HPow[1]=1;for (int i=2;i<=Id;i++) HPow[i]=HPow[i-1]*hashbase;
for (int i=1;i<=n;i++)
{
for (int j=1;j<=Id;j++) UFS[j][i]=i,Size[j][i]=1,NodeHash[i]=NodeHash[i]+(ull)i*HPow[j];
Insert(NodeHash[i]);
}
while (m--)
{
int id,u,v;scanf("%d%d%d",&u,&v,&id);//cin>>u>>v>>id;
Union(u,v,id);
printf("%lld\n",Ans);//cout<<Ans<<endl;
}
return 0;
}
void Insert(ull key)
{
ull p=key%Mod;
for (int i=HHead[p];i!=-1;i=HNext[i])
if (HVal[i]==key)
{
Ans+=Cnt[i]*2+1;Cnt[i]++;
return;
}
Ans++;
int pos=ReuseStack[restacktop--];
HNext[pos]=HHead[p];HVal[pos]=key;Cnt[pos]=1;HHead[p]=pos;
return;
}
void Delete(ull key)
{
int p=key%Mod;
if (HVal[HHead[p]]==key)
{
Cnt[HHead[p]]--;Ans=Ans-(2ll*Cnt[HHead[p]]+1);
if (Cnt[HHead[p]]==0)
{
ReuseStack[++restacktop]=HHead[p];
HHead[p]=HNext[HHead[p]];
}
return;
}
for (int i=HHead[p],last=0;i!=-1;last=i,i=HNext[i])
if (HVal[i]==key)
{
Cnt[i]--;Ans=Ans-(2ll*Cnt[i]+1);
if (Cnt[i]==0)
{
ReuseStack[++restacktop]=i;
HNext[last]=HNext[i];
}
return;
}
return;
}
void EAdd_Edge(int u,int v,int id)
{
edgecnt++;ENext[edgecnt]=EHead[id][u];EHead[id][u]=edgecnt;EV[edgecnt]=v;
return;
}
void Union(int u,int v,int id)
{
if (UFS[id][u]==UFS[id][v]) return;
//u=UFS[id][u];v=UFS[id][v];
if (Size[id][UFS[id][u]]>Size[id][UFS[id][v]]) swap(u,v);
Size[id][UFS[id][v]]+=Size[id][UFS[id][u]];
EAdd_Edge(u,v,id);EAdd_Edge(v,u,id);
dfs(u,v,id,UFS[id][v]);
return;
}
void dfs(int u,int fa,int id,int anc)
{
Delete(NodeHash[u]);
NodeHash[u]-=HPow[id]*(ull)UFS[id][u];
UFS[id][u]=anc;
NodeHash[u]+=HPow[id]*(ull)UFS[id][u];
Insert(NodeHash[u]);
for (int i=EHead[id][u];i!=-1;i=ENext[i])
if (EV[i]!=fa) dfs(EV[i],u,id,anc);
return;
}
| 21.269841
| 90
| 0.615672
|
SYCstudio
|
44273152ef0bbeb5644ad64f23b039447890dc9e
| 977
|
hpp
|
C++
|
arbor/util/config.hpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 53
|
2018-10-18T12:08:21.000Z
|
2022-03-26T22:03:51.000Z
|
arbor/util/config.hpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 864
|
2018-10-01T08:06:00.000Z
|
2022-03-31T08:06:48.000Z
|
arbor/util/config.hpp
|
kanzl/arbor
|
86b1eb065ac252bf0026de7cf7cbc6748a528254
|
[
"BSD-3-Clause"
] | 37
|
2019-03-03T16:18:49.000Z
|
2022-03-24T10:39:51.000Z
|
#pragma once
namespace arb {
namespace config {
// has_memory_measurement
// Support for measuring total allocated memory.
// * true: calls to util::allocated_memory() will return valid results
// * false: calls to util::allocated_memory() will return -1
//
// has_power_measurement
// Support for measuring energy consumption.
// Currently only on Cray XC30/40/50 systems.
// * true: calls to util::energy() will return valid results
// * false: calls to util::energy() will return -1
//
// has_gpu
// Has been compiled with CUDA/HIP back end support
#ifdef __linux__
constexpr bool has_memory_measurement = true;
#else
constexpr bool has_memory_measurement = false;
#endif
#ifdef ARB_HAVE_CRAY
constexpr bool has_power_measurement = true;
#else
constexpr bool has_power_measurement = false;
#endif
#ifdef ARB_HAVE_GPU
constexpr bool has_gpu = true;
#else
constexpr bool has_gpu = false;
#endif
} // namespace config
} // namespace arb
| 24.425
| 75
| 0.732856
|
kanzl
|
44276f528596e612acb0073f0b8b3b24fd6ef072
| 502
|
cpp
|
C++
|
src/queue.cpp
|
andryblack/pcb-printer-firmware
|
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
|
[
"MIT"
] | 1
|
2020-07-18T18:34:41.000Z
|
2020-07-18T18:34:41.000Z
|
src/queue.cpp
|
andryblack/pcb-printer-firmware
|
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
|
[
"MIT"
] | null | null | null |
src/queue.cpp
|
andryblack/pcb-printer-firmware
|
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
|
[
"MIT"
] | 1
|
2020-01-29T10:29:08.000Z
|
2020-01-29T10:29:08.000Z
|
#include "queue.h"
uint32_t Queue::w_pos = 0;
uint32_t Queue::r_pos = 0;
uint32_t Queue::size = 0;
print_t* Queue::write() {
print_t* res = &mem_overlay.print_queue[w_pos];
return res;
}
print_t* Queue::read() {
print_t* res = &mem_overlay.print_queue[r_pos];
return res;
}
void Queue::push() {
++size;
w_pos = (w_pos + 1) % max_print_queue;
}
void Queue::pop() {
if (size) {
--size;
r_pos = (r_pos + 1) % max_print_queue;
}
}
void Queue::reset() {
w_pos = 0;
r_pos = 0;
size = 0;
}
| 15.6875
| 48
| 0.629482
|
andryblack
|
442941ee745e40a642d088a0fc4b511951ee166b
| 4,020
|
cpp
|
C++
|
runtime/libpgmath/lib/common/log/fma3/fslog8.cpp
|
abrahamtovarmob/flang
|
bcd84b29df046b6d6574f0bfa34ea5059092615a
|
[
"Apache-2.0"
] | 716
|
2017-05-17T17:58:45.000Z
|
2022-03-30T11:20:58.000Z
|
runtime/libpgmath/lib/common/log/fma3/fslog8.cpp
|
abrahamtovarmob/flang
|
bcd84b29df046b6d6574f0bfa34ea5059092615a
|
[
"Apache-2.0"
] | 794
|
2017-05-18T19:27:40.000Z
|
2022-03-31T23:22:11.000Z
|
runtime/libpgmath/lib/common/log/fma3/fslog8.cpp
|
abrahamtovarmob/flang
|
bcd84b29df046b6d6574f0bfa34ea5059092615a
|
[
"Apache-2.0"
] | 157
|
2017-05-17T18:50:33.000Z
|
2022-03-30T07:06:45.000Z
|
/*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#if defined(TARGET_LINUX_POWER)
#error "Source cannot be compiled for POWER architectures"
#include "xmm2altivec.h"
#else
#include <immintrin.h>
#endif
#include "fslog_defs.h"
extern "C" __m256 __fvs_log_fma3_256(__m256);
__m256 __fvs_log_fma3_256(__m256 a) {
__m256 const LOG_C1_VEC = _mm256_set1_ps(LOG_C1);
__m256 const LOG_C2_VEC = _mm256_set1_ps(LOG_C2);
__m256 const LOG_C3_VEC = _mm256_set1_ps(LOG_C3);
__m256 const LOG_C4_VEC = _mm256_set1_ps(LOG_C4);
__m256 const LOG_C5_VEC = _mm256_set1_ps(LOG_C5);
__m256 const LOG_C6_VEC = _mm256_set1_ps(LOG_C6);
__m256 const LOG_C7_VEC = _mm256_set1_ps(LOG_C7);
__m256 const LOG_C8_VEC = _mm256_set1_ps(LOG_C8);
__m256 const LOG_C9_VEC = _mm256_set1_ps(LOG_C9);
__m256 const LOG_CA_VEC = _mm256_set1_ps(LOG_CA);
__m256i const CANONICAL_NAN_VEC = _mm256_set1_epi32(CANONICAL_NAN);
__m256i const MINUS_INF_VEC = _mm256_set1_epi32(MINUS_INF);
__m256i const NAN_INF_MASK_VEC = _mm256_set1_epi32(NAN_INF_MASK);
__m256 const PARTITION_CONST_VEC = _mm256_set1_ps(PARTITION_CONST);
__m256 const TWO_TO_M126_F_VEC = _mm256_set1_ps(TWO_TO_M126_F);
__m256 const TWO_TO_24_F_VEC = _mm256_set1_ps(TWO_TO_24_F);
__m256 const ONE_VEC = _mm256_set1_ps(1.0f);
__m256 const F24_VEC = _mm256_set1_ps(U24);
__m256i const BIT_MASK2_VEC = _mm256_set1_epi32(BIT_MASK2);
__m256i const OFFSET_VEC = _mm256_set1_epi32(OFFSET);
__m256i exp_offset_vec = _mm256_set1_epi32(EXP_OFFSET);
__m256 const FLT2INT_CVT = _mm256_set1_ps(12582912.0f);
__m256 FLT2INT_CVT_BIAS = _mm256_set1_ps(12582912.0f + 126.0f);
__m256 mask = _mm256_cmp_ps(a, TWO_TO_M126_F_VEC, _CMP_LT_OS);
__m256 fix = _mm256_blendv_ps(ONE_VEC, TWO_TO_24_F_VEC, mask);
a = _mm256_mul_ps(a, fix);
FLT2INT_CVT_BIAS = _mm256_add_ps(FLT2INT_CVT_BIAS, _mm256_and_ps(mask, F24_VEC));
__m256 tmpm;
__m256 spec;
mask = _mm256_cmp_ps(a, _mm256_set1_ps(0.0f), _CMP_LT_OS);
spec = _mm256_and_ps((__m256)CANONICAL_NAN_VEC, mask);
mask = _mm256_cmp_ps(a, _mm256_set1_ps(0.0f), _CMP_EQ_OS);
tmpm = _mm256_and_ps(mask, (__m256)MINUS_INF_VEC);
spec = _mm256_or_ps(tmpm, spec);
mask = _mm256_cmp_ps(a, (__m256)NAN_INF_MASK_VEC, _CMP_EQ_OS);
tmpm = _mm256_and_ps(mask, a);
spec = _mm256_or_ps(tmpm,spec);
mask = _mm256_cmp_ps(a, a, 4);
tmpm = _mm256_and_ps(mask, _mm256_add_ps(a,a));
spec = _mm256_or_ps(tmpm,spec);
__m256 e = (__m256)_mm256_srli_epi32((__m256i)a, 23);
e = (__m256)_mm256_add_epi32((__m256i)e, (__m256i)FLT2INT_CVT);
e = _mm256_sub_ps(e, FLT2INT_CVT_BIAS);
__m256 m = _mm256_and_ps((__m256)BIT_MASK2_VEC, a);
m = (__m256)_mm256_add_epi32((__m256i)m, OFFSET_VEC);
__m256 mask_shift = _mm256_cmp_ps(m, PARTITION_CONST_VEC, _CMP_LT_OS);
e = _mm256_sub_ps(e, _mm256_and_ps(mask_shift, _mm256_set1_ps(1.0f)));
m = _mm256_add_ps(m, _mm256_and_ps(mask_shift, m));
m = _mm256_sub_ps(m, _mm256_set1_ps(1.0f));
__m256 const LN2 = _mm256_set1_ps(0x1.62E43p-01);
e = _mm256_mul_ps(e, LN2);
__m256 t = LOG_CA_VEC;
t = _mm256_fmadd_ps(t, m, LOG_C9_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C8_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C7_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C6_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C5_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C4_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C3_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C2_VEC);
t = _mm256_fmadd_ps(t, m, LOG_C1_VEC);
__m256 m2 = _mm256_mul_ps(m, m);
t = _mm256_fmadd_ps(t, m2, m);
t = _mm256_add_ps(t, e);
t = _mm256_add_ps(t, spec);
return t;
}
| 37.924528
| 85
| 0.694776
|
abrahamtovarmob
|
44303340c02f87760a5e0fc106c87333f04e66c6
| 1,240
|
cpp
|
C++
|
0018_4Sum/0018_4Sum.cpp
|
princeroshanantony/LeetCode
|
fd77c137dfcaddcae04d0b2191fdb32cb7ee825b
|
[
"MIT"
] | null | null | null |
0018_4Sum/0018_4Sum.cpp
|
princeroshanantony/LeetCode
|
fd77c137dfcaddcae04d0b2191fdb32cb7ee825b
|
[
"MIT"
] | 2
|
2020-10-21T06:34:28.000Z
|
2020-10-23T12:13:23.000Z
|
0018_4Sum/0018_4Sum.cpp
|
princeroshanantony/LeetCode
|
fd77c137dfcaddcae04d0b2191fdb32cb7ee825b
|
[
"MIT"
] | 3
|
2020-10-21T13:03:11.000Z
|
2020-10-30T05:42:51.000Z
|
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(begin(nums), end(nums));
return kSum(nums, target, 0, 4);
}
vector<vector<int>> kSum(vector<int>& nums, int target, int start, int k) {
vector<vector<int>> res;
if (start == nums.size() || nums[start] * k > target || target > nums.back() * k)
return res;
if (k == 2)
return twoSum(nums, target, start);
for (int i = start; i < nums.size(); ++i)
if (i == start || nums[i - 1] != nums[i])
for (auto &set : kSum(nums, target - nums[i], i + 1, k - 1)) {
res.push_back({nums[i]});
res.back().insert(end(res.back()), begin(set), end(set));
}
return res;
}
vector<vector<int>> twoSum(vector<int>& nums, int target, int start) {
vector<vector<int>> res;
int lo = start, hi = nums.size() - 1;
while (lo < hi) {
int sum = nums[lo] + nums[hi];
if (sum < target || (lo > start && nums[lo] == nums[lo - 1]))
++lo;
else if (sum > target || (hi < nums.size() - 1 && nums[hi] == nums[hi + 1]))
--hi;
else
res.push_back({ nums[lo++], nums[hi--]});
}
return res;
}
};
| 35.428571
| 85
| 0.505645
|
princeroshanantony
|
44353875d7a9f13fcbf1cb4458a789ac95394da4
| 1,351
|
cpp
|
C++
|
Codeforces/1000~1999/1481/D.cpp
|
tiger0132/code-backup
|
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
|
[
"MIT"
] | 6
|
2018-12-30T06:16:54.000Z
|
2022-03-23T08:03:33.000Z
|
Codeforces/1000~1999/1481/D.cpp
|
tiger0132/code-backup
|
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
|
[
"MIT"
] | null | null | null |
Codeforces/1000~1999/1481/D.cpp
|
tiger0132/code-backup
|
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <cstdio>
#include <cstring>
const int N = 1e3 + 31;
char g[N][N];
int n, m;
int main() {
for (scanf("%*d"); ~scanf("%d%d", &n, &m);) {
for (int i = 1; i <= n; i++) scanf("%s", g[i] + 1);
if (m % 2) {
puts("YES");
for (int i = 1; i <= m + 1; i++) printf("%d%c", 2 - i % 2, " \n"[i == m + 1]);
continue;
}
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
if (g[i][j] == g[j][i]) {
puts("YES");
for (int k = 1; k <= m + 1; k++)
printf("%d%c", k % 2 ? i : j, " \n"[k == m + 1]);
goto end;
}
for (int i = 1; i <= n; i++) {
int ai = 0, ao = 0, bi = 0, bo = 0;
for (int j = 1; j <= n; j++)
if (i != j) {
if (g[j][i] == 'a') ai = j;
if (g[i][j] == 'a') ao = j;
if (g[j][i] == 'b') bi = j;
if (g[i][j] == 'b') bo = j;
}
if ((!ai || !bo) && (bi && bo)) ai = bi, ao = bo;
if (ai && ao) {
int cyc = m / 2;
puts("YES");
if (cyc % 2) {
for (int j = 1; j <= cyc / 2 + 1; j++) printf("%d %d ", ai, i);
for (int j = 1; j <= cyc / 2; j++) printf("%d %d ", ao, i);
printf("%d\n", ao);
} else {
for (int j = 1; j <= cyc / 2; j++) printf("%d %d ", i, ai);
for (int j = 1; j <= cyc / 2; j++) printf("%d %d ", i, ao);
printf("%d\n", i);
}
goto end;
}
}
puts("NO");
end:;
}
}
| 25.490566
| 81
| 0.366395
|
tiger0132
|
443ad8a8cab4aadde9a94c62e5c2c84c4024caa2
| 861
|
hpp
|
C++
|
Inc/Core/deferredFunction.hpp
|
CodogoFreddie/FredLib
|
8c7307d039f285e16a1a6979e05a071a2c18717e
|
[
"Apache-2.0"
] | 2
|
2016-04-28T22:59:58.000Z
|
2016-05-04T01:04:27.000Z
|
Inc/Core/deferredFunction.hpp
|
CodogoFreddie/FredLib
|
8c7307d039f285e16a1a6979e05a071a2c18717e
|
[
"Apache-2.0"
] | null | null | null |
Inc/Core/deferredFunction.hpp
|
CodogoFreddie/FredLib
|
8c7307d039f285e16a1a6979e05a071a2c18717e
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <functional>
#include <vector>
#include <mutex>
namespace core {
template<bool locks = true>
class DeferredFunctionQueue{
private:
std::vector<std::function<void()>> funQueue;
std::mutex mtx;
public:
DeferredFunctionQueue(){}
template<typename Ret, typename ...Args>
void push(Ret func(Args...), Args... args){
if(locks)mtx.lock();
funQueue.push_back(
std::bind(func, args...)
);
if(locks)mtx.unlock();
}
template<typename Ret = void, class Class, typename ...Args>
void push(Ret (Class::*func)(Args...), Class* inst, Args... args){
if(locks)mtx.lock();
funQueue.push_back(
std::bind(func, inst, args...)
);
if(locks)mtx.unlock();
}
void flush(){
if(locks) mtx.lock();
for(auto& fn : funQueue){
fn();
}
funQueue.clear();
if(locks) mtx.unlock();
}
};
} //core
| 16.245283
| 70
| 0.622532
|
CodogoFreddie
|
443ae662bf47af74726ca3ba33d7f9c2b8a22d02
| 81,368
|
cc
|
C++
|
libqpdf/QPDF_linearization.cc
|
freedlp/qpdf
|
38d8362c09e1d41c85f808995ad93a3bed238cf7
|
[
"Apache-2.0"
] | null | null | null |
libqpdf/QPDF_linearization.cc
|
freedlp/qpdf
|
38d8362c09e1d41c85f808995ad93a3bed238cf7
|
[
"Apache-2.0"
] | null | null | null |
libqpdf/QPDF_linearization.cc
|
freedlp/qpdf
|
38d8362c09e1d41c85f808995ad93a3bed238cf7
|
[
"Apache-2.0"
] | null | null | null |
// See doc/linearization.
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/Pl_Buffer.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_Count.hh>
#include <qpdf/BitWriter.hh>
#include <qpdf/BitStream.hh>
#include <iostream>
#include <algorithm>
#include <assert.h>
#include <math.h>
#include <string.h>
template <class T, class int_type>
static void
load_vector_int(BitStream& bit_stream, int nitems, std::vector<T>& vec,
int bits_wanted, int_type T::*field)
{
bool append = vec.empty();
// nitems times, read bits_wanted from the given bit stream,
// storing results in the ith vector entry.
for (size_t i = 0; i < QIntC::to_size(nitems); ++i)
{
if (append)
{
vec.push_back(T());
}
vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted));
}
if (QIntC::to_int(vec.size()) != nitems)
{
throw std::logic_error("vector has wrong size in load_vector_int");
}
// The PDF spec says that each hint table starts at a byte
// boundary. Each "row" actually must start on a byte boundary.
bit_stream.skipToNextByte();
}
template <class T>
static void
load_vector_vector(BitStream& bit_stream,
int nitems1, std::vector<T>& vec1, int T::*nitems2,
int bits_wanted, std::vector<int> T::*vec2)
{
// nitems1 times, read nitems2 (from the ith element of vec1) items
// into the vec2 vector field of the ith item of vec1.
for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1)
{
for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2)
{
(vec1.at(i1).*vec2).push_back(
bit_stream.getBitsInt(QIntC::to_size(bits_wanted)));
}
}
bit_stream.skipToNextByte();
}
bool
QPDF::checkLinearization()
{
bool result = false;
try
{
readLinearizationData();
result = checkLinearizationInternal();
}
catch (std::runtime_error& e)
{
*this->m->err_stream
<< "WARNING: error encountered while checking linearization data: "
<< e.what() << std::endl;
}
return result;
}
bool
QPDF::isLinearized()
{
// If the first object in the file is a dictionary with a suitable
// /Linearized key and has an /L key that accurately indicates the
// file size, initialize this->m->lindict and return true.
// A linearized PDF spec's first object will be contained within
// the first 1024 bytes of the file and will be a dictionary with
// a valid /Linearized key. This routine looks for that and does
// no additional validation.
// The PDF spec says the linearization dictionary must be
// completely contained within the first 1024 bytes of the file.
// Add a byte for a null terminator.
static int const tbuf_size = 1025;
auto b = std::make_unique<char[]>(tbuf_size);
char* buf = b.get();
this->m->file->seek(0, SEEK_SET);
memset(buf, '\0', tbuf_size);
this->m->file->read(buf, tbuf_size - 1);
int lindict_obj = -1;
char* p = buf;
while (lindict_obj == -1)
{
// Find a digit or end of buffer
while (((p - buf) < tbuf_size) && (! QUtil::is_digit(*p)))
{
++p;
}
if (p - buf == tbuf_size)
{
break;
}
// Seek to the digit. Then skip over digits for a potential
// next iteration.
this->m->file->seek(p - buf, SEEK_SET);
while (((p - buf) < tbuf_size) && QUtil::is_digit(*p))
{
++p;
}
QPDFTokenizer::Token t1 = readToken(this->m->file);
QPDFTokenizer::Token t2 = readToken(this->m->file);
QPDFTokenizer::Token t3 = readToken(this->m->file);
QPDFTokenizer::Token t4 = readToken(this->m->file);
if ((t1.getType() == QPDFTokenizer::tt_integer) &&
(t2.getType() == QPDFTokenizer::tt_integer) &&
(t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")) &&
(t4.getType() == QPDFTokenizer::tt_dict_open))
{
lindict_obj =
QIntC::to_int(QUtil::string_to_ll(t1.getValue().c_str()));
}
}
if (lindict_obj <= 0)
{
return false;
}
QPDFObjectHandle candidate = QPDFObjectHandle::Factory::newIndirect(
this, lindict_obj, 0);
if (! candidate.isDictionary())
{
return false;
}
QPDFObjectHandle linkey = candidate.getKey("/Linearized");
if (! (linkey.isNumber() &&
(QIntC::to_int(floor(linkey.getNumericValue())) == 1)))
{
return false;
}
QPDFObjectHandle L = candidate.getKey("/L");
if (L.isInteger())
{
qpdf_offset_t Li = L.getIntValue();
this->m->file->seek(0, SEEK_END);
if (Li != this->m->file->tell())
{
QTC::TC("qpdf", "QPDF /L mismatch");
return false;
}
else
{
this->m->linp.file_size = Li;
}
}
this->m->lindict = candidate;
return true;
}
void
QPDF::readLinearizationData()
{
// This function throws an exception (which is trapped by
// checkLinearization()) for any errors that prevent loading.
// Hint table parsing code needs at least 32 bits in a long.
assert(sizeof(long) >= 4);
if (! isLinearized())
{
throw std::logic_error("called readLinearizationData for file"
" that is not linearized");
}
// /L is read and stored in linp by isLinearized()
QPDFObjectHandle H = this->m->lindict.getKey("/H");
QPDFObjectHandle O = this->m->lindict.getKey("/O");
QPDFObjectHandle E = this->m->lindict.getKey("/E");
QPDFObjectHandle N = this->m->lindict.getKey("/N");
QPDFObjectHandle T = this->m->lindict.getKey("/T");
QPDFObjectHandle P = this->m->lindict.getKey("/P");
if (! (H.isArray() &&
O.isInteger() &&
E.isInteger() &&
N.isInteger() &&
T.isInteger() &&
(P.isInteger() || P.isNull())))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization dictionary",
this->m->file->getLastOffset(),
"some keys in linearization dictionary are of "
"the wrong type");
}
// Hint table array: offset length [ offset length ]
size_t n_H_items = toS(H.getArrayNItems());
if (! ((n_H_items == 2) || (n_H_items == 4)))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization dictionary",
this->m->file->getLastOffset(),
"H has the wrong number of items");
}
std::vector<int> H_items;
for (size_t i = 0; i < n_H_items; ++i)
{
QPDFObjectHandle oh(H.getArrayItem(toI(i)));
if (oh.isInteger())
{
H_items.push_back(oh.getIntValueAsInt());
}
else
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization dictionary",
this->m->file->getLastOffset(),
"some H items are of the wrong type");
}
}
// H: hint table offset/length for primary and overflow hint tables
int H0_offset = H_items.at(0);
int H0_length = H_items.at(1);
int H1_offset = 0;
int H1_length = 0;
if (H_items.size() == 4)
{
// Acrobat doesn't read or write these (as PDF 1.4), so we
// don't have a way to generate a test case.
// QTC::TC("qpdf", "QPDF overflow hint table");
H1_offset = H_items.at(2);
H1_length = H_items.at(3);
}
// P: first page number
int first_page = 0;
if (P.isInteger())
{
QTC::TC("qpdf", "QPDF P present in lindict");
first_page = P.getIntValueAsInt();
}
else
{
QTC::TC("qpdf", "QPDF P absent in lindict");
}
// Store linearization parameter data
// Various places in the code use linp.npages, which is
// initialized from N, to pre-allocate memory, so make sure it's
// accurate and bail right now if it's not.
if (N.getIntValue() != static_cast<long long>(getAllPages().size()))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization hint table",
this->m->file->getLastOffset(),
"/N does not match number of pages");
}
// file_size initialized by isLinearized()
this->m->linp.first_page_object = O.getIntValueAsInt();
this->m->linp.first_page_end = E.getIntValue();
this->m->linp.npages = N.getIntValueAsInt();
this->m->linp.xref_zero_offset = T.getIntValue();
this->m->linp.first_page = first_page;
this->m->linp.H_offset = H0_offset;
this->m->linp.H_length = H0_length;
// Read hint streams
Pl_Buffer pb("hint buffer");
QPDFObjectHandle H0 = readHintStream(pb, H0_offset, toS(H0_length));
if (H1_offset)
{
(void) readHintStream(pb, H1_offset, toS(H1_length));
}
// PDF 1.4 hint tables that we ignore:
// /T thumbnail
// /A thread information
// /E named destination
// /V interactive form
// /I information dictionary
// /C logical structure
// /L page label
// Individual hint table offsets
QPDFObjectHandle HS = H0.getKey("/S"); // shared object
QPDFObjectHandle HO = H0.getKey("/O"); // outline
auto hbp = pb.getBufferSharedPointer();
Buffer* hb = hbp.get();
unsigned char const* h_buf = hb->getBuffer();
size_t h_size = hb->getSize();
readHPageOffset(BitStream(h_buf, h_size));
int HSi = HS.getIntValueAsInt();
if ((HSi < 0) || (toS(HSi) >= h_size))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization hint table",
this->m->file->getLastOffset(),
"/S (shared object) offset is out of bounds");
}
readHSharedObject(BitStream(h_buf + HSi, h_size - toS(HSi)));
if (HO.isInteger())
{
int HOi = HO.getIntValueAsInt();
if ((HOi < 0) || (toS(HOi) >= h_size))
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization hint table",
this->m->file->getLastOffset(),
"/O (outline) offset is out of bounds");
}
readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)),
this->m->outline_hints);
}
}
QPDFObjectHandle
QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length)
{
int obj;
int gen;
QPDFObjectHandle H = readObjectAtOffset(
false, offset, "linearization hint stream", -1, 0, obj, gen);
ObjCache& oc = this->m->obj_cache[QPDFObjGen(obj, gen)];
qpdf_offset_t min_end_offset = oc.end_before_space;
qpdf_offset_t max_end_offset = oc.end_after_space;
if (! H.isStream())
{
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization dictionary",
this->m->file->getLastOffset(),
"hint table is not a stream");
}
QPDFObjectHandle Hdict = H.getDict();
// Some versions of Acrobat make /Length indirect and place it
// immediately after the stream, increasing length to cover it,
// even though the specification says all objects in the
// linearization parameter dictionary must be direct. We have to
// get the file position of the end of length in this case.
QPDFObjectHandle length_obj = Hdict.getKey("/Length");
if (length_obj.isIndirect())
{
QTC::TC("qpdf", "QPDF hint table length indirect");
// Force resolution
(void) length_obj.getIntValue();
ObjCache& oc2 = this->m->obj_cache[length_obj.getObjGen()];
min_end_offset = oc2.end_before_space;
max_end_offset = oc2.end_after_space;
}
else
{
QTC::TC("qpdf", "QPDF hint table length direct");
}
qpdf_offset_t computed_end = offset + toO(length);
if ((computed_end < min_end_offset) ||
(computed_end > max_end_offset))
{
*this->m->err_stream << "expected = " << computed_end
<< "; actual = " << min_end_offset << ".."
<< max_end_offset << std::endl;
throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),
"linearization dictionary",
this->m->file->getLastOffset(),
"hint table length mismatch");
}
H.pipeStreamData(&pl, 0, qpdf_dl_specialized);
return Hdict;
}
void
QPDF::readHPageOffset(BitStream h)
{
// All comments referring to the PDF spec refer to the spec for
// version 1.4.
HPageOffset& t = this->m->page_offset_hints;
t.min_nobjects = h.getBitsInt(32); // 1
t.first_page_offset = h.getBitsInt(32); // 2
t.nbits_delta_nobjects = h.getBitsInt(16); // 3
t.min_page_length = h.getBitsInt(32); // 4
t.nbits_delta_page_length = h.getBitsInt(16); // 5
t.min_content_offset = h.getBitsInt(32); // 6
t.nbits_delta_content_offset = h.getBitsInt(16); // 7
t.min_content_length = h.getBitsInt(32); // 8
t.nbits_delta_content_length = h.getBitsInt(16); // 9
t.nbits_nshared_objects = h.getBitsInt(16); // 10
t.nbits_shared_identifier = h.getBitsInt(16); // 11
t.nbits_shared_numerator = h.getBitsInt(16); // 12
t.shared_denominator = h.getBitsInt(16); // 13
std::vector<HPageOffsetEntry>& entries = t.entries;
entries.clear();
int nitems = this->m->linp.npages;
load_vector_int(h, nitems, entries,
t.nbits_delta_nobjects,
&HPageOffsetEntry::delta_nobjects);
load_vector_int(h, nitems, entries,
t.nbits_delta_page_length,
&HPageOffsetEntry::delta_page_length);
load_vector_int(h, nitems, entries,
t.nbits_nshared_objects,
&HPageOffsetEntry::nshared_objects);
load_vector_vector(h, nitems, entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_identifier,
&HPageOffsetEntry::shared_identifiers);
load_vector_vector(h, nitems, entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_numerator,
&HPageOffsetEntry::shared_numerators);
load_vector_int(h, nitems, entries,
t.nbits_delta_content_offset,
&HPageOffsetEntry::delta_content_offset);
load_vector_int(h, nitems, entries,
t.nbits_delta_content_length,
&HPageOffsetEntry::delta_content_length);
}
void
QPDF::readHSharedObject(BitStream h)
{
HSharedObject& t = this->m->shared_object_hints;
t.first_shared_obj = h.getBitsInt(32); // 1
t.first_shared_offset = h.getBitsInt(32); // 2
t.nshared_first_page = h.getBitsInt(32); // 3
t.nshared_total = h.getBitsInt(32); // 4
t.nbits_nobjects = h.getBitsInt(16); // 5
t.min_group_length = h.getBitsInt(32); // 6
t.nbits_delta_group_length = h.getBitsInt(16); // 7
QTC::TC("qpdf", "QPDF lin nshared_total > nshared_first_page",
(t.nshared_total > t.nshared_first_page) ? 1 : 0);
std::vector<HSharedObjectEntry>& entries = t.entries;
entries.clear();
int nitems = t.nshared_total;
load_vector_int(h, nitems, entries,
t.nbits_delta_group_length,
&HSharedObjectEntry::delta_group_length);
load_vector_int(h, nitems, entries,
1, &HSharedObjectEntry::signature_present);
for (size_t i = 0; i < toS(nitems); ++i)
{
if (entries.at(i).signature_present)
{
// Skip 128-bit MD5 hash. These are not supported by
// acrobat, so they should probably never be there. We
// have no test case for this.
for (int j = 0; j < 4; ++j)
{
(void) h.getBits(32);
}
}
}
load_vector_int(h, nitems, entries,
t.nbits_nobjects,
&HSharedObjectEntry::nobjects_minus_one);
}
void
QPDF::readHGeneric(BitStream h, HGeneric& t)
{
t.first_object = h.getBitsInt(32); // 1
t.first_object_offset = h.getBitsInt(32); // 2
t.nobjects = h.getBitsInt(32); // 3
t.group_length = h.getBitsInt(32); // 4
}
bool
QPDF::checkLinearizationInternal()
{
// All comments referring to the PDF spec refer to the spec for
// version 1.4.
std::list<std::string> errors;
std::list<std::string> warnings;
// Check all values in linearization parameter dictionary
LinParameters& p = this->m->linp;
// L: file size in bytes -- checked by isLinearized
// O: object number of first page
std::vector<QPDFObjectHandle> const& pages = getAllPages();
if (p.first_page_object != pages.at(0).getObjectID())
{
QTC::TC("qpdf", "QPDF err /O mismatch");
errors.push_back("first page object (/O) mismatch");
}
// N: number of pages
int npages = toI(pages.size());
if (p.npages != npages)
{
// Not tested in the test suite
errors.push_back("page count (/N) mismatch");
}
for (size_t i = 0; i < toS(npages); ++i)
{
QPDFObjectHandle const& page = pages.at(i);
QPDFObjGen og(page.getObjGen());
if (this->m->xref_table[og].getType() == 2)
{
errors.push_back("page dictionary for page " +
QUtil::uint_to_string(i) + " is compressed");
}
}
// T: offset of whitespace character preceding xref entry for object 0
this->m->file->seek(p.xref_zero_offset, SEEK_SET);
while (1)
{
char ch;
this->m->file->read(&ch, 1);
if (! ((ch == ' ') || (ch == '\r') || (ch == '\n')))
{
this->m->file->seek(-1, SEEK_CUR);
break;
}
}
if (this->m->file->tell() != this->m->first_xref_item_offset)
{
QTC::TC("qpdf", "QPDF err /T mismatch");
errors.push_back("space before first xref item (/T) mismatch "
"(computed = " +
QUtil::int_to_string(this->m->first_xref_item_offset) +
"; file = " +
QUtil::int_to_string(this->m->file->tell()));
}
// P: first page number -- Implementation note 124 says Acrobat
// ignores this value, so we will too.
// Check numbering of compressed objects in each xref section.
// For linearized files, all compressed objects are supposed to be
// at the end of the containing xref section if any object streams
// are in use.
if (this->m->uncompressed_after_compressed)
{
errors.push_back("linearized file contains an uncompressed object"
" after a compressed one in a cross-reference stream");
}
// Further checking requires optimization and order calculation.
// Don't allow optimization to make changes. If it has to, then
// the file is not properly linearized. We use the xref table to
// figure out which objects are compressed and which are
// uncompressed.
{ // local scope
std::map<int, int> object_stream_data;
for (std::map<QPDFObjGen, QPDFXRefEntry>::const_iterator iter =
this->m->xref_table.begin();
iter != this->m->xref_table.end(); ++iter)
{
QPDFObjGen const& og = (*iter).first;
QPDFXRefEntry const& entry = (*iter).second;
if (entry.getType() == 2)
{
object_stream_data[og.getObj()] = entry.getObjStreamNumber();
}
}
optimize(object_stream_data, false);
calculateLinearizationData(object_stream_data);
}
// E: offset of end of first page -- Implementation note 123 says
// Acrobat includes on extra object here by mistake. pdlin fails
// to place thumbnail images in section 9, so when thumbnails are
// present, it also gets the wrong value for /E. It also doesn't
// count outlines here when it should even though it places them
// in part 6. This code fails to put thread information
// dictionaries in part 9, so it actually gets the wrong value for
// E when threads are present. In that case, it would probably
// agree with pdlin. As of this writing, the test suite doesn't
// contain any files with threads.
if (this->m->part6.empty())
{
stopOnError("linearization part 6 unexpectedly empty");
}
qpdf_offset_t min_E = -1;
qpdf_offset_t max_E = -1;
for (std::vector<QPDFObjectHandle>::iterator iter = this->m->part6.begin();
iter != this->m->part6.end(); ++iter)
{
QPDFObjGen og((*iter).getObjGen());
if (this->m->obj_cache.count(og) == 0)
{
// All objects have to have been dereferenced to be classified.
throw std::logic_error("linearization part6 object not in cache");
}
ObjCache const& oc = this->m->obj_cache[og];
min_E = std::max(min_E, oc.end_before_space);
max_E = std::max(max_E, oc.end_after_space);
}
if ((p.first_page_end < min_E) || (p.first_page_end > max_E))
{
QTC::TC("qpdf", "QPDF warn /E mismatch");
warnings.push_back("end of first page section (/E) mismatch: /E = " +
QUtil::int_to_string(p.first_page_end) +
"; computed = " +
QUtil::int_to_string(min_E) + ".." +
QUtil::int_to_string(max_E));
}
// Check hint tables
std::map<int, int> shared_idx_to_obj;
checkHSharedObject(errors, warnings, pages, shared_idx_to_obj);
checkHPageOffset(errors, warnings, pages, shared_idx_to_obj);
checkHOutlines(warnings);
// Report errors
bool result = true;
// Treat all linearization errors as warnings. Many of them occur
// in otherwise working files, so it's really misleading to treat
// them as errors. We'll hang onto the distinction in the code for
// now in case we ever have a chance to clean up the linearization
// code.
if (! errors.empty())
{
result = false;
for (std::list<std::string>::iterator iter = errors.begin();
iter != errors.end(); ++iter)
{
*this->m->err_stream << "WARNING: " << (*iter) << std::endl;
}
}
if (! warnings.empty())
{
result = false;
for (std::list<std::string>::iterator iter = warnings.begin();
iter != warnings.end(); ++iter)
{
*this->m->err_stream << "WARNING: " << (*iter) << std::endl;
}
}
return result;
}
qpdf_offset_t
QPDF::maxEnd(ObjUser const& ou)
{
if (this->m->obj_user_to_objects.count(ou) == 0)
{
stopOnError("no entry in object user table for requested object user");
}
std::set<QPDFObjGen> const& ogs = this->m->obj_user_to_objects[ou];
qpdf_offset_t end = 0;
for (std::set<QPDFObjGen>::const_iterator iter = ogs.begin();
iter != ogs.end(); ++iter)
{
QPDFObjGen const& og = *iter;
if (this->m->obj_cache.count(og) == 0)
{
stopOnError("unknown object referenced in object user table");
}
end = std::max(end, this->m->obj_cache[og].end_after_space);
}
return end;
}
qpdf_offset_t
QPDF::getLinearizationOffset(QPDFObjGen const& og)
{
QPDFXRefEntry entry = this->m->xref_table[og];
qpdf_offset_t result = 0;
switch (entry.getType())
{
case 1:
result = entry.getOffset();
break;
case 2:
// For compressed objects, return the offset of the object
// stream that contains them.
result = getLinearizationOffset(
QPDFObjGen(entry.getObjStreamNumber(), 0));
break;
default:
stopOnError(
"getLinearizationOffset called for xref entry not of type 1 or 2");
break;
}
return result;
}
QPDFObjectHandle
QPDF::getUncompressedObject(QPDFObjectHandle& obj,
std::map<int, int> const& object_stream_data)
{
if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0))
{
return obj;
}
else
{
int repl = (*(object_stream_data.find(obj.getObjectID()))).second;
return objGenToIndirect(QPDFObjGen(repl, 0));
}
}
int
QPDF::lengthNextN(int first_object, int n,
std::list<std::string>& errors)
{
int length = 0;
for (int i = 0; i < n; ++i)
{
QPDFObjGen og(first_object + i, 0);
if (this->m->xref_table.count(og) == 0)
{
errors.push_back(
"no xref table entry for " +
QUtil::int_to_string(first_object + i) + " 0");
}
else
{
if (this->m->obj_cache.count(og) == 0)
{
stopOnError("found unknown object while"
" calculating length for linearization data");
}
length += toI(this->m->obj_cache[og].end_after_space -
getLinearizationOffset(og));
}
}
return length;
}
void
QPDF::checkHPageOffset(std::list<std::string>& errors,
std::list<std::string>& warnings,
std::vector<QPDFObjectHandle> const& pages,
std::map<int, int>& shared_idx_to_obj)
{
// Implementation note 126 says Acrobat always sets
// delta_content_offset and delta_content_length in the page
// offset header dictionary to 0. It also states that
// min_content_offset in the per-page information is always 0,
// which is an incorrect value.
// Implementation note 127 explains that Acrobat always sets item
// 8 (min_content_length) to zero, item 9
// (nbits_delta_content_length) to the value of item 5
// (nbits_delta_page_length), and item 7 of each per-page hint
// table (delta_content_length) to item 2 (delta_page_length) of
// that entry. Acrobat ignores these values when reading files.
// Empirically, it also seems that Acrobat sometimes puts items
// under a page's /Resources dictionary in with shared objects
// even when they are private.
int npages = toI(pages.size());
qpdf_offset_t table_offset = adjusted_offset(
this->m->page_offset_hints.first_page_offset);
QPDFObjGen first_page_og(pages.at(0).getObjGen());
if (this->m->xref_table.count(first_page_og) == 0)
{
stopOnError("supposed first page object is not known");
}
qpdf_offset_t offset = getLinearizationOffset(first_page_og);
if (table_offset != offset)
{
warnings.push_back("first page object offset mismatch");
}
for (int pageno = 0; pageno < npages; ++pageno)
{
QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen());
int first_object = page_og.getObj();
if (this->m->xref_table.count(page_og) == 0)
{
stopOnError("unknown object in page offset hint table");
}
offset = getLinearizationOffset(page_og);
HPageOffsetEntry& he =
this->m->page_offset_hints.entries.at(toS(pageno));
CHPageOffsetEntry& ce =
this->m->c_page_offset_data.entries.at(toS(pageno));
int h_nobjects = he.delta_nobjects +
this->m->page_offset_hints.min_nobjects;
if (h_nobjects != ce.nobjects)
{
// This happens with pdlin when there are thumbnails.
warnings.push_back(
"object count mismatch for page " +
QUtil::int_to_string(pageno) + ": hint table = " +
QUtil::int_to_string(h_nobjects) + "; computed = " +
QUtil::int_to_string(ce.nobjects));
}
// Use value for number of objects in hint table rather than
// computed value if there is a discrepancy.
int length = lengthNextN(first_object, h_nobjects, errors);
int h_length = toI(he.delta_page_length +
this->m->page_offset_hints.min_page_length);
if (length != h_length)
{
// This condition almost certainly indicates a bad hint
// table or a bug in this code.
errors.push_back(
"page length mismatch for page " +
QUtil::int_to_string(pageno) + ": hint table = " +
QUtil::int_to_string(h_length) + "; computed length = " +
QUtil::int_to_string(length) + " (offset = " +
QUtil::int_to_string(offset) + ")");
}
offset += h_length;
// Translate shared object indexes to object numbers.
std::set<int> hint_shared;
std::set<int> computed_shared;
if ((pageno == 0) && (he.nshared_objects > 0))
{
// pdlin and Acrobat both do this even though the spec
// states clearly and unambiguously that they should not.
warnings.push_back("page 0 has shared identifier entries");
}
for (size_t i = 0; i < toS(he.nshared_objects); ++i)
{
int idx = he.shared_identifiers.at(i);
if (shared_idx_to_obj.count(idx) == 0)
{
stopOnError(
"unable to get object for item in"
" shared objects hint table");
}
hint_shared.insert(shared_idx_to_obj[idx]);
}
for (size_t i = 0; i < toS(ce.nshared_objects); ++i)
{
int idx = ce.shared_identifiers.at(i);
if (idx >= this->m->c_shared_object_data.nshared_total)
{
stopOnError(
"index out of bounds for shared object hint table");
}
int obj = this->m->c_shared_object_data.entries.at(toS(idx)).object;
computed_shared.insert(obj);
}
for (std::set<int>::iterator iter = hint_shared.begin();
iter != hint_shared.end(); ++iter)
{
if (! computed_shared.count(*iter))
{
// pdlin puts thumbnails here even though it shouldn't
warnings.push_back(
"page " + QUtil::int_to_string(pageno) +
": shared object " + QUtil::int_to_string(*iter) +
": in hint table but not computed list");
}
}
for (std::set<int>::iterator iter = computed_shared.begin();
iter != computed_shared.end(); ++iter)
{
if (! hint_shared.count(*iter))
{
// Acrobat does not put some things including at least
// built-in fonts and procsets here, at least in some
// cases.
warnings.push_back(
"page " + QUtil::int_to_string(pageno) +
": shared object " + QUtil::int_to_string(*iter) +
": in computed list but not hint table");
}
}
}
}
void
QPDF::checkHSharedObject(std::list<std::string>& errors,
std::list<std::string>& warnings,
std::vector<QPDFObjectHandle> const& pages,
std::map<int, int>& idx_to_obj)
{
// Implementation note 125 says shared object groups always
// contain only one object. Implementation note 128 says that
// Acrobat always nbits_nobjects to zero. Implementation note 130
// says that Acrobat does not support more than one shared object
// per group. These are all consistent.
// Implementation note 129 states that MD5 signatures are not
// implemented in Acrobat, so signature_present must always be
// zero.
// Implementation note 131 states that first_shared_obj and
// first_shared_offset have meaningless values for single-page
// files.
// Empirically, Acrobat and pdlin generate incorrect values for
// these whenever there are no shared objects not referenced by
// the first page (i.e., nshared_total == nshared_first_page).
HSharedObject& so = this->m->shared_object_hints;
if (so.nshared_total < so.nshared_first_page)
{
errors.push_back("shared object hint table: ntotal < nfirst_page");
}
else
{
// The first nshared_first_page objects are consecutive
// objects starting with the first page object. The rest are
// consecutive starting from the first_shared_obj object.
int cur_object = pages.at(0).getObjectID();
for (int i = 0; i < so.nshared_total; ++i)
{
if (i == so.nshared_first_page)
{
QTC::TC("qpdf", "QPDF lin check shared past first page");
if (this->m->part8.empty())
{
errors.push_back(
"part 8 is empty but nshared_total > "
"nshared_first_page");
}
else
{
int obj = this->m->part8.at(0).getObjectID();
if (obj != so.first_shared_obj)
{
errors.push_back(
"first shared object number mismatch: "
"hint table = " +
QUtil::int_to_string(so.first_shared_obj) +
"; computed = " +
QUtil::int_to_string(obj));
}
}
cur_object = so.first_shared_obj;
QPDFObjGen og(cur_object, 0);
if (this->m->xref_table.count(og) == 0)
{
stopOnError("unknown object in shared object hint table");
}
qpdf_offset_t offset = getLinearizationOffset(og);
qpdf_offset_t h_offset =
adjusted_offset(so.first_shared_offset);
if (offset != h_offset)
{
errors.push_back(
"first shared object offset mismatch: hint table = " +
QUtil::int_to_string(h_offset) + "; computed = " +
QUtil::int_to_string(offset));
}
}
idx_to_obj[i] = cur_object;
HSharedObjectEntry& se = so.entries.at(toS(i));
int nobjects = se.nobjects_minus_one + 1;
int length = lengthNextN(cur_object, nobjects, errors);
int h_length = so.min_group_length + se.delta_group_length;
if (length != h_length)
{
errors.push_back(
"shared object " + QUtil::int_to_string(i) +
" length mismatch: hint table = " +
QUtil::int_to_string(h_length) + "; computed = " +
QUtil::int_to_string(length));
}
cur_object += nobjects;
}
}
}
void
QPDF::checkHOutlines(std::list<std::string>& warnings)
{
// Empirically, Acrobat generates the correct value for the object
// number but incorrectly stores the next object number's offset
// as the offset, at least when outlines appear in part 6. It
// also generates an incorrect value for length (specifically, the
// length that would cover the correct number of objects from the
// wrong starting place). pdlin appears to generate correct
// values in those cases.
if (this->m->c_outline_data.nobjects == this->m->outline_hints.nobjects)
{
if (this->m->c_outline_data.nobjects == 0)
{
return;
}
if (this->m->c_outline_data.first_object ==
this->m->outline_hints.first_object)
{
// Check length and offset. Acrobat gets these wrong.
QPDFObjectHandle outlines = getRoot().getKey("/Outlines");
if (! outlines.isIndirect())
{
// This case is not exercised in test suite since not
// permitted by the spec, but if this does occur, the
// code below would fail.
warnings.push_back(
"/Outlines key of root dictionary is not indirect");
return;
}
QPDFObjGen og(outlines.getObjGen());
if (this->m->xref_table.count(og) == 0)
{
stopOnError("unknown object in outlines hint table");
}
qpdf_offset_t offset = getLinearizationOffset(og);
ObjUser ou(ObjUser::ou_root_key, "/Outlines");
int length = toI(maxEnd(ou) - offset);
qpdf_offset_t table_offset =
adjusted_offset(this->m->outline_hints.first_object_offset);
if (offset != table_offset)
{
warnings.push_back(
"incorrect offset in outlines table: hint table = " +
QUtil::int_to_string(table_offset) +
"; computed = " + QUtil::int_to_string(offset));
}
int table_length = this->m->outline_hints.group_length;
if (length != table_length)
{
warnings.push_back(
"incorrect length in outlines table: hint table = " +
QUtil::int_to_string(table_length) +
"; computed = " + QUtil::int_to_string(length));
}
}
else
{
warnings.push_back("incorrect first object number in outline "
"hints table.");
}
}
else
{
warnings.push_back("incorrect object count in outline hint table");
}
}
void
QPDF::showLinearizationData()
{
try
{
readLinearizationData();
checkLinearizationInternal();
dumpLinearizationDataInternal();
}
catch (QPDFExc& e)
{
*this->m->err_stream << e.what() << std::endl;
}
}
void
QPDF::dumpLinearizationDataInternal()
{
*this->m->out_stream
<< this->m->file->getName() << ": linearization data:" << std::endl
<< std::endl;
*this->m->out_stream
<< "file_size: " << this->m->linp.file_size << std::endl
<< "first_page_object: " << this->m->linp.first_page_object << std::endl
<< "first_page_end: " << this->m->linp.first_page_end << std::endl
<< "npages: " << this->m->linp.npages << std::endl
<< "xref_zero_offset: " << this->m->linp.xref_zero_offset << std::endl
<< "first_page: " << this->m->linp.first_page << std::endl
<< "H_offset: " << this->m->linp.H_offset << std::endl
<< "H_length: " << this->m->linp.H_length << std::endl
<< std::endl;
*this->m->out_stream << "Page Offsets Hint Table" << std::endl
<< std::endl;
dumpHPageOffset();
*this->m->out_stream << std::endl
<< "Shared Objects Hint Table" << std::endl
<< std::endl;
dumpHSharedObject();
if (this->m->outline_hints.nobjects > 0)
{
*this->m->out_stream << std::endl
<< "Outlines Hint Table" << std::endl
<< std::endl;
dumpHGeneric(this->m->outline_hints);
}
}
qpdf_offset_t
QPDF::adjusted_offset(qpdf_offset_t offset)
{
// All offsets >= H_offset have to be increased by H_length
// since all hint table location values disregard the hint table
// itself.
if (offset >= this->m->linp.H_offset)
{
return offset + this->m->linp.H_length;
}
return offset;
}
void
QPDF::dumpHPageOffset()
{
HPageOffset& t = this->m->page_offset_hints;
*this->m->out_stream
<< "min_nobjects: " << t.min_nobjects
<< std::endl
<< "first_page_offset: " << adjusted_offset(t.first_page_offset)
<< std::endl
<< "nbits_delta_nobjects: " << t.nbits_delta_nobjects
<< std::endl
<< "min_page_length: " << t.min_page_length
<< std::endl
<< "nbits_delta_page_length: " << t.nbits_delta_page_length
<< std::endl
<< "min_content_offset: " << t.min_content_offset
<< std::endl
<< "nbits_delta_content_offset: " << t.nbits_delta_content_offset
<< std::endl
<< "min_content_length: " << t.min_content_length
<< std::endl
<< "nbits_delta_content_length: " << t.nbits_delta_content_length
<< std::endl
<< "nbits_nshared_objects: " << t.nbits_nshared_objects
<< std::endl
<< "nbits_shared_identifier: " << t.nbits_shared_identifier
<< std::endl
<< "nbits_shared_numerator: " << t.nbits_shared_numerator
<< std::endl
<< "shared_denominator: " << t.shared_denominator
<< std::endl;
for (size_t i1 = 0; i1 < toS(this->m->linp.npages); ++i1)
{
HPageOffsetEntry& pe = t.entries.at(i1);
*this->m->out_stream
<< "Page " << i1 << ":" << std::endl
<< " nobjects: " << pe.delta_nobjects + t.min_nobjects
<< std::endl
<< " length: " << pe.delta_page_length + t.min_page_length
<< std::endl
// content offset is relative to page, not file
<< " content_offset: "
<< pe.delta_content_offset + t.min_content_offset << std::endl
<< " content_length: "
<< pe.delta_content_length + t.min_content_length << std::endl
<< " nshared_objects: " << pe.nshared_objects << std::endl;
for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2)
{
*this->m->out_stream << " identifier " << i2 << ": "
<< pe.shared_identifiers.at(i2) << std::endl;
*this->m->out_stream << " numerator " << i2 << ": "
<< pe.shared_numerators.at(i2) << std::endl;
}
}
}
void
QPDF::dumpHSharedObject()
{
HSharedObject& t = this->m->shared_object_hints;
*this->m->out_stream
<< "first_shared_obj: " << t.first_shared_obj
<< std::endl
<< "first_shared_offset: " << adjusted_offset(t.first_shared_offset)
<< std::endl
<< "nshared_first_page: " << t.nshared_first_page
<< std::endl
<< "nshared_total: " << t.nshared_total
<< std::endl
<< "nbits_nobjects: " << t.nbits_nobjects
<< std::endl
<< "min_group_length: " << t.min_group_length
<< std::endl
<< "nbits_delta_group_length: " << t.nbits_delta_group_length
<< std::endl;
for (size_t i = 0; i < toS(t.nshared_total); ++i)
{
HSharedObjectEntry& se = t.entries.at(i);
*this->m->out_stream
<< "Shared Object " << i << ":" << std::endl
<< " group length: "
<< se.delta_group_length + t.min_group_length << std::endl;
// PDF spec says signature present nobjects_minus_one are
// always 0, so print them only if they have a non-zero value.
if (se.signature_present)
{
*this->m->out_stream << " signature present" << std::endl;
}
if (se.nobjects_minus_one != 0)
{
*this->m->out_stream << " nobjects: "
<< se.nobjects_minus_one + 1 << std::endl;
}
}
}
void
QPDF::dumpHGeneric(HGeneric& t)
{
*this->m->out_stream
<< "first_object: " << t.first_object
<< std::endl
<< "first_object_offset: " << adjusted_offset(t.first_object_offset)
<< std::endl
<< "nobjects: " << t.nobjects
<< std::endl
<< "group_length: " << t.group_length
<< std::endl;
}
QPDFObjectHandle
QPDF::objGenToIndirect(QPDFObjGen const& og)
{
return getObjectByID(og.getObj(), og.getGen());
}
void
QPDF::calculateLinearizationData(std::map<int, int> const& object_stream_data)
{
// This function calculates the ordering of objects, divides them
// into the appropriate parts, and computes some values for the
// linearization parameter dictionary and hint tables. The file
// must be optimized (via calling optimize()) prior to calling
// this function. Note that actual offsets and lengths are not
// computed here, but anything related to object ordering is.
if (this->m->object_to_obj_users.empty())
{
// Note that we can't call optimize here because we don't know
// whether it should be called with or without allow changes.
throw std::logic_error(
"INTERNAL ERROR: QPDF::calculateLinearizationData "
"called before optimize()");
}
// Separate objects into the categories sufficient for us to
// determine which part of the linearized file should contain the
// object. This categorization is useful for other purposes as
// well. Part numbers refer to version 1.4 of the PDF spec.
// Parts 1, 3, 5, 10, and 11 don't contain any objects from the
// original file (except the trailer dictionary in part 11).
// Part 4 is the document catalog (root) and the following root
// keys: /ViewerPreferences, /PageMode, /Threads, /OpenAction,
// /AcroForm, /Encrypt. Note that Thread information dictionaries
// are supposed to appear in part 9, but we are disregarding that
// recommendation for now.
// Part 6 is the first page section. It includes all remaining
// objects referenced by the first page including shared objects
// but not including thumbnails. Additionally, if /PageMode is
// /Outlines, then information from /Outlines also appears here.
// Part 7 contains remaining objects private to pages other than
// the first page.
// Part 8 contains all remaining shared objects except those that
// are shared only within thumbnails.
// Part 9 contains all remaining objects.
// We sort objects into the following categories:
// * open_document: part 4
// * first_page_private: part 6
// * first_page_shared: part 6
// * other_page_private: part 7
// * other_page_shared: part 8
// * thumbnail_private: part 9
// * thumbnail_shared: part 9
// * other: part 9
// * outlines: part 6 or 9
this->m->part4.clear();
this->m->part6.clear();
this->m->part7.clear();
this->m->part8.clear();
this->m->part9.clear();
this->m->c_linp = LinParameters();
this->m->c_page_offset_data = CHPageOffset();
this->m->c_shared_object_data = CHSharedObject();
this->m->c_outline_data = HGeneric();
QPDFObjectHandle root = getRoot();
bool outlines_in_first_page = false;
QPDFObjectHandle pagemode = root.getKey("/PageMode");
QTC::TC("qpdf", "QPDF categorize pagemode present",
pagemode.isName() ? 1 : 0);
if (pagemode.isName())
{
if (pagemode.getName() == "/UseOutlines")
{
if (root.hasKey("/Outlines"))
{
outlines_in_first_page = true;
}
else
{
QTC::TC("qpdf", "QPDF UseOutlines but no Outlines");
}
}
QTC::TC("qpdf", "QPDF categorize pagemode outlines",
outlines_in_first_page ? 1 : 0);
}
std::set<std::string> open_document_keys;
open_document_keys.insert("/ViewerPreferences");
open_document_keys.insert("/PageMode");
open_document_keys.insert("/Threads");
open_document_keys.insert("/OpenAction");
open_document_keys.insert("/AcroForm");
std::set<QPDFObjGen> lc_open_document;
std::set<QPDFObjGen> lc_first_page_private;
std::set<QPDFObjGen> lc_first_page_shared;
std::set<QPDFObjGen> lc_other_page_private;
std::set<QPDFObjGen> lc_other_page_shared;
std::set<QPDFObjGen> lc_thumbnail_private;
std::set<QPDFObjGen> lc_thumbnail_shared;
std::set<QPDFObjGen> lc_other;
std::set<QPDFObjGen> lc_outlines;
std::set<QPDFObjGen> lc_root;
for (std::map<QPDFObjGen, std::set<ObjUser> >::iterator oiter =
this->m->object_to_obj_users.begin();
oiter != this->m->object_to_obj_users.end(); ++oiter)
{
QPDFObjGen const& og = (*oiter).first;
std::set<ObjUser>& ous = (*oiter).second;
bool in_open_document = false;
bool in_first_page = false;
int other_pages = 0;
int thumbs = 0;
int others = 0;
bool in_outlines = false;
bool is_root = false;
for (std::set<ObjUser>::iterator uiter = ous.begin();
uiter != ous.end(); ++uiter)
{
ObjUser const& ou = *uiter;
switch (ou.ou_type)
{
case ObjUser::ou_trailer_key:
if (ou.key == "/Encrypt")
{
in_open_document = true;
}
else
{
++others;
}
break;
case ObjUser::ou_thumb:
++thumbs;
break;
case ObjUser::ou_root_key:
if (open_document_keys.count(ou.key) > 0)
{
in_open_document = true;
}
else if (ou.key == "/Outlines")
{
in_outlines = true;
}
else
{
++others;
}
break;
case ObjUser::ou_page:
if (ou.pageno == 0)
{
in_first_page = true;
}
else
{
++other_pages;
}
break;
case ObjUser::ou_root:
is_root = true;
break;
case ObjUser::ou_bad:
stopOnError(
"INTERNAL ERROR: QPDF::calculateLinearizationData: "
"invalid user type");
break;
}
}
if (is_root)
{
lc_root.insert(og);
}
else if (in_outlines)
{
lc_outlines.insert(og);
}
else if (in_open_document)
{
lc_open_document.insert(og);
}
else if ((in_first_page) &&
(others == 0) && (other_pages == 0) && (thumbs == 0))
{
lc_first_page_private.insert(og);
}
else if (in_first_page)
{
lc_first_page_shared.insert(og);
}
else if ((other_pages == 1) && (others == 0) && (thumbs == 0))
{
lc_other_page_private.insert(og);
}
else if (other_pages > 1)
{
lc_other_page_shared.insert(og);
}
else if ((thumbs == 1) && (others == 0))
{
lc_thumbnail_private.insert(og);
}
else if (thumbs > 1)
{
lc_thumbnail_shared.insert(og);
}
else
{
lc_other.insert(og);
}
}
// Generate ordering for objects in the output file. Sometimes we
// just dump right from a set into a vector. Rather than
// optimizing this by going straight into the vector, we'll leave
// these phases separate for now. That way, this section can be
// concerned only with ordering, and the above section can be
// considered only with categorization. Note that sets of
// QPDFObjGens are sorted by QPDFObjGen. In a linearized file,
// objects appear in sequence with the possible exception of hints
// tables which we won't see here anyway. That means that running
// calculateLinearizationData() on a linearized file should give
// results identical to the original file ordering.
// We seem to traverse the page tree a lot in this code, but we
// can address this for a future code optimization if necessary.
// Premature optimization is the root of all evil.
std::vector<QPDFObjectHandle> pages;
{ // local scope
// Map all page objects to the containing object stream. This
// should be a no-op in a properly linearized file.
std::vector<QPDFObjectHandle> t = getAllPages();
for (std::vector<QPDFObjectHandle>::iterator iter = t.begin();
iter != t.end(); ++iter)
{
pages.push_back(getUncompressedObject(*iter, object_stream_data));
}
}
int npages = toI(pages.size());
// We will be initializing some values of the computed hint
// tables. Specifically, we can initialize any items that deal
// with object numbers or counts but not any items that deal with
// lengths or offsets. The code that writes linearized files will
// have to fill in these values during the first pass. The
// validation code can compute them relatively easily given the
// rest of the information.
// npages is the size of the existing pages vector, which has been
// created by traversing the pages tree, and as such is a
// reasonable size.
this->m->c_linp.npages = npages;
this->m->c_page_offset_data.entries =
std::vector<CHPageOffsetEntry>(toS(npages));
// Part 4: open document objects. We don't care about the order.
if (lc_root.size() != 1)
{
stopOnError("found other than one root while"
" calculating linearization data");
}
this->m->part4.push_back(objGenToIndirect(*(lc_root.begin())));
for (std::set<QPDFObjGen>::iterator iter = lc_open_document.begin();
iter != lc_open_document.end(); ++iter)
{
this->m->part4.push_back(objGenToIndirect(*iter));
}
// Part 6: first page objects. Note: implementation note 124
// states that Acrobat always treats page 0 as the first page for
// linearization regardless of /OpenAction. pdlin doesn't provide
// any option to set this and also disregards /OpenAction. We
// will do the same.
// First, place the actual first page object itself.
if (pages.empty())
{
stopOnError("no pages found while calculating linearization data");
}
QPDFObjGen first_page_og(pages.at(0).getObjGen());
if (! lc_first_page_private.count(first_page_og))
{
stopOnError(
"INTERNAL ERROR: QPDF::calculateLinearizationData: first page "
"object not in lc_first_page_private");
}
lc_first_page_private.erase(first_page_og);
this->m->c_linp.first_page_object = pages.at(0).getObjectID();
this->m->part6.push_back(pages.at(0));
// The PDF spec "recommends" an order for the rest of the objects,
// but we are going to disregard it except to the extent that it
// groups private and shared objects contiguously for the sake of
// hint tables.
for (std::set<QPDFObjGen>::iterator iter = lc_first_page_private.begin();
iter != lc_first_page_private.end(); ++iter)
{
this->m->part6.push_back(objGenToIndirect(*iter));
}
for (std::set<QPDFObjGen>::iterator iter = lc_first_page_shared.begin();
iter != lc_first_page_shared.end(); ++iter)
{
this->m->part6.push_back(objGenToIndirect(*iter));
}
// Place the outline dictionary if it goes in the first page section.
if (outlines_in_first_page)
{
pushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data);
}
// Fill in page offset hint table information for the first page.
// The PDF spec says that nshared_objects should be zero for the
// first page. pdlin does not appear to obey this, but it fills
// in garbage values for all the shared object identifiers on the
// first page.
this->m->c_page_offset_data.entries.at(0).nobjects =
toI(this->m->part6.size());
// Part 7: other pages' private objects
// For each page in order:
for (size_t i = 1; i < toS(npages); ++i)
{
// Place this page's page object
QPDFObjGen page_og(pages.at(i).getObjGen());
if (! lc_other_page_private.count(page_og))
{
stopOnError(
"INTERNAL ERROR: "
"QPDF::calculateLinearizationData: page object for page " +
QUtil::uint_to_string(i) + " not in lc_other_page_private");
}
lc_other_page_private.erase(page_og);
this->m->part7.push_back(pages.at(i));
// Place all non-shared objects referenced by this page,
// updating the page object count for the hint table.
this->m->c_page_offset_data.entries.at(i).nobjects = 1;
ObjUser ou(ObjUser::ou_page, toI(i));
if (this->m->obj_user_to_objects.count(ou) == 0)
{
stopOnError("found unreferenced page while"
" calculating linearization data");
}
std::set<QPDFObjGen> ogs = this->m->obj_user_to_objects[ou];
for (std::set<QPDFObjGen>::iterator iter = ogs.begin();
iter != ogs.end(); ++iter)
{
QPDFObjGen const& og = (*iter);
if (lc_other_page_private.count(og))
{
lc_other_page_private.erase(og);
this->m->part7.push_back(objGenToIndirect(og));
++this->m->c_page_offset_data.entries.at(i).nobjects;
}
}
}
// That should have covered all part7 objects.
if (! lc_other_page_private.empty())
{
stopOnError(
"INTERNAL ERROR:"
" QPDF::calculateLinearizationData: lc_other_page_private is "
"not empty after generation of part7");
}
// Part 8: other pages' shared objects
// Order is unimportant.
for (std::set<QPDFObjGen>::iterator iter = lc_other_page_shared.begin();
iter != lc_other_page_shared.end(); ++iter)
{
this->m->part8.push_back(objGenToIndirect(*iter));
}
// Part 9: other objects
// The PDF specification makes recommendations on ordering here.
// We follow them only to a limited extent. Specifically, we put
// the pages tree first, then private thumbnail objects in page
// order, then shared thumbnail objects, and then outlines (unless
// in part 6). After that, we throw all remaining objects in
// arbitrary order.
// Place the pages tree.
std::set<QPDFObjGen> pages_ogs =
this->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, "/Pages")];
if (pages_ogs.empty())
{
stopOnError("found empty pages tree while"
" calculating linearization data");
}
for (std::set<QPDFObjGen>::iterator iter = pages_ogs.begin();
iter != pages_ogs.end(); ++iter)
{
QPDFObjGen const& og = *iter;
if (lc_other.count(og))
{
lc_other.erase(og);
this->m->part9.push_back(objGenToIndirect(og));
}
}
// Place private thumbnail images in page order. Slightly more
// information would be required if we were going to bother with
// thumbnail hint tables.
for (size_t i = 0; i < toS(npages); ++i)
{
QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb");
thumb = getUncompressedObject(thumb, object_stream_data);
if (! thumb.isNull())
{
// Output the thumbnail itself
QPDFObjGen thumb_og(thumb.getObjGen());
if (lc_thumbnail_private.count(thumb_og))
{
lc_thumbnail_private.erase(thumb_og);
this->m->part9.push_back(thumb);
}
else
{
// No internal error this time...there's nothing to
// stop this object from having been referred to
// somewhere else outside of a page's /Thumb, and if
// it had been, there's nothing to prevent it from
// having been in some set other than
// lc_thumbnail_private.
}
std::set<QPDFObjGen>& ogs =
this->m->obj_user_to_objects[
ObjUser(ObjUser::ou_thumb, toI(i))];
for (std::set<QPDFObjGen>::iterator iter = ogs.begin();
iter != ogs.end(); ++iter)
{
QPDFObjGen const& og = *iter;
if (lc_thumbnail_private.count(og))
{
lc_thumbnail_private.erase(og);
this->m->part9.push_back(objGenToIndirect(og));
}
}
}
}
if (! lc_thumbnail_private.empty())
{
stopOnError(
"INTERNAL ERROR: "
"QPDF::calculateLinearizationData: lc_thumbnail_private "
"not empty after placing thumbnails");
}
// Place shared thumbnail objects
for (std::set<QPDFObjGen>::iterator iter = lc_thumbnail_shared.begin();
iter != lc_thumbnail_shared.end(); ++iter)
{
this->m->part9.push_back(objGenToIndirect(*iter));
}
// Place outlines unless in first page
if (! outlines_in_first_page)
{
pushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data);
}
// Place all remaining objects
for (std::set<QPDFObjGen>::iterator iter = lc_other.begin();
iter != lc_other.end(); ++iter)
{
this->m->part9.push_back(objGenToIndirect(*iter));
}
// Make sure we got everything exactly once.
size_t num_placed =
this->m->part4.size() + this->m->part6.size() + this->m->part7.size() +
this->m->part8.size() + this->m->part9.size();
size_t num_wanted = this->m->object_to_obj_users.size();
if (num_placed != num_wanted)
{
stopOnError(
"INTERNAL ERROR: QPDF::calculateLinearizationData: wrong "
"number of objects placed (num_placed = " +
QUtil::uint_to_string(num_placed) +
"; number of objects: " +
QUtil::uint_to_string(num_wanted));
}
// Calculate shared object hint table information including
// references to shared objects from page offset hint data.
// The shared object hint table consists of all part 6 (whether
// shared or not) in order followed by all part 8 objects in
// order. Add the objects to shared object data keeping a map of
// object number to index. Then populate the shared object
// information for the pages.
// Note that two objects never have the same object number, so we
// can map from object number only without regards to generation.
std::map<int, int> obj_to_index;
this->m->c_shared_object_data.nshared_first_page =
toI(this->m->part6.size());
this->m->c_shared_object_data.nshared_total =
this->m->c_shared_object_data.nshared_first_page +
toI(this->m->part8.size());
std::vector<CHSharedObjectEntry>& shared =
this->m->c_shared_object_data.entries;
for (std::vector<QPDFObjectHandle>::iterator iter = this->m->part6.begin();
iter != this->m->part6.end(); ++iter)
{
QPDFObjectHandle& oh = *iter;
int obj = oh.getObjectID();
obj_to_index[obj] = toI(shared.size());
shared.push_back(CHSharedObjectEntry(obj));
}
QTC::TC("qpdf", "QPDF lin part 8 empty", this->m->part8.empty() ? 1 : 0);
if (! this->m->part8.empty())
{
this->m->c_shared_object_data.first_shared_obj =
this->m->part8.at(0).getObjectID();
for (std::vector<QPDFObjectHandle>::iterator iter =
this->m->part8.begin();
iter != this->m->part8.end(); ++iter)
{
QPDFObjectHandle& oh = *iter;
int obj = oh.getObjectID();
obj_to_index[obj] = toI(shared.size());
shared.push_back(CHSharedObjectEntry(obj));
}
}
if (static_cast<size_t>(this->m->c_shared_object_data.nshared_total) !=
this->m->c_shared_object_data.entries.size())
{
stopOnError(
"shared object hint table has wrong number of entries");
}
// Now compute the list of shared objects for each page after the
// first page.
for (size_t i = 1; i < toS(npages); ++i)
{
CHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i);
ObjUser ou(ObjUser::ou_page, toI(i));
if (this->m->obj_user_to_objects.count(ou) == 0)
{
stopOnError("found unreferenced page while"
" calculating linearization data");
}
std::set<QPDFObjGen> const& ogs = this->m->obj_user_to_objects[ou];
for (std::set<QPDFObjGen>::const_iterator iter = ogs.begin();
iter != ogs.end(); ++iter)
{
QPDFObjGen const& og = *iter;
if ((this->m->object_to_obj_users[og].size() > 1) &&
(obj_to_index.count(og.getObj()) > 0))
{
int idx = obj_to_index[og.getObj()];
++pe.nshared_objects;
pe.shared_identifiers.push_back(idx);
}
}
}
}
void
QPDF::pushOutlinesToPart(
std::vector<QPDFObjectHandle>& part,
std::set<QPDFObjGen>& lc_outlines,
std::map<int, int> const& object_stream_data)
{
QPDFObjectHandle root = getRoot();
QPDFObjectHandle outlines = root.getKey("/Outlines");
if (outlines.isNull())
{
return;
}
outlines = getUncompressedObject(outlines, object_stream_data);
QPDFObjGen outlines_og(outlines.getObjGen());
QTC::TC("qpdf", "QPDF lin outlines in part",
((&part == (&this->m->part6)) ? 0
: (&part == (&this->m->part9)) ? 1
: 9999)); // can't happen
this->m->c_outline_data.first_object = outlines_og.getObj();
this->m->c_outline_data.nobjects = 1;
lc_outlines.erase(outlines_og);
part.push_back(outlines);
for (std::set<QPDFObjGen>::iterator iter = lc_outlines.begin();
iter != lc_outlines.end(); ++iter)
{
part.push_back(objGenToIndirect(*iter));
++this->m->c_outline_data.nobjects;
}
}
void
QPDF::getLinearizedParts(
std::map<int, int> const& object_stream_data,
std::vector<QPDFObjectHandle>& part4,
std::vector<QPDFObjectHandle>& part6,
std::vector<QPDFObjectHandle>& part7,
std::vector<QPDFObjectHandle>& part8,
std::vector<QPDFObjectHandle>& part9)
{
calculateLinearizationData(object_stream_data);
part4 = this->m->part4;
part6 = this->m->part6;
part7 = this->m->part7;
part8 = this->m->part8;
part9 = this->m->part9;
}
static inline int nbits(int val)
{
return (val == 0 ? 0 : (1 + nbits(val >> 1)));
}
int
QPDF::outputLengthNextN(
int in_object, int n,
std::map<int, qpdf_offset_t> const& lengths,
std::map<int, int> const& obj_renumber)
{
// Figure out the length of a series of n consecutive objects in
// the output file starting with whatever object in_object from
// the input file mapped to.
if (obj_renumber.count(in_object) == 0)
{
stopOnError("found object that is not renumbered while"
" writing linearization data");
}
int first = (*(obj_renumber.find(in_object))).second;
int length = 0;
for (int i = 0; i < n; ++i)
{
if (lengths.count(first + i) == 0)
{
stopOnError("found item with unknown length"
" while writing linearization data");
}
length += toI((*(lengths.find(first + toI(i)))).second);
}
return length;
}
void
QPDF::calculateHPageOffset(
std::map<int, QPDFXRefEntry> const& xref,
std::map<int, qpdf_offset_t> const& lengths,
std::map<int, int> const& obj_renumber)
{
// Page Offset Hint Table
// We are purposely leaving some values set to their initial zero
// values.
std::vector<QPDFObjectHandle> const& pages = getAllPages();
size_t npages = pages.size();
CHPageOffset& cph = this->m->c_page_offset_data;
std::vector<CHPageOffsetEntry>& cphe = cph.entries;
// Calculate minimum and maximum values for number of objects per
// page and page length.
int min_nobjects = cphe.at(0).nobjects;
int max_nobjects = min_nobjects;
int min_length = outputLengthNextN(
pages.at(0).getObjectID(), min_nobjects, lengths, obj_renumber);
int max_length = min_length;
int max_shared = cphe.at(0).nshared_objects;
HPageOffset& ph = this->m->page_offset_hints;
std::vector<HPageOffsetEntry>& phe = ph.entries;
// npages is the size of the existing pages array.
phe = std::vector<HPageOffsetEntry>(npages);
for (unsigned int i = 0; i < npages; ++i)
{
// Calculate values for each page, assigning full values to
// the delta items. They will be adjusted later.
// Repeat calculations for page 0 so we can assign to phe[i]
// without duplicating those assignments.
int nobjects = cphe.at(i).nobjects;
int length = outputLengthNextN(
pages.at(i).getObjectID(), nobjects, lengths, obj_renumber);
int nshared = cphe.at(i).nshared_objects;
min_nobjects = std::min(min_nobjects, nobjects);
max_nobjects = std::max(max_nobjects, nobjects);
min_length = std::min(min_length, length);
max_length = std::max(max_length, length);
max_shared = std::max(max_shared, nshared);
phe.at(i).delta_nobjects = nobjects;
phe.at(i).delta_page_length = length;
phe.at(i).nshared_objects = nshared;
}
ph.min_nobjects = min_nobjects;
int in_page0_id = pages.at(0).getObjectID();
int out_page0_id = (*(obj_renumber.find(in_page0_id))).second;
ph.first_page_offset = (*(xref.find(out_page0_id))).second.getOffset();
ph.nbits_delta_nobjects = nbits(max_nobjects - min_nobjects);
ph.min_page_length = min_length;
ph.nbits_delta_page_length = nbits(max_length - min_length);
ph.nbits_nshared_objects = nbits(max_shared);
ph.nbits_shared_identifier =
nbits(this->m->c_shared_object_data.nshared_total);
ph.shared_denominator = 4; // doesn't matter
// It isn't clear how to compute content offset and content
// length. Since we are not interleaving page objects with the
// content stream, we'll use the same values for content length as
// page length. We will use 0 as content offset because this is
// what Adobe does (implementation note 127) and pdlin as well.
ph.nbits_delta_content_length = ph.nbits_delta_page_length;
ph.min_content_length = ph.min_page_length;
for (size_t i = 0; i < npages; ++i)
{
// Adjust delta entries
if ((phe.at(i).delta_nobjects < min_nobjects) ||
(phe.at(i).delta_page_length < min_length))
{
stopOnError("found too small delta nobjects or delta page length"
" while writing linearization data");
}
phe.at(i).delta_nobjects -= min_nobjects;
phe.at(i).delta_page_length -= min_length;
phe.at(i).delta_content_length = phe.at(i).delta_page_length;
for (size_t j = 0; j < toS(cphe.at(i).nshared_objects); ++j)
{
phe.at(i).shared_identifiers.push_back(
cphe.at(i).shared_identifiers.at(j));
phe.at(i).shared_numerators.push_back(0);
}
}
}
void
QPDF::calculateHSharedObject(
std::map<int, QPDFXRefEntry> const& xref,
std::map<int, qpdf_offset_t> const& lengths,
std::map<int, int> const& obj_renumber)
{
CHSharedObject& cso = this->m->c_shared_object_data;
std::vector<CHSharedObjectEntry>& csoe = cso.entries;
HSharedObject& so = this->m->shared_object_hints;
std::vector<HSharedObjectEntry>& soe = so.entries;
soe.clear();
int min_length = outputLengthNextN(
csoe.at(0).object, 1, lengths, obj_renumber);
int max_length = min_length;
for (size_t i = 0; i < toS(cso.nshared_total); ++i)
{
// Assign absolute numbers to deltas; adjust later
int length = outputLengthNextN(
csoe.at(i).object, 1, lengths, obj_renumber);
min_length = std::min(min_length, length);
max_length = std::max(max_length, length);
soe.push_back(HSharedObjectEntry());
soe.at(i).delta_group_length = length;
}
if (soe.size() != QIntC::to_size(cso.nshared_total))
{
stopOnError("soe has wrong size after initialization");
}
so.nshared_total = cso.nshared_total;
so.nshared_first_page = cso.nshared_first_page;
if (so.nshared_total > so.nshared_first_page)
{
so.first_shared_obj =
(*(obj_renumber.find(cso.first_shared_obj))).second;
so.first_shared_offset =
(*(xref.find(so.first_shared_obj))).second.getOffset();
}
so.min_group_length = min_length;
so.nbits_delta_group_length = nbits(max_length - min_length);
for (size_t i = 0; i < toS(cso.nshared_total); ++i)
{
// Adjust deltas
if (soe.at(i).delta_group_length < min_length)
{
stopOnError("found too small group length while"
" writing linearization data");
}
soe.at(i).delta_group_length -= min_length;
}
}
void
QPDF::calculateHOutline(
std::map<int, QPDFXRefEntry> const& xref,
std::map<int, qpdf_offset_t> const& lengths,
std::map<int, int> const& obj_renumber)
{
HGeneric& cho = this->m->c_outline_data;
if (cho.nobjects == 0)
{
return;
}
HGeneric& ho = this->m->outline_hints;
ho.first_object =
(*(obj_renumber.find(cho.first_object))).second;
ho.first_object_offset =
(*(xref.find(ho.first_object))).second.getOffset();
ho.nobjects = cho.nobjects;
ho.group_length = outputLengthNextN(
cho.first_object, ho.nobjects, lengths, obj_renumber);
}
template <class T, class int_type>
static void
write_vector_int(BitWriter& w, int nitems, std::vector<T>& vec,
int bits, int_type T::*field)
{
// nitems times, write bits bits from the given field of the ith
// vector to the given bit writer.
for (size_t i = 0; i < QIntC::to_size(nitems); ++i)
{
w.writeBits(QIntC::to_ulonglong(vec.at(i).*field),
QIntC::to_size(bits));
}
// The PDF spec says that each hint table starts at a byte
// boundary. Each "row" actually must start on a byte boundary.
w.flush();
}
template <class T>
static void
write_vector_vector(BitWriter& w,
int nitems1, std::vector<T>& vec1, int T::*nitems2,
int bits, std::vector<int> T::*vec2)
{
// nitems1 times, write nitems2 (from the ith element of vec1) items
// from the vec2 vector field of the ith item of vec1.
for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1)
{
for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2)
{
w.writeBits(QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)),
QIntC::to_size(bits));
}
}
w.flush();
}
void
QPDF::writeHPageOffset(BitWriter& w)
{
HPageOffset& t = this->m->page_offset_hints;
w.writeBitsInt(t.min_nobjects, 32); // 1
w.writeBitsInt(toI(t.first_page_offset), 32); // 2
w.writeBitsInt(t.nbits_delta_nobjects, 16); // 3
w.writeBitsInt(t.min_page_length, 32); // 4
w.writeBitsInt(t.nbits_delta_page_length, 16); // 5
w.writeBitsInt(t.min_content_offset, 32); // 6
w.writeBitsInt(t.nbits_delta_content_offset, 16); // 7
w.writeBitsInt(t.min_content_length, 32); // 8
w.writeBitsInt(t.nbits_delta_content_length, 16); // 9
w.writeBitsInt(t.nbits_nshared_objects, 16); // 10
w.writeBitsInt(t.nbits_shared_identifier, 16); // 11
w.writeBitsInt(t.nbits_shared_numerator, 16); // 12
w.writeBitsInt(t.shared_denominator, 16); // 13
int nitems = toI(getAllPages().size());
std::vector<HPageOffsetEntry>& entries = t.entries;
write_vector_int(w, nitems, entries,
t.nbits_delta_nobjects,
&HPageOffsetEntry::delta_nobjects);
write_vector_int(w, nitems, entries,
t.nbits_delta_page_length,
&HPageOffsetEntry::delta_page_length);
write_vector_int(w, nitems, entries,
t.nbits_nshared_objects,
&HPageOffsetEntry::nshared_objects);
write_vector_vector(w, nitems, entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_identifier,
&HPageOffsetEntry::shared_identifiers);
write_vector_vector(w, nitems, entries,
&HPageOffsetEntry::nshared_objects,
t.nbits_shared_numerator,
&HPageOffsetEntry::shared_numerators);
write_vector_int(w, nitems, entries,
t.nbits_delta_content_offset,
&HPageOffsetEntry::delta_content_offset);
write_vector_int(w, nitems, entries,
t.nbits_delta_content_length,
&HPageOffsetEntry::delta_content_length);
}
void
QPDF::writeHSharedObject(BitWriter& w)
{
HSharedObject& t = this->m->shared_object_hints;
w.writeBitsInt(t.first_shared_obj, 32); // 1
w.writeBitsInt(toI(t.first_shared_offset), 32); // 2
w.writeBitsInt(t.nshared_first_page, 32); // 3
w.writeBitsInt(t.nshared_total, 32); // 4
w.writeBitsInt(t.nbits_nobjects, 16); // 5
w.writeBitsInt(t.min_group_length, 32); // 6
w.writeBitsInt(t.nbits_delta_group_length, 16); // 7
QTC::TC("qpdf", "QPDF lin write nshared_total > nshared_first_page",
(t.nshared_total > t.nshared_first_page) ? 1 : 0);
int nitems = t.nshared_total;
std::vector<HSharedObjectEntry>& entries = t.entries;
write_vector_int(w, nitems, entries,
t.nbits_delta_group_length,
&HSharedObjectEntry::delta_group_length);
write_vector_int(w, nitems, entries,
1, &HSharedObjectEntry::signature_present);
for (size_t i = 0; i < toS(nitems); ++i)
{
// If signature were present, we'd have to write a 128-bit hash.
if (entries.at(i).signature_present != 0)
{
stopOnError("found unexpected signature present"
" while writing linearization data");
}
}
write_vector_int(w, nitems, entries,
t.nbits_nobjects,
&HSharedObjectEntry::nobjects_minus_one);
}
void
QPDF::writeHGeneric(BitWriter& w, HGeneric& t)
{
w.writeBitsInt(t.first_object, 32); // 1
w.writeBitsInt(toI(t.first_object_offset), 32); // 2
w.writeBitsInt(t.nobjects, 32); // 3
w.writeBitsInt(t.group_length, 32); // 4
}
void
QPDF::generateHintStream(std::map<int, QPDFXRefEntry> const& xref,
std::map<int, qpdf_offset_t> const& lengths,
std::map<int, int> const& obj_renumber,
PointerHolder<Buffer>& hint_buffer,
int& S, int& O)
{
// Populate actual hint table values
calculateHPageOffset(xref, lengths, obj_renumber);
calculateHSharedObject(xref, lengths, obj_renumber);
calculateHOutline(xref, lengths, obj_renumber);
// Write the hint stream itself into a compressed memory buffer.
// Write through a counter so we can get offsets.
Pl_Buffer hint_stream("hint stream");
Pl_Flate f("compress hint stream", &hint_stream, Pl_Flate::a_deflate);
Pl_Count c("count", &f);
BitWriter w(&c);
writeHPageOffset(w);
S = toI(c.getCount());
writeHSharedObject(w);
O = 0;
if (this->m->outline_hints.nobjects > 0)
{
O = toI(c.getCount());
writeHGeneric(w, this->m->outline_hints);
}
c.finish();
hint_buffer = hint_stream.getBufferSharedPointer();
}
| 35.578487
| 80
| 0.577807
|
freedlp
|
443bc49ac48e684e394c19a84c1c441888f3fc2e
| 47,739
|
cc
|
C++
|
garnet/public/lib/inspect/tests/children_manager_unittest.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | null | null | null |
garnet/public/lib/inspect/tests/children_manager_unittest.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | 4
|
2020-09-06T07:59:32.000Z
|
2022-02-12T16:06:47.000Z
|
garnet/public/lib/inspect/tests/children_manager_unittest.cc
|
myself659/fuchsia
|
18eb5ad3d995fba458b32d8600b2af97f89a5726
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2019 The Fuchsia 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 <fuchsia/inspect/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/async_promise/executor.h>
#include <lib/callback/auto_cleanable.h>
#include <lib/callback/capture.h>
#include <lib/callback/ensure_called.h>
#include <lib/callback/set_when_called.h>
#include <lib/gtest/test_loop_fixture.h>
#include <lib/inspect/hierarchy.h>
#include <lib/inspect/inspect.h>
#include <lib/inspect/reader.h>
#include <lib/inspect/testing/inspect.h>
#include <map>
#include <random>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "peridot/lib/rng/test_random.h"
#include "src/lib/fxl/memory/weak_ptr.h"
namespace {
using testing::AllOf;
using testing::ElementsAre;
using testing::IsEmpty;
using testing::UnorderedElementsAre;
using namespace inspect::testing;
bool NextBool(rng::Random* random) {
auto bit_generator = random->NewBitGenerator<bool>();
return bool(std::uniform_int_distribution(0, 1)(bit_generator));
}
std::vector<std::string> RandomlyReorderAndRepeat(
std::vector<std::string> items, rng::Random* random) {
size_t limit = 4 * items.size();
auto bit_generator = random->NewBitGenerator<size_t>();
std::shuffle(items.begin(), items.end(), bit_generator);
while (items.size() < limit) {
if (std::uniform_int_distribution(0, 9)(bit_generator) == 9) {
break;
}
items.push_back(items[0]);
std::shuffle(items.begin(), items.end(), bit_generator);
}
return items;
}
struct Table {
std::map<std::string, std::unique_ptr<Table>> children;
};
// |table_description| is a set of the full names of leaf elements.
Table TableFromTableDescription(
const std::set<std::vector<std::string>>& table_description) {
Table table;
for (const std::vector<std::string>& leaf_full_name : table_description) {
Table* current = &table;
for (const std::string& short_name : leaf_full_name) {
auto emplacement =
current->children.emplace(short_name, std::make_unique<Table>());
current = emplacement.first->second.get();
}
}
return table;
}
bool PresentInTable(const Table* table,
const std::vector<std::string>& full_name) {
const Table* current = table;
for (const auto& short_name : full_name) {
const auto& it = current->children.find(short_name);
if (it == current->children.end()) {
return false;
}
current = it->second.get();
}
return true;
}
// Constructs the full names of all leaf nodes of a table of depth |depth|. The
// table has a branching factor of three and all siblings are named "a", "b",
// and "c".
std::set<std::vector<std::string>> CompleteTableDescription(int depth) {
if (depth == 1) {
return {{"a"}, {"b"}, {"c"}};
} else {
std::set<std::vector<std::string>> depth_minus_one_table =
CompleteTableDescription(depth - 1);
std::set<std::vector<std::string>> table;
for (const auto& prefix : depth_minus_one_table) {
for (const auto& suffix : {"a", "b", "c"}) {
std::vector<std::string> table_entry = prefix;
table_entry.emplace_back(suffix);
table.insert(table_entry);
}
}
return table;
}
}
::testing::Matcher<const inspect::ObjectHierarchy&> CompleteMatcher(int depth) {
if (depth == 0) {
return ChildrenMatch(IsEmpty());
} else {
return ChildrenMatch(ElementsAre(
AllOf(NodeMatches(NameMatches("a")), CompleteMatcher(depth - 1)),
AllOf(NodeMatches(NameMatches("b")), CompleteMatcher(depth - 1)),
AllOf(NodeMatches(NameMatches("c")), CompleteMatcher(depth - 1))));
}
}
class Element final : public inspect::ChildrenManager {
public:
Element(async::TestLoop* test_loop, rng::Random* random, Table* table,
inspect::Node inspect_node)
: random_(random),
test_loop_(test_loop),
table_(table),
inspect_node_(std::move(inspect_node)),
children_manager_retainer_(inspect_node_.SetChildrenManager(this)),
user_serving_retention_(0),
inspect_retention_(0),
weak_factory_(this) {
children_.set_on_empty([this]() { CheckEmpty(); });
}
~Element() override {
children_.set_on_empty([]() {});
};
void set_on_empty(fit::closure on_empty_callback) {
on_empty_callback_ = std::move(on_empty_callback);
}
void GetNames(
fit::function<void(std::vector<std::string>)> callback) override {
std::vector<std::string> names;
for (const auto& [child_name, unused_child_unique_pointer] :
table_->children) {
names.push_back(child_name);
}
names = RandomlyReorderAndRepeat(std::move(names), random_);
if (NextBool(random_)) {
async::PostTask(test_loop_->dispatcher(),
[callback = std::move(callback),
names = std::move(names)]() { callback(names); });
} else {
callback(names);
}
}
void Attach(std::string name,
fit::function<void(fit::closure)> callback) override {
if (table_->children.find(name) == table_->children.end()) {
if (NextBool(random_)) {
async::PostTask(
test_loop_->dispatcher(),
[callback = std::move(callback)]() { callback([]() {}); });
} else {
callback([]() {});
}
return;
}
auto child = ActivateChild(name);
auto retainer = child->RetainForInspect();
if (NextBool(random_)) {
async::PostTask(test_loop_->dispatcher(),
[callback = std::move(callback),
retainer = std::move(retainer)]() mutable {
callback(std::move(retainer));
});
} else {
callback(std::move(retainer));
}
}
std::pair<Element*, fit::closure> GetChild(
const std::string& child_short_name) {
Element* child_ptr = ActivateChild(child_short_name);
return std::make_pair(child_ptr, child_ptr->RetainToServeUser());
}
void ActivateDescendant(std::vector<std::string> relative_descendant_name,
fit::function<void(bool, fit::closure)> callback) {
auto implementation = [this, weak_this = weak_factory_.GetWeakPtr(),
relative_descendant_name =
std::move(relative_descendant_name),
callback = std::move(callback)]() mutable {
if (!weak_this) {
callback(false, []() {});
return;
}
auto child = ActivateChild(relative_descendant_name[0]);
if (relative_descendant_name.size() == 1) {
callback(true, child->RetainToServeUser());
} else {
child->ActivateDescendant({relative_descendant_name.begin() + 1,
relative_descendant_name.end()},
std::move(callback));
}
};
if (NextBool(random_)) {
async::PostTask(test_loop_->dispatcher(), std::move(implementation));
} else {
implementation();
}
}
void DeleteDescendant(std::vector<std::string> relative_descendant_name) {
auto it = children_.find(relative_descendant_name[0]);
if (it != children_.end()) {
if (relative_descendant_name.size() == 1) {
children_.erase(it);
} else {
it->second.DeleteDescendant({relative_descendant_name.begin() + 1,
relative_descendant_name.end()});
}
}
}
Element* DebugGetDescendant(
std::vector<std::string> relative_descendant_name) {
const auto& it = children_.find(relative_descendant_name[0]);
if (it == children_.end()) {
return nullptr;
} else if (relative_descendant_name.size() == 1) {
return &it->second;
} else {
return it->second.DebugGetDescendant(
{relative_descendant_name.begin() + 1,
relative_descendant_name.end()});
}
}
fit::closure RetainToServeUser() {
user_serving_retention_++;
auto weak_this = weak_factory_.GetWeakPtr();
return [this, weak_this]() {
if (weak_this) {
user_serving_retention_--;
CheckEmpty();
}
};
}
private:
Element* ActivateChild(const std::string& child_short_name) {
auto it = children_.find(child_short_name);
if (it == children_.end()) {
inspect::Node child_inspect_node =
inspect_node_.CreateChild(child_short_name);
auto emplacement = children_.emplace(
std::piecewise_construct, std::forward_as_tuple(child_short_name),
std::forward_as_tuple(
test_loop_, random_,
table_->children.find(child_short_name)->second.get(),
std::move(child_inspect_node)));
return &emplacement.first->second;
} else {
return &it->second;
}
}
fit::closure RetainForInspect() {
inspect_retention_++;
return [this]() {
inspect_retention_--;
CheckEmpty();
};
}
void CheckEmpty() {
FXL_DCHECK(0 <= user_serving_retention_);
FXL_DCHECK(0 <= inspect_retention_);
if (user_serving_retention_ == 0 && inspect_retention_ == 0 &&
children_.empty() && on_empty_callback_) {
on_empty_callback_();
}
}
rng::Random* random_;
async::TestLoop* test_loop_;
Table* table_;
inspect::Node inspect_node_;
fit::deferred_callback children_manager_retainer_;
fit::closure on_empty_callback_;
int64_t user_serving_retention_;
int64_t inspect_retention_;
callback::AutoCleanableMap<std::string, Element> children_;
// Must be the last member.
fxl::WeakPtrFactory<Element> weak_factory_;
FXL_DISALLOW_COPY_AND_ASSIGN(Element);
};
enum class Activity {
ABSENT,
INACTIVE,
ACTIVE,
};
// Inspect-using application representative of those that use and that we think
// are likely to use a ChildrenManager. The application:
// (1) Maintains a frequently-changing-shape variable-depth tree of elements
// that each statically maintain an inspect::Node.
// (2) The application is asynchronous.
class Application final {
public:
Application(async::TestLoop* loop, rng::Random* random,
inspect::Node* application_inspect_node,
const std::set<std::vector<std::string>>& table_description)
: loop_(loop),
random_(random),
application_inspect_node_(application_inspect_node),
table_(TableFromTableDescription(table_description)){};
// The "user interface" of the application, this method is called by the test
// when the test is acting as the application's user. If the element for
// |full_name| is not resident in memory, this method "activates" it by
// creating an in-memory Element (and thus alters the Inspect hierarchy).
// Passed to |callback| are:
// (1) A boolean "success" indicator that is representative of how in real
// applications analogs of this method can fail or time out.
// (2) A closure to call when the "user" (again, the test acting as the
// user) no longer needs the element to remain "activated".
void Activate(std::vector<std::string> full_name,
fit::function<void(bool, fit::closure)> callback) {
auto implementation = [this, full_name = std::move(full_name),
callback = std::move(callback)]() mutable {
auto& first_short_name = full_name[0];
Element* element;
const auto& it = elements_.find(first_short_name);
if (it == elements_.end()) {
inspect::Node child_inspect_node =
application_inspect_node_->CreateChild(first_short_name);
auto emplacement = elements_.emplace(
std::piecewise_construct, std::forward_as_tuple(first_short_name),
std::forward_as_tuple(
loop_, random_,
table_.children.find(first_short_name)->second.get(),
std::move(child_inspect_node)));
element = &emplacement.first->second;
} else {
element = &it->second;
}
if (full_name.size() == 1) {
callback(true, element->RetainToServeUser());
} else {
element->ActivateDescendant({full_name.begin() + 1, full_name.end()},
std::move(callback));
}
};
if (NextBool(random_)) {
async::PostTask(loop_->dispatcher(), std::move(implementation));
} else {
implementation();
}
}
// The "administrator interface" of the application, this method is called
// when the test is acting as the application's owner and decides for whatever
// reason that some portion of the activated elements (the element at
// |full_name| and all elements under it) must be deleted from memory.
void Delete(const std::vector<std::string>& full_name) {
if (full_name.empty()) {
while (!elements_.empty()) {
elements_.erase(elements_.begin());
}
} else {
auto it = elements_.find(full_name[0]);
if (it != elements_.end()) {
if (full_name.size() == 1) {
elements_.erase(it);
} else {
it->second.DeleteDescendant({full_name.begin() + 1, full_name.end()});
}
}
}
}
// Called by the test acting as the test, this method describes for use in
// assertions whether an element is active at |full_name|, is inactive at
// |full_name|, or is not understood as either active or inactive.
Activity DebugGetActivity(const std::vector<std::string>& full_name) {
if (!PresentInTable(&table_, full_name)) {
return Activity::ABSENT;
} else {
auto it = elements_.find(full_name[0]);
if (it == elements_.end()) {
return Activity::INACTIVE;
} else if (full_name.size() == 1) {
return Activity::ACTIVE;
} else {
auto descendant = it->second.DebugGetDescendant(
{full_name.begin() + 1, full_name.end()});
return descendant == nullptr ? Activity::INACTIVE : Activity::ACTIVE;
}
}
}
private:
async::TestLoop* loop_;
rng::Random* random_;
inspect::Node* application_inspect_node_;
// Representative of the application's persistent data on disk, the set of
// names for which the application considers elements to exist (whether
// activated or not).
Table table_;
callback::AutoCleanableMap<std::string, Element> elements_;
};
constexpr char kTestTopLevelNodeName[] = "top-level-of-test node";
constexpr char kElementsInspectPathComponent[] = "elements";
class ChildrenManagerTest : public gtest::TestLoopFixture {
public:
ChildrenManagerTest()
: executor_(dispatcher()),
random_(test_loop().initial_state()),
top_level_node_(inspect::Node(kTestTopLevelNodeName)) {
elements_node_ = top_level_node_.CreateChild(kElementsInspectPathComponent);
}
protected:
::testing::AssertionResult OpenElementsNode(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* elements);
::testing::AssertionResult ReadData(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* node,
fuchsia::inspect::Object* object);
::testing::AssertionResult ListChildren(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* node,
std::vector<std::string>* child_names);
::testing::AssertionResult OpenChild(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* parent,
const std::string& child_name,
fidl::InterfacePtr<fuchsia::inspect::Inspect>* child);
::testing::AssertionResult Activate(Application* application,
std::vector<std::string> full_name,
fit::closure* retainer);
::testing::AssertionResult ReadWithReaderAPI(
inspect::ObjectHierarchy* hierarchy);
async::Executor executor_;
rng::TestRandom random_;
inspect::Node top_level_node_;
inspect::Node elements_node_;
};
::testing::AssertionResult ChildrenManagerTest::OpenElementsNode(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* elements) {
bool callback_called;
bool success;
top_level_node_.object_dir().object()->OpenChild(
kElementsInspectPathComponent, elements->NewRequest(),
callback::Capture(callback::SetWhenCalled(&callback_called), &success));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "OpenElementsNode callback passed to OpenChild not called!";
} else if (!success) {
return ::testing::AssertionFailure() << "OpenElementsNode unsuccessful!";
} else {
return ::testing::AssertionSuccess();
}
}
::testing::AssertionResult ChildrenManagerTest::ReadData(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* node,
fuchsia::inspect::Object* object) {
bool callback_called;
(*node)->ReadData(
callback::Capture(callback::SetWhenCalled(&callback_called), object));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to ReadData not called!";
} else {
return ::testing::AssertionSuccess();
}
}
::testing::AssertionResult ChildrenManagerTest::ListChildren(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* node,
std::vector<std::string>* child_names) {
bool callback_called;
(*node)->ListChildren(callback::Capture(
callback::SetWhenCalled(&callback_called), child_names));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to ListChildren not called!";
} else {
return ::testing::AssertionSuccess();
}
}
::testing::AssertionResult ChildrenManagerTest::OpenChild(
fidl::InterfacePtr<fuchsia::inspect::Inspect>* parent,
const std::string& child_name,
fidl::InterfacePtr<fuchsia::inspect::Inspect>* child) {
bool callback_called;
bool success;
(*parent)->OpenChild(
child_name, child->NewRequest(),
callback::Capture(callback::SetWhenCalled(&callback_called), &success));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to OpenChild not called!";
} else if (!success) {
return ::testing::AssertionFailure() << "OpenChild unsuccessful!";
} else {
return ::testing::AssertionSuccess();
}
}
::testing::AssertionResult ChildrenManagerTest::Activate(
Application* application, std::vector<std::string> full_name,
fit::closure* retainer) {
bool callback_called;
bool success;
application->Activate(
std::move(full_name),
callback::Capture(callback::SetWhenCalled(&callback_called), &success,
retainer));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to Activate not called!";
} else if (!success) {
return ::testing::AssertionFailure() << "Activate not successful!";
} else {
return ::testing::AssertionSuccess();
}
}
::testing::AssertionResult ChildrenManagerTest::ReadWithReaderAPI(
inspect::ObjectHierarchy* hierarchy) {
bool callback_called;
bool success;
fidl::InterfaceHandle<fuchsia::inspect::Inspect> inspect_handle;
top_level_node_.object_dir().object()->OpenChild(
kElementsInspectPathComponent, inspect_handle.NewRequest(),
callback::Capture(callback::SetWhenCalled(&callback_called), &success));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to OpenChild not called!";
} else if (!success) {
return ::testing::AssertionFailure() << "OpenChild not successful!";
}
callback_called = false;
fit::result<inspect::ObjectHierarchy> hierarchy_result;
auto hierarchy_promise =
inspect::ReadFromFidl(inspect::ObjectReader(std::move(inspect_handle)))
.then([&](fit::result<inspect::ObjectHierarchy>&
then_hierarchy_result) {
callback_called = true;
hierarchy_result = std::move(then_hierarchy_result);
});
executor_.schedule_task(std::move(hierarchy_promise));
RunLoopUntilIdle();
if (!callback_called) {
return ::testing::AssertionFailure()
<< "Callback passed to ReadFromFidl(<...>).then not called!";
} else if (!hierarchy_result.is_ok()) {
return ::testing::AssertionFailure() << "Hierarchy result not okay!";
}
*hierarchy = hierarchy_result.take_value();
return ::testing::AssertionSuccess();
}
// Verifies that a single inactive element is made active by an inspection and
// made inactive by the inspection's completion.
TEST_F(ChildrenManagerTest, SingleDynamicElement) {
std::vector<std::string> dynamic_child_full_name({"a", "b"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{dynamic_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {dynamic_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, dynamic_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, dynamic_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_ptr, &object));
ASSERT_EQ(dynamic_child_full_name[1], object.name);
a_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
}
// Verifies one-quarter of the "overlap" core use case: that the user can begin
// making use of an element, an inspection can start, the inspection can end,
// the user can release the element, and the element was active exactly as long
// as it should have been.
TEST_F(ChildrenManagerTest, SingleElementInspectInsideUse) {
std::vector<std::string> dynamic_child_full_name({"a", "b"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{dynamic_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {dynamic_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, dynamic_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fit::closure a_b_retainer;
ASSERT_TRUE(Activate(&application, dynamic_child_full_name, &a_b_retainer));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, dynamic_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_ptr, &object));
ASSERT_EQ(dynamic_child_full_name[1], object.name);
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_retainer();
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
}
// Verifies one-quarter of the "overlap" core use case: that an inspection can
// start, the user can start making use of an element, the inspection can end,
// the user can release the element, and the element was active exactly as long
// as it should have been.
TEST_F(ChildrenManagerTest, SingleElementInspectBeforeAndIntoUse) {
std::vector<std::string> dynamic_child_full_name({"a", "b"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{dynamic_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {dynamic_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, dynamic_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, dynamic_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fit::closure a_b_retainer;
ASSERT_TRUE(Activate(&application, dynamic_child_full_name, &a_b_retainer));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_ptr, &object));
ASSERT_EQ(dynamic_child_full_name[1], object.name);
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_retainer();
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
}
// Verifies one-quarter of the "overlap" core use case: that an inspection can
// start, the user can start making use of an element, the user can release the
// element, the inspection can end, and the element was active exactly as long
// as it should have been.
TEST_F(ChildrenManagerTest, SingleElementUseInsideInspect) {
std::vector<std::string> dynamic_child_full_name({"a", "b"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{dynamic_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {dynamic_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, dynamic_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, dynamic_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fit::closure a_b_retainer;
ASSERT_TRUE(Activate(&application, dynamic_child_full_name, &a_b_retainer));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_retainer();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_ptr, &object));
ASSERT_EQ(dynamic_child_full_name[1], object.name);
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
}
// Verifies one-quarter of the "overlap" core use case: that the user can begin
// making use of an element, an inspection can start, the user can release the
// element, the inspection can end, and the element was active exactly as long
// as it should have been.
TEST_F(ChildrenManagerTest, SingleElementUseBeforeAndIntoInspect) {
std::vector<std::string> dynamic_child_full_name({"a", "b"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{dynamic_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {dynamic_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, dynamic_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fit::closure a_b_retainer;
ASSERT_TRUE(Activate(&application, dynamic_child_full_name, &a_b_retainer));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, dynamic_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_ptr, &object));
ASSERT_EQ(dynamic_child_full_name[1], object.name);
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_retainer();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
a_b_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(dynamic_child_full_name));
}
// Verifies that the application does not surrender control of the lifetimes of
// its objects: the application can delete elements in the middle of an ongoing
// inspection and the inspection completes without crashing.
TEST_F(ChildrenManagerTest, ElementsDeletedDuringInspection) {
std::vector<std::string> deepest_child_full_name({"a", "b", "c"});
auto application = Application(&test_loop(), &random_, &elements_node_,
{deepest_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(
Activate(&application, {deepest_child_full_name[0]}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
bool a_error_callback_called;
zx_status_t a_error_status;
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
a_ptr.set_error_handler(callback::Capture(
callback::SetWhenCalled(&a_error_callback_called), &a_error_status));
ASSERT_TRUE(OpenChild(&elements_ptr, deepest_child_full_name[0], &a_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(deepest_child_full_name));
bool a_b_error_callback_called;
zx_status_t a_b_error_status;
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_ptr;
a_b_ptr.set_error_handler(callback::Capture(
callback::SetWhenCalled(&a_b_error_callback_called), &a_b_error_status));
ASSERT_TRUE(OpenChild(&a_ptr, deepest_child_full_name[1], &a_b_ptr));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(deepest_child_full_name));
bool a_b_c_error_callback_called;
zx_status_t a_b_c_error_status;
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_b_c_ptr;
a_b_c_ptr.set_error_handler(
callback::Capture(callback::SetWhenCalled(&a_b_c_error_callback_called),
&a_b_c_error_status));
ASSERT_TRUE(OpenChild(&a_b_ptr, deepest_child_full_name[2], &a_b_c_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deepest_child_full_name));
fuchsia::inspect::Object object;
ASSERT_TRUE(ReadData(&a_b_c_ptr, &object));
ASSERT_EQ(deepest_child_full_name[2], object.name);
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deepest_child_full_name));
application.Delete(
{deepest_child_full_name.begin(), deepest_child_full_name.begin() + 2});
RunLoopUntilIdle();
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity(deepest_child_full_name));
ASSERT_EQ(Activity::INACTIVE, application.DebugGetActivity(
{deepest_child_full_name.begin(),
deepest_child_full_name.begin() + 2}));
// TODO(crjohns, nathaniel): We would like it to be the case that when nodes
// are deleted in the middle of an inspection that the FIDL connections are
// broken and the inspection cannot continue, but... nodes being deleted in
// the middle of an inspection is enough of an edge-case that the current
// behavior of (1) not crashing and (2) reporting stale data is acceptable for
// the remainder of the FIDL implementation's life.
//
// The behavior we'd like:
// ASSERT_TRUE(a_b_c_error_callback_called);
// ASSERT_EQ(ZX_OK, a_b_c_error_status);
// ASSERT_TRUE(!a_b_c_ptr.is_bound());
// ASSERT_EQ(Activity::INACTIVE,
// application.DebugGetActivity(deepest_child_full_name));
// ASSERT_TRUE(a_b_error_callback_called);
// ASSERT_EQ(ZX_OK, a_b_error_status);
// ASSERT_TRUE(!a_b_ptr.is_bound());
// ASSERT_EQ(Activity::INACTIVE, application.DebugGetActivity(
// {deepest_child_full_name.begin(),
// deepest_child_full_name.begin() + 2}));
// ASSERT_TRUE(!a_error_callback_called);
// ASSERT_TRUE(a_ptr.is_bound());
// ASSERT_EQ(Activity::ACTIVE,
// application.DebugGetActivity({deepest_child_full_name[0]}));
//
// ASSERT_TRUE(ReadData(&a_ptr, &object));
// ASSERT_EQ(deepest_child_full_name[0], object.name);
//
// a_ptr.Unbind();
// RunLoopUntilIdle();
//
// ASSERT_EQ(Activity::INACTIVE,
// application.DebugGetActivity({deepest_child_full_name[0]}));
}
// Verifies that activation of elements can be multi-level and that active
// inspections serve to keep active only those portions of the tree of elements
// that should be kept active.
TEST_F(ChildrenManagerTest, FiveLevelsOfDynamicism) {
std::vector<std::string> deep_child_full_name({"a", "b", "c", "d", "e"});
std::vector<std::string> deeper_child_full_name(
{"a", "b", "c", "1", "2", "3"});
auto application =
Application(&test_loop(), &random_, &elements_node_,
{deep_child_full_name, deeper_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(Activate(&application, {"a"}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, "a", &a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> b_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, "b", &b_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> c_ptr;
ASSERT_TRUE(OpenChild(&b_ptr, "c", &c_ptr));
std::vector<std::string> c_child_names;
ASSERT_TRUE(ListChildren(&c_ptr, &c_child_names));
ASSERT_THAT(c_child_names, ElementsAre("1", "d"));
fidl::InterfacePtr<fuchsia::inspect::Inspect> d_ptr;
ASSERT_TRUE(OpenChild(&c_ptr, "d", &d_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> e_ptr;
ASSERT_TRUE(OpenChild(&d_ptr, "e", &e_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> one_ptr;
ASSERT_TRUE(OpenChild(&c_ptr, "1", &one_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> two_ptr;
ASSERT_TRUE(OpenChild(&one_ptr, "2", &two_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> three_ptr;
ASSERT_TRUE(OpenChild(&two_ptr, "3", &three_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deep_child_full_name));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deeper_child_full_name));
// Dropping connections to intermediate nodes doesn't cause those intermediate
// nodes to go inactive.
a_ptr.Unbind();
b_ptr.Unbind();
c_ptr.Unbind();
d_ptr.Unbind();
one_ptr.Unbind();
two_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b", "c"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "d"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1", "2"}));
// Dropping the connection to one end of the "fork" causes the nodes on that
// "fork" to go inactive but not the nodes on the shared "stem".
three_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b", "c"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "d"}));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity({"a", "b", "c", "1"}));
ASSERT_EQ(Activity::INACTIVE,
application.DebugGetActivity({"a", "b", "c", "1", "2"}));
}
// Verifies that concurrent inspections complement one another rather than
// conflict.
TEST_F(ChildrenManagerTest, ConcurrentInspections) {
std::vector<std::string> deep_child_full_name({"a", "b", "c", "d", "e"});
std::vector<std::string> deeper_child_full_name(
{"a", "b", "c", "1", "2", "3"});
auto application =
Application(&test_loop(), &random_, &elements_node_,
{deep_child_full_name, deeper_child_full_name});
fit::closure a_retainer;
ASSERT_TRUE(Activate(&application, {"a"}, &a_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_elements_ptr;
ASSERT_TRUE(OpenElementsNode(&first_elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_elements_ptr;
ASSERT_TRUE(OpenElementsNode(&second_elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_a_ptr;
ASSERT_TRUE(OpenChild(&first_elements_ptr, "a", &first_a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_b_ptr;
ASSERT_TRUE(OpenChild(&first_a_ptr, "b", &first_b_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_c_ptr;
ASSERT_TRUE(OpenChild(&first_b_ptr, "c", &first_c_ptr));
std::vector<std::string> c_child_names;
ASSERT_TRUE(ListChildren(&first_c_ptr, &c_child_names));
ASSERT_THAT(c_child_names, ElementsAre("1", "d"));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_d_ptr;
ASSERT_TRUE(OpenChild(&first_c_ptr, "d", &first_d_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_e_ptr;
ASSERT_TRUE(OpenChild(&first_d_ptr, "e", &first_e_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_one_ptr;
ASSERT_TRUE(OpenChild(&first_c_ptr, "1", &first_one_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_two_ptr;
ASSERT_TRUE(OpenChild(&first_one_ptr, "2", &first_two_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> first_three_ptr;
ASSERT_TRUE(OpenChild(&first_two_ptr, "3", &first_three_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_a_ptr;
ASSERT_TRUE(OpenChild(&second_elements_ptr, "a", &second_a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_b_ptr;
ASSERT_TRUE(OpenChild(&second_a_ptr, "b", &second_b_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_c_ptr;
ASSERT_TRUE(OpenChild(&second_b_ptr, "c", &second_c_ptr));
ASSERT_TRUE(ListChildren(&second_c_ptr, &c_child_names));
ASSERT_THAT(c_child_names, ElementsAre("1", "d"));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_d_ptr;
ASSERT_TRUE(OpenChild(&second_c_ptr, "d", &second_d_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_e_ptr;
ASSERT_TRUE(OpenChild(&second_d_ptr, "e", &second_e_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_one_ptr;
ASSERT_TRUE(OpenChild(&second_c_ptr, "1", &second_one_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_two_ptr;
ASSERT_TRUE(OpenChild(&second_one_ptr, "2", &second_two_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> second_three_ptr;
ASSERT_TRUE(OpenChild(&second_two_ptr, "3", &second_three_ptr));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deep_child_full_name));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity(deeper_child_full_name));
// Dropping connections to intermediate nodes doesn't cause those intermediate
// nodes to go inactive.
first_a_ptr.Unbind();
first_b_ptr.Unbind();
first_c_ptr.Unbind();
first_d_ptr.Unbind();
first_one_ptr.Unbind();
first_two_ptr.Unbind();
second_a_ptr.Unbind();
second_b_ptr.Unbind();
second_c_ptr.Unbind();
second_d_ptr.Unbind();
second_one_ptr.Unbind();
second_two_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b", "c"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "d"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1", "2"}));
// Dropping one but not the other the connection to each end of the "fork"
// causes no nodes to go inactive since all nodes either are or are ancestors
// of nodes that are still "under inspection".
first_three_ptr.Unbind();
second_e_ptr.Unbind();
RunLoopUntilIdle();
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b"}));
ASSERT_EQ(Activity::ACTIVE, application.DebugGetActivity({"a", "b", "c"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "d"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1"}));
ASSERT_EQ(Activity::ACTIVE,
application.DebugGetActivity({"a", "b", "c", "1", "2"}));
}
// Verifies that the Reader API reads an only-active-at-the-first-level
// application hierarchy.
TEST_F(ChildrenManagerTest, ReaderAPIMinimalActiveElements) {
auto depth = 3;
auto application = Application(&test_loop(), &random_, &elements_node_,
CompleteTableDescription(depth));
fit::closure a_retainer;
ASSERT_TRUE(Activate(&application, {"a"}, &a_retainer));
fit::closure b_retainer;
ASSERT_TRUE(Activate(&application, {"b"}, &b_retainer));
fit::closure c_retainer;
ASSERT_TRUE(Activate(&application, {"c"}, &c_retainer));
inspect::ObjectHierarchy hierarchy;
ASSERT_TRUE(ReadWithReaderAPI(&hierarchy));
ASSERT_THAT(hierarchy, CompleteMatcher(depth));
}
// Verifies that the Reader API reads a hierarchy with scattershot activity
// throughout.
TEST_F(ChildrenManagerTest, ReaderAPISomeInactiveElements) {
auto depth = 3;
auto application = Application(&test_loop(), &random_, &elements_node_,
CompleteTableDescription(depth));
fit::closure a_a_a_retainer;
ASSERT_TRUE(Activate(&application, {"a", "a", "a"}, &a_a_a_retainer));
fit::closure b_b_retainer;
ASSERT_TRUE(Activate(&application, {"b", "b"}, &b_b_retainer));
fit::closure c_retainer;
ASSERT_TRUE(Activate(&application, {"c"}, &c_retainer));
inspect::ObjectHierarchy hierarchy;
ASSERT_TRUE(ReadWithReaderAPI(&hierarchy));
ASSERT_THAT(hierarchy, CompleteMatcher(depth));
}
// Verifies that the Reader API reads a hierarchy in which every element is
// active.
TEST_F(ChildrenManagerTest, ReaderAPINoInactiveElements) {
auto depth = 3;
auto leaf_full_names = CompleteTableDescription(depth);
auto application =
Application(&test_loop(), &random_, &elements_node_, leaf_full_names);
std::vector<fit::closure> retainers;
for (const auto& leaf_full_name : leaf_full_names) {
fit::closure retainer;
ASSERT_TRUE(Activate(&application, leaf_full_name, &retainer));
retainers.push_back(std::move(retainer));
}
inspect::ObjectHierarchy hierarchy;
ASSERT_TRUE(ReadWithReaderAPI(&hierarchy));
ASSERT_THAT(hierarchy, CompleteMatcher(depth));
}
// Verifies that the Reader API reads a hierarchy in which another inspection
// is already progressing.
TEST_F(ChildrenManagerTest, ReaderAPIConcurrentInspection) {
auto depth = 3;
auto application = Application(&test_loop(), &random_, &elements_node_,
CompleteTableDescription(depth));
fit::closure a_retainer;
ASSERT_TRUE(Activate(&application, {"a"}, &a_retainer));
fit::closure b_retainer;
ASSERT_TRUE(Activate(&application, {"b"}, &b_retainer));
fit::closure c_retainer;
ASSERT_TRUE(Activate(&application, {"c"}, &c_retainer));
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, "a", &a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_a_ptr;
ASSERT_TRUE(OpenChild(&a_ptr, "a", &a_a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> a_a_a_ptr;
ASSERT_TRUE(OpenChild(&a_a_ptr, "a", &a_a_a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> b_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, "b", &b_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> b_b_ptr;
ASSERT_TRUE(OpenChild(&b_ptr, "b", &b_b_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> c_ptr;
ASSERT_TRUE(OpenChild(&elements_ptr, "c", &c_ptr));
// And for the heck of it: keep a connection to b-a-b without keeping a
// connection to b-a:
fidl::InterfacePtr<fuchsia::inspect::Inspect> b_a_ptr;
ASSERT_TRUE(OpenChild(&b_ptr, "a", &b_a_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> b_a_b_ptr;
ASSERT_TRUE(OpenChild(&b_a_ptr, "b", &b_a_b_ptr));
b_a_ptr.Unbind();
RunLoopUntilIdle();
inspect::ObjectHierarchy hierarchy;
ASSERT_TRUE(ReadWithReaderAPI(&hierarchy));
ASSERT_THAT(hierarchy, CompleteMatcher(depth));
}
TEST_F(ChildrenManagerTest, AbsentChildDoesNotDeadlock) {
// Since we're testing an edge behavior our "representative application"
// doesn't work and we use a custom ChildrenManager.
class ChildrenManager final : public component::ChildrenManager {
public:
ChildrenManager(fit::closure on_detachment)
: on_detachment_(std::move(on_detachment)) {}
private:
void GetNames(
fit::function<void(std::vector<std::string>)> callback) override {}
void Attach(std::string name,
fit::function<void(fit::closure)> callback) override {
callback(std::move(on_detachment_));
}
fit::closure on_detachment_;
};
bool on_detachment_called = false;
ChildrenManager children_manager([this, &on_detachment_called]() {
on_detachment_called = true;
auto int_metric = elements_node_.CreateIntMetric("ignored_int_metric", 0);
});
auto children_manager_retainer =
elements_node_.SetChildrenManager(&children_manager);
fidl::InterfacePtr<fuchsia::inspect::Inspect> elements_ptr;
ASSERT_TRUE(OpenElementsNode(&elements_ptr));
fidl::InterfacePtr<fuchsia::inspect::Inspect> no_such_child_ptr;
ASSERT_FALSE(OpenChild(&elements_ptr, "no_such_child", &no_such_child_ptr));
ASSERT_TRUE(on_detachment_called);
}
} // namespace
| 37.73834
| 80
| 0.69417
|
myself659
|
443eb389a5337bb3d6d7036d42919cf46beae2eb
| 971
|
cp
|
C++
|
libs/cpascal/ASCII.cp
|
imt-ag/gpcp
|
1c3de23993e0979d672f1c8fe7f193d0de22991a
|
[
"BSD-3-Clause"
] | 32
|
2017-08-15T11:49:34.000Z
|
2021-12-24T13:10:29.000Z
|
libs/cpascal/ASCII.cp
|
imt-ag/gpcp
|
1c3de23993e0979d672f1c8fe7f193d0de22991a
|
[
"BSD-3-Clause"
] | 14
|
2017-10-14T16:44:02.000Z
|
2022-03-09T08:17:56.000Z
|
libs/cpascal/ASCII.cp
|
imt-ag/gpcp
|
1c3de23993e0979d672f1c8fe7f193d0de22991a
|
[
"BSD-3-Clause"
] | 7
|
2017-11-10T14:55:30.000Z
|
2022-02-07T01:23:22.000Z
|
(** This is the dummy module that sits in the runtime system,
* or will do if it ever gets a body.
*
* Version: 19 May 2001 (kjg).
*)
SYSTEM MODULE ASCII;
CONST
NUL* = 00X;
SOH* = 01X;
STX* = 02X;
ETX* = 03X;
EOT* = 04X;
ENQ* = 05X;
ACK* = 06X;
BEL* = 07X;
BS* = 08X; (* backspace character *)
HT* = 09X; (* horizontal tab character *)
LF* = 0AX; (* line feed character *)
VT* = 0BX;
FF* = 0CX;
CR* = 0DX; (* carriage return character *)
SO* = 0EX;
SI* = 0FX;
DLE* = 10X;
DC1* = 11X;
DC2* = 12X;
DC3* = 13X;
DC4* = 14X;
NAK* = 15X;
SYN* = 16X;
ETB* = 17X;
CAN* = 18X;
EM* = 19X;
SUB* = 1AX;
ESC* = 1BX; (* escape character *)
FS* = 1CX;
GS* = 1DX;
RS* = 1EX;
US* = 1FX;
SP* = 20X; (* space character *)
DEL* = 7FX; (* delete character *)
END ASCII.
| 21.108696
| 63
| 0.446962
|
imt-ag
|
443ec7d8a58afa6d0d96195e1c2feca9f65c28e3
| 10,238
|
cpp
|
C++
|
3rdparty/mygui/src/MyGUI_SkinManager.cpp
|
Osumi-Akari/energytycoon
|
25d18a0ee4a9f8833e678af297734602918a92e9
|
[
"Unlicense"
] | null | null | null |
3rdparty/mygui/src/MyGUI_SkinManager.cpp
|
Osumi-Akari/energytycoon
|
25d18a0ee4a9f8833e678af297734602918a92e9
|
[
"Unlicense"
] | null | null | null |
3rdparty/mygui/src/MyGUI_SkinManager.cpp
|
Osumi-Akari/energytycoon
|
25d18a0ee4a9f8833e678af297734602918a92e9
|
[
"Unlicense"
] | null | null | null |
/*!
@file
@author Albert Semenov
@date 11/2007
@module
*//*
This file is part of MyGUI.
MyGUI 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.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_SkinManager.h"
#include "MyGUI_LanguageManager.h"
#include "MyGUI_WidgetSkinInfo.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_SubWidgetManager.h"
#include "MyGUI_Gui.h"
namespace MyGUI
{
const std::string XML_TYPE("Skin");
MYGUI_INSTANCE_IMPLEMENT(SkinManager);
void SkinManager::initialise()
{
MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().registerLoadXmlDelegate(XML_TYPE) = newDelegate(this, &SkinManager::_load);
createDefault();
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
mIsInitialise = true;
}
void SkinManager::shutdown()
{
if (false == mIsInitialise) return;
MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);
ResourceManager::getInstance().unregisterLoadXmlDelegate(XML_TYPE);
for (MapWidgetSkinInfoPtr::iterator iter=mSkins.begin(); iter!=mSkins.end(); ++iter) {
WidgetSkinInfoPtr info = iter->second;
info->clear();
delete info;
}
mSkins.clear();
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
mIsInitialise = false;
}
WidgetSkinInfo * SkinManager::getSkin(const Ogre::String & _name)
{
MapWidgetSkinInfoPtr::iterator iter = mSkins.find(_name);
// если не нашли, то вернем дефолтный скин
if (iter == mSkins.end()) {
MYGUI_LOG(Warning, "Skin '" << _name << "' not found, set Default");
return mSkins["Default"];
}
return iter->second;
}
// для ручного создания скина
WidgetSkinInfo * SkinManager::create(const Ogre::String & _name)
{
WidgetSkinInfo * skin = new WidgetSkinInfo();
if (mSkins.find(_name) != mSkins.end()){
MYGUI_LOG(Warning, "Skin with name '" + _name + "' already exist");
mSkins[_name]->clear();
delete mSkins[_name];
}
mSkins[_name] = skin;
return skin;
}
bool SkinManager::load(const std::string & _file, const std::string & _group)
{
return ResourceManager::getInstance()._loadImplement(_file, _group, true, XML_TYPE, INSTANCE_TYPE_NAME);
}
void SkinManager::_load(xml::ElementPtr _node, const std::string & _file, Version _version)
{
LanguageManager& localizator = LanguageManager::getInstance();
// вспомогательный класс для биндинга сабскинов
SubWidgetBinding bind;
// берем детей и крутимся, основной цикл со скинами
xml::ElementEnumerator skin = _node->getElementEnumerator();
while (skin.next(XML_TYPE)) {
// парсим атрибуты скина
Ogre::String name, texture, tmp;
IntSize size;
skin->findAttribute("name", name);
skin->findAttribute("texture", texture);
if (skin->findAttribute("size", tmp)) size = IntSize::parse(tmp);
// поддержка замены тегов в скинах
if (_version >= Version(1, 1)) {
texture = localizator.replaceTags(texture);
}
// создаем скин
WidgetSkinInfo * widget_info = create(name);
widget_info->setInfo(size, texture);
IntSize materialSize = getTextureSize(texture);
// проверяем маску
if (skin->findAttribute("mask", tmp)) {
if (false == widget_info->loadMask(tmp)) {
MYGUI_LOG(Error, "Skin: " << _file << ", mask not load '" << tmp << "'");
}
}
// берем детей и крутимся, цикл с саб скинами
xml::ElementEnumerator basis = skin->getElementEnumerator();
while (basis.next()) {
if (basis->getName() == "Property") {
// загружаем свойства
std::string key, value;
if (false == basis->findAttribute("key", key)) continue;
if (false == basis->findAttribute("value", value)) continue;
// поддержка замены тегов в скинах
if (_version >= Version(1, 1)) {
value = localizator.replaceTags(value);
}
// добавляем свойство
widget_info->addProperty(key, value);
}
else if (basis->getName() == "Child") {
ChildSkinInfo child(
basis->findAttribute("type"),
WidgetStyle::parse(basis->findAttribute("style")),
basis->findAttribute("skin"),
IntCoord::parse(basis->findAttribute("offset")),
Align::parse(basis->findAttribute("align")),
basis->findAttribute("layer"),
basis->findAttribute("name")
);
xml::ElementEnumerator child_params = basis->getElementEnumerator();
while (child_params.next("Property"))
child.addParam(child_params->findAttribute("key"), child_params->findAttribute("value"));
widget_info->addChild(child);
//continue;
}
else if (basis->getName() == "BasisSkin") {
// парсим атрибуты
Ogre::String basisSkinType, tmp;
IntCoord offset;
Align align = Align::Default;
basis->findAttribute("type", basisSkinType);
if (basis->findAttribute("offset", tmp)) offset = IntCoord::parse(tmp);
if (basis->findAttribute("align", tmp)) align = Align::parse(tmp);
bind.create(offset, align, basisSkinType);
// берем детей и крутимся, цикл со стейтами
xml::ElementEnumerator state = basis->getElementEnumerator();
// проверяем на новый формат стейтов
bool new_format = false;
// если версия меньше 1.0 то переименовываем стейты
if (_version < Version(1, 0)) {
while (state.next()) {
if (state->getName() == "State") {
const std::string & name_state = state->findAttribute("name");
if ((name_state == "normal_checked") || (state->findAttribute("name") == "normal_check")) {
new_format = true;
break;
}
}
};
// обновляем
state = basis->getElementEnumerator();
}
while (state.next()) {
if (state->getName() == "State") {
// парсим атрибуты стейта
Ogre::String basisStateName;
state->findAttribute("name", basisStateName);
// если версия меньше 1.0 то переименовываем стейты
if (_version < Version(1, 0)) {
// это обсолет новых типов
if (basisStateName == "disable_check") basisStateName = "disabled_checked";
else if (basisStateName == "normal_check") basisStateName = "normal_checked";
else if (basisStateName == "active_check") basisStateName = "highlighted_checked";
else if (basisStateName == "pressed_check") basisStateName = "pushed_checked";
else if (basisStateName == "disable") basisStateName = "disabled";
else if (basisStateName == "active") basisStateName = "highlighted";
else if (basisStateName == "select") basisStateName = "pushed";
else if (basisStateName == "pressed") {
if (new_format) basisStateName = "pushed";
else basisStateName = "normal_checked";
}
}
// конвертируем инфу о стейте
StateInfo * data = SubWidgetManager::getInstance().getStateData(basisSkinType, state.current(), skin.current(), _version);
// добавляем инфо о стайте
bind.add(basisStateName, data, name);
}
else if (state->getName() == "Property") {
// загружаем свойства
std::string key, value;
if (false == state->findAttribute("key", key)) continue;
if (false == state->findAttribute("value", value)) continue;
// поддержка замены тегов в скинах
/*if (_version >= Version(1, 1)) {
value = localizator.replaceTags(value);
}*/
// добавляем свойство
bind.addProperty(key, value);
}
};
// теперь всё вместе добавляем в скин
widget_info->addInfo(bind);
}
};
};
}
IntSize SkinManager::getTextureSize(const std::string & _texture)
{
// предыдущя текстура
static std::string old_texture;
static IntSize old_size;
if (old_texture == _texture) return old_size;
old_texture = _texture;
old_size.clear();
if (_texture.empty()) return old_size;
Ogre::TextureManager & manager = Ogre::TextureManager::getSingleton();
if (false == manager.resourceExists(_texture)) {
std::string group = Gui::getInstance().getResourceGroup();
if (!helper::isFileExist(_texture, group)) {
MYGUI_LOG(Error, "Texture '" + _texture + "' not found in group '" << group << "'");
return old_size;
}
else {
manager.load(
_texture,
group,
Ogre::TEX_TYPE_2D,
0);
}
}
Ogre::TexturePtr tex = (Ogre::TexturePtr)manager.getByName(_texture);
if (tex.isNull()) {
MYGUI_LOG(Error, "Texture '" + _texture + "' not found");
return old_size;
}
tex->load();
old_size.set((int)tex->getWidth(), (int)tex->getHeight());
#if MYGUI_DEBUG_MODE == 1
if (isPowerOfTwo(old_size) == false) {
MYGUI_LOG(Warning, "Texture '" + _texture + "' have non power ow two size");
}
#endif
return old_size;
}
FloatRect SkinManager::convertTextureCoord(const FloatRect & _source, const IntSize & _textureSize)
{
if (!_textureSize.width || !_textureSize.height) return FloatRect();
return FloatRect(
_source.left / _textureSize.width,
_source.top / _textureSize.height,
(_source.left + _source.right) / _textureSize.width,
(_source.top + _source.bottom) / _textureSize.height);
}
void SkinManager::createDefault()
{
// создаем дефолтный скин
WidgetSkinInfo * widget_info = create("Default");
widget_info->setInfo(IntSize(0, 0), "");
}
bool SkinManager::isPowerOfTwo(IntSize _size)
{
int count = 0;
while (_size.width > 0) {
count += _size.width & 1;
_size.width >>= 1;
};
if (count != 1) return false;
count = 0;
while (_size.height > 0) {
count += _size.height & 1;
_size.height >>= 1;
};
if (count != 1) return false;
return true;
}
} // namespace MyGUI
| 30.289941
| 129
| 0.66175
|
Osumi-Akari
|
444223c1ee136fd49ca8cdee73f57cee300a5b83
| 2,343
|
cpp
|
C++
|
src/cpp/chromosomes.cpp
|
srbehera/Nebula
|
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
|
[
"MIT"
] | 11
|
2021-01-28T12:08:36.000Z
|
2022-03-21T01:42:08.000Z
|
src/cpp/chromosomes.cpp
|
srbehera/Nebula
|
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
|
[
"MIT"
] | 6
|
2021-07-19T08:11:23.000Z
|
2021-09-17T21:05:35.000Z
|
src/cpp/chromosomes.cpp
|
srbehera/Nebula
|
3dba4c0aef5d0c1660748ee9bd8e1e4e74b933c3
|
[
"MIT"
] | 3
|
2021-08-02T05:10:06.000Z
|
2021-11-17T03:20:28.000Z
|
#include <iomanip>
#include "chromosomes.hpp"
using namespace std ;
std::vector<std::string> chromosomes ;
std::unordered_map<std::string, char*> chromosome_seqs ;
int get_reference_size(ifstream &fasta_file) {
fasta_file.seekg(0, ios_base::end) ;
int l = fasta_file.tellg() ;
fasta_file.seekg(0, ios_base::beg) ;
return l ;
}
void load_chromosomes(string path) {
cout << "Loading reference genome.." << endl ;
ifstream fasta_file ;
fasta_file.open(path, ios::binary) ;
// maximum size of a chromosome, kinda arbitrary
char* buffer = (char*) malloc(sizeof(char) * 300000000) ;
int state ;
uint64_t n = 0 ;
std::string line ;
std::getline(fasta_file, line) ;
while (true) {
if (line[0] == '>') {
int o = 3 ; //hg19 style
if (line.substr(1, 3) == "chr") {
o = 0 ;
}
int l = line.length() ;
if (l == 6 - o || l == 5 - o) {
if (line[4 - o] == 'X' || line[4 - o] == 'Y' || (line[4 - o] >= '1' && line[4 - o] <= '9')) {
string chrom = (o == 3 ? "chr" : "") + line.substr(1, l - 1) ; // chromosome names will begin with "chr"
//cout << "Collecting " << chrom << ".." << endl ;
while(std::getline(fasta_file, line)) {
if (line[0] == '>') {
break ;
}
for (int i = 0; i < line.length(); i++) {
line[i] = toupper(line[i]) ;
}
memcpy(buffer + n, line.c_str(), line.length()) ;
n += line.length() ;
}
buffer[n] = '\0' ;
cout << "Extracted " << std::setw(6) << std::left << chrom << " with " << std::setw(11) << left << n << " bases." << endl ;
char* s = (char*) malloc(sizeof(char) * (n + 1)) ;
memcpy(s, buffer, n + 1) ;
chromosomes.push_back(chrom) ;
chromosome_seqs[chrom] = s ;
n = 0 ;
continue ;
}
}
}
if (!std::getline(fasta_file, line)) {
break ;
}
}
free(buffer) ;
}
| 36.046154
| 143
| 0.423816
|
srbehera
|
4443c3f55fef52a1f378600e298b0af1044b01e7
| 637
|
cpp
|
C++
|
src/editablemesh.cpp
|
honoriocassiano/skbar
|
e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4
|
[
"MIT"
] | null | null | null |
src/editablemesh.cpp
|
honoriocassiano/skbar
|
e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4
|
[
"MIT"
] | 5
|
2020-09-01T12:16:28.000Z
|
2020-09-01T12:21:41.000Z
|
src/editablemesh.cpp
|
honoriocassiano/skbar
|
e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4
|
[
"MIT"
] | null | null | null |
#include "editablemesh.h"
#include "opquadmesh.h"
#include "optrimesh.h"
#include "utils/debug.h"
#include <set>
skbar::EditableMesh::EditableMesh() : quadMesh(new skbar::OPQuadMesh()), triMesh(new skbar::OPTriMesh()) {
}
skbar::EditableMesh::~EditableMesh() {
delete quadMesh;
delete triMesh;
quadMesh = nullptr;
triMesh = nullptr;
}
bool skbar::EditableMesh::Load(const std::string &filename) {
quadMesh->Load(filename);
triMesh->Load(*quadMesh);
}
skbar::BBox skbar::EditableMesh::GetBBox() const {
return quadMesh->GetBBox();
}
void skbar::EditableMesh::Render() const {
triMesh->Render();
}
| 19.30303
| 106
| 0.686028
|
honoriocassiano
|
444417d952fe4a0453b2b692de9f372ba854ed6b
| 32,591
|
hpp
|
C++
|
boost/numeric/ublasx/operation/ql.hpp
|
comcon1/boost-ublasx
|
290b92b643a944825df99bece3468a4f81518056
|
[
"BSL-1.0"
] | null | null | null |
boost/numeric/ublasx/operation/ql.hpp
|
comcon1/boost-ublasx
|
290b92b643a944825df99bece3468a4f81518056
|
[
"BSL-1.0"
] | null | null | null |
boost/numeric/ublasx/operation/ql.hpp
|
comcon1/boost-ublasx
|
290b92b643a944825df99bece3468a4f81518056
|
[
"BSL-1.0"
] | null | null | null |
/**
* \file boost/numeric/ublasx/operation/ql.hpp
*
* \brief The QL matrix decomposition.
*
* Given an \f$m\f$-by-\f$n\f$ matrix \f$A\f$, its QL-decomposition is a matrix
* decomposition of the form:
* \f[
* A=QL
* \f]
* where \f$L\f$ is an m-by-n lower trapezoidal (or, when \f$m \ge n\f$,
* triangular) matrix and \f$Q\f$ is an m-by-m orthogonal (or unitary) matrix,
* that is one satisfying:
* \f[
* Q^{T}Q=I
* \f]
where \f$Q^{T}\f$ is the transpose of \f$Q\f$ and \f$I\f$ is the identity
* matrix.
*
* For the special case of \f$m \ge n\f$, the factorization can be rewritten as:
* \f[
* A=\begin{pmatrix}
* Q_1 & Q_2
* \end{pmatrix}
* \begin{pmatrix}
* L_1 \\
* L_2 \\
* \end{pmatrix}
* =\begin{pmatrix}
* Q_1 & Q_2
* \end{pmatrix}
* \begin{pmatrix}
* 0 \\
* L_2 \\
* \end{pmatrix}
* = Q_2 L_2
* \f]
* where \f$Q_1\f$ is an m-by-(m-n) matrix, \f$Q_2\f$ is an m-by-n matrix,
* \f$L_1\f$ is an (m-n)-by-n zero matrix, and \f$L_2\f$ is an n-by-n lower
* triangular matrix.
*
* The QL factorization is particular useful for computing minimum-phase
* filters.
*
* <hr/>
*
* Copyright (c) 2010, Marco Guazzone
*
* 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)
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
#ifndef BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP
#define BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP
#include <algorithm>
#include <boost/mpl/and.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/numeric/bindings/lapack/computational/geqlf.hpp>
#include <boost/numeric/bindings/lapack/computational/orgql.hpp>
#include <boost/numeric/bindings/lapack/computational/ormql.hpp>
#include <boost/numeric/bindings/lapack/computational/ungql.hpp>
#include <boost/numeric/bindings/ublas.hpp>
#include <boost/numeric/bindings/tag.hpp>
#include <boost/numeric/bindings/trans.hpp>
#include <boost/numeric/ublas/detail/temporary.hpp>
#include <boost/numeric/ublas/expression_types.hpp>
#include <boost/numeric/ublas/fwd.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_expression.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_expression.hpp>
#include <boost/numeric/ublasx/operation/num_columns.hpp>
#include <boost/numeric/ublasx/operation/num_rows.hpp>
#include <boost/numeric/ublasx/operation/size.hpp>
#include <boost/numeric/ublasx/traits/layout_type.hpp>
#include <boost/type_traits/is_same.hpp>
#include <complex>
#include <cstddef>
#include <stdint.h>
namespace boost { namespace numeric { namespace ublasx {
using namespace ::boost::numeric::ublas;
namespace detail { namespace /*<unnamed>*/ {
struct ql_decomposition_impl_common;
/**
* \brief Type-oriented operations for QL decomposition.
*
* \tparam IsComplex Logical parameter telling if the we are doing either a real
* or a complex QL decomposition.
*
* This class makes distinction between the real and the complex case.
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
template <bool IsComplex>
struct ql_decomposition_impl;
/**
* \brief Common operations for QL decomposition.
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
struct ql_decomposition_impl_common
{
/// Performan QL decomposition of the given input matrix \a A
/// (row-major case).
template <typename AMatrixT, typename TauVectorT>
static void decompose(AMatrixT& A, TauVectorT& tau, row_major_tag)
{
matrix<typename matrix_traits<AMatrixT>::value_type, column_major> tmp_A(A);
decompose(tmp_A, tau, column_major_tag());
A = tmp_A;
}
/// Performan QL decomposition of the given input matrix \a A
/// (column-major case).
template <typename AMatrixT, typename TauVectorT>
static void decompose(AMatrixT& A, TauVectorT& tau, column_major_tag)
{
typedef typename matrix_traits<AMatrixT>::size_type size_type;
size_type m = num_rows(A);
size_type n = num_columns(A);
size_type k = ::std::min(m,n);
if (size(tau) != k)
{
tau.resize(k, false);
}
::boost::numeric::bindings::lapack::geqlf(A, tau);
}
/// Extract the L matrix from a previously computing QL decomposition
/// (row-major case).
template <typename QLMatrixT, typename LMatrixT>
static void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, row_major_tag)
{
matrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);
matrix<typename matrix_traits<LMatrixT>::value_type, column_major> tmp_L(L);
extract_L(tmp_QL, tmp_L, full, column_major_tag());
L = tmp_L;
}
/**
* \brief Extract the L matrix from a previously computing QL decomposition
* (column-major case).
*
* Let QL be an m-by-n matrix, then the L matrix is built as:
* - If m >= n, the lower triangle of the submatrix QL(m-n+1:m,1:n)
* contains the n-by-n lower triangular matrix L;
* - if m <= n, the elements on and below the (n-m)-th
* superdiagonal contain the m-by-n lower trapezoidal matrix L.
* .
*/
template <typename QLMatrixT, typename LMatrixT>
static void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, column_major_tag)
{
typedef typename matrix_traits<LMatrixT>::size_type size_type;
typedef typename matrix_traits<LMatrixT>::value_type value_type;
size_type m = num_rows(QL);
size_type n = num_columns(QL);
size_type nr = full ? m : ::std::min(m,n);
if (num_rows(L) != nr && num_columns(L) != n)
{
L.resize(nr, n, false);
}
//::std::fill(L.data().begin(), L.data().end(), value_type/*zero*/());
if (m >= n)
{
size_type k = m-n;
size_type kr = k;
// Set to zero the first m-n rows
if (full)
{
subrange(L, 0, k, 0, n) = scalar_matrix<value_type>(k, n, value_type/*zero*/());
// for (size_type row = 0; row < k; ++row)
// {
// for(size_type col = 0; col < n; ++col)
// {
// L(row,col) = value_type/*zero*/();
// }
// }
kr = 0;
}
// the lower triangle of the submatrix QL(m-n+1:m,1:n) contains the
// n-by-n lower triangular matrix L
for (size_type row = k; row < m; ++row)
{
for (size_type col = 0; col < n; ++col)
{
if (col <= (row-k))
{
L(row-kr,col) = QL(row,col);
}
else
{
L(row-kr,col) = value_type/*zero*/();
}
}
}
}
else
{
// the elements on and below the (n-m)-th
// superdiagonal contain the m-by-n lower trapezoidal matrix L.
size_type k = n-m;
for (size_type row = 0; row < m; ++row)
{
for(size_type col = 0; col < n; ++col)
{
if (col <= (row+k))
{
L(row,col) = QL(row,col);
}
else
{
L(row,col) = value_type/*zero*/();
}
}
}
}
}
/**
* \brief Multiply the given \a C matrix by the \c Q matrix obtained from
* the QL decomposition.
*
* \tparam QLMatrixT The type of the \a QL matrix.
* \tparam TAUMatrixT The type of the \a tau vector.
* \tparam CMatrixT The type of the \a C matrix.
*
* \param QL The matrix obtained by the QL decomposition such that the i-th
* column contains the vector which defines the elementary reflector
* \f$H(i)\f$, for \f$i = 1,2,\ldots,k\f$.
* \param tau The vector obtained by the QL decomposition containing the
* scalar factors of the elementary reflectors \f$H(i)\f$, for
* \f$i=1,2,\ldots,k\f$.
* \param left_Q A boolean value indicating which side of the product the
* matrix \c Q will occupy. A \c true value indicates that \c Q is the left
* operand, while a \c false value indicates that \c Q is the right
* operand.
* \param trans_Q A boolean value indicating if the matrix \c Q is to be
* transposed. A \c true value indicates that \c Q is to be transposed,
* while a \c false value indicates that \c Q is to be taken as-is.
* \param orientation The matrix orientation fixed to row-major.
*
* Let \c Q be the matrix obtained from the QL decomposition represented
* by the \a QL matrix and the \a tau vector parameters.
* Then this function computes the following matrix product:
* \f{equation*}{
* \begin{cases}
* Q C, & \text{\texttt{left\_Q} = \emph{true} and \texttt{trans\_Q} = \emph{false}}, \\
* Q^T C, & \text{\texttt{left\_Q} = \emph{true} and \texttt{trans\_Q} = \emph{true}}, \\
* C Q, & \text{\texttt{left\_Q} = \emph{false} and \texttt{trans\_Q} = \emph{false}}, \\
* C Q^T, & \text{\texttt{left\_Q} = \emph{false} and \texttt{trans\_Q} = \emph{true}}.
* \end{cases}
* \f}
*/
template <typename QLMatrixT, typename TAUVectorT, typename CMatrixT>
static void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, row_major_tag)
{
//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring
// it at the end of the function.
matrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);
matrix<typename matrix_traits<CMatrixT>::value_type, column_major> tmp_C(C);
prod(tmp_QL, tau, tmp_C, left_Q, trans_Q, column_major_tag());
C = tmp_C;
}
/**
* \brief Multiply the given \a C matrix by the \c Q matrix obtained from
* the QL decomposition.
*
* \tparam QLMatrixT The type of the \a QL matrix.
* \tparam TAUMatrixT The type of the \a tau vector.
* \tparam CMatrixT The type of the \a C matrix.
*
* \param QL The matrix obtained by the QL decomposition such that the i-th
* column contains the vector which defines the elementary reflector
* \f$H(i)\f$, for \f$i = 1,2,\ldots,k\f$.
* \param tau The vector obtained by the QL decomposition containing the
* scalar factors of the elementary reflectors \f$H(i)\f$, for
* \f$i=1,2,\ldots,k\f$.
* \param left_Q A boolean value indicating which side of the product the
* matrix \c Q will occupy. A \c true value indicates that \c Q is the left
* operand, while a \c false value indicates that \c Q is the right
* operand.
* \param trans_Q A boolean value indicating if the matrix \c Q is to be
* transposed. A \c true value indicates that \c Q is to be transposed,
* while a \c false value indicates that \c Q is to be taken as-is.
* \param orientation The matrix orientation fixed to column-major.
*
* Let \c Q be the matrix obtained from the QL decomposition represented
* by the \a QL matrix and the \a tau vector parameters.
* Then this function computes the following matrix product:
* \f{equation*}{
* \begin{cases}
* Q C, & \text{\texttt{left\_Q} = \emph{true} and \texttt{trans\_Q} = \emph{false}}, \\
* Q^T C, & \text{\texttt{left\_Q} = \emph{true} and \texttt{trans\_Q} = \emph{true}}, \\
* C Q, & \text{\texttt{left\_Q} = \emph{false} and \texttt{trans\_Q} = \emph{false}}, \\
* C Q^T, & \text{\texttt{left\_Q} = \emph{false} and \texttt{trans\_Q} = \emph{true}}.
* \end{cases}
* \f}
*/
template <typename QLMatrixT, typename TAUVectorT, typename CMatrixT>
static void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, column_major_tag /*orientation*/)
{
//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring
// it at the end of the function.
// typedef typename matrix_traits<QLMatrixT>::value_type value_type;
// typedef typename matrix_traits<QLMatrixT>::size_type size_type;
// typedef typename type_traits<value_type>::real_type real_type;
//
// const ::fortran_int_t m = num_rows(C);
// const ::fortran_int_t n = num_columns(C);
// const ::fortran_int_t k = size(tau);
// const ::fortran_int_t lda = num_rows(QL);
// const ::fortran_int_t ldc = m;
// real_type* work;
// real_type opt_work_size;
// ::fortran_int_t lwork;
// ::std::ptrdiff_t info;
if (left_Q)
{
if (trans_Q)
{
// //FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::left(),
// ::boost::numeric::bindings::tag::transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// &opt_work_size,
// -1
// );
// lwork = static_cast< ::fortran_int_t >(opt_work_size);
// work = new real_type[lwork];
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::left(),
// ::boost::numeric::bindings::tag::transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// work,
// lwork
// );
// delete[] work;
::boost::numeric::bindings::lapack::ormql(
::boost::numeric::bindings::tag::left(),
::boost::numeric::bindings::trans(QL),
tau,
C
);
}
else
{
// //FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::left(),
// ::boost::numeric::bindings::tag::no_transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// &opt_work_size,
// -1
// );
// lwork = static_cast< ::fortran_int_t >(opt_work_size);
// work = new real_type[lwork];
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::left(),
// ::boost::numeric::bindings::tag::no_transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// work,
// lwork
// );
// delete[] work;
::boost::numeric::bindings::lapack::ormql(
::boost::numeric::bindings::tag::left(),
QL,
tau,
C
);
}
}
else
{
if (trans_Q)
{
// //FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::right(),
// ::boost::numeric::bindings::tag::transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// &opt_work_size,
// -1
// );
// lwork = static_cast< ::fortran_int_t >(opt_work_size);
// work = new real_type[lwork];
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::right(),
// ::boost::numeric::bindings::tag::transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// work,
// lwork
// );
// delete[] work;
::boost::numeric::bindings::lapack::ormql(
::boost::numeric::bindings::tag::right(),
::boost::numeric::bindings::trans(QL),
tau,
C
);
}
else
{
// //FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::right(),
// ::boost::numeric::bindings::tag::no_transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// &opt_work_size,
// -1
// );
// lwork = static_cast< ::fortran_int_t >(opt_work_size);
// work = new real_type[lwork];
// info = ::boost::numeric::bindings::lapack::detail::ormql(
// ::boost::numeric::bindings::tag::right(),
// ::boost::numeric::bindings::tag::no_transpose(),
// m,
// n,
// k,
// QL.data().begin(),
// lda,
// tau.data().begin(),
// C.data().begin(),
// ldc,
// work,
// lwork
// );
// delete[] work;
::boost::numeric::bindings::lapack::ormql(
::boost::numeric::bindings::tag::right(),
QL,
tau,
C
);
}
}
}
};
/**
* \brief QL decomposition operations for non-complex types.
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
template <>
struct ql_decomposition_impl<false>: public ql_decomposition_impl_common
{
/// Extract the Q matrix from a previously computing QL decomposition
/// (row-major case).
template <typename QLMatrixT, typename TauVectorT, typename QMatrixT>
static void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)
{
matrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);
matrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);
extract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());
Q = tmp_Q;
}
/// Extract the Q matrix from a previously computing QL decomposition
/// (column-major case).
template <typename QLMatrixT, typename TauVectorT, typename QMatrixT>
static void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)
{
typedef typename matrix_traits<QMatrixT>::size_type size_type;
typedef typename matrix_traits<QMatrixT>::value_type value_type;
size_type m = num_rows(QL);
size_type n = num_columns(QL);
size_type nc = full ? m : ::std::min(m,n);
if (num_rows(Q) != m || num_columns(Q) != nc)
{
Q.resize(m, nc, false);
}
if (m > n)
{
if (full)
{
subrange(Q, 0, m, 0, m-n) = scalar_matrix<value_type>(m, m-n, value_type/*zero*/());
subrange(Q, 0, m, m-n, m) = QL;
}
else
{
Q = QL;
}
}
else if (m < n)
{
subrange(Q, 0, m-1, 0, 1) = scalar_matrix<value_type>(m-1, 1, value_type/*zero*/());
subrange(Q, m-1, m, 0, m) = scalar_matrix<value_type>(1, m, value_type/*zero*/());
subrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);
}
else
{
Q = QL;
}
::boost::numeric::bindings::lapack::orgql(Q, tau);
/*
// Compute Q without LAPACK
//
// The matrix Q is represented as a product of elementary reflectors
// Q = H(k) . . . H(2) H(1), where k = min(m,n).
// Each H(i) has the form
// H(i) = I - tau * v * v'
// where tau is a real scalar, and v is a real vector with
// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in
// A(1:m-k+i-1,n-k+i), and tau in TAU(i).
size_type k = std::min(m, n);
if (num_rows(Q) != m || num_columns(Q) != m)
{
Q.resize(m, m, false);
}
identity_matrix<value_type> I(m);
Q = I;
for (size_type i = k-1; (i+1) > 0; --i)
{
// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]
vector<value_type> v(m, value_type());
for (size_type j = 0; j < m-k+i; ++j)
{
v(j) = QL(j,i);
}
v(m-k+i) = value_type(1);
matrix<value_type, column_major> H = I - tau(i)*outer_prod(v, v);
Q = prod(Q, H);
}
*/
}
};
/**
* \brief QL decomposition operations for complex types.
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
template <>
struct ql_decomposition_impl<true>: public ql_decomposition_impl_common
{
/// Extract the Q matrix from a previously computing QL decomposition
/// (row-major case).
template <typename QLMatrixT, typename TauVectorT, typename QMatrixT>
static void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)
{
matrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);
matrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);
extract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());
Q = tmp_Q;
}
/// Extract the Q matrix from a previously computing QL decomposition
/// (column-major case).
template <typename QLMatrixT, typename TauVectorT, typename QMatrixT>
static void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)
{
typedef typename matrix_traits<QMatrixT>::size_type size_type;
typedef typename matrix_traits<QMatrixT>::value_type value_type;
size_type m = num_rows(QL);
size_type n = num_columns(QL);
size_type nc = full ? m : std::min(m,n);
if (num_rows(Q) != m || num_columns(Q) != nc)
{
Q.resize(m, nc, false);
}
if (m > n)
{
if (full)
{
subrange(Q, 0, m, 0, m-n) = scalar_matrix<value_type>(m, m-n, 0);
subrange(Q, 0, m, m-n, m) = QL;
}
else
{
Q = QL;
}
}
else if (m < n)
{
subrange(Q, 0, m-1, 0, 1) = scalar_matrix<value_type>(m-1, 1, 0);
subrange(Q, m-1, m, 0, m) = scalar_matrix<value_type>(1, m, 0);
subrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);
}
else
{
Q = QL;
}
::boost::numeric::bindings::lapack::ungql(Q, tau);
/*
// Compute Q without LAPACK
//
// The matrix Q is represented as a product of elementary reflectors
// Q = H(k) . . . H(2) H(1), where k = min(m,n).
// Each H(i) has the form
// H(i) = I - tau * v * v'
// where tau is a real scalar, and v is a real vector with
// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in
// A(1:m-k+i-1,n-k+i), and tau in TAU(i).
size_type k = std::min(m, n);
if (num_rows(Q) != m || num_columns(Q) != m)
{
Q.resize(m, m, false);
}
identity_matrix<value_type> I(m);
Q = I;
for (size_type i = k-1; (i+1) > 0; --i)
{
// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]
vector<value_type> v(m, value_type());
for (size_type j = 0; j < m-k+i; ++j)
{
v(j) = QL(j,i);
}
v(m-k+i) = value_type(1);
matrix<value_type, column_major> H = I - tau(i)*outer_prod(v, v);
Q = prod(Q, H);
}
*/
}
};
/// Free function performing the QL decomposition of the given matrix expression \a A.
template<typename MatrixExprT, typename QMatrixT, typename LMatrixT, typename OrientationT>
void ql_decompose_impl(matrix_expression<MatrixExprT> const& A, QMatrixT& Q, LMatrixT& L, bool full, OrientationT orientation)
{
typedef typename matrix_traits<MatrixExprT>::value_type value_type;
matrix<value_type, typename layout_type<MatrixExprT>::type> tmp_QL(A);
vector<value_type> tmp_tau;
ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template decompose(tmp_QL, tmp_tau, orientation);
ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template extract_Q(tmp_QL, tmp_tau, Q, full, orientation);
ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template extract_L(tmp_QL, L, full, orientation);
}
}} // Namespace detail::<unnamed>
/**
* \brief QL decomposition.
*
* \tparam ValueT The type of the elements stored in the input matrices.
*
* \todo Currently, the type of the L matrix is a dense matrix.
* Can we use a better matrix structure?
*
* \author Marco Guazzone, marco.guazzone@gmail.com
*/
template <typename ValueT>
class ql_decomposition
{
public: typedef ValueT value_type;
private: typedef matrix<value_type, column_major> work_matrix_type;
private: typedef vector<value_type> tau_vector_type;
public: typedef work_matrix_type QL_matrix_type;
public: typedef work_matrix_type Q_matrix_type;
public: typedef work_matrix_type L_matrix_type;//TODO: Can I use a special matrix
/// Default constructor.
public: ql_decomposition()
{
// empty
}
/// Decompose the given matrix expression \a A.
public: template <typename MatrixExprT>
ql_decomposition(matrix_expression<MatrixExprT> const& A)
: QL_(A)
{
decompose();
}
/// Decompose the given matrix expression \a A.
public: template <typename MatrixExprT>
void decompose(matrix_expression<MatrixExprT> const& A)
{
QL_ = A;
decompose();
}
/**
* \brief Extract the \c Q matrix.
* \param full If \c false enables the economy-size mode whereby a
* reduced (rectangular) Q matrix is returned instead of full (square) one.
* \return The \c Q matrix.
*
* The <em>economy-size</em> mode is useful when \f$m > n\f$ (where \f$m\f$
* and \f$n\f$ are the number of rows and columns of the decomposed matrix
* \f$A\f$).
* As a matter of fact, in this case, the QL factorization can be viewed as:
* \f[
* A = QL = \begin{pmatrix} Q_1 & Q_2 \end{pmatrix} \begin{pmatrix} 0 \\ L \end{pmatrix} = Q_2 L
* \f]
* where \f$Q_2\f$ is an m-by-n matrix containing the n trailing columns of
* \f$Q\f$.
*/
public: Q_matrix_type Q(bool full = true) const
{
Q_matrix_type tmp_Q;
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template extract_Q(QL_, tau_, tmp_Q, full, column_major_tag());
return tmp_Q;
}
/**
* \brief Extract the \c L matrix.
* \param full If \c false enables the economy-size mode whereby a
* reduced \f$\min(m,n)\f$-by\f$n\f$ \c L matrix is returned instead of the
* full \f$m\f$-by-\f$n\f$ one.
* \return The \c L matrix.
*
* The <em>economy-size</em> mode is useful when \f$m > n\f$ (where \f$m\f$
* and \f$n\f$ are the number of rows and columns of the decomposed matrix
* \f$A\f$).
* As a matter of fact, in this case, the QL factorization can be viewed as:
* \f[
* A = QL = \begin{pmatrix} Q_1 & Q_2 \end{pmatrix} \begin{pmatrix} 0 \\ L \end{pmatrix} = Q_2 L
* \f]
* where \f$Q_2\f$ is an m-by-n matrix containing the n trailing columns of
* \f$Q\f$.
*/
public: L_matrix_type L(bool full = true) const
{
L_matrix_type tmp_L;
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template extract_L(QL_, tmp_L, full, column_major_tag());
return tmp_L;
}
/// Perform the product \f$Q C\f$ and store the result in \a C.
public: template <typename CMatrixT>
void lprod_inplace(CMatrixT& C) const
{
typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;
lprod_inplace(C, orientation_category());
}
/// Perform the product \f$C Q\f$ and store the result in \a C.
public: template <typename CMatrixT>
void rprod_inplace(CMatrixT& C) const
{
typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;
rprod_inplace(C, orientation_category());
}
/// Perform the product \f$Q^T C\f$ and store the result in \a C.
public: template <typename CMatrixT>
void tlprod_inplace(CMatrixT& C) const
{
typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;
tlprod_inplace(C, orientation_category());
}
/// Perform the product \f$C Q^T\f$ and store the result in \a C.
public: template <typename CMatrixT>
void trprod_inplace(CMatrixT& C) const
{
typedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;
trprod_inplace(C, orientation_category());
}
/// Perform the product \f$Q C\f$ and return the result.
public: template <typename CMatrixExprT>
typename matrix_temporary_traits<CMatrixExprT>::type lprod(matrix_expression<CMatrixExprT> const& C) const
{
typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);
lprod_inplace(tmp_C);
return tmp_C;
}
/// Perform the product \f$C Q\f$ and return the result.
public: template <typename CMatrixExprT>
typename matrix_temporary_traits<CMatrixExprT>::type rprod(matrix_expression<CMatrixExprT> const& C) const
{
typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);
rprod_inplace(tmp_C);
return tmp_C;
}
/// Perform the product \f$Q^T C\f$ and return the result.
public: template <typename CMatrixExprT>
typename matrix_temporary_traits<CMatrixExprT>::type tlprod(matrix_expression<CMatrixExprT> const& C) const
{
typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);
tlprod_inplace(tmp_C);
return tmp_C;
}
/// Perform the product \f$C Q^T\f$ and return the result.
public: template <typename CMatrixExprT>
typename matrix_temporary_traits<CMatrixExprT>::type trprod(matrix_expression<CMatrixExprT> const& C) const
{
typename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);
trprod_inplace(tmp_C);
return tmp_C;
}
private: void decompose()
{
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template decompose(QL_, tau_, column_major_tag());
}
/// Perform the product \f$Q C\f$ and store the result in \a C (column-major
/// case).
private: template <typename CMatrixT>
void lprod_inplace(CMatrixT& C, column_major_tag) const
{
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, C, true, false, column_major_tag());
}
/// Perform the product \f$Q C\f$ and store the result in \a C (row-major
/// case).
private: template <typename CMatrixT>
void lprod_inplace(CMatrixT& C, row_major_tag) const
{
work_matrix_type tmp_C(C);
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, tmp_C, true, false, column_major_tag());
C = tmp_C;
}
/// Perform the product \f$C Q\f$ and store the result in \a C (column-major
/// case).
private: template <typename CMatrixT>
void rprod_inplace(CMatrixT& C, column_major_tag) const
{
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, C, false, false, column_major_tag());
}
/// Perform the product \f$C Q\f$ and store the result in \a C (row-major
/// case).
private: template <typename CMatrixT>
void rprod_inplace(CMatrixT& C, row_major_tag) const
{
work_matrix_type tmp_C(C);
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, tmp_C, false, false, column_major_tag());
C = tmp_C;
}
/// Perform the product \f$Q^T C\f$ and store the result in \a C
/// (column-major case).
private: template <typename CMatrixT>
void tlprod_inplace(CMatrixT& C, column_major_tag) const
{
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, C, true, true, column_major_tag());
}
/// Perform the product \f$Q^T C\f$ and store the result in \a C
/// (row-major case).
private: template <typename CMatrixT>
void tlprod_inplace(CMatrixT& C, row_major_tag) const
{
work_matrix_type tmp_C(C);
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, tmp_C, true, true, column_major_tag());
C = tmp_C;
}
/// Perform the product \f$C Q^T\f$ and store the result in \a C
/// (column-major case).
private: template <typename CMatrixT>
void trprod_inplace(CMatrixT& C, column_major_tag) const
{
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, C, false, true, column_major_tag());
}
/// Perform the product \f$C Q^T\f$ and store the result in \a C
/// (row-major case).
private: template <typename CMatrixT>
void trprod_inplace(CMatrixT& C, row_major_tag) const
{
work_matrix_type tmp_C(C);
detail::ql_decomposition_impl<
::boost::is_complex<value_type>::value
>::template prod(QL_, tau_, tmp_C, false, true, column_major_tag());
C = tmp_C;
}
// NOTE: the 'mutable' keyword is needed in order to make 'const' the
// '?prod' methods ('lprod', 'tlprod', 'rprod', 'trprod').
// Indeed, these methods call the respective '?prod_inplace' methods
// which, in turns, call the LAPACK::ORMQL function which temporarily
// changes the QL matrix (and restores it before returning).
private: mutable QL_matrix_type QL_;
private: tau_vector_type tau_;
};
/// Free function performing the QL decomposition of the given matrix expression \a A.
template<typename MatrixExprT, typename OutMatrix1T, typename OutMatrix2T>
BOOST_UBLAS_INLINE
void ql_decompose(matrix_expression<MatrixExprT> const& A, OutMatrix1T& Q, OutMatrix2T& L, bool full = true)
{
typedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category1;
typedef typename matrix_traits<OutMatrix1T>::orientation_category orientation_category2;
typedef typename matrix_traits<OutMatrix2T>::orientation_category orientation_category3;
// precondition: same orientation category
BOOST_MPL_ASSERT(
(::boost::mpl::and_<
::boost::is_same<orientation_category1,orientation_category2>,
::boost::is_same<orientation_category1,orientation_category3>
>)
);
detail::ql_decompose_impl(A, Q, L, full, orientation_category1());
}
/// Free function performing the QL decomposition of the given matrix expression \a A.
template<typename MatrixExprT>
BOOST_UBLAS_INLINE
ql_decomposition<typename matrix_traits<MatrixExprT>::value_type> ql_decompose(matrix_expression<MatrixExprT> const& A)
{
typedef typename matrix_traits<MatrixExprT>::value_type value_type;
return ql_decomposition<value_type>(A);
}
}}} // Namespace boost::numeric::ublasx
#endif // BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP
| 29.334833
| 130
| 0.657973
|
comcon1
|
4445f5f6ce2ab179438b1a089ffc9ed7d4c442dd
| 490
|
cpp
|
C++
|
src/RE/I/ItemsPickpocketed.cpp
|
colinswrath/CommonLibSSE
|
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
|
[
"MIT"
] | 118
|
2019-02-07T22:34:11.000Z
|
2022-03-29T10:40:40.000Z
|
src/RE/I/ItemsPickpocketed.cpp
|
colinswrath/CommonLibSSE
|
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
|
[
"MIT"
] | 63
|
2019-07-30T13:50:11.000Z
|
2022-02-19T02:14:33.000Z
|
src/RE/I/ItemsPickpocketed.cpp
|
colinswrath/CommonLibSSE
|
9c693f6a2406fb6128ee0dd0462bfc9ddbd83eee
|
[
"MIT"
] | 71
|
2019-05-21T00:15:51.000Z
|
2022-03-03T15:14:19.000Z
|
#include "RE/I/ItemsPickpocketed.h"
namespace RE
{
BSTEventSource<ItemsPickpocketed::Event>* ItemsPickpocketed::GetEventSource()
{
using func_t = decltype(&ItemsPickpocketed::GetEventSource);
REL::Relocation<func_t> func{ Offset::ItemsPickpocketed::GetEventSource };
return func();
}
void ItemsPickpocketed::SendEvent(std::int32_t a_numItems)
{
Event e = { a_numItems, 0 };
auto source = GetEventSource();
if (source) {
source->SendEvent(std::addressof(e));
}
}
}
| 23.333333
| 78
| 0.720408
|
colinswrath
|
444925f2e934c3bcb90ced3b1a963f4997910eca
| 1,368
|
hpp
|
C++
|
cpuemu/common/memory.hpp
|
deqyra/cpuemu
|
b30d39e01ef03a165169d53397d117a2550c650e
|
[
"MIT"
] | 2
|
2021-04-23T13:40:45.000Z
|
2022-03-28T13:59:30.000Z
|
cpuemu/common/memory.hpp
|
deqyra/cpuemu
|
b30d39e01ef03a165169d53397d117a2550c650e
|
[
"MIT"
] | null | null | null |
cpuemu/common/memory.hpp
|
deqyra/cpuemu
|
b30d39e01ef03a165169d53397d117a2550c650e
|
[
"MIT"
] | null | null | null |
#ifndef CPUEMU__COMMON__MEMORY_HPP
#define CPUEMU__COMMON__MEMORY_HPP
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <type_traits>
#include <vector>
#include <cpptools/type_utils.hpp>
#include "types.hpp"
namespace emu
{
template<uint64_t Size>
struct Memory
{
struct _cell
{
Byte* data;
uint64_t where;
operator Byte()
{
return data[where];
}
void operator=(Byte b)
{
data[where] = b;
}
void operator=(const std::vector<Byte>& c)
{
assert(where + c.size() <= Size);
std::copy(c.begin(), c.end(), data + where);
}
};
Byte data[Size]{ 0 };
_cell operator[](uint64_t where)
{
assert(where < Size);
return {data, where};
}
template<Endianness E>
_cell operator[](Word<E> where)
{
assert(where < Size);
return {data, (uint16_t)where};
}
uint64_t operator=(const std::vector<Byte>& c)
{
using std::size;
assert(c.size() <= Size);
using std::begin;
using std::end;
std::copy(c.begin(), c.end(), data);
std::memset(data + c.size(), 0, (size_t)(Size - c.size()));
return c.size();
}
};
}//namespace emu
#endif//CPUEMU__COMMON__MEMORY_HPP
| 17.766234
| 67
| 0.546053
|
deqyra
|
444b37653ae8ff8a443381d151460ac7922c2657
| 4,441
|
cpp
|
C++
|
Reflection/TypeConversions/FullConversionGraph.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
Reflection/TypeConversions/FullConversionGraph.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
Reflection/TypeConversions/FullConversionGraph.cpp
|
dnv-opensource/Reflection
|
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2021 DNV AS
//
// 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
#include <list>
#include <memory>
#include <boost\foreach.hpp>
#include "Reflection/TypeConversions/ConversionSequence.h"
#include "Reflection/TypeConversions/ComplexConversionGraph.h"
#include "Reflection/TypeConversions/FullConversionGraph.h"
#include "Reflection/Types/DynamicTypeTraits.h"
using namespace std;
namespace DNVS {namespace MoFa {namespace Reflection {namespace TypeConversions {
ConversionSequencePointer FullConversionGraph::GetConversionSequence(const Variants::Variant& from,
const Types::DecoratedTypeInfo& to) const
{
ConversionSequencePointer sequence = GetStandardConversionSequence(from, to);
if (!sequence->IsValid() && from.IsValid())
sequence = ComplexConversionGraph::GetConversionSequence(Types::TypeId<const Variants::Variant&>(), to);
return sequence;
}
Variants::Variant FullConversionGraph::CreateLValue(const Variants::Variant& from) const
{
list<ConversionPointer> dynamicConversions;
Variants::Variant dynamicValue(from);
GetDynamicConversionSequence(dynamicConversions, dynamicValue, Types::TypeId<void>());
if (Types::IsNonConstLValue(dynamicValue.GetDecoratedTypeInfo()))
return dynamicValue;
return ComplexConversionGraph::CreateLValue(dynamicValue);
}
void FullConversionGraph::AddConversion(const Types::DecoratedTypeInfo& from, const Types::DecoratedTypeInfo& to, ConversionType::Type conversionType, const ConversionPointer& conversion)
{
if (conversionType == ConversionType::ReflectionConversion)
{
auto sequence = std::make_shared<ConversionSequence>(conversionType);
if (conversion)
sequence->Add(conversion);
m_reflectionConversions[to.GetTypeInfo()] = sequence;
}
else
ComplexConversionGraph::AddConversion(from, to, conversionType, conversion);
}
ConversionSequencePointer FullConversionGraph::GetStandardConversionSequence(const Variants::Variant& from,
const Types::DecoratedTypeInfo& to) const
{
auto it = m_reflectionConversions.find(to.GetTypeInfo());
if (it != m_reflectionConversions.end())
return it->second;
if (from.GetDecoratedTypeInfo().GetTypeInfo() == to.GetTypeInfo())
return ComplexConversionGraph::GetConversionSequence(from, to);
list<ConversionPointer> dynamicConversions;
Variants::Variant dynamicValue(from);
GetDynamicConversionSequence(dynamicConversions, dynamicValue, to);
ConversionSequencePointer sequence = ComplexConversionGraph::GetConversionSequence(dynamicValue, to);
if (!sequence->IsValid())
return ComplexConversionGraph::GetConversionSequence(from, to);
if (dynamicConversions.empty())
return sequence;
shared_ptr<ConversionSequence> preSequence(new ConversionSequence(ConversionType::DynamicTypeConversion));
BOOST_REVERSE_FOREACH(ConversionPointer conversion, dynamicConversions)
preSequence->Add(conversion);
preSequence->Join(sequence);
sequence = preSequence;
return sequence;
}
void FullConversionGraph::GetDynamicConversionSequence(std::list<ConversionPointer>& dynamicConversions,
Variants::Variant& dynamicValue, const Types::DecoratedTypeInfo& to) const
{
auto it = m_dynamicTypeDeduction.find(dynamicValue.GetDecoratedTypeInfo().GetTypeInfo());
if (it == m_dynamicTypeDeduction.end())
return;
ConversionPointer conversion = it->second.first;
Variants::Variant converted = conversion->Convert(dynamicValue);
if(converted.GetDecoratedTypeInfo() == dynamicValue.GetDecoratedTypeInfo())
return;
dynamicConversions.push_back(conversion);
dynamicValue = converted;
if (to == converted.GetDecoratedTypeInfo())
return;
GetDynamicConversionSequence(dynamicConversions, dynamicValue, to);
}
}}}}
| 41.896226
| 191
| 0.680477
|
dnv-opensource
|
444e0b2bf3a355fb88931869e0b7b127daa41420
| 8,485
|
hpp
|
C++
|
include/RAJA/pattern/WorkGroup/WorkRunner.hpp
|
ggeorgakoudis/RAJA
|
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
|
[
"BSD-3-Clause"
] | 1
|
2020-11-19T04:55:20.000Z
|
2020-11-19T04:55:20.000Z
|
include/RAJA/pattern/WorkGroup/WorkRunner.hpp
|
ggeorgakoudis/RAJA
|
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
|
[
"BSD-3-Clause"
] | null | null | null |
include/RAJA/pattern/WorkGroup/WorkRunner.hpp
|
ggeorgakoudis/RAJA
|
05f4a5e473a4160ddfdb5e829b4fdc9e0384ae26
|
[
"BSD-3-Clause"
] | null | null | null |
/*!
******************************************************************************
*
* \file
*
* \brief Header file providing RAJA WorkStorage.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-20, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_PATTERN_WORKGROUP_WorkRunner_HPP
#define RAJA_PATTERN_WORKGROUP_WorkRunner_HPP
#include "RAJA/config.hpp"
#include <utility>
#include <type_traits>
#include "RAJA/policy/loop/policy.hpp"
#include "RAJA/pattern/forall.hpp"
#include "RAJA/pattern/WorkGroup/Vtable.hpp"
#include "RAJA/policy/WorkGroup.hpp"
namespace RAJA
{
namespace detail
{
/*!
* A body and args holder for storing loops that are being executed in foralls
*/
template <typename LoopBody, typename ... Args>
struct HoldBodyArgs_base
{
// NOTE: This constructor is disabled when body_in is not LoopBody
// to avoid it conflicting with the copy and move constructors
template < typename body_in,
typename = typename std::enable_if<
std::is_same<LoopBody, camp::decay<body_in>>::value>::type >
HoldBodyArgs_base(body_in&& body, Args... args)
: m_body(std::forward<body_in>(body))
, m_arg_tuple(std::forward<Args>(args)...)
{ }
protected:
LoopBody m_body;
camp::tuple<Args...> m_arg_tuple;
};
/*!
* A body and args holder for storing loops that are being executed in foralls
* that run on the host
*/
template <typename LoopBody, typename index_type, typename ... Args>
struct HoldBodyArgs_host : HoldBodyArgs_base<LoopBody, Args...>
{
using base = HoldBodyArgs_base<LoopBody, Args...>;
using base::base;
RAJA_INLINE void operator()(index_type i) const
{
invoke(i, camp::make_idx_seq_t<sizeof...(Args)>{});
}
template < camp::idx_t ... Is >
RAJA_INLINE void invoke(index_type i, camp::idx_seq<Is...>) const
{
this->m_body(i, get<Is>(this->m_arg_tuple)...);
}
};
/*!
* A body and args holder for storing loops that are being executed in foralls
* that run on the device
*/
template <typename LoopBody, typename index_type, typename ... Args>
struct HoldBodyArgs_device : HoldBodyArgs_base<LoopBody, Args...>
{
using base = HoldBodyArgs_base<LoopBody, Args...>;
using base::base;
RAJA_DEVICE RAJA_INLINE void operator()(index_type i) const
{
invoke(i, camp::make_idx_seq_t<sizeof...(Args)>{});
}
template < camp::idx_t ... Is >
RAJA_DEVICE RAJA_INLINE void invoke(index_type i, camp::idx_seq<Is...>) const
{
this->m_body(i, get<Is>(this->m_arg_tuple)...);
}
};
/*!
* A body and segment holder for storing loops that will be executed as foralls
*/
template <typename ExecutionPolicy, typename Segment_type, typename LoopBody,
typename index_type, typename ... Args>
struct HoldForall
{
using HoldBodyArgs = typename std::conditional<
!type_traits::is_device_exec_policy<ExecutionPolicy>::value,
HoldBodyArgs_host<LoopBody, index_type, Args...>,
HoldBodyArgs_device<LoopBody, index_type, Args...> >::type;
template < typename segment_in, typename body_in >
HoldForall(segment_in&& segment, body_in&& body)
: m_segment(std::forward<segment_in>(segment))
, m_body(std::forward<body_in>(body))
{ }
RAJA_INLINE void operator()(Args... args) const
{
wrap::forall(resources::get_resource<ExecutionPolicy>::type::get_default(),
ExecutionPolicy(),
m_segment,
HoldBodyArgs{m_body, std::forward<Args>(args)...});
}
private:
Segment_type m_segment;
LoopBody m_body;
};
/*!
* A class that handles running work in a work container
*/
template <typename EXEC_POLICY_T,
typename ORDER_POLICY_T,
typename ALLOCATOR_T,
typename INDEX_T,
typename ... Args>
struct WorkRunner;
/*!
* Base class describing storage for ordered runners using forall
*/
template <typename FORALL_EXEC_POLICY,
typename EXEC_POLICY_T,
typename ORDER_POLICY_T,
typename ALLOCATOR_T,
typename INDEX_T,
typename ... Args>
struct WorkRunnerForallOrdered_base
{
using exec_policy = EXEC_POLICY_T;
using order_policy = ORDER_POLICY_T;
using Allocator = ALLOCATOR_T;
using index_type = INDEX_T;
using forall_exec_policy = FORALL_EXEC_POLICY;
using vtable_type = Vtable<Args...>;
WorkRunnerForallOrdered_base() = default;
WorkRunnerForallOrdered_base(WorkRunnerForallOrdered_base const&) = delete;
WorkRunnerForallOrdered_base& operator=(WorkRunnerForallOrdered_base const&) = delete;
WorkRunnerForallOrdered_base(WorkRunnerForallOrdered_base &&) = default;
WorkRunnerForallOrdered_base& operator=(WorkRunnerForallOrdered_base &&) = default;
// The type that will hold the segment and loop body in work storage
template < typename segment_type, typename loop_type >
using holder_type = HoldForall<forall_exec_policy, segment_type, loop_type,
index_type, Args...>;
// The policy indicating where the call function is invoked
// in this case the values are called on the host in a loop
using vtable_exec_policy = RAJA::loop_work;
// runner interfaces with storage to enqueue so the runner can get
// information from the segment and loop at enqueue time
template < typename WorkContainer, typename segment_T, typename loop_T >
inline void enqueue(WorkContainer& storage, segment_T&& seg, loop_T&& loop)
{
using holder = holder_type<camp::decay<segment_T>, camp::decay<loop_T>>;
storage.template emplace<holder>(
get_Vtable<holder, vtable_type>(vtable_exec_policy{}),
std::forward<segment_T>(seg), std::forward<loop_T>(loop));
}
// clear any state so ready to be destroyed or reused
void clear()
{ }
// no extra storage required here
using per_run_storage = int;
};
/*!
* Runs work in a storage container in order using forall
*/
template <typename FORALL_EXEC_POLICY,
typename EXEC_POLICY_T,
typename ORDER_POLICY_T,
typename ALLOCATOR_T,
typename INDEX_T,
typename ... Args>
struct WorkRunnerForallOrdered
: WorkRunnerForallOrdered_base<
FORALL_EXEC_POLICY,
EXEC_POLICY_T,
ORDER_POLICY_T,
ALLOCATOR_T,
INDEX_T,
Args...>
{
using base = WorkRunnerForallOrdered_base<
FORALL_EXEC_POLICY,
EXEC_POLICY_T,
ORDER_POLICY_T,
ALLOCATOR_T,
INDEX_T,
Args...>;
using base::base;
// run the loops using forall in the order that they were enqueued
template < typename WorkContainer >
typename base::per_run_storage run(WorkContainer const& storage, Args... args) const
{
using value_type = typename WorkContainer::value_type;
typename base::per_run_storage run_storage{};
auto end = storage.end();
for (auto iter = storage.begin(); iter != end; ++iter) {
value_type::call(&*iter, args...);
}
return run_storage;
}
};
/*!
* Runs work in a storage container in reverse order using forall
*/
template <typename FORALL_EXEC_POLICY,
typename EXEC_POLICY_T,
typename ORDER_POLICY_T,
typename ALLOCATOR_T,
typename INDEX_T,
typename ... Args>
struct WorkRunnerForallReverse
: WorkRunnerForallOrdered_base<
FORALL_EXEC_POLICY,
EXEC_POLICY_T,
ORDER_POLICY_T,
ALLOCATOR_T,
INDEX_T,
Args...>
{
using base = WorkRunnerForallOrdered_base<
FORALL_EXEC_POLICY,
EXEC_POLICY_T,
ORDER_POLICY_T,
ALLOCATOR_T,
INDEX_T,
Args...>;
using base::base;
// run the loops using forall in the reverse order to the order they were enqueued
template < typename WorkContainer >
typename base::per_run_storage run(WorkContainer const& storage, Args... args) const
{
using value_type = typename WorkContainer::value_type;
typename base::per_run_storage run_storage{};
auto begin = storage.begin();
for (auto iter = storage.end(); iter != begin; --iter) {
value_type::call(&*(iter-1), args...);
}
return run_storage;
}
};
} // namespace detail
} // namespace RAJA
#endif // closing endif for header file include guard
| 28.569024
| 88
| 0.66812
|
ggeorgakoudis
|
444f384893782b7fda8e49b939a00aac5a2eba09
| 2,958
|
cc
|
C++
|
examples/sframesync_timing_example.cc
|
jgaeddert/sframe
|
9bd4c7234fda49e819447ef9eda21ea1ac059a08
|
[
"MIT"
] | 4
|
2020-11-12T15:56:40.000Z
|
2021-09-14T16:31:46.000Z
|
examples/sframesync_timing_example.cc
|
jgaeddert/sframe
|
9bd4c7234fda49e819447ef9eda21ea1ac059a08
|
[
"MIT"
] | null | null | null |
examples/sframesync_timing_example.cc
|
jgaeddert/sframe
|
9bd4c7234fda49e819447ef9eda21ea1ac059a08
|
[
"MIT"
] | 1
|
2019-11-24T01:05:38.000Z
|
2019-11-24T01:05:38.000Z
|
// test timing bias in estimator
#include "sframegen.hh"
#include "sframesync.hh"
struct results {
float tau; // actual time offset
float tau_avg; // average estimate
float tau_rmse; // root mean-squared error
void print() { printf(" %12.8f %12.8f %12.4e\n", tau, tau_avg, tau_rmse); }
};
results run_batch(unsigned int _payload_len,
unsigned int _num_trials,
float _tau);
int main() {
// options
unsigned int payload_len = 64; // number of bytes in payload
float tau_min = -1.0f; // starting timing offset [samples]
float tau_max = 1.0f; // ending timing offset [samples]
unsigned int num_steps = 101; // number of timing offset steps
unsigned int num_trials = 100; // number of trials to run
printf("# %12s %12s %12s\n", "tau", "bias", "rmse");
float tau_step = (tau_max - tau_min) / (float)(num_steps-1);
for (unsigned int i=0; i<num_steps; i++) {
float tau = tau_min + i*tau_step;
results r = run_batch(payload_len, num_trials, tau);
r.print();
}
return 0;
}
results run_batch(unsigned int _payload_len,
unsigned int _num_trials,
float _tau)
{
// create objects
sframegen gen = sframegen (_payload_len);
sframesync sync = sframesync(_payload_len);
// generate buffers
unsigned int buf_len = gen.get_slot_len();
std::complex<float> buf_channel[buf_len];
// delay filter
unsigned int m = 15; // delay filter semi-length
int d = (int)roundf(_tau); // integer sample delay
float mu = _tau - (float)d; // fractional sample delay
firfilt_crcf fdelay = firfilt_crcf_create_kaiser(2*m+1, 0.4f, 60.0f, -mu);
// run trials
float tau_rmse = 0.0f; // timing root mean-squared error
float tau_avg = 0.0f; // average timing estimate (bias)
for (unsigned int t=0; t<_num_trials; t++) {
// generate frame with random payload
const std::complex<float> * buf = gen.generate();
firfilt_crcf_reset(fdelay);
// run through channel
unsigned int n = 0;
for (unsigned int i=0; i<buf_len+m-d; i++) {
// push sample into filter and save results at appropriate indices
firfilt_crcf_push(fdelay, i < buf_len ? buf[i] : 0);
if (n < buf_len) firfilt_crcf_execute(fdelay, &buf_channel[n]);
if (i >= m-d) n++;
}
// run through detector and get results
sframesync::results r = sync.receive(buf_channel);
tau_avg += r.tau_hat;
tau_rmse += (_tau - r.tau_hat) * (_tau - r.tau_hat);
}
firfilt_crcf_destroy(fdelay);
// populate and return results
return {.tau = _tau,
.tau_avg = tau_avg / (float)_num_trials,
.tau_rmse = sqrtf(tau_rmse/(float)_num_trials) };
}
| 36.073171
| 81
| 0.590602
|
jgaeddert
|
4455537bb1f3a7fef31282b04b8065f92d624730
| 24,002
|
cpp
|
C++
|
src/game/Object/Vehicle.cpp
|
Zilvereyes/MaNGOSTwoServer
|
2d11181b3701c848d8beb14e4a5676dc25eb2ad0
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
src/game/Object/Vehicle.cpp
|
Zilvereyes/MaNGOSTwoServer
|
2d11181b3701c848d8beb14e4a5676dc25eb2ad0
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
src/game/Object/Vehicle.cpp
|
Zilvereyes/MaNGOSTwoServer
|
2d11181b3701c848d8beb14e4a5676dc25eb2ad0
|
[
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null |
/*
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2016 MaNGOS project <https://getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/*
* @addtogroup TransportSystem
* @{
*
* @file Vehicle.cpp
* This file contains the code needed for CMaNGOS to support vehicles
* Currently implemented
* - Board to board a passenger onto a vehicle (includes checks)
* - Unboard to unboard a passenger from the vehicle
* - SwitchSeat to switch to another seat of the same vehicle
* - CanBoard to check if a passenger can board a vehicle
* - Internal helper to set the controlling and spells for a vehicle's seat
* - Internal helper to control the available seats of a vehicle
*/
#include "Vehicle.h"
#include "Common.h"
#include "SharedDefines.h"
#include "ObjectGuid.h"
#include "Log.h"
#include "Unit.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "ObjectMgr.h"
#include "SQLStorages.h"
#include "Util.h"
#include "movement/MoveSplineInit.h"
#include "movement/MoveSpline.h"
#include "MapManager.h"
#include "TemporarySummon.h"
#ifdef ENABLE_ELUNA
#include "LuaEngine.h"
#endif /*ENABLE_ELUNA*/
void ObjectMgr::LoadVehicleAccessory()
{
sVehicleAccessoryStorage.Load();
sLog.outString(">> Loaded %u vehicle accessories", sVehicleAccessoryStorage.GetRecordCount());
sLog.outString();
// Check content
for (SQLMultiStorage::SQLSIterator<VehicleAccessory> itr = sVehicleAccessoryStorage.getDataBegin<VehicleAccessory>(); itr < sVehicleAccessoryStorage.getDataEnd<VehicleAccessory>(); ++itr)
{
if (!sCreatureStorage.LookupEntry<CreatureInfo>(itr->vehicleEntry))
{
sLog.outErrorDb("Table `vehicle_accessory` has entry (vehicle entry: %u, seat %u, passenger %u) where vehicle_entry is invalid, skip vehicle.", itr->vehicleEntry, itr->seatId, itr->passengerEntry);
sVehicleAccessoryStorage.EraseEntry(itr->vehicleEntry);
continue;
}
if (!sCreatureStorage.LookupEntry<CreatureInfo>(itr->passengerEntry))
{
sLog.outErrorDb("Table `vehicle_accessory` has entry (vehicle entry: %u, seat %u, passenger %u) where accessory_entry is invalid, skip vehicle.", itr->vehicleEntry, itr->seatId, itr->passengerEntry);
sVehicleAccessoryStorage.EraseEntry(itr->vehicleEntry);
continue;
}
if (itr->seatId >= MAX_VEHICLE_SEAT)
{
sLog.outErrorDb("Table `vehicle_accessory` has entry (vehicle entry: %u, seat %u, passenger %u) where seat is invalid (must be between 0 and %u), skip vehicle.", itr->vehicleEntry, itr->seatId, itr->passengerEntry, MAX_VEHICLE_SEAT - 1);
sVehicleAccessoryStorage.EraseEntry(itr->vehicleEntry);
continue;
}
}
}
/*
* Constructor of VehicleInfo
*
* @param owner MUST be provided owner of the vehicle (type Unit)
* @param vehicleEntry MUST be provided dbc-entry of the vehicle
* @param overwriteNpcEntry Use to overwrite the GetEntry() result for selecting associated passengers
*
* This function will initialise the VehicleInfo of the vehicle owner
* Also the seat-map is created here
*/
VehicleInfo::VehicleInfo(Unit* owner, VehicleEntry const* vehicleEntry, uint32 overwriteNpcEntry) : TransportBase(owner),
m_vehicleEntry(vehicleEntry),
m_creatureSeats(0),
m_playerSeats(0),
m_overwriteNpcEntry(overwriteNpcEntry),
m_isInitialized(false)
{
MANGOS_ASSERT(vehicleEntry);
// Initial fill of available seats for the vehicle
for (uint8 i = 0; i < MAX_VEHICLE_SEAT; ++i)
{
if (uint32 seatId = vehicleEntry->m_seatID[i])
{
if (VehicleSeatEntry const* seatEntry = sVehicleSeatStore.LookupEntry(seatId))
{
m_vehicleSeats.insert(VehicleSeatMap::value_type(i, seatEntry));
if (IsUsableSeatForCreature(seatEntry->m_flags))
m_creatureSeats |= 1 << i;
if (IsUsableSeatForPlayer(seatEntry->m_flags, seatEntry->m_flagsB))
m_playerSeats |= 1 << i;
}
}
}
}
VehicleInfo::~VehicleInfo()
{
((Unit*)m_owner)->RemoveSpellsCausingAura(SPELL_AURA_CONTROL_VEHICLE);
RemoveAccessoriesFromMap(); // Remove accessories (for example required with player vehicles)
}
void VehicleInfo::Initialize()
{
if (!m_overwriteNpcEntry)
m_overwriteNpcEntry = m_owner->GetEntry();
// Loading passengers (rough version only!)
SQLMultiStorage::SQLMSIteratorBounds<VehicleAccessory> bounds = sVehicleAccessoryStorage.getBounds<VehicleAccessory>(m_overwriteNpcEntry);
for (SQLMultiStorage::SQLMultiSIterator<VehicleAccessory> itr = bounds.first; itr != bounds.second; ++itr)
{
if (Creature* summoned = m_owner->SummonCreature(itr->passengerEntry, m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ(), 2 * m_owner->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0))
{
DEBUG_LOG("VehicleInfo(of %s)::Initialize: Load vehicle accessory %s onto seat %u", m_owner->GetGuidStr().c_str(), summoned->GetGuidStr().c_str(), itr->seatId);
m_accessoryGuids.insert(summoned->GetObjectGuid());
int32 basepoint0 = itr->seatId + 1;
summoned->CastCustomSpell((Unit*)m_owner, SPELL_RIDE_VEHICLE_HARDCODED, &basepoint0, NULL, NULL, true);
#ifdef ENABLE_ELUNA
sEluna->OnInstallAccessory(this, summoned);
#endif
}
}
// Initialize movement limitations
uint32 vehicleFlags = GetVehicleEntry()->m_flags;
Unit* pVehicle = (Unit*)m_owner;
if (vehicleFlags & VEHICLE_FLAG_NO_STRAFE)
pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_NO_STRAFE);
if (vehicleFlags & VEHICLE_FLAG_NO_JUMPING)
pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_NO_JUMPING);
if (vehicleFlags & VEHICLE_FLAG_FULLSPEEDTURNING)
pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_FULLSPEEDTURNING);
if (vehicleFlags & VEHICLE_FLAG_ALLOW_PITCHING)
pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_ALLOW_PITCHING);
if (vehicleFlags & VEHICLE_FLAG_FULLSPEEDPITCHING)
pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_FULLSPEEDPITCHING);
// Initialize power type based on DBC values (creatures only)
if (pVehicle->GetTypeId() == TYPEID_UNIT)
{
if (PowerDisplayEntry const* powerEntry = sPowerDisplayStore.LookupEntry(GetVehicleEntry()->m_powerDisplayID))
pVehicle->SetPowerType(Powers(powerEntry->power));
}
m_isInitialized = true;
#ifdef ENABLE_ELUNA
sEluna->OnInstall(this);
#endif
}
/*
* This function will board a passenger onto a vehicle
*
* @param passenger MUST be provided. This Unit will be boarded onto the vehicles (if it checks out)
* @param seat Seat to which the passenger will be boarded (if can, elsewise an alternative will be selected if possible)
*/
void VehicleInfo::Board(Unit* passenger, uint8 seat)
{
MANGOS_ASSERT(passenger);
DEBUG_LOG("VehicleInfo(of %s)::Board: Try to board passenger %s to seat %u", m_owner->GetGuidStr().c_str(), passenger->GetGuidStr().c_str(), seat);
// This check is also called in Spell::CheckCast()
if (!CanBoard(passenger))
return;
// Use the planned seat only if the seat is valid, possible to choose and empty
if (!IsSeatAvailableFor(passenger, seat))
if (!GetUsableSeatFor(passenger, seat))
return;
VehicleSeatEntry const* seatEntry = GetSeatEntry(seat);
MANGOS_ASSERT(seatEntry);
// ToDo: Unboard passenger from a MOTransport when they are properly implemented
/*if (TransportInfo* transportInfo = passenger->GetTransportInfo())
{
WorldObject* transporter = transportInfo->GetTransport();
// Must be a MO transporter
MANGOS_ASSERT(transporter->GetObjectGuid().IsMOTransport());
((Transport*)transporter)->UnBoardPassenger(passenger);
}*/
DEBUG_LOG("VehicleInfo::Board: Board passenger: %s to seat %u", passenger->GetGuidStr().c_str(), seat);
// Calculate passengers local position
float lx, ly, lz, lo;
CalculateBoardingPositionOf(passenger->GetPositionX(), passenger->GetPositionY(), passenger->GetPositionZ(), passenger->GetOrientation(), lx, ly, lz, lo);
BoardPassenger(passenger, lx, ly, lz, lo, seat); // Use TransportBase to store the passenger
// Set data for createobject packets
passenger->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT);
passenger->m_movementInfo.SetTransportData(m_owner->GetObjectGuid(), lx, ly, lz, lo, 0, seat);
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
Player* pPlayer = (Player*)passenger;
pPlayer->RemovePet(PET_SAVE_AS_CURRENT);
WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA);
pPlayer->GetSession()->SendPacket(&data);
// SMSG_BREAK_TARGET (?)
}
if (!passenger->IsRooted())
passenger->SetRoot(true);
Movement::MoveSplineInit init(*passenger);
init.MoveTo(0.0f, 0.0f, 0.0f); // ToDo: Set correct local coords
init.SetFacing(0.0f); // local orientation ? ToDo: Set proper orientation!
init.SetBoardVehicle();
init.Launch();
// Apply passenger modifications
ApplySeatMods(passenger, seatEntry->m_flags);
#ifdef ENABLE_ELUNA
sEluna->OnAddPassenger(this, passenger, seat);
#endif
}
/*
* This function will switch the seat of a passenger on the same vehicle
*
* @param passenger MUST be provided. This Unit will change its seat on the vehicle
* @param seat Seat to which the passenger will be switched
*/
void VehicleInfo::SwitchSeat(Unit* passenger, uint8 seat)
{
MANGOS_ASSERT(passenger);
DEBUG_LOG("VehicleInfo::SwitchSeat: passenger: %s try to switch to seat %u", passenger->GetGuidStr().c_str(), seat);
// Switching seats is not possible
if (m_vehicleEntry->m_flags & VEHICLE_FLAG_DISABLE_SWITCH)
return;
PassengerMap::const_iterator itr = m_passengers.find(passenger);
MANGOS_ASSERT(itr != m_passengers.end());
// We are already boarded to this seat
if (itr->second->GetTransportSeat() == seat)
return;
// Check if it's a valid seat
if (!IsSeatAvailableFor(passenger, seat))
return;
VehicleSeatEntry const* seatEntry = GetSeatEntry(itr->second->GetTransportSeat());
MANGOS_ASSERT(seatEntry);
// Switching seats is only allowed if this flag is set
if (~seatEntry->m_flags & SEAT_FLAG_CAN_SWITCH)
return;
// Remove passenger modifications of the old seat
RemoveSeatMods(passenger, seatEntry->m_flags);
// Set to new seat
itr->second->SetTransportSeat(seat);
Movement::MoveSplineInit init(*passenger);
init.MoveTo(0.0f, 0.0f, 0.0f); // ToDo: Set correct local coords
//if (oldorientation != neworientation) (?)
//init.SetFacing(0.0f); // local orientation ? ToDo: Set proper orientation!
// It seems that Seat switching is sent without SplineFlag BoardVehicle
init.Launch();
// Get seatEntry of new seat
seatEntry = GetSeatEntry(seat);
MANGOS_ASSERT(seatEntry);
// Apply passenger modifications of the new seat
ApplySeatMods(passenger, seatEntry->m_flags);
}
/*
* This function will Unboard a passenger
*
* @param passenger MUST be provided. This Unit will be unboarded from the vehicle
* @param changeVehicle If set, the passenger is expected to be directly boarded to another vehicle,
* and hence he will not be unboarded but only removed from this vehicle.
*/
void VehicleInfo::UnBoard(Unit* passenger, bool changeVehicle)
{
MANGOS_ASSERT(passenger);
DEBUG_LOG("VehicleInfo::Unboard: passenger: %s", passenger->GetGuidStr().c_str());
PassengerMap::const_iterator itr = m_passengers.find(passenger);
MANGOS_ASSERT(itr != m_passengers.end());
VehicleSeatEntry const* seatEntry = GetSeatEntry(itr->second->GetTransportSeat());
MANGOS_ASSERT(seatEntry);
UnBoardPassenger(passenger); // Use TransportBase to remove the passenger from storage list
if (!changeVehicle) // Send expected unboarding packages
{
// Update movementInfo
passenger->m_movementInfo.RemoveMovementFlag(MOVEFLAG_ONTRANSPORT);
passenger->m_movementInfo.ClearTransportData();
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
Player* pPlayer = (Player*)passenger;
pPlayer->ResummonPetTemporaryUnSummonedIfAny();
pPlayer->SetFallInformation(0, pPlayer->GetPositionZ());
// SMSG_PET_DISMISS_SOUND (?)
}
if (passenger->IsRooted())
passenger->SetRoot(false);
Movement::MoveSplineInit init(*passenger);
// ToDo: Set proper unboard coordinates
init.MoveTo(m_owner->GetPositionX(), m_owner->GetPositionY(), m_owner->GetPositionZ());
init.SetExitVehicle();
init.Launch();
// Despawn if passenger was accessory
if (passenger->GetTypeId() == TYPEID_UNIT && m_accessoryGuids.find(passenger->GetObjectGuid()) != m_accessoryGuids.end())
{
Creature* cPassenger = static_cast<Creature*>(passenger);
// TODO Same TODO as in VehicleInfo::RemoveAccessoriesFromMap
cPassenger->ForcedDespawn(5000);
m_accessoryGuids.erase(passenger->GetObjectGuid());
}
}
// Remove passenger modifications
RemoveSeatMods(passenger, seatEntry->m_flags);
#ifdef ENABLE_ELUNA
sEluna->OnRemovePassenger(this, passenger);
#endif
// Some creature vehicles get despawned after passenger unboarding
if (m_owner->GetTypeId() == TYPEID_UNIT)
{
// TODO: Guesswork, but seems to be fairly near correct
// Only if the passenger was on control seat? Also depending on some flags
if ((seatEntry->m_flags & SEAT_FLAG_CAN_CONTROL) &&
!(m_vehicleEntry->m_flags & (VEHICLE_FLAG_UNK4 | VEHICLE_FLAG_UNK20)))
{
if (((Creature*)m_owner)->IsTemporarySummon())
((Creature*)m_owner)->ForcedDespawn(1000);
}
}
}
/*
* This function will check if a passenger can be boarded
*
* @param passenger Unit that attempts to board onto a vehicle
*/
bool VehicleInfo::CanBoard(Unit* passenger) const
{
if (!passenger)
return false;
// Passenger is this vehicle
if (passenger == m_owner)
return false;
// Passenger is already on this vehicle (in this case switching seats is required)
if (passenger->IsBoarded() && passenger->GetTransportInfo()->GetTransport() == m_owner)
return false;
// Prevent circular boarding: passenger (could only be vehicle) must not have m_owner on board
if (passenger->IsVehicle() && passenger->GetVehicleInfo()->HasOnBoard(m_owner))
return false;
// Check if we have at least one empty seat
if (!GetEmptySeats())
return false;
// Passenger is already boarded
if (m_passengers.find(passenger) != m_passengers.end())
return false;
// Check for empty player seats
if (passenger->GetTypeId() == TYPEID_PLAYER)
return GetEmptySeatsMask() & m_playerSeats;
// Check for empty creature seats
return GetEmptySeatsMask() & m_creatureSeats;
}
Unit* VehicleInfo::GetPassenger(uint8 seat) const
{
for (PassengerMap::const_iterator itr = m_passengers.begin(); itr != m_passengers.end(); ++itr)
if (itr->second->GetTransportSeat() == seat)
return (Unit*)itr->first;
return NULL;
}
// Helper function to undo the turning of the vehicle to calculate a relative position of the passenger when boarding
void VehicleInfo::CalculateBoardingPositionOf(float gx, float gy, float gz, float go, float& lx, float& ly, float& lz, float& lo) const
{
NormalizeRotatedPosition(gx - m_owner->GetPositionX(), gy - m_owner->GetPositionY(), lx, ly);
lz = gz - m_owner->GetPositionZ();
lo = MapManager::NormalizeOrientation(go - m_owner->GetOrientation());
}
void VehicleInfo::RemoveAccessoriesFromMap()
{
// Remove all accessories
for (GuidSet::const_iterator itr = m_accessoryGuids.begin(); itr != m_accessoryGuids.end(); ++itr)
{
if (Creature* pAccessory = m_owner->GetMap()->GetCreature(*itr))
{
// TODO - unclear how long to despawn, also maybe some flag etc depending
pAccessory->ForcedDespawn(5000);
}
}
m_accessoryGuids.clear();
m_isInitialized = false;
}
/* ************************************************************************************************
* Helper function for seat control
* ***********************************************************************************************/
/// Get the Vehicle SeatEntry of a seat by position
VehicleSeatEntry const* VehicleInfo::GetSeatEntry(uint8 seat) const
{
VehicleSeatMap::const_iterator itr = m_vehicleSeats.find(seat);
return itr != m_vehicleSeats.end() ? itr->second : NULL;
}
/*
* This function will get a usable seat for a passenger
*
* @param passenger MUST be provided. Unit for which to try to get a free seat
* @param seat will contain an available seat if returned true
* @return return TRUE if and only if an available seat was found. In this case @seat will contain the id
*/
bool VehicleInfo::GetUsableSeatFor(Unit* passenger, uint8& seat) const
{
MANGOS_ASSERT(passenger);
uint8 possibleSeats = (passenger->GetTypeId() == TYPEID_PLAYER) ? (GetEmptySeatsMask() & m_playerSeats) : (GetEmptySeatsMask() & m_creatureSeats);
// No usable seats available
if (!possibleSeats)
return false;
// Start with 0
seat = 0;
for (uint8 i = 1; seat < MAX_VEHICLE_SEAT; i <<= 1, ++seat)
if (possibleSeats & i)
return true;
return false;
}
/// Returns if a @passenger could board onto @seat - @passenger MUST be provided
bool VehicleInfo::IsSeatAvailableFor(Unit* passenger, uint8 seat) const
{
MANGOS_ASSERT(passenger);
return seat < MAX_VEHICLE_SEAT &&
(GetEmptySeatsMask() & (passenger->GetTypeId() == TYPEID_PLAYER ? m_playerSeats : m_creatureSeats) & (1 << seat));
}
/// Wrapper to collect all taken seats
uint8 VehicleInfo::GetTakenSeatsMask() const
{
uint8 takenSeatsMask = 0;
for (PassengerMap::const_iterator itr = m_passengers.begin(); itr != m_passengers.end(); ++itr)
takenSeatsMask |= 1 << itr->second->GetTransportSeat();
return takenSeatsMask;
}
bool VehicleInfo:: IsUsableSeatForPlayer(uint32 seatFlags, uint32 seatFlagsB) const
{
return seatFlags & SEAT_FLAG_CAN_EXIT ||
seatFlags & SEAT_FLAG_UNCONTROLLED ||
seatFlagsB &
(SEAT_FLAG_B_USABLE_FORCED | SEAT_FLAG_B_USABLE_FORCED_2 |
SEAT_FLAG_B_USABLE_FORCED_3 | SEAT_FLAG_B_USABLE_FORCED_4);
}
/// Add control and such modifiers to a passenger if required
void VehicleInfo::ApplySeatMods(Unit* passenger, uint32 seatFlags)
{
Unit* pVehicle = (Unit*)m_owner; // Vehicles are alawys Unit
if (seatFlags & SEAT_FLAG_NOT_SELECTABLE)
passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
Player* pPlayer = (Player*)passenger;
// group update
if (pPlayer->GetGroup())
pPlayer->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_VEHICLE_SEAT);
if (seatFlags & SEAT_FLAG_CAN_CONTROL)
{
pPlayer->GetCamera().SetView(pVehicle);
pPlayer->SetCharm(pVehicle);
pVehicle->SetCharmerGuid(pPlayer->GetObjectGuid());
pVehicle->addUnitState(UNIT_STAT_CONTROLLED);
pVehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
pPlayer->SetClientControl(pVehicle, 1);
pPlayer->SetMover(pVehicle);
// Unconfirmed - default speed handling
if (pVehicle->GetTypeId() == TYPEID_UNIT)
{
if (!pPlayer->IsWalking() && pVehicle->IsWalking())
{
((Creature*)pVehicle)->SetWalk(false, true);
}
else if (pPlayer->IsWalking() && !pVehicle->IsWalking())
{
((Creature*)pVehicle)->SetWalk(true, true);
}
}
}
if (seatFlags & SEAT_FLAG_CAN_CAST)
{
CharmInfo* charmInfo = pVehicle->InitCharmInfo(pVehicle);
charmInfo->InitVehicleCreateSpells();
pPlayer->PossessSpellInitialize();
}
}
else if (passenger->GetTypeId() == TYPEID_UNIT)
{
if (seatFlags & SEAT_FLAG_CAN_CONTROL)
{
passenger->SetCharm(pVehicle);
pVehicle->SetCharmerGuid(passenger->GetObjectGuid());
}
((Creature*)passenger)->AI()->SetCombatMovement(false);
// Not entirely sure how this must be handled in relation to CONTROL
// But in any way this at least would require some changes in the movement system most likely
passenger->GetMotionMaster()->Clear(false, true);
passenger->GetMotionMaster()->MoveIdle();
}
}
/// Remove control and such modifiers to a passenger if they were added
void VehicleInfo::RemoveSeatMods(Unit* passenger, uint32 seatFlags)
{
Unit* pVehicle = (Unit*)m_owner;
if (seatFlags & SEAT_FLAG_NOT_SELECTABLE)
passenger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
Player* pPlayer = (Player*)passenger;
// group update
if (pPlayer->GetGroup())
pPlayer->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_VEHICLE_SEAT);
if (seatFlags & SEAT_FLAG_CAN_CONTROL)
{
pPlayer->SetCharm(NULL);
pVehicle->SetCharmerGuid(ObjectGuid());
pPlayer->SetClientControl(pVehicle, 0);
pPlayer->SetMover(NULL);
pVehicle->clearUnitState(UNIT_STAT_CONTROLLED);
pVehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
// must be called after movement control unapplying
pPlayer->GetCamera().ResetView();
}
if (seatFlags & SEAT_FLAG_CAN_CAST)
pPlayer->RemovePetActionBar();
}
else if (passenger->GetTypeId() == TYPEID_UNIT)
{
if (seatFlags & SEAT_FLAG_CAN_CONTROL)
{
passenger->SetCharm(NULL);
pVehicle->SetCharmerGuid(ObjectGuid());
}
// Reinitialize movement
((Creature*)passenger)->AI()->SetCombatMovement(true, true);
if (!passenger->getVictim())
passenger->GetMotionMaster()->Initialize();
}
}
/*! @} */
| 37.154799
| 249
| 0.663028
|
Zilvereyes
|
4456445245c806eb7f3a12bc4bc4f1bdd6c407c9
| 1,757
|
cpp
|
C++
|
wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp
|
Ashray-g/allwpilib
|
8d81e085f3af4d7bc2e08a0fe2bc4068d6dfa588
|
[
"BSD-3-Clause"
] | null | null | null |
wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp
|
Ashray-g/allwpilib
|
8d81e085f3af4d7bc2e08a0fe2bc4068d6dfa588
|
[
"BSD-3-Clause"
] | null | null | null |
wpilibcExamples/src/main/cpp/examples/GettingStarted/cpp/Robot.cpp
|
Ashray-g/allwpilib
|
8d81e085f3af4d7bc2e08a0fe2bc4068d6dfa588
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include <frc/TimedRobot.h>
#include <frc/Timer.h>
#include <frc/XboxController.h>
#include <frc/drive/DifferentialDrive.h>
#include <frc/motorcontrol/PWMSparkMax.h>
class Robot : public frc::TimedRobot {
public:
Robot() {
m_right.SetInverted(true);
m_robotDrive.SetExpiration(100_ms);
// We need to invert one side of the drivetrain so that positive voltages
// result in both sides moving forward. Depending on how your robot's
// gearbox is constructed, you might have to invert the left side instead.
m_timer.Start();
}
void AutonomousInit() override {
m_timer.Reset();
m_timer.Start();
}
void AutonomousPeriodic() override {
// Drive for 2 seconds
if (m_timer.Get() < 2_s) {
// Drive forwards half speed, make sure to turn input squaring off
m_robotDrive.ArcadeDrive(0.5, 0.0, false);
} else {
// Stop robot
m_robotDrive.ArcadeDrive(0.0, 0.0, false);
}
}
void TeleopInit() override {}
void TeleopPeriodic() override {
// Drive with arcade style (use right stick to steer)
m_robotDrive.ArcadeDrive(-m_controller.GetLeftY(),
m_controller.GetRightX());
}
void TestInit() override {}
void TestPeriodic() override {}
private:
// Robot drive system
frc::PWMSparkMax m_left{0};
frc::PWMSparkMax m_right{1};
frc::DifferentialDrive m_robotDrive{m_left, m_right};
frc::XboxController m_controller{0};
frc::Timer m_timer;
};
#ifndef RUNNING_FRC_TESTS
int main() {
return frc::StartRobot<Robot>();
}
#endif
| 27.030769
| 78
| 0.686966
|
Ashray-g
|
4459a492b6c95320fc774e82c65519d4d5282171
| 397
|
cpp
|
C++
|
td/telegram/net/NetQueryCounter.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | 1
|
2021-01-12T07:18:07.000Z
|
2021-01-12T07:18:07.000Z
|
td/telegram/net/NetQueryCounter.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | 2
|
2021-03-09T16:37:27.000Z
|
2021-05-10T12:15:58.000Z
|
td/telegram/net/NetQueryCounter.cpp
|
sintyaaaaa/td
|
0e930c15d3cd65dc5cc3fa6e8492684038129510
|
[
"BSL-1.0"
] | 1
|
2020-08-14T12:43:30.000Z
|
2020-08-14T12:43:30.000Z
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019
//
// 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)
//
#include "td/telegram/net/NetQueryCounter.h"
namespace td {
std::atomic<uint64> NetQueryCounter::net_query_cnt_{0};
} // namespace td
| 28.357143
| 96
| 0.748111
|
sintyaaaaa
|
445aaea3836fc82fcf7986e003097d69fa583e01
| 1,228
|
cpp
|
C++
|
BaekJoon/1963.cpp
|
falconlee236/Algorithm_Practice
|
4e6e380a0e6c840525ca831a05c35253eeaaa25c
|
[
"MIT"
] | null | null | null |
BaekJoon/1963.cpp
|
falconlee236/Algorithm_Practice
|
4e6e380a0e6c840525ca831a05c35253eeaaa25c
|
[
"MIT"
] | null | null | null |
BaekJoon/1963.cpp
|
falconlee236/Algorithm_Practice
|
4e6e380a0e6c840525ca831a05c35253eeaaa25c
|
[
"MIT"
] | null | null | null |
/*1963*/
/*Got it!*/
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int prime[10000];
int main() {
for(int i = 0; i < 10000; i++) prime[i] = 1;
prime[0] = 0; prime[1] = 0;
for(int i = 2; i * i <= 10000; i++){
if(!prime[i]) continue;
for(int j = i + i; j < 10000; j += i) prime[j] = 0;
}
int t; scanf("%d", &t);
while(t--){
int a, b; scanf("%d %d", &a, &b);
int visit[10000];
for(int i = 0; i < 10000; i++) visit[i] = 0;
int res = 0;
queue<pair<int, int>> q;
q.emplace(a, 0);
while(!q.empty()){
int p = q.front().first, cost = q.front().second;
if(p == b){
res = cost;
break;
}
q.pop();
for(int i = 0; i < 4; i++){
string str = to_string(p);
for(int j = 0; j < 10; j++){
if(i == 0 && j == 0) continue;
str[i] = (char)(j + '0');
int num = stoi(str);
if(prime[num] && !visit[num]){
visit[num] = 1;
q.emplace(num, cost + 1);
}
}
}
}
printf("%d\n", res);
}
return 0;
}
| 24.56
| 58
| 0.390065
|
falconlee236
|
445ced6a7035688b6a64b53292ed41fdc8741abb
| 118
|
hpp
|
C++
|
src/kernel/arch/x86_64/interrupts.hpp
|
Abb1x/tisix
|
f79de11dae657b2b5e082c4a0057192763d6c15a
|
[
"MIT"
] | 13
|
2021-11-14T00:42:36.000Z
|
2022-02-21T14:19:50.000Z
|
src/kernel/arch/x86_64/interrupts.hpp
|
Abb1x/tisix
|
f79de11dae657b2b5e082c4a0057192763d6c15a
|
[
"MIT"
] | null | null | null |
src/kernel/arch/x86_64/interrupts.hpp
|
Abb1x/tisix
|
f79de11dae657b2b5e082c4a0057192763d6c15a
|
[
"MIT"
] | 1
|
2021-11-20T16:15:45.000Z
|
2021-11-20T16:15:45.000Z
|
#pragma once
#include <scheduler.hpp>
#include <tisix/log.hpp>
extern "C" uint64_t interrupts_handler(uint64_t rsp);
| 19.666667
| 53
| 0.771186
|
Abb1x
|
4462c0b18dc2032b529e09a225eb04efff58c9da
| 595
|
ipp
|
C++
|
include/data_structures/implementation/component/AdjacencyListCSR.ipp
|
thorbenlouw/CUP-CFD
|
d06f7673a1ed12bef24de4f1b828ef864fa45958
|
[
"MIT"
] | 3
|
2021-06-24T10:20:12.000Z
|
2021-07-18T14:43:19.000Z
|
include/data_structures/implementation/component/AdjacencyListCSR.ipp
|
thorbenlouw/CUP-CFD
|
d06f7673a1ed12bef24de4f1b828ef864fa45958
|
[
"MIT"
] | 2
|
2021-07-22T15:31:03.000Z
|
2021-07-28T14:27:28.000Z
|
include/data_structures/implementation/component/AdjacencyListCSR.ipp
|
thorbenlouw/CUP-CFD
|
d06f7673a1ed12bef24de4f1b828ef864fa45958
|
[
"MIT"
] | 1
|
2021-07-22T15:24:24.000Z
|
2021-07-22T15:24:24.000Z
|
/**
* @file
* @author University of Warwick
* @version 1.0
*
* @section LICENSE
*
* @section DESCRIPTION
*
* Contains header level definitions for the AdjacencyListCSR class
*/
#ifndef CUPCFD_DATA_STRUCTURES_ADJACENCY_LIST_CSR_IPP_H
#define CUPCFD_DATA_STRUCTURES_ADJACENCY_LIST_CSR_IPP_H
namespace cupcfd
{
namespace data_structures
{
template <class I, class T>
template <class S>
void AdjacencyListCSR<I,T>::operator=(AdjacencyList<S,I,T>& source)
{
// Forward operation to base class
AdjacencyList<AdjacencyListCSR<I,T>, I,T>::operator=(source);
}
}
}
#endif
| 19.193548
| 69
| 0.734454
|
thorbenlouw
|
4463a082045cbd73cb3b0f3d25d35475a0de6f7f
| 5,992
|
hpp
|
C++
|
include/sdsl/construct_lcp_helper.hpp
|
qPCR4vir/sdsl-lite
|
3ae7ac30c3837553cf20243cc3df8ee658b9f00f
|
[
"BSD-3-Clause"
] | 1
|
2021-02-10T11:26:38.000Z
|
2021-02-10T11:26:38.000Z
|
include/sdsl/construct_lcp_helper.hpp
|
Irallia/sdsl-lite
|
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
|
[
"BSD-3-Clause"
] | 1
|
2019-03-10T23:59:27.000Z
|
2019-03-10T23:59:27.000Z
|
include/sdsl/construct_lcp_helper.hpp
|
Irallia/sdsl-lite
|
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2016, the SDSL Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#ifndef INCLUDED_SDSL_CONSTRUCT_LCP_HELPER
#define INCLUDED_SDSL_CONSTRUCT_LCP_HELPER
#include "sdsl/int_vector.hpp"
#include <queue>
#include <list>
#include <vector>
namespace sdsl {
//! Merges a partial LCP array into the LCP array on disk.
/*!
* \param partial_lcp Vector containing LCP values for all indexes \f$i\f$ with
* index_done[i] == 0. Let x=partail_lcp[rank(index_done, i, 0)];
* LCP[i]=x if x!=0 and index_done[i] == 0
* \param lcp_file Path to the LCP array on disk.
* \param index_done Entry index_done[i] indicates if LCP[i] is already calculated.
* \param max_lcp_value Maximum known LCP value
* \param lcp_value_offset Largest LCP value in lcp_file
*/
inline void insert_lcp_values(int_vector<>& partial_lcp,
bit_vector& index_done,
std::string lcp_file,
uint64_t max_lcp_value,
uint64_t lcp_value_offset)
{
std::string tmp_lcp_file = lcp_file + "_TMP";
const uint64_t buffer_size = 1000000; // has to be a multiple of 64
typedef int_vector<>::size_type size_type;
int_vector_buffer<> lcp_buffer(lcp_file, std::ios::in, buffer_size); // open lcp_file
uint64_t n = lcp_buffer.size();
// open tmp_lcp_file
uint8_t int_width = bits::hi(max_lcp_value)+1;
int_vector_buffer<> out_buf(tmp_lcp_file, std::ios::out, buffer_size, int_width); // Output buffer
// Write values into buffer
for (size_type i=0, calc_idx=0; i < n; ++i) {
if (index_done[i]) { // If value was already calculated
out_buf[i] = lcp_buffer[i]; // Copy value
} else {
if (partial_lcp[calc_idx]) { // If value was calculated now
// Insert value
out_buf[i] = partial_lcp[calc_idx]+lcp_value_offset;
index_done[i] = true;
}
++calc_idx;
}
}
lcp_buffer.close();
out_buf.close();
// Close file and replace old file with new one
sdsl::rename(tmp_lcp_file, lcp_file);
}
template <class tWT>
void create_C_array(std::vector<uint64_t>& C, const tWT& wt)
{
uint64_t quantity; // quantity of characters in interval
std::vector<unsigned char> cs(wt.sigma); // list of characters in the interval
std::vector<uint64_t> rank_c_i(wt.sigma); // number of occurrence of character in [0 .. i-1]
std::vector<uint64_t> rank_c_j(wt.sigma); // number of occurrence of character in [0 .. j-1]
C = std::vector<uint64_t>(257, 0);
interval_symbols(wt, 0, wt.size(), quantity, cs, rank_c_i, rank_c_j);
for (uint64_t i = 0; i < quantity; ++i) {
unsigned char c = cs[i];
C[c + 1] = rank_c_j[i];
}
for (uint64_t i = 1; i < C.size() - 1; ++i) {
C[i + 1] += C[i];
}
}
class buffered_char_queue {
typedef bit_vector::size_type size_type;
typedef std::queue<uint8_t> tQ;
private:
static const uint32_t m_buffer_size = 10000; //409600;
uint8_t m_write_buf[m_buffer_size];
uint8_t m_read_buf[m_buffer_size];
size_type m_widx; // write index
size_type m_ridx; // read index
bool m_sync; // are read and write buffer the same?
size_type m_disk_buffered_blocks; // number of blocks written to disk and not read again yet
char m_c;
size_type m_rb; // read blocks
size_type m_wb; // written blocks
std::string m_file_name;
std::fstream m_stream;
public:
buffered_char_queue()
: m_widx(0), m_ridx(0), m_sync(true), m_disk_buffered_blocks(0), m_c('?'), m_rb(0), m_wb(0)
{ }
void init(const std::string& dir, char c)
{
m_c = c;
m_file_name = dir + "buffered_char_queue_" + util::to_string(util::pid());
// m_stream.rdbuf()->pubsetbuf(0, 0);
}
~buffered_char_queue()
{
m_stream.close();
sdsl::remove(m_file_name);
}
void push_back(uint8_t x)
{
m_write_buf[m_widx] = x;
if (m_sync) {
m_read_buf[m_widx] = x;
}
++m_widx;
if (m_widx == m_buffer_size) {
if (!m_sync) { // if not sync, write block to disk
if (!m_stream.is_open()) {
m_stream.open(m_file_name,
std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
}
m_stream.seekp(m_buffer_size * (m_wb++), std::ios::beg);
m_stream.write((char*)m_write_buf, m_buffer_size);
++m_disk_buffered_blocks;
}
m_sync = 0;
m_widx = 0;
}
}
uint8_t pop_front()
{
uint8_t x = m_read_buf[m_ridx];
++m_ridx;
if (m_ridx == m_buffer_size) {
if (m_disk_buffered_blocks > 0) {
m_stream.seekg(m_buffer_size * (m_rb++), std::ios::beg);
m_stream.read((char*)m_read_buf, m_buffer_size);
--m_disk_buffered_blocks;
} else { // m_disk_buffered_blocks == 0
m_sync = 1;
memcpy(m_read_buf, m_write_buf, m_widx + 1);
}
m_ridx = 0;
}
return x;
}
};
typedef std::list<int_vector<>::size_type> tLI;
typedef std::vector<int_vector<>::size_type> tVI;
template <class size_type_class>
void push_front_m_index(size_type_class i,
uint8_t c,
tLI (&m_list)[256],
uint8_t (&m_chars)[256],
size_type_class& m_char_count)
{
if (m_list[c].empty()) {
m_chars[m_char_count++] = c;
}
m_list[c].push_front(i);
}
template <class size_type_class>
void push_back_m_index(size_type_class i,
uint8_t c,
tLI (&m_list)[256],
uint8_t (&m_chars)[256],
size_type_class& m_char_count)
{
if (m_list[c].empty()) {
m_chars[m_char_count++] = c;
}
m_list[c].push_back(i);
}
}
#endif
| 31.371728
| 103
| 0.609312
|
qPCR4vir
|
4463be6c978c077fc8e841c49cd76449ff604e24
| 5,871
|
cpp
|
C++
|
Core/Contents/Source/PolySceneLabel.cpp
|
cartman300/Polycode
|
b6fe41c6123281db3caee3c11f655de79df6fbfb
|
[
"MIT"
] | null | null | null |
Core/Contents/Source/PolySceneLabel.cpp
|
cartman300/Polycode
|
b6fe41c6123281db3caee3c11f655de79df6fbfb
|
[
"MIT"
] | null | null | null |
Core/Contents/Source/PolySceneLabel.cpp
|
cartman300/Polycode
|
b6fe41c6123281db3caee3c11f655de79df6fbfb
|
[
"MIT"
] | null | null | null |
/*
Copyright (C) 2011 by Ivan Safrin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "PolySceneLabel.h"
#include "PolyCoreServices.h"
#include "PolyFontManager.h"
#include "PolyLabel.h"
#include "PolyMesh.h"
#include "PolyRenderer.h"
#include "PolyMaterialManager.h"
using namespace Polycode;
Vector3 SceneLabel::defaultAnchor = Vector3();
bool SceneLabel::defaultPositionAtBaseline = false;
bool SceneLabel::defaultSnapToPixels = false;
bool SceneLabel::createMipmapsForLabels = true;
SceneLabel::SceneLabel(const String& text, int size, const String& fontName, int amode, Number actualHeight, bool premultiplyAlpha, const Color &backgroundColor, const Color &foregroundColor) : ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 1, 1){
label = new Label(CoreServices::getInstance()->getFontManager()->getFontByName(fontName), text, size * CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX(), amode, premultiplyAlpha, backgroundColor, foregroundColor);
positionAtBaseline = SceneLabel::defaultPositionAtBaseline;
setAnchorPoint(SceneLabel::defaultAnchor);
snapToPixels = SceneLabel::defaultSnapToPixels;
setLabelActualHeight(actualHeight);
}
Entity *SceneLabel::Clone(bool deepClone, bool ignoreEditorOnly) const {
SceneLabel *newLabel = new SceneLabel(label->getText(), label->getSize(), label->getFont()->getFontName(), label->getAntialiasMode(), actualHeight, label->getPremultiplyAlpha(), label->getBackgroundColor(), label->getForegroundColor());
applyClone(newLabel, deepClone, ignoreEditorOnly);
return newLabel;
}
void SceneLabel::applyClone(Entity *clone, bool deepClone, bool ignoreEditorOnly) const {
SceneLabel* cloneLabel = (SceneLabel*) clone;
cloneLabel->getLabel()->setSize(label->getSize());
cloneLabel->getLabel()->setAntialiasMode(label->getAntialiasMode());
cloneLabel->getLabel()->setFont(label->getFont());
cloneLabel->getLabel()->setPremultiplyAlpha(label->getPremultiplyAlpha());
cloneLabel->setLabelActualHeight(actualHeight);
cloneLabel->getLabel()->setBackgroundColor(label->getBackgroundColor());
cloneLabel->getLabel()->setForegroundColor(label->getForegroundColor());
cloneLabel->positionAtBaseline = positionAtBaseline;
cloneLabel->setText(label->getText());
ScenePrimitive::applyClone(clone, deepClone, ignoreEditorOnly);
}
SceneLabel::~SceneLabel() {
delete label;
}
Label *SceneLabel::getLabel() {
return label;
}
String SceneLabel::getText() {
return label->getText();
}
void SceneLabel::setLabelActualHeight(Number actualHeight) {
this->actualHeight = actualHeight;
if(actualHeight > 0.0) {
labelScale = actualHeight/((Number)label->getSize()) * CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX();
} else {
labelScale = 1.0;
}
updateFromLabel();
}
Number SceneLabel::getLabelActualHeight() {
return actualHeight;
}
void SceneLabel::updateFromLabel() {
MaterialManager *materialManager = CoreServices::getInstance()->getMaterialManager();
if(texture)
materialManager->deleteTexture(texture);
if(SceneLabel::createMipmapsForLabels) {
texture = materialManager->createTextureFromImage(label, materialManager->clampDefault, materialManager->mipmapsDefault);
} else {
texture = materialManager->createTextureFromImage(label, materialManager->clampDefault, false);
}
if(material) {
localShaderOptions->clearTexture("diffuse");
localShaderOptions->addTexture("diffuse", texture);
}
setPrimitiveOptions(type, label->getWidth()*labelScale/CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX(),label->getHeight()*labelScale/CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX());
setLocalBoundingBox(label->getWidth()*labelScale / CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX(), label->getHeight()*labelScale/ CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX(), 0.001);
if(useVertexBuffer)
CoreServices::getInstance()->getRenderer()->createVertexBufferForMesh(mesh);
}
void SceneLabel::Render() {
if(positionAtBaseline) {
CoreServices::getInstance()->getRenderer()->translate2D(0.0, (((Number)label->getSize()*labelScale) * -1.0 / CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleY()) + (((Number)label->getBaselineAdjust())*labelScale/CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleY()));
}
ScenePrimitive::Render();
}
int SceneLabel::getTextWidthForString(String text) {
return label->getTextWidthForString(text) / CoreServices::getInstance()->getRenderer()->getBackingResolutionScaleX();
}
void SceneLabel::setText(const String& newText) {
if(newText == label->getText() && !label->optionsChanged()) {
return;
}
label->setText(newText);
updateFromLabel();
}
| 40.212329
| 311
| 0.762221
|
cartman300
|
44661d1a714b5f73c15eea2772f005dd9866097e
| 2,345
|
cpp
|
C++
|
cpp/src/render/utils/vega/vega.cpp
|
shengjh/arctern
|
6b52bacf29d84ec41d97f9dd67aa7e36da266287
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/render/utils/vega/vega.cpp
|
shengjh/arctern
|
6b52bacf29d84ec41d97f9dd67aa7e36da266287
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/render/utils/vega/vega.cpp
|
shengjh/arctern
|
6b52bacf29d84ec41d97f9dd67aa7e36da266287
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2019-2020 Zilliz. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <string>
#include "render/utils/vega/vega.h"
namespace arctern {
namespace render {
bool Vega::JsonLabelCheck(rapidjson::Value& value, const std::string& label) {
if (!value.HasMember(label.c_str())) {
// TODO: add log here
std::cout << "Cannot find label [" << label << "] !";
return false;
}
return true;
}
bool Vega::JsonSizeCheck(rapidjson::Value& value, const std::string& label, size_t size) {
if (value.Size() != size) {
// TODO: add log here
std::cout << "Member [" << label << "].size should be " << size << ", but get "
<< value.Size() << std::endl;
return false;
}
return true;
}
bool Vega::JsonTypeCheck(rapidjson::Value& value, rapidjson::Type type) {
switch (type) {
case rapidjson::Type::kNumberType:
if (!value.IsNumber()) {
// TODO: add log here
std::cout << "not number type" << std::endl;
return false;
}
return true;
case rapidjson::Type::kArrayType:
if (!value.IsArray()) {
// TODO: add log here
std::cout << "not array type" << std::endl;
return false;
}
return true;
case rapidjson::Type::kStringType:
if (!value.IsString()) {
// TODO: add log here
std::cout << "not string type" << std::endl;
return false;
}
return true;
default: {
// TODO: add log here
std::cout << "unknown type" << std::endl;
return false;
}
}
}
bool Vega::JsonNullCheck(rapidjson::Value& value) {
if (value.IsNull()) {
// TODO: add log here
std::cout << "null!!!" << std::endl;
return false;
}
return true;
}
} // namespace render
} // namespace arctern
| 27.588235
| 90
| 0.613646
|
shengjh
|
4466fabcef6303be865fef8471bc0191edcd6bcb
| 668
|
hpp
|
C++
|
module-apps/application-settings/windows/display-keypad/EditQuotesWindow.hpp
|
SP2FET/MuditaOS-1
|
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
|
[
"BSL-1.0"
] | 1
|
2021-11-11T22:56:43.000Z
|
2021-11-11T22:56:43.000Z
|
module-apps/application-settings/windows/display-keypad/EditQuotesWindow.hpp
|
SP2FET/MuditaOS-1
|
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
|
[
"BSL-1.0"
] | null | null | null |
module-apps/application-settings/windows/display-keypad/EditQuotesWindow.hpp
|
SP2FET/MuditaOS-1
|
2906bb8a2fb3cdd39b167e600f6cc6d9ce1327bd
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <application-settings/windows/BaseSettingsWindow.hpp>
namespace gui
{
class CheckBoxWithLabel;
class EditQuotesWindow : public BaseSettingsWindow
{
public:
explicit EditQuotesWindow(app::ApplicationCommon *app);
private:
void switchHandler(bool &optionSwitch);
auto buildOptionsList() -> std::list<Option> override;
bool isOurFavouritesSwitchOn = false;
bool isCustomSwitchOn = false;
Item *quotes;
};
} // namespace gui
| 24.740741
| 67
| 0.679641
|
SP2FET
|
4468d68e808fb9c481dd44ab93bb817fe7cdd9dc
| 812
|
cpp
|
C++
|
export/release/windows/obj/src/haxe/IMap.cpp
|
SamuraiOfSecrets/Goatmeal-Time-v0.2
|
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
|
[
"Apache-2.0"
] | null | null | null |
export/release/windows/obj/src/haxe/IMap.cpp
|
SamuraiOfSecrets/Goatmeal-Time-v0.2
|
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
|
[
"Apache-2.0"
] | null | null | null |
export/release/windows/obj/src/haxe/IMap.cpp
|
SamuraiOfSecrets/Goatmeal-Time-v0.2
|
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
|
[
"Apache-2.0"
] | null | null | null |
// Generated by Haxe 4.2.2
#include <hxcpp.h>
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
namespace haxe{
static ::String IMap_obj_sMemberFields[] = {
HX_("get",96,80,4e,00),
HX_("set",a2,9b,57,00),
HX_("exists",dc,1d,e0,bf),
HX_("remove",44,9c,88,04),
HX_("keys",f4,e1,06,47),
HX_("iterator",ee,49,9a,93),
HX_("keyValueIterator",60,cd,ee,4a),
::String(null()) };
::hx::Class IMap_obj::__mClass;
void IMap_obj::__register()
{
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("haxe.IMap",1b,07,35,eb);
__mClass->mSuper = &super::__SGetClass();
__mClass->mMembers = ::hx::Class_obj::dupFunctions(IMap_obj_sMemberFields);
__mClass->mCanCast = ::hx::TIsInterface< (int)0x09c2bd39 >;
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace haxe
| 23.882353
| 76
| 0.681034
|
SamuraiOfSecrets
|
44693ec5484eb313e6fc7c17ec4ca254b3bb0338
| 1,440
|
cpp
|
C++
|
graph/tarjan_bridge.cpp
|
KSkun/OI-Templates
|
a193da03a531700858fe45d455a946074bda5007
|
[
"WTFPL"
] | 12
|
2018-03-30T08:44:07.000Z
|
2021-09-03T07:43:56.000Z
|
graph/tarjan_bridge.cpp
|
KSkun/OI-Templates
|
a193da03a531700858fe45d455a946074bda5007
|
[
"WTFPL"
] | null | null | null |
graph/tarjan_bridge.cpp
|
KSkun/OI-Templates
|
a193da03a531700858fe45d455a946074bda5007
|
[
"WTFPL"
] | 1
|
2018-08-09T01:39:30.000Z
|
2018-08-09T01:39:30.000Z
|
// Code by KSkun, 2018/7
#include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>
#include <vector>
typedef long long LL;
inline char fgc() {
static char buf[100000], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
? EOF : *p1++;
}
inline LL readint() {
register LL res = 0, neg = 1; register char c = fgc();
for(; !isdigit(c); c = fgc()) if(c == '-') neg = -1;
for(; isdigit(c); c = fgc()) res = (res << 1) + (res << 3) + c - '0';
return res * neg;
}
const int MAXN = 10005;
int n, m;
std::vector<int> gra[MAXN];
int dfn[MAXN], low[MAXN], clk, deg[MAXN];
void tarjan(int u, int fa) {
dfn[u] = low[u] = ++clk;
for(int i = 0; i < gra[u].size(); i++) {
int v = gra[u][i];
if(v == fa) continue;
if(!dfn[v]) {
tarjan(v, u);
low[u] = std::min(low[u], low[v]);
} else {
low[u] = std::min(low[u], dfn[v]);
}
}
}
// an example of Tarjan algorithm of finding bridge edges
// can pass poj 3352
int main() {
n = readint(); m = readint();
for(int i = 1, u, v; i <= m; i++) {
u = readint(); v = readint();
gra[u].push_back(v);
gra[v].push_back(u);
}
tarjan(1, 0);
for(int u = 1; u <= n; u++) {
for(int i = 0; i < gra[u].size(); i++) {
int v = gra[u][i];
if(low[u] != low[v]) {
deg[low[u]]++;
}
}
}
int cnt = 0;
for(int i = 1; i <= n; i++) {
if(deg[i] == 1) cnt++;
}
printf("%d", (cnt + 1) / 2);
return 0;
}
| 20.571429
| 78
| 0.515972
|
KSkun
|
446ae101fac943c6833400fb9a92c5c89c5f46dc
| 2,880
|
cpp
|
C++
|
FCollada/FColladaTest/FCTestXRef/FCTestXRefAcyclic.cpp
|
matthewlai/fcollada
|
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
|
[
"MIT"
] | 9
|
2016-04-22T05:47:37.000Z
|
2021-03-02T08:58:56.000Z
|
FCollada/FColladaTest/FCTestXRef/FCTestXRefAcyclic.cpp
|
matthewlai/fcollada
|
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
|
[
"MIT"
] | 5
|
2018-12-17T13:49:54.000Z
|
2021-11-26T17:22:16.000Z
|
FCollada/FColladaTest/FCTestXRef/FCTestXRefAcyclic.cpp
|
matthewlai/fcollada
|
d02e475d45e01a33c2c588a4a62a3ac0d70ef9e0
|
[
"MIT"
] | 5
|
2018-06-26T19:42:58.000Z
|
2021-10-11T13:03:31.000Z
|
/*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
#include "StdAfx.h"
#include "FCDocument/FCDocument.h"
#include "FCDocument/FCDAsset.h"
#include "FCDocument/FCDLibrary.h"
#include "FCDocument/FCDGeometry.h"
#include "FCDocument/FCDEntityInstance.h"
#include "FCDocument/FCDExternalReferenceManager.h"
#include "FCDocument/FCDSceneNode.h"
#include "FUtils/FUTestBed.h"
TESTSUITE_START(FCTestXRefAcyclic)
TESTSUITE_TEST(0, Export)
// None of the previous tests should be leaving dangling documents.
PassIf(FCollada::GetTopDocumentCount() == 0);
FCDocument* firstDoc = FCollada::NewTopDocument();
FCDocument* secondDoc = FCollada::NewTopDocument();
FCDGeometry* mesh1 = firstDoc->GetGeometryLibrary()->AddEntity();
FCDGeometry* mesh2 = secondDoc->GetGeometryLibrary()->AddEntity();
FCDSceneNode* node1 = firstDoc->AddVisualScene();
node1 = node1->AddChildNode();
FCDSceneNode* node2 = secondDoc->AddVisualScene();
node2 = node2->AddChildNode();
node2->AddInstance(mesh1);
node1->AddInstance(mesh2);
firstDoc->SetFileUrl(FS("XRefDoc1.dae"));
FCollada::SaveDocument(secondDoc, FC("XRefDoc2.dae"));
FCollada::SaveDocument(firstDoc, FC("XRefDoc1.dae"));
SAFE_RELEASE(firstDoc);
SAFE_RELEASE(secondDoc);
TESTSUITE_TEST(1, ImportOne)
// None of the previous tests should be leaving dangling documents.
PassIf(FCollada::GetTopDocumentCount() == 0);
FUErrorSimpleHandler errorHandler;
FCollada::SetDereferenceFlag(false);
FCDocument* firstDoc = FCollada::NewTopDocument();
PassIf(FCollada::LoadDocumentFromFile(firstDoc, FC("XRefDoc1.dae")));
FCDocument* secondDoc = FCollada::NewTopDocument();
PassIf(FCollada::LoadDocumentFromFile(secondDoc, FC("XRefDoc2.dae")));
PassIf(errorHandler.IsSuccessful());
FCDSceneNode* node1 = firstDoc->GetVisualSceneInstance();
FCDSceneNode* node2 = secondDoc->GetVisualSceneInstance();
FailIf(node1 == NULL || node2 == NULL || node1->GetChildrenCount() == 0 || node2->GetChildrenCount() == 0);
node1 = node1->GetChild(0);
node2 = node2->GetChild(0);
FailIf(node1 == NULL || node2 == NULL);
PassIf(node1->GetInstanceCount() == 1 && node2->GetInstanceCount() == 1);
FCDEntityInstance* instance1 = node1->GetInstance(0);
FCDEntityInstance* instance2 = node2->GetInstance(0);
PassIf(instance1 != NULL && instance2 != NULL);
PassIf(instance1->GetEntityType() == FCDEntity::GEOMETRY && instance2->GetEntityType() == FCDEntity::GEOMETRY);
FCDGeometry* mesh1 = (FCDGeometry*) instance1->GetEntity();
FCDGeometry* mesh2 = (FCDGeometry*) instance2->GetEntity();
PassIf(mesh1 != NULL && mesh2 != NULL);
PassIf(mesh1->GetDocument() == secondDoc);
PassIf(mesh2->GetDocument() == firstDoc);
SAFE_RELEASE(firstDoc);
SAFE_RELEASE(secondDoc);
TESTSUITE_END
| 36.455696
| 112
| 0.751042
|
matthewlai
|
447533658405d0b3e50e451a2aea5451740024b8
| 2,316
|
cpp
|
C++
|
310_Minimum_Height_Trees.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
310_Minimum_Height_Trees.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
310_Minimum_Height_Trees.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
/*
310. Minimum Height Trees
Medium
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
Return a list of all MHTs' root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
Example 3:
Input: n = 1, edges = []
Output: [0]
Example 4:
Input: n = 2, edges = [[0,1]]
Output: [0,1]
Constraints:
1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
All the pairs (ai, bi) are distinct.
The given input is guaranteed to be a tree and there will be no repeated edges.
*/
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if(n==1) return {0};
vector<vector<int>> adj(n);
vector<int> indegree(n,0);
int u,v,size;
for(auto e:edges){
u=e[0];
v=e[1];
adj[u].push_back(v);
adj[v].push_back(u);
indegree[u]++;
indegree[v]++;
}
queue<int> q;
vector<int> res;
for(int i=0;i<n;i++) if(indegree[i]==1) q.push(i);
while(!q.empty()){
res.clear();
size=q.size();
for(int i=0;i<size;i++){
u=q.front();
q.pop();
res.push_back(u);
for(auto v:adj[u]){
indegree[v]--;
if(indegree[v]==1) q.push(v);
}
}
}
return res;
}
};
| 32.619718
| 422
| 0.567789
|
AvadheshChamola
|
44795f9d12d6bcde60cf97d03de847a0dfe42ab7
| 1,540
|
cpp
|
C++
|
POJ/POJ - 1654/Wrong Answer.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
POJ/POJ - 1654/Wrong Answer.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
POJ/POJ - 1654/Wrong Answer.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: 2019-04-03 01:23:59
* solution_verdict: Wrong Answer language: C++
* run_time (ms): memory_used (MB):
* problem: https://vjudge.net/problem/POJ-1654
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cmath>
#define long long long
using namespace std;
const int N=1e6;
struct point
{
int x,y;
point(){}
point(int _x,int _y){x=_x,y=_y;}
int operator^(point p){return x*p.y-y*p.x;}
};
int polygonarea2(vector<point>&v)
{
int ret=0;
for(int i=0;i<v.size()-1;i++)
ret+=v[i]^v[i+1];
if(ret<0)ret=-ret;
return ret;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
string s;cin>>s;vector<point>v;
point p(0,0);v.push_back(p);
for(int i=0;i<s.size();i++)
{
if(s[i]=='5')break;
if(s[i]=='8')p.y++;
if(s[i]=='9')p.x++,p.y++;
if(s[i]=='6')p.x++;
if(s[i]=='3')p.x++,p.y--;
if(s[i]=='2')p.y--;
if(s[i]=='1')p.x--,p.y--;
if(s[i]=='4')p.x--;
if(s[i]=='7')p.x--,p.y++;
v.push_back(p);
}
int area=polygonarea2(v);
if(area%2==0)cout<<area/2<<endl;
else cout<<area/2<<".5"<<endl;
}
return 0;
}
| 28.518519
| 111
| 0.406494
|
kzvd4729
|
447ad53dafabcec380cbffb82c9a076039265ae0
| 836
|
hpp
|
C++
|
PA2/src/Light.hpp
|
dowoncha/COMP575
|
6e48bdd80cb1a3e677c07655640efa941325e59c
|
[
"MIT"
] | null | null | null |
PA2/src/Light.hpp
|
dowoncha/COMP575
|
6e48bdd80cb1a3e677c07655640efa941325e59c
|
[
"MIT"
] | null | null | null |
PA2/src/Light.hpp
|
dowoncha/COMP575
|
6e48bdd80cb1a3e677c07655640efa941325e59c
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* filename: Light.hpp
* author: Do Won Cha
* content: Light class to put in scenes
*
******************************************************************************/
#pragma once
#ifndef _RAST_LIGHT_
#define _RAST_LIGHT_
#include <glm/vec3.hpp>
class Light
{
public:
glm::vec3 pos;
float intensity;
int specPower;
Light(const glm::vec3& _pos, float _intensity) :
pos(_pos),
intensity(_intensity),
specPower(32)
{ }
Light(const glm::vec3& _pos, float _intensity, int pow) :
pos(_pos),
intensity(_intensity),
specPower(pow)
{ }
Light(float x, float y, float z, float _intensity) :
pos(x, y, z),
intensity(_intensity)
{ }
~Light() {}
};
#endif // _RAST_LIGHT_
| 19.44186
| 80
| 0.494019
|
dowoncha
|
447b361c0d3f3f76cdd8a41752db6911985e74bf
| 4,525
|
cpp
|
C++
|
OverEngine/src/Platform/OpenGL/OpenGLTexture.cpp
|
larrymason01/OverEngine
|
4e44fe8385cc1780f2189ee5135f70b1e69104fd
|
[
"MIT"
] | 159
|
2020-03-16T14:46:46.000Z
|
2022-03-31T23:38:14.000Z
|
OverEngine/src/Platform/OpenGL/OpenGLTexture.cpp
|
larrymason01/OverEngine
|
4e44fe8385cc1780f2189ee5135f70b1e69104fd
|
[
"MIT"
] | 5
|
2020-11-22T14:40:20.000Z
|
2022-01-16T03:45:54.000Z
|
OverEngine/src/Platform/OpenGL/OpenGLTexture.cpp
|
larrymason01/OverEngine
|
4e44fe8385cc1780f2189ee5135f70b1e69104fd
|
[
"MIT"
] | 17
|
2020-06-01T05:58:32.000Z
|
2022-02-10T17:28:36.000Z
|
#include "pcheader.h"
#include "OpenGLTexture.h"
#include <glad/gl.h>
#include <stb_image.h>
namespace OverEngine
{
static TextureFormat GetFormatFromChannelCount(int channels)
{
switch (channels)
{
case 3: return TextureFormat::RGB8;
case 4: return TextureFormat::RGBA8;
default: return TextureFormat::None;
}
}
static auto GetOpenGLDataAndInternalFormat(TextureFormat format)
{
struct _out
{
_out(GLenum internalFormat, GLenum dataFormat)
: InternalFormat(internalFormat), DataFormat(dataFormat)
{
}
GLenum InternalFormat;
GLenum DataFormat;
};
switch (format)
{
case TextureFormat::RGB8: return _out{ GL_RGB8, GL_RGB };
case TextureFormat::RGBA8: return _out{ GL_RGBA8, GL_RGBA };
default: return _out{ 0, 0 };
}
}
static GLenum GetOpenGLTextureFilter(TextureFilter filter)
{
switch (filter)
{
case TextureFilter::Nearest: return GL_NEAREST;
case TextureFilter::BiLinear: return GL_LINEAR;
default: return 0;
}
}
static GLenum GetOpenGLTextureWrap(TextureWrap wrap)
{
switch (wrap)
{
case TextureWrap::Repeat: return GL_REPEAT;
case TextureWrap::Clamp: return GL_CLAMP_TO_EDGE;
case TextureWrap::Mirror: return GL_MIRRORED_REPEAT;
default: return 0;
}
}
OpenGLTexture2D::OpenGLTexture2D(const String& path)
{
// Load image using stb_image
int width, height, channels;
stbi_uc* data = stbi_load(path.c_str(), &width, &height, &channels, 0);
OE_CORE_ASSERT(data, "Failed to load image at path '{}'! reason: '{}'", path, stbi_failure_reason());
// Check channel count and format
m_Format = GetFormatFromChannelCount(channels);
OE_CORE_ASSERT(m_Format != TextureFormat::None, "Unsupported image format (channel count = {}).", channels);
// Put values in members
m_Width = width;
m_Height = height;
m_Filter = TextureFilter::BiLinear;
m_Wrap = { TextureWrap::Repeat, TextureWrap::Repeat };
// Upload image to GPU
auto glFormat = GetOpenGLDataAndInternalFormat(m_Format);
glCreateTextures(GL_TEXTURE_2D, 1, &m_RendererID);
glTextureStorage2D(m_RendererID, 1, glFormat.InternalFormat, m_Width, m_Height);
glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTextureSubImage2D(m_RendererID, 0, 0, 0, m_Width, m_Height, glFormat.DataFormat, GL_UNSIGNED_BYTE, data);
// Free image buffer created by stb_image
stbi_image_free(data);
}
OpenGLTexture2D::OpenGLTexture2D(const uint64_t& guid)
{
SetGuid(guid);
}
void OpenGLTexture2D::Acquire(Ref<Asset> other)
{
if (auto otherGLTexture = std::dynamic_pointer_cast<OpenGLTexture2D>(other))
{
m_RendererID = otherGLTexture->m_RendererID;
m_Width = otherGLTexture->m_Width;
m_Height = otherGLTexture->m_Height;
m_Format = otherGLTexture->m_Format;
m_Filter = otherGLTexture->m_Filter;
m_Wrap = otherGLTexture->m_Wrap;
otherGLTexture->m_RendererID = 0;
}
}
OpenGLTexture2D::~OpenGLTexture2D()
{
if (m_RendererID != 0)
glDeleteTextures(1, &m_RendererID);
}
uint32_t OpenGLTexture2D::GetWidth() const
{
return m_Width;
}
uint32_t OpenGLTexture2D::GetHeight() const
{
return m_Height;
}
uint32_t OpenGLTexture2D::GetRendererID() const
{
return m_RendererID;
}
void OpenGLTexture2D::Bind(uint32_t slot)
{
glBindTextureUnit(slot, m_RendererID);
}
TextureFilter OpenGLTexture2D::GetFilter() const
{
return m_Filter;
}
void OpenGLTexture2D::SetFilter(TextureFilter filter)
{
m_Filter = filter;
GLenum glFilter = GetOpenGLTextureFilter(filter);
glTextureParameteri(m_RendererID, GL_TEXTURE_MIN_FILTER, glFilter);
glTextureParameteri(m_RendererID, GL_TEXTURE_MAG_FILTER, glFilter);
}
TextureWrap OpenGLTexture2D::GetUWrap() const
{
return m_Wrap.u;
}
void OpenGLTexture2D::SetUWrap(TextureWrap wrap)
{
m_Wrap.u = wrap;
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_S, GetOpenGLTextureWrap(wrap));
}
TextureWrap OpenGLTexture2D::GetVWrap() const
{
return m_Wrap.v;
}
void OpenGLTexture2D::SetVWrap(TextureWrap wrap)
{
m_Wrap.v = wrap;
glTextureParameteri(m_RendererID, GL_TEXTURE_WRAP_T, GetOpenGLTextureWrap(wrap));
}
TextureFormat OpenGLTexture2D::GetFormat() const
{
return m_Format;
}
TextureType OpenGLTexture2D::GetType() const
{
return TextureType::Master;
}
}
| 23.567708
| 110
| 0.740773
|
larrymason01
|
447c404aacc0b5764eef6ebdd750adf15a5a0bb9
| 10,297
|
cpp
|
C++
|
gen/irstate.cpp
|
bcarneal/ldc
|
9651acd24e1ce2be21c34c163ec6beb9dd77018a
|
[
"Apache-2.0"
] | 3
|
2016-07-14T17:48:47.000Z
|
2016-09-20T05:33:41.000Z
|
gen/irstate.cpp
|
bcarneal/ldc
|
9651acd24e1ce2be21c34c163ec6beb9dd77018a
|
[
"Apache-2.0"
] | 1
|
2019-08-30T05:05:40.000Z
|
2019-08-30T05:05:40.000Z
|
gen/irstate.cpp
|
bcarneal/ldc
|
9651acd24e1ce2be21c34c163ec6beb9dd77018a
|
[
"Apache-2.0"
] | 2
|
2019-08-30T03:10:44.000Z
|
2019-09-17T02:54:21.000Z
|
//===-- irstate.cpp -------------------------------------------------------===//
//
// LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//
#include "gen/irstate.h"
#include "dmd/declaration.h"
#include "dmd/expression.h"
#include "dmd/identifier.h"
#include "dmd/mtype.h"
#include "dmd/statement.h"
#include "gen/funcgenstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/tollvm.h"
#include "ir/irfunction.h"
#include <cstdarg>
IRState *gIR = nullptr;
llvm::TargetMachine *gTargetMachine = nullptr;
const llvm::DataLayout *gDataLayout = nullptr;
TargetABI *gABI = nullptr;
////////////////////////////////////////////////////////////////////////////////
IRState::IRState(const char *name, llvm::LLVMContext &context)
: builder(context), module(name, context), objc(module), DBuilder(this) {
ir.state = this;
mem.addRange(&inlineAsmLocs, sizeof(inlineAsmLocs));
}
IRState::~IRState() { mem.removeRange(&inlineAsmLocs); }
FuncGenState &IRState::funcGen() {
assert(!funcGenStates.empty() && "Function stack is empty!");
return *funcGenStates.back();
}
IrFunction *IRState::func() { return &funcGen().irFunc; }
llvm::Function *IRState::topfunc() { return func()->getLLVMFunc(); }
llvm::Instruction *IRState::topallocapoint() { return funcGen().allocapoint; }
std::unique_ptr<IRBuilderScope> IRState::setInsertPoint(llvm::BasicBlock *bb) {
auto savedScope = llvm::make_unique<IRBuilderScope>(builder);
builder.SetInsertPoint(bb);
return savedScope;
}
std::unique_ptr<llvm::IRBuilderBase::InsertPointGuard>
IRState::saveInsertPoint() {
return llvm::make_unique<llvm::IRBuilderBase::InsertPointGuard>(builder);
}
bool IRState::scopereturned() {
auto bb = scopebb();
return !bb->empty() && bb->back().isTerminator();
}
llvm::BasicBlock *IRState::insertBBBefore(llvm::BasicBlock *successor,
const llvm::Twine &name) {
return llvm::BasicBlock::Create(context(), name, topfunc(), successor);
}
llvm::BasicBlock *IRState::insertBBAfter(llvm::BasicBlock *predecessor,
const llvm::Twine &name) {
auto bb = llvm::BasicBlock::Create(context(), name, topfunc());
bb->moveAfter(predecessor);
return bb;
}
llvm::BasicBlock *IRState::insertBB(const llvm::Twine &name) {
return insertBBAfter(scopebb(), name);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
const char *Name) {
return CreateCallOrInvoke(Callee, {}, Name);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
llvm::ArrayRef<LLValue *> Args,
const char *Name,
bool isNothrow) {
return funcGen().callOrInvoke(Callee, Callee->getFunctionType(), Args, Name,
isNothrow);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
LLValue *Arg1,
const char *Name) {
return CreateCallOrInvoke(Callee, llvm::ArrayRef<LLValue *>(Arg1), Name);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
LLValue *Arg1, LLValue *Arg2,
const char *Name) {
return CreateCallOrInvoke(Callee, {Arg1, Arg2}, Name);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
LLValue *Arg1, LLValue *Arg2,
LLValue *Arg3,
const char *Name) {
return CreateCallOrInvoke(Callee, {Arg1, Arg2, Arg3}, Name);
}
llvm::Instruction *IRState::CreateCallOrInvoke(LLFunction *Callee,
LLValue *Arg1, LLValue *Arg2,
LLValue *Arg3, LLValue *Arg4,
const char *Name) {
return CreateCallOrInvoke(Callee, {Arg1, Arg2, Arg3, Arg4}, Name);
}
bool IRState::emitArrayBoundsChecks() {
if (global.params.useArrayBounds != CHECKENABLEsafeonly) {
return global.params.useArrayBounds == CHECKENABLEon;
}
// Safe functions only.
if (funcGenStates.empty()) {
return false;
}
Type *t = func()->decl->type;
return t->ty == Tfunction && ((TypeFunction *)t)->trust == TRUST::safe;
}
LLConstant *
IRState::setGlobalVarInitializer(LLGlobalVariable *&globalVar,
LLConstant *initializer,
Dsymbol *symbolForLinkageAndVisibility) {
if (initializer->getType() == globalVar->getType()->getContainedType(0)) {
defineGlobal(globalVar, initializer, symbolForLinkageAndVisibility);
return globalVar;
}
// Create the global helper variable matching the initializer type.
// It inherits most properties from the existing globalVar.
auto globalHelperVar = new LLGlobalVariable(
module, initializer->getType(), globalVar->isConstant(),
globalVar->getLinkage(), nullptr, "", nullptr,
globalVar->getThreadLocalMode());
globalHelperVar->setAlignment(LLMaybeAlign(globalVar->getAlignment()));
globalHelperVar->setComdat(globalVar->getComdat());
globalHelperVar->setDLLStorageClass(globalVar->getDLLStorageClass());
globalHelperVar->setSection(globalVar->getSection());
globalHelperVar->takeName(globalVar);
defineGlobal(globalHelperVar, initializer, symbolForLinkageAndVisibility);
// Replace all existing uses of globalVar by the bitcast pointer.
auto castHelperVar = DtoBitCast(globalHelperVar, globalVar->getType());
globalVar->replaceAllUsesWith(castHelperVar);
// Register replacement for later occurrences of the original globalVar.
globalsToReplace.emplace_back(globalVar, castHelperVar);
// Reset globalVar to the helper variable.
globalVar = globalHelperVar;
return castHelperVar;
}
void IRState::replaceGlobals() {
for (const auto &pair : globalsToReplace) {
pair.first->replaceAllUsesWith(pair.second);
pair.first->eraseFromParent();
}
globalsToReplace.resize(0);
}
////////////////////////////////////////////////////////////////////////////////
LLConstant *IRState::getStructLiteralConstant(StructLiteralExp *sle) const {
return static_cast<LLConstant *>(structLiteralConstants.lookup(sle->origin));
}
void IRState::setStructLiteralConstant(StructLiteralExp *sle,
LLConstant *constant) {
structLiteralConstants[sle->origin] = constant;
}
////////////////////////////////////////////////////////////////////////////////
namespace {
template <typename F>
LLGlobalVariable *
getCachedStringLiteralImpl(llvm::Module &module,
llvm::StringMap<LLGlobalVariable *> &cache,
llvm::StringRef key, F initFactory) {
auto iter = cache.find(key);
if (iter != cache.end()) {
return iter->second;
}
LLConstant *constant = initFactory();
auto gvar =
new LLGlobalVariable(module, constant->getType(), true,
LLGlobalValue::PrivateLinkage, constant, ".str");
gvar->setUnnamedAddr(LLGlobalValue::UnnamedAddr::Global);
cache[key] = gvar;
return gvar;
}
}
LLGlobalVariable *IRState::getCachedStringLiteral(StringExp *se) {
llvm::StringMap<LLGlobalVariable *> *cache;
switch (se->sz) {
default:
llvm_unreachable("Unknown char type");
case 1:
cache = &cachedStringLiterals;
break;
case 2:
cache = &cachedWstringLiterals;
break;
case 4:
cache = &cachedDstringLiterals;
break;
}
const DArray<const unsigned char> keyData = se->peekData();
const llvm::StringRef key(reinterpret_cast<const char *>(keyData.ptr),
keyData.length);
return getCachedStringLiteralImpl(module, *cache, key, [se]() {
return buildStringLiteralConstant(se, true);
});
}
LLGlobalVariable *IRState::getCachedStringLiteral(llvm::StringRef s) {
return getCachedStringLiteralImpl(module, cachedStringLiterals, s, [&]() {
return llvm::ConstantDataArray::getString(context(), s, true);
});
}
////////////////////////////////////////////////////////////////////////////////
void IRState::addLinkerOption(llvm::ArrayRef<llvm::StringRef> options) {
llvm::SmallVector<llvm::Metadata *, 2> mdStrings;
mdStrings.reserve(options.size());
for (const auto &s : options)
mdStrings.push_back(llvm::MDString::get(context(), s));
linkerOptions.push_back(llvm::MDNode::get(context(), mdStrings));
}
void IRState::addLinkerDependentLib(llvm::StringRef libraryName) {
auto n = llvm::MDString::get(context(), libraryName);
linkerDependentLibs.push_back(llvm::MDNode::get(context(), n));
}
////////////////////////////////////////////////////////////////////////////////
void IRState::addInlineAsmSrcLoc(const Loc &loc,
llvm::CallInst *inlineAsmCall) {
// Simply use a stack of Loc* per IR module, and use index+1 as 32-bit
// cookie to be mapped back by the InlineAsmDiagnosticHandler.
// 0 is not a valid cookie.
inlineAsmLocs.push_back(loc);
auto srcLocCookie = static_cast<unsigned>(inlineAsmLocs.size());
auto constant =
LLConstantInt::get(LLType::getInt32Ty(context()), srcLocCookie);
inlineAsmCall->setMetadata(
"srcloc",
llvm::MDNode::get(context(), llvm::ConstantAsMetadata::get(constant)));
}
const Loc &IRState::getInlineAsmSrcLoc(unsigned srcLocCookie) const {
assert(srcLocCookie > 0 && srcLocCookie <= inlineAsmLocs.size());
return inlineAsmLocs[srcLocCookie - 1];
}
////////////////////////////////////////////////////////////////////////////////
IRBuilder<> *IRBuilderHelper::operator->() {
IRBuilder<> &b = state->builder;
assert(b.GetInsertBlock());
return &b;
}
////////////////////////////////////////////////////////////////////////////////
bool useMSVCEH() {
return global.params.targetTriple->isWindowsMSVCEnvironment();
}
| 34.670034
| 80
| 0.608333
|
bcarneal
|
447ee518b20a820ae2bf91d6a76dfc3badd5fd00
| 1,491
|
cpp
|
C++
|
app/src/main/cpp/engine/material.cpp
|
JsMarq96/Quest-Testing
|
e2017f20fa2a1ca1bbaa25b36ab4c58fa4cf7761
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/engine/material.cpp
|
JsMarq96/Quest-Testing
|
e2017f20fa2a1ca1bbaa25b36ab4c58fa4cf7761
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/engine/material.cpp
|
JsMarq96/Quest-Testing
|
e2017f20fa2a1ca1bbaa25b36ab4c58fa4cf7761
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Juan S. Marquerie on 31/05/2021.
//
#include "material.h"
void material_add_shader(sMaterial *mat,
const char *vertex_shader,
const char *fragment_shader) {
mat->shader.load_shaders(vertex_shader,
fragment_shader);
}
void material_add_texture(sMaterial *mat,
const char* text_dir,
const eTextureType text_type) {
mat->enabled_textures[text_type] = true;
load_texture(&mat->textures[text_type],
false,
false,
text_dir);
}
void material_add_cubemap_texture(sMaterial *mat,
const char *text_dir) {
mat->enabled_textures[COLOR_MAP] = true;
load_texture(&mat->textures[COLOR_MAP],
true,
false,
text_dir);
}
/**
* Binds the textures on Opengl
* COLOR - Texture 0
* NORMAL - Texture 1
* SPECULAR - TEXTURE 2
* */
void material_enable(const sMaterial *mat) {
for (int texture = 0; texture < TEXTURE_TYPE_COUNT; texture++) {
if (!mat->enabled_textures[texture]) {
continue;
}
glActiveTexture(GL_TEXTURE0 + texture);
glBindTexture(GL_TEXTURE_2D, mat->textures[texture].texture_id);
}
mat->shader.enable();
}
void material_disable(const sMaterial *mat) {
mat->shader.disable();
}
| 28.132075
| 72
| 0.551308
|
JsMarq96
|
447f5a44ec84f3babb4c709232c661700476b70a
| 37,643
|
cpp
|
C++
|
src/ompl/geometric/planners/fmt/src/BFMT.cpp
|
sbgisen/ompl
|
f814f614b0581f9b9b150bec23ba1446ff1d7e94
|
[
"BSD-3-Clause"
] | null | null | null |
src/ompl/geometric/planners/fmt/src/BFMT.cpp
|
sbgisen/ompl
|
f814f614b0581f9b9b150bec23ba1446ff1d7e94
|
[
"BSD-3-Clause"
] | null | null | null |
src/ompl/geometric/planners/fmt/src/BFMT.cpp
|
sbgisen/ompl
|
f814f614b0581f9b9b150bec23ba1446ff1d7e94
|
[
"BSD-3-Clause"
] | null | null | null |
#include <boost/math/constants/constants.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <ompl/datastructures/BinaryHeap.h>
#include <ompl/tools/config/SelfConfig.h>
#include <ompl/datastructures/NearestNeighborsGNAT.h>
#include <ompl/base/objectives/PathLengthOptimizationObjective.h>
#include <ompl/geometric/planners/fmt/BFMT.h>
#include <fstream>
#include <ompl/base/spaces/RealVectorStateSpace.h>
namespace ompl
{
namespace geometric
{
BFMT::BFMT(const base::SpaceInformationPtr &si)
: base::Planner(si, "BFMT")
, freeSpaceVolume_(si_->getStateSpace()->getMeasure()) // An upper bound on the free space volume is the
// total space volume; the free fraction is estimated
// in sampleFree
{
specs_.approximateSolutions = false;
specs_.directed = false;
ompl::base::Planner::declareParam<unsigned int>("num_samples", this, &BFMT::setNumSamples,
&BFMT::getNumSamples, "10:10:1000000");
ompl::base::Planner::declareParam<double>("radius_multiplier", this, &BFMT::setRadiusMultiplier,
&BFMT::getRadiusMultiplier, "0.1:0.05:50.");
ompl::base::Planner::declareParam<bool>("nearest_k", this, &BFMT::setNearestK, &BFMT::getNearestK, "0,1");
ompl::base::Planner::declareParam<bool>("balanced", this, &BFMT::setExploration, &BFMT::getExploration,
"0,1");
ompl::base::Planner::declareParam<bool>("optimality", this, &BFMT::setTermination, &BFMT::getTermination,
"0,1");
ompl::base::Planner::declareParam<bool>("heuristics", this, &BFMT::setHeuristics, &BFMT::getHeuristics,
"0,1");
ompl::base::Planner::declareParam<bool>("cache_cc", this, &BFMT::setCacheCC, &BFMT::getCacheCC, "0,1");
ompl::base::Planner::declareParam<bool>("extended_fmt", this, &BFMT::setExtendedFMT, &BFMT::getExtendedFMT,
"0,1");
}
ompl::geometric::BFMT::~BFMT()
{
freeMemory();
}
void BFMT::setup()
{
if (pdef_)
{
/* Setup the optimization objective. If no optimization objective was
specified, then default to optimizing path length as computed by the
distance() function in the state space */
if (pdef_->hasOptimizationObjective())
opt_ = pdef_->getOptimizationObjective();
else
{
OMPL_INFORM("%s: No optimization objective specified. Defaulting to optimizing path length.",
getName().c_str());
opt_ = std::make_shared<base::PathLengthOptimizationObjective>(si_);
// Store the new objective in the problem def'n
pdef_->setOptimizationObjective(opt_);
}
Open_[0].getComparisonOperator().opt_ = opt_.get();
Open_[0].getComparisonOperator().heuristics_ = heuristics_;
Open_[1].getComparisonOperator().opt_ = opt_.get();
Open_[1].getComparisonOperator().heuristics_ = heuristics_;
if (!nn_)
nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<BiDirMotion *>(this));
nn_->setDistanceFunction([this](const BiDirMotion *a, const BiDirMotion *b)
{
return distanceFunction(a, b);
});
if (nearestK_ && !nn_->reportsSortedResults())
{
OMPL_WARN("%s: NearestNeighbors datastructure does not return sorted solutions. Nearest K strategy "
"disabled.",
getName().c_str());
nearestK_ = false;
}
}
else
{
OMPL_INFORM("%s: problem definition is not set, deferring setup completion...", getName().c_str());
setup_ = false;
}
}
void BFMT::freeMemory()
{
if (nn_)
{
BiDirMotionPtrs motions;
nn_->list(motions);
for (auto &motion : motions)
{
si_->freeState(motion->getState());
delete motion;
}
}
}
void BFMT::clear()
{
Planner::clear();
sampler_.reset();
freeMemory();
if (nn_)
nn_->clear();
Open_[FWD].clear();
Open_[REV].clear();
Open_elements[FWD].clear();
Open_elements[REV].clear();
neighborhoods_.clear();
collisionChecks_ = 0;
}
void BFMT::getPlannerData(base::PlannerData &data) const
{
base::Planner::getPlannerData(data);
BiDirMotionPtrs motions;
nn_->list(motions);
int numStartNodes = 0;
int numGoalNodes = 0;
int numEdges = 0;
int numFwdEdges = 0;
int numRevEdges = 0;
int fwd_tree_tag = 1;
int rev_tree_tag = 2;
for (auto motion : motions)
{
bool inFwdTree = (motion->currentSet_[FWD] != BiDirMotion::SET_UNVISITED);
// For samples added to the fwd tree, add incoming edges (from fwd tree parent)
if (inFwdTree)
{
if (motion->parent_[FWD] == nullptr)
{
// Motion is a forward tree root node
++numStartNodes;
}
else
{
bool success =
data.addEdge(base::PlannerDataVertex(motion->parent_[FWD]->getState(), fwd_tree_tag),
base::PlannerDataVertex(motion->getState(), fwd_tree_tag));
if (success)
{
++numFwdEdges;
++numEdges;
}
}
}
}
// The edges in the goal tree are reversed so that they are in the same direction as start tree
for (auto motion : motions)
{
bool inRevTree = (motion->currentSet_[REV] != BiDirMotion::SET_UNVISITED);
// For samples added to a tree, add incoming edges (from fwd tree parent)
if (inRevTree)
{
if (motion->parent_[REV] == nullptr)
{
// Motion is a reverse tree root node
++numGoalNodes;
}
else
{
bool success =
data.addEdge(base::PlannerDataVertex(motion->getState(), rev_tree_tag),
base::PlannerDataVertex(motion->parent_[REV]->getState(), rev_tree_tag));
if (success)
{
++numRevEdges;
++numEdges;
}
}
}
}
}
void BFMT::saveNeighborhood(BiDirMotion *m)
{
// Check if neighborhood has already been saved
if (neighborhoods_.find(m) == neighborhoods_.end())
{
BiDirMotionPtrs neighborhood;
if (nearestK_)
nn_->nearestK(m, NNk_, neighborhood);
else
nn_->nearestR(m, NNr_, neighborhood);
if (!neighborhood.empty())
{
// Save the neighborhood but skip the first element (m)
neighborhoods_[m] = std::vector<BiDirMotion *>(neighborhood.size() - 1, nullptr);
std::copy(neighborhood.begin() + 1, neighborhood.end(), neighborhoods_[m].begin());
}
else
{
// Save an empty neighborhood
neighborhoods_[m] = std::vector<BiDirMotion *>(0);
}
}
}
void BFMT::sampleFree(const std::shared_ptr<NearestNeighbors<BiDirMotion *>> &nn,
const base::PlannerTerminationCondition &ptc)
{
unsigned int nodeCount = 0;
unsigned int sampleAttempts = 0;
auto *motion = new BiDirMotion(si_, &tree_);
// Sample numSamples_ number of nodes from the free configuration space
while (nodeCount < numSamples_ && !ptc)
{
sampler_->sampleUniform(motion->getState());
sampleAttempts++;
if (si_->isValid(motion->getState()))
{ // collision checking
++nodeCount;
nn->add(motion);
motion = new BiDirMotion(si_, &tree_);
}
}
si_->freeState(motion->getState());
delete motion;
// 95% confidence limit for an upper bound for the true free space volume
freeSpaceVolume_ =
boost::math::binomial_distribution<>::find_upper_bound_on_p(sampleAttempts, nodeCount, 0.05) *
si_->getStateSpace()->getMeasure();
}
double BFMT::calculateUnitBallVolume(const unsigned int dimension) const
{
if (dimension == 0)
return 1.0;
if (dimension == 1)
return 2.0;
return 2.0 * boost::math::constants::pi<double>() / dimension * calculateUnitBallVolume(dimension - 2);
}
double BFMT::calculateRadius(const unsigned int dimension, const unsigned int n) const
{
double a = 1.0 / (double)dimension;
double unitBallVolume = calculateUnitBallVolume(dimension);
return radiusMultiplier_ * 2.0 * std::pow(a, a) * std::pow(freeSpaceVolume_ / unitBallVolume, a) *
std::pow(log((double)n) / (double)n, a);
}
void BFMT::initializeProblem(base::GoalSampleableRegion *&goal_s)
{
checkValidity();
if (!sampler_)
{
sampler_ = si_->allocStateSampler();
}
goal_s = dynamic_cast<base::GoalSampleableRegion *>(pdef_->getGoal().get());
}
base::PlannerStatus BFMT::solve(const base::PlannerTerminationCondition &ptc)
{
base::GoalSampleableRegion *goal_s;
initializeProblem(goal_s);
if (goal_s == nullptr)
{
OMPL_ERROR("%s: Unknown type of goal", getName().c_str());
return base::PlannerStatus::UNRECOGNIZED_GOAL_TYPE;
}
useFwdTree();
// Add start states to Unvisitedfwd and Openfwd
bool valid_initMotion = false;
BiDirMotion *initMotion;
while (const base::State *st = pis_.nextStart())
{
initMotion = new BiDirMotion(si_, &tree_);
si_->copyState(initMotion->getState(), st);
initMotion->currentSet_[REV] = BiDirMotion::SET_UNVISITED;
nn_->add(initMotion); // S <-- {x_init}
if (si_->isValid(initMotion->getState()))
{
// Take the first valid initial state as the forward tree root
Open_elements[FWD][initMotion] = Open_[FWD].insert(initMotion);
initMotion->currentSet_[FWD] = BiDirMotion::SET_OPEN;
initMotion->cost_[FWD] = opt_->initialCost(initMotion->getState());
valid_initMotion = true;
heurGoalState_[1] = initMotion->getState();
}
}
if ((initMotion == nullptr) || !valid_initMotion)
{
OMPL_ERROR("Start state undefined or invalid.");
return base::PlannerStatus::INVALID_START;
}
// Sample N free states in configuration state_
sampleFree(nn_, ptc); // S <-- SAMPLEFREE(N)
OMPL_INFORM("%s: Starting planning with %u states already in datastructure", getName().c_str(),
nn_->size());
// Calculate the nearest neighbor search radius
if (nearestK_)
{
NNk_ = std::ceil(std::pow(2.0 * radiusMultiplier_, (double)si_->getStateDimension()) *
(boost::math::constants::e<double>() / (double)si_->getStateDimension()) *
log((double)nn_->size()));
OMPL_DEBUG("Using nearest-neighbors k of %d", NNk_);
}
else
{
NNr_ = calculateRadius(si_->getStateDimension(), nn_->size());
OMPL_DEBUG("Using radius of %f", NNr_);
}
// Add goal states to Unvisitedrev and Openrev
bool valid_goalMotion = false;
BiDirMotion *goalMotion;
while (const base::State *st = pis_.nextGoal())
{
goalMotion = new BiDirMotion(si_, &tree_);
si_->copyState(goalMotion->getState(), st);
goalMotion->currentSet_[FWD] = BiDirMotion::SET_UNVISITED;
nn_->add(goalMotion); // S <-- {x_goal}
if (si_->isValid(goalMotion->getState()))
{
// Take the first valid goal state as the reverse tree root
Open_elements[REV][goalMotion] = Open_[REV].insert(goalMotion);
goalMotion->currentSet_[REV] = BiDirMotion::SET_OPEN;
goalMotion->cost_[REV] = opt_->terminalCost(goalMotion->getState());
valid_goalMotion = true;
heurGoalState_[0] = goalMotion->getState();
}
}
if ((goalMotion == nullptr) || !valid_goalMotion)
{
OMPL_ERROR("Goal state undefined or invalid.");
return base::PlannerStatus::INVALID_GOAL;
}
useRevTree();
// Plan a path
BiDirMotion *connection_point = nullptr;
bool earlyFailure = true;
if (initMotion != nullptr && goalMotion != nullptr)
{
earlyFailure = plan(initMotion, goalMotion, connection_point, ptc);
}
else
{
OMPL_ERROR("Initial/goal state(s) are undefined!");
}
if (earlyFailure)
{
return base::PlannerStatus(false, false);
}
// Save the best path (through z)
if (!ptc)
{
base::Cost fwd_cost, rev_cost, connection_cost;
// Construct the solution path
useFwdTree();
BiDirMotionPtrs path_fwd;
tracePath(connection_point, path_fwd);
fwd_cost = connection_point->getCost();
useRevTree();
BiDirMotionPtrs path_rev;
tracePath(connection_point, path_rev);
rev_cost = connection_point->getCost();
// ASSUMES FROM THIS POINT THAT z = path_fwd[0] = path_rev[0]
// Remove the first element, z, in the traced reverse path
// (the same as the first element in the traced forward path)
if (path_rev.size() > 1)
{
connection_cost = base::Cost(rev_cost.value() - path_rev[1]->getCost().value());
path_rev.erase(path_rev.begin());
}
else if (path_fwd.size() > 1)
{
connection_cost = base::Cost(fwd_cost.value() - path_fwd[1]->getCost().value());
path_fwd.erase(path_fwd.begin());
}
else
{
OMPL_ERROR("Solution path traced incorrectly or otherwise constructed improperly \
through forward/reverse trees (both paths are one node in length, each).");
}
// Adjust costs/parents in reverse tree nodes as cost/direction from forward tree root
useFwdTree();
path_rev[0]->setCost(base::Cost(path_fwd[0]->getCost().value() + connection_cost.value()));
path_rev[0]->setParent(path_fwd[0]);
for (unsigned int i = 1; i < path_rev.size(); ++i)
{
path_rev[i]->setCost(
base::Cost(fwd_cost.value() + (rev_cost.value() - path_rev[i]->getCost().value())));
path_rev[i]->setParent(path_rev[i - 1]);
}
BiDirMotionPtrs mpath;
std::reverse(path_rev.begin(), path_rev.end());
mpath.reserve(path_fwd.size() + path_rev.size()); // preallocate memory
mpath.insert(mpath.end(), path_rev.begin(), path_rev.end());
mpath.insert(mpath.end(), path_fwd.begin(), path_fwd.end());
// Set the solution path
auto path(std::make_shared<PathGeometric>(si_));
for (int i = mpath.size() - 1; i >= 0; --i)
{
path->append(mpath[i]->getState());
}
static const bool approximate = false;
static const double cost_difference_from_goal = 0.0;
pdef_->addSolutionPath(path, approximate, cost_difference_from_goal, getName());
OMPL_DEBUG("Total path cost: %f\n", fwd_cost.value() + rev_cost.value());
return base::PlannerStatus(true, false);
}
// Planner terminated without accomplishing goal
return {false, false};
}
void BFMT::expandTreeFromNode(BiDirMotion *&z, BiDirMotion *&connection_point)
{
// Define Opennew and set it to NULL
BiDirMotionPtrs Open_new;
// Define Znear as all unexplored nodes in the neighborhood around z
BiDirMotionPtrs zNear;
const BiDirMotionPtrs &zNeighborhood = neighborhoods_[z];
for (auto i : zNeighborhood)
{
if (i->getCurrentSet() == BiDirMotion::SET_UNVISITED)
{
zNear.push_back(i);
}
}
// For each node x in Znear
for (auto x : zNear)
{
if (!precomputeNN_)
saveNeighborhood(x); // nearest neighbors
// Define Xnear as all frontier nodes in the neighborhood around the unexplored node x
BiDirMotionPtrs xNear;
const BiDirMotionPtrs &xNeighborhood = neighborhoods_[x];
for (auto j : xNeighborhood)
{
if (j->getCurrentSet() == BiDirMotion::SET_OPEN)
{
xNear.push_back(j);
}
}
// Find the node in Xnear with minimum cost-to-come in the current tree
BiDirMotion *xMin = nullptr;
double cMin = std::numeric_limits<double>::infinity();
for (auto &j : xNear)
{
// check if node costs are smaller than minimum
double cNew = j->getCost().value() + distanceFunction(j, x);
if (cNew < cMin)
{
xMin = j;
cMin = cNew;
}
}
// xMin was found
if (xMin != nullptr)
{
bool collision_free = false;
if (cacheCC_)
{
if (!xMin->alreadyCC(x))
{
collision_free = si_->checkMotion(xMin->getState(), x->getState());
++collisionChecks_;
// Due to FMT3* design, it is only necessary to save unsuccesful
// connection attemps because of collision
if (!collision_free)
xMin->addCC(x);
}
}
else
{
++collisionChecks_;
collision_free = si_->checkMotion(xMin->getState(), x->getState());
}
if (collision_free)
{ // motion between yMin and x is obstacle free
// add edge from xMin to x
x->setParent(xMin);
x->setCost(base::Cost(cMin));
xMin->getChildren().push_back(x);
if (heuristics_)
x->setHeuristicCost(opt_->motionCostHeuristic(x->getState(), heurGoalState_[tree_]));
// check if new node x is in the other tree; if so, save result
if (x->getOtherSet() != BiDirMotion::SET_UNVISITED)
{
if (connection_point == nullptr)
{
connection_point = x;
if (termination_ == FEASIBILITY)
{
break;
}
}
else
{
if ((connection_point->cost_[FWD].value() + connection_point->cost_[REV].value()) >
(x->cost_[FWD].value() + x->cost_[REV].value()))
{
connection_point = x;
}
}
}
Open_new.push_back(x); // add x to Open_new
x->setCurrentSet(BiDirMotion::SET_CLOSED); // remove x from Unvisited
}
}
} // End "for x in Znear"
// Remove motion z from binary heap and map
BiDirMotionBinHeap::Element *zElement = Open_elements[tree_][z];
Open_[tree_].remove(zElement);
Open_elements[tree_].erase(z);
z->setCurrentSet(BiDirMotion::SET_CLOSED);
// add nodes in Open_new to Open
for (auto &i : Open_new)
{
if(Open_elements[tree_][i] == nullptr)
{
Open_elements[tree_][i] = Open_[tree_].insert(i);
i->setCurrentSet(BiDirMotion::SET_OPEN);
}
}
}
bool BFMT::plan(BiDirMotion *x_init, BiDirMotion *x_goal, BiDirMotion *&connection_point,
const base::PlannerTerminationCondition &ptc)
{
// If pre-computation, find neighborhoods for all N sample nodes plus initial
// and goal state(s). Otherwise compute the neighborhoods of the initial and
// goal states separately and compute the others as needed.
BiDirMotionPtrs sampleNodes;
nn_->list(sampleNodes);
/// \todo This precomputation is useful only if the same planner is used many times.
/// otherwise is probably a waste of time. Do a real precomputation before calling solve().
if (precomputeNN_)
{
for (auto &sampleNode : sampleNodes)
{
saveNeighborhood(sampleNode); // nearest neighbors
}
}
else
{
saveNeighborhood(x_init); // nearest neighbors
saveNeighborhood(x_goal); // nearest neighbors
}
// Copy nodes in the sample set to Unvisitedfwd. Overwrite the label of the initial
// node with set Open for the forward tree, since it starts in set Openfwd.
useFwdTree();
for (auto &sampleNode : sampleNodes)
{
sampleNode->setCurrentSet(BiDirMotion::SET_UNVISITED);
}
x_init->setCurrentSet(BiDirMotion::SET_OPEN);
// Copy nodes in the sample set to Unvisitedrev. Overwrite the label of the goal
// node with set Open for the reverse tree, since it starts in set Openrev.
useRevTree();
for (auto &sampleNode : sampleNodes)
{
sampleNode->setCurrentSet(BiDirMotion::SET_UNVISITED);
}
x_goal->setCurrentSet(BiDirMotion::SET_OPEN);
// Expand the trees until reaching the termination condition
bool earlyFailure = false;
bool success = false;
useFwdTree();
BiDirMotion *z = x_init;
while (!success)
{
expandTreeFromNode(z, connection_point);
// Check if the algorithm should terminate. Possibly redefines connection_point.
if (termination(z, connection_point, ptc))
success = true;
else
{
if (Open_[tree_].empty()) // If this heap is empty...
{
if (!extendedFMT_) // ... eFMT not enabled...
{
if (Open_[(tree_ + 1) % 2].empty()) // ... and this one, failure.
{
OMPL_INFORM("Both Open are empty before path was found --> no feasible path exists");
earlyFailure = true;
return earlyFailure;
}
}
else // However, if eFMT is enabled, run it.
insertNewSampleInOpen(ptc);
}
// This function will be always reached with at least one state in one heap.
// However, if ptc terminates, we should skip this.
if (!ptc)
chooseTreeAndExpansionNode(z);
else
return true;
}
}
earlyFailure = false;
return earlyFailure;
}
void BFMT::insertNewSampleInOpen(const base::PlannerTerminationCondition &ptc)
{
// Sample and connect samples to tree only if there is
// a possibility to connect to unvisited nodes.
std::vector<BiDirMotion *> nbh;
std::vector<base::Cost> costs;
std::vector<base::Cost> incCosts;
std::vector<std::size_t> sortedCostIndices;
// our functor for sorting nearest neighbors
CostIndexCompare compareFn(costs, *opt_);
auto *m = new BiDirMotion(si_, &tree_);
while (!ptc && Open_[tree_].empty()) //&& oneSample)
{
// Get new sample and check whether it is valid.
sampler_->sampleUniform(m->getState());
if (!si_->isValid(m->getState()))
continue;
// Get neighbours of the new sample.
std::vector<BiDirMotion *> yNear;
if (nearestK_)
nn_->nearestK(m, NNk_, nbh);
else
nn_->nearestR(m, NNr_, nbh);
yNear.reserve(nbh.size());
for (auto &j : nbh)
{
if (j->getCurrentSet() == BiDirMotion::SET_CLOSED)
{
if (nearestK_)
{
// Only include neighbors that are mutually k-nearest
// Relies on NN datastructure returning k-nearest in sorted order
const base::Cost connCost = opt_->motionCost(j->getState(), m->getState());
if(neighborhoods_[j].size() == 0){
printf("***** empty neighboorhood detected, skipping ****\n");
continue;
}
const base::Cost worstCost =
opt_->motionCost(neighborhoods_[j].back()->getState(), j->getState());
if (opt_->isCostBetterThan(worstCost, connCost))
continue;
yNear.push_back(j);
}
else
yNear.push_back(j);
}
}
// Sample again if the new sample does not connect to the tree.
if (yNear.empty())
continue;
// cache for distance computations
//
// Our cost caches only increase in size, so they're only
// resized if they can't fit the current neighborhood
if (costs.size() < yNear.size())
{
costs.resize(yNear.size());
incCosts.resize(yNear.size());
sortedCostIndices.resize(yNear.size());
}
// Finding the nearest neighbor to connect to
// By default, neighborhood states are sorted by cost, and collision checking
// is performed in increasing order of cost
//
// calculate all costs and distances
for (std::size_t i = 0; i < yNear.size(); ++i)
{
incCosts[i] = opt_->motionCost(yNear[i]->getState(), m->getState());
costs[i] = opt_->combineCosts(yNear[i]->getCost(), incCosts[i]);
}
// sort the nodes
//
// we're using index-value pairs so that we can get at
// original, unsorted indices
for (std::size_t i = 0; i < yNear.size(); ++i)
sortedCostIndices[i] = i;
std::sort(sortedCostIndices.begin(), sortedCostIndices.begin() + yNear.size(), compareFn);
// collision check until a valid motion is found
for (std::vector<std::size_t>::const_iterator i = sortedCostIndices.begin();
i != sortedCostIndices.begin() + yNear.size(); ++i)
{
++collisionChecks_;
if (si_->checkMotion(yNear[*i]->getState(), m->getState()))
{
const base::Cost incCost = opt_->motionCost(yNear[*i]->getState(), m->getState());
m->setParent(yNear[*i]);
yNear[*i]->getChildren().push_back(m);
m->setCost(opt_->combineCosts(yNear[*i]->getCost(), incCost));
m->setHeuristicCost(opt_->motionCostHeuristic(m->getState(), heurGoalState_[tree_]));
m->setCurrentSet(BiDirMotion::SET_OPEN);
Open_elements[tree_][m] = Open_[tree_].insert(m);
nn_->add(m);
saveNeighborhood(m);
updateNeighborhood(m, nbh);
break;
}
}
} // While Open_[tree_] empty
}
bool BFMT::termination(BiDirMotion *&z, BiDirMotion *&connection_point,
const base::PlannerTerminationCondition &ptc)
{
bool terminate = false;
switch (termination_)
{
case FEASIBILITY:
// Test if a connection point was found during tree expansion
return (connection_point != nullptr || ptc);
break;
case OPTIMALITY:
// Test if z is in SET_CLOSED (interior) of other tree
if (ptc)
terminate = true;
else if (z->getOtherSet() == BiDirMotion::SET_CLOSED)
terminate = true;
break;
};
return terminate;
}
// Choose exploration tree and node z to expand
void BFMT::chooseTreeAndExpansionNode(BiDirMotion *&z)
{
switch (exploration_)
{
case SWAP_EVERY_TIME:
if (Open_[(tree_ + 1) % 2].empty())
z = Open_[tree_].top()->data; // Continue expanding the current tree (not empty by exit
// condition in plan())
else
{
z = Open_[(tree_ + 1) % 2].top()->data; // Take top of opposite tree heap as new z
swapTrees(); // Swap to the opposite tree
}
break;
case CHOOSE_SMALLEST_Z:
BiDirMotion *z1, *z2;
if (Open_[(tree_ + 1) % 2].empty())
z = Open_[tree_].top()->data; // Continue expanding the current tree (not empty by exit
// condition in plan())
else if (Open_[tree_].empty())
{
z = Open_[(tree_ + 1) % 2].top()->data; // Take top of opposite tree heap as new z
swapTrees(); // Swap to the opposite tree
}
else
{
z1 = Open_[tree_].top()->data;
z2 = Open_[(tree_ + 1) % 2].top()->data;
if (z1->getCost().value() < z2->getOtherCost().value())
z = z1;
else
{
z = z2;
swapTrees();
}
}
break;
};
}
// Trace a path of nodes along a tree towards the root (forward or reverse)
void BFMT::tracePath(BiDirMotion *z, BiDirMotionPtrs &path)
{
BiDirMotion *solution = z;
while (solution != nullptr)
{
path.push_back(solution);
solution = solution->getParent();
}
}
void BFMT::swapTrees()
{
tree_ = (TreeType)((((int)tree_) + 1) % 2);
}
void BFMT::updateNeighborhood(BiDirMotion *m, const std::vector<BiDirMotion *> nbh)
{
// Neighborhoods are only updated if the new motion is within bounds (k nearest or within r).
for (auto i : nbh)
{
// If CLOSED, that neighborhood won't be used again.
// Else, if neighhboorhod already exists, we have to insert the node in
// the corresponding place of the neighborhood of the neighbor of m.
if (i->getCurrentSet() == BiDirMotion::SET_CLOSED)
continue;
auto it = neighborhoods_.find(i);
if (it != neighborhoods_.end())
{
if (it->second.empty())
continue;
const base::Cost connCost = opt_->motionCost(i->getState(), m->getState());
const base::Cost worstCost = opt_->motionCost(it->second.back()->getState(), i->getState());
if (opt_->isCostBetterThan(worstCost, connCost))
continue;
// insert the neighbor in the vector in the correct order
std::vector<BiDirMotion *> &nbhToUpdate = it->second;
for (std::size_t j = 0; j < nbhToUpdate.size(); ++j)
{
// If connection to the new state is better than the current neighbor tested, insert.
const base::Cost cost = opt_->motionCost(i->getState(), nbhToUpdate[j]->getState());
if (opt_->isCostBetterThan(connCost, cost))
{
nbhToUpdate.insert(nbhToUpdate.begin() + j, m);
break;
}
}
}
}
}
} // End "geometric" namespace
} // End "ompl" namespace
| 42.295506
| 120
| 0.464203
|
sbgisen
|
4482074a4748630dba7f80fc46e4d0e0c563e4d1
| 975
|
cpp
|
C++
|
Questless/Questless/src/animation/particles/black_magic_particle.cpp
|
jonathansharman/questless
|
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
|
[
"MIT"
] | 2
|
2020-07-14T12:50:06.000Z
|
2020-11-04T02:25:09.000Z
|
Questless/Questless/src/animation/particles/black_magic_particle.cpp
|
jonathansharman/questless
|
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
|
[
"MIT"
] | null | null | null |
Questless/Questless/src/animation/particles/black_magic_particle.cpp
|
jonathansharman/questless
|
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
|
[
"MIT"
] | null | null | null |
//! @file
//! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>.
#include "black_magic_particle.hpp"
#include "rsrc/particle.hpp"
#include "utility/random.hpp"
using namespace vecx::literals;
namespace ql {
using namespace view::literals;
black_magic_particle::black_magic_particle(rsrc::particle const& resources)
: sprite_particle{2.0_s, resources.black_magic} //
{
constexpr auto dtheta_max = 2.0 * vecx::circle_rad;
constexpr auto min_vel = 5.0_px;
constexpr auto max_vel = 25.0_px;
velocity = vecx::make_polar_vector(uniform(min_vel, max_vel), random_radians()) / 1.0_s;
angle = random_radians();
uniform(-dtheta_max, dtheta_max) * dtheta_max / 1.0_s;
}
auto black_magic_particle::sprite_particle_subupdate(sec elapsed_time) -> void {
constexpr auto acceleration_factor = 1.25_hz;
constexpr auto turn_rate = 4.0_rad / 1.0_s;
velocity += velocity * acceleration_factor * elapsed_time;
velocity.rotate(turn_rate * elapsed_time);
}
}
| 28.676471
| 90
| 0.741538
|
jonathansharman
|
4483fe138279f7b7cadc20ba6c50e7858908e76c
| 706
|
hpp
|
C++
|
Library/Source/EnergyManager/Profiling/Profilers/NWProfiler.hpp
|
NB4444/BachelorProjectEnergyManager
|
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
|
[
"MIT"
] | null | null | null |
Library/Source/EnergyManager/Profiling/Profilers/NWProfiler.hpp
|
NB4444/BachelorProjectEnergyManager
|
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
|
[
"MIT"
] | null | null | null |
Library/Source/EnergyManager/Profiling/Profilers/NWProfiler.hpp
|
NB4444/BachelorProjectEnergyManager
|
d1fd93dcc83af6d6acd36b7efda364ac2aab90eb
|
[
"MIT"
] | null | null | null |
#pragma once
#include <EnergyManager.hpp>
#include <memory>
class NWProfiler : public EnergyManager::Profiling::Profilers::Profiler {
using EnergyManager::Profiling::Profilers::Profiler::Profiler;
protected:
/**
* Gets called whenever a profiler session is initiated and is provided with the current profile to run.
* @param profile The profile to run, consisting of named variables and their associated values.
*/
void onProfile(const std::map<std::string, std::string>& profile) final;
public:
/**
* Creates a new NWProfiler.
* @param arguments The command line arguments that were passed when starting.
*/
explicit NWProfiler(const std::map<std::string, std::string>& arguments);
};
| 32.090909
| 105
| 0.747875
|
NB4444
|
44853c2e7255bbd9598b5ecbee63e0ca7f105e12
| 1,585
|
cpp
|
C++
|
kernel/graphics.cpp
|
three-0-3/my-mikanos
|
e85f9e15d735babde1650c6fa87ffed210dece6d
|
[
"Apache-2.0"
] | null | null | null |
kernel/graphics.cpp
|
three-0-3/my-mikanos
|
e85f9e15d735babde1650c6fa87ffed210dece6d
|
[
"Apache-2.0"
] | null | null | null |
kernel/graphics.cpp
|
three-0-3/my-mikanos
|
e85f9e15d735babde1650c6fa87ffed210dece6d
|
[
"Apache-2.0"
] | null | null | null |
#include "graphics.hpp"
void RGBResv8BitPerColorPixelWriter::Write(Vector2D<int> pos, const PixelColor& c) {
auto p = PixelAt(pos);
p[0] = c.r;
p[1] = c.g;
p[2] = c.b;
}
void BGRResv8BitPerColorPixelWriter::Write(Vector2D<int> pos, const PixelColor& c) {
auto p = PixelAt(pos);
p[0] = c.b;
p[1] = c.g;
p[2] = c.r;
}
// Draw rectangle outline only
void DrawRectangle(PixelWriter& writer, const Vector2D<int>& pos, const Vector2D<int>& size, const PixelColor& c) {
// horizontal line
for (int dx = 0; dx < size.x; ++dx) {
writer.Write(pos + Vector2D<int>{dx, 0}, c);
writer.Write(pos + Vector2D<int>{dx, size.y - 1}, c);
}
// vertical line
for (int dy = 1; dy < size.y - 1; ++dy) {
writer.Write(pos + Vector2D<int>{0, dy}, c);
writer.Write(pos + Vector2D<int>{size.x - 1, dy}, c);
}
}
// Draw rectangle and fill
void FillRectangle(PixelWriter& writer, const Vector2D<int>& pos, const Vector2D<int>& size, const PixelColor& c) {
for (int dx = 0; dx < size.x; ++dx) {
for (int dy = 0; dy < size.y; ++dy) {
writer.Write(pos + Vector2D<int>{dx, dy}, c);
}
}
}
void DrawDesktop(PixelWriter& writer) {
const auto width = writer.Width();
const auto height = writer.Height();
FillRectangle(writer,
{0, 0},
{width, height - 50},
kDesktopBGColor);
FillRectangle(writer,
{0, height - 50},
{width, 50},
{1, 8, 17});
FillRectangle(writer,
{0, height - 50},
{width / 5, 50},
{80, 80, 80});
DrawRectangle(writer,
{10, height - 40},
{30, 30},
{160, 160, 160});
}
| 26.864407
| 115
| 0.594953
|
three-0-3
|
44881bde6e8f824960bb78ce40bb76f2e8928e2a
| 40
|
hpp
|
C++
|
libng/core/src/libng_core/debug/Util.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
libng/core/src/libng_core/debug/Util.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
libng/core/src/libng_core/debug/Util.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
#pragma once
#define LIBNG_DEBUG _DEBUG
| 13.333333
| 26
| 0.825
|
gapry
|
449041cee6c13855b2d81ccdd0928f1427af2d7b
| 36,617
|
cpp
|
C++
|
lib/SILOptimizer/Utils/CFG.cpp
|
sysidos/swift-1
|
90aab6a99c173c9a045dce348a88c73e1fc4f1e8
|
[
"Apache-2.0"
] | null | null | null |
lib/SILOptimizer/Utils/CFG.cpp
|
sysidos/swift-1
|
90aab6a99c173c9a045dce348a88c73e1fc4f1e8
|
[
"Apache-2.0"
] | null | null | null |
lib/SILOptimizer/Utils/CFG.cpp
|
sysidos/swift-1
|
90aab6a99c173c9a045dce348a88c73e1fc4f1e8
|
[
"Apache-2.0"
] | null | null | null |
//===--- CFG.cpp - Utilities for SIL CFG transformations ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/Dominance.h"
#include "swift/SIL/LoopInfo.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
using namespace swift;
/// \brief Adds a new argument to an edge between a branch and a destination
/// block.
///
/// \param Branch The terminator to add the argument to.
/// \param Dest The destination block of the edge.
/// \param Val The value to the arguments of the branch.
/// \return The created branch. The old branch is deleted.
/// The argument is appended at the end of the argument tuple.
TermInst *swift::addNewEdgeValueToBranch(TermInst *Branch, SILBasicBlock *Dest,
SILValue Val) {
SILBuilderWithScope Builder(Branch);
TermInst *NewBr = nullptr;
if (auto *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
for (auto A : CBI->getTrueArgs())
TrueArgs.push_back(A);
for (auto A : CBI->getFalseArgs())
FalseArgs.push_back(A);
if (Dest == CBI->getTrueBB()) {
TrueArgs.push_back(Val);
assert(TrueArgs.size() == Dest->getNumArguments());
}
if (Dest == CBI->getFalseBB()) {
FalseArgs.push_back(Val);
assert(FalseArgs.size() == Dest->getNumArguments());
}
NewBr = Builder.createCondBranch(
CBI->getLoc(), CBI->getCondition(), CBI->getTrueBB(), TrueArgs,
CBI->getFalseBB(), FalseArgs, CBI->getTrueBBCount(),
CBI->getFalseBBCount());
} else if (auto *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
for (auto A : BI->getArgs())
Args.push_back(A);
Args.push_back(Val);
assert(Args.size() == Dest->getNumArguments());
NewBr = Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
} else {
// At the moment we can only add arguments to br and cond_br.
llvm_unreachable("Can't add argument to terminator");
}
Branch->dropAllReferences();
Branch->eraseFromParent();
return NewBr;
}
/// \brief Changes the edge value between a branch and destination basic block
/// at the specified index. Changes all edges from \p Branch to \p Dest to carry
/// the value.
///
/// \param Branch The branch to modify.
/// \param Dest The destination of the edge.
/// \param Idx The index of the argument to modify.
/// \param Val The new value to use.
/// \return The new branch. Deletes the old one.
/// Changes the edge value between a branch and destination basic block at the
/// specified index.
TermInst *swift::changeEdgeValue(TermInst *Branch, SILBasicBlock *Dest,
size_t Idx, SILValue Val) {
SILBuilderWithScope Builder(Branch);
if (auto *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
OperandValueArrayRef OldTrueArgs = CBI->getTrueArgs();
bool BranchOnTrue = CBI->getTrueBB() == Dest;
assert((!BranchOnTrue || Idx < OldTrueArgs.size()) && "Not enough edges");
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldTrueArgs.size(); i != e; ++i) {
if (BranchOnTrue && Idx == i)
TrueArgs.push_back(Val);
else
TrueArgs.push_back(OldTrueArgs[i]);
}
assert(TrueArgs.size() == CBI->getTrueBB()->getNumArguments() &&
"Destination block's number of arguments must match");
OperandValueArrayRef OldFalseArgs = CBI->getFalseArgs();
bool BranchOnFalse = CBI->getFalseBB() == Dest;
assert((!BranchOnFalse || Idx < OldFalseArgs.size()) && "Not enough edges");
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldFalseArgs.size(); i != e; ++i) {
if (BranchOnFalse && Idx == i)
FalseArgs.push_back(Val);
else
FalseArgs.push_back(OldFalseArgs[i]);
}
assert(FalseArgs.size() == CBI->getFalseBB()->getNumArguments() &&
"Destination block's number of arguments must match");
CBI = Builder.createCondBranch(
CBI->getLoc(), CBI->getCondition(), CBI->getTrueBB(), TrueArgs,
CBI->getFalseBB(), FalseArgs, CBI->getTrueBBCount(),
CBI->getFalseBBCount());
Branch->dropAllReferences();
Branch->eraseFromParent();
return CBI;
}
if (auto *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
assert(Idx < BI->getNumArgs() && "Not enough edges");
OperandValueArrayRef OldArgs = BI->getArgs();
// Copy the edge values overwriting the edge at Idx.
for (unsigned i = 0, e = OldArgs.size(); i != e; ++i) {
if (Idx == i)
Args.push_back(Val);
else
Args.push_back(OldArgs[i]);
}
assert(Args.size() == Dest->getNumArguments());
BI = Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
Branch->dropAllReferences();
Branch->eraseFromParent();
return BI;
}
llvm_unreachable("Unhandled terminator leading to merge block");
}
template <class SwitchEnumTy, class SwitchEnumCaseTy>
SILBasicBlock *replaceSwitchDest(SwitchEnumTy *S,
SmallVectorImpl<SwitchEnumCaseTy> &Cases,
unsigned EdgeIdx, SILBasicBlock *NewDest) {
auto *DefaultBB = S->hasDefault() ? S->getDefaultBB() : nullptr;
for (unsigned i = 0, e = S->getNumCases(); i != e; ++i)
if (EdgeIdx != i)
Cases.push_back(S->getCase(i));
else
Cases.push_back(std::make_pair(S->getCase(i).first, NewDest));
if (EdgeIdx == S->getNumCases())
DefaultBB = NewDest;
return DefaultBB;
}
void swift::changeBranchTarget(TermInst *T, unsigned EdgeIdx,
SILBasicBlock *NewDest, bool PreserveArgs) {
SILBuilderWithScope B(T);
switch (T->getTermKind()) {
// Only Branch and CondBranch may have arguments.
case TermKind::BranchInst: {
auto Br = dyn_cast<BranchInst>(T);
SmallVector<SILValue, 8> Args;
if (PreserveArgs) {
for (auto Arg : Br->getArgs())
Args.push_back(Arg);
}
B.createBranch(T->getLoc(), NewDest, Args);
Br->dropAllReferences();
Br->eraseFromParent();
return;
}
case TermKind::CondBranchInst: {
auto CondBr = dyn_cast<CondBranchInst>(T);
SmallVector<SILValue, 8> TrueArgs;
if (EdgeIdx == CondBranchInst::FalseIdx || PreserveArgs) {
for (auto Arg : CondBr->getTrueArgs())
TrueArgs.push_back(Arg);
}
SmallVector<SILValue, 8> FalseArgs;
if (EdgeIdx == CondBranchInst::TrueIdx || PreserveArgs) {
for (auto Arg : CondBr->getFalseArgs())
FalseArgs.push_back(Arg);
}
SILBasicBlock *TrueDest = CondBr->getTrueBB();
SILBasicBlock *FalseDest = CondBr->getFalseBB();
if (EdgeIdx == CondBranchInst::TrueIdx)
TrueDest = NewDest;
else
FalseDest = NewDest;
B.createCondBranch(CondBr->getLoc(), CondBr->getCondition(), TrueDest,
TrueArgs, FalseDest, FalseArgs, CondBr->getTrueBBCount(),
CondBr->getFalseBBCount());
CondBr->dropAllReferences();
CondBr->eraseFromParent();
return;
}
case TermKind::SwitchValueInst: {
auto SII = dyn_cast<SwitchValueInst>(T);
SmallVector<std::pair<SILValue, SILBasicBlock *>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SII, Cases, EdgeIdx, NewDest);
B.createSwitchValue(SII->getLoc(), SII->getOperand(), DefaultBB, Cases);
SII->eraseFromParent();
return;
}
case TermKind::SwitchEnumInst: {
auto SEI = dyn_cast<SwitchEnumInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, EdgeIdx, NewDest);
B.createSwitchEnum(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::SwitchEnumAddrInst: {
auto SEI = dyn_cast<SwitchEnumAddrInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, EdgeIdx, NewDest);
B.createSwitchEnumAddr(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::DynamicMethodBranchInst: {
auto DMBI = dyn_cast<DynamicMethodBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto HasMethodBB = !EdgeIdx ? NewDest : DMBI->getHasMethodBB();
auto NoMethodBB = EdgeIdx ? NewDest : DMBI->getNoMethodBB();
B.createDynamicMethodBranch(DMBI->getLoc(), DMBI->getOperand(),
DMBI->getMember(), HasMethodBB, NoMethodBB);
DMBI->eraseFromParent();
return;
}
case TermKind::CheckedCastBranchInst: {
auto CBI = dyn_cast<CheckedCastBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto SuccessBB = !EdgeIdx ? NewDest : CBI->getSuccessBB();
auto FailureBB = EdgeIdx ? NewDest : CBI->getFailureBB();
B.createCheckedCastBranch(CBI->getLoc(), CBI->isExact(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB,
CBI->getTrueBBCount(), CBI->getFalseBBCount());
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastValueBranchInst: {
auto CBI = dyn_cast<CheckedCastValueBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto SuccessBB = !EdgeIdx ? NewDest : CBI->getSuccessBB();
auto FailureBB = EdgeIdx ? NewDest : CBI->getFailureBB();
B.createCheckedCastValueBranch(CBI->getLoc(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastAddrBranchInst: {
auto CBI = dyn_cast<CheckedCastAddrBranchInst>(T);
assert(EdgeIdx == 0 || EdgeIdx == 1 && "Invalid edge index");
auto SuccessBB = !EdgeIdx ? NewDest : CBI->getSuccessBB();
auto FailureBB = EdgeIdx ? NewDest : CBI->getFailureBB();
auto TrueCount = CBI->getTrueBBCount();
auto FalseCount = CBI->getFalseBBCount();
B.createCheckedCastAddrBranch(CBI->getLoc(), CBI->getConsumptionKind(),
CBI->getSrc(), CBI->getSourceType(),
CBI->getDest(), CBI->getTargetType(),
SuccessBB, FailureBB, TrueCount, FalseCount);
CBI->eraseFromParent();
return;
}
case TermKind::TryApplyInst: {
auto *TAI = dyn_cast<TryApplyInst>(T);
assert((EdgeIdx == 0 || EdgeIdx == 1) && "Invalid edge index");
auto *NormalBB = !EdgeIdx ? NewDest : TAI->getNormalBB();
auto *ErrorBB = EdgeIdx ? NewDest : TAI->getErrorBB();
SmallVector<SILValue, 4> Arguments;
for (auto &Op : TAI->getArgumentOperands())
Arguments.push_back(Op.get());
B.createTryApply(TAI->getLoc(), TAI->getCallee(), TAI->getSubstitutions(),
Arguments, NormalBB, ErrorBB);
TAI->eraseFromParent();
return;
}
case TermKind::YieldInst: {
auto *YI = cast<YieldInst>(T);
assert((EdgeIdx == 0 || EdgeIdx == 1) && "Invalid edge index");
auto *resumeBB = !EdgeIdx ? NewDest : YI->getResumeBB();
auto *unwindBB = EdgeIdx ? NewDest : YI->getUnwindBB();
SmallVector<SILValue, 4> yieldedValues;
for (auto value : YI->getYieldedValues())
yieldedValues.push_back(value);
B.createYield(YI->getLoc(), yieldedValues, resumeBB, unwindBB);
YI->eraseFromParent();
return;
}
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::UnreachableInst:
case TermKind::UnwindInst:
llvm_unreachable("Branch target cannot be changed for this terminator instruction!");
}
llvm_unreachable("Not yet implemented!");
}
template <class SwitchEnumTy, class SwitchEnumCaseTy>
SILBasicBlock *replaceSwitchDest(SwitchEnumTy *S,
SmallVectorImpl<SwitchEnumCaseTy> &Cases,
SILBasicBlock *OldDest, SILBasicBlock *NewDest) {
auto *DefaultBB = S->hasDefault() ? S->getDefaultBB() : nullptr;
for (unsigned i = 0, e = S->getNumCases(); i != e; ++i)
if (S->getCase(i).second != OldDest)
Cases.push_back(S->getCase(i));
else
Cases.push_back(std::make_pair(S->getCase(i).first, NewDest));
if (OldDest == DefaultBB)
DefaultBB = NewDest;
return DefaultBB;
}
/// \brief Replace a branch target.
///
/// \param T The terminating instruction to modify.
/// \param OldDest The successor block that will be replaced.
/// \param NewDest The new target block.
/// \param PreserveArgs If set, preserve arguments on the replaced edge.
void swift::replaceBranchTarget(TermInst *T, SILBasicBlock *OldDest,
SILBasicBlock *NewDest, bool PreserveArgs) {
SILBuilderWithScope B(T);
switch (T->getTermKind()) {
// Only Branch and CondBranch may have arguments.
case TermKind::BranchInst: {
auto Br = cast<BranchInst>(T);
assert(OldDest == Br->getDestBB() && "wrong branch target");
SmallVector<SILValue, 8> Args;
if (PreserveArgs) {
for (auto Arg : Br->getArgs())
Args.push_back(Arg);
}
B.createBranch(T->getLoc(), NewDest, Args);
Br->dropAllReferences();
Br->eraseFromParent();
return;
}
case TermKind::CondBranchInst: {
auto CondBr = cast<CondBranchInst>(T);
SmallVector<SILValue, 8> TrueArgs;
if (OldDest == CondBr->getFalseBB() || PreserveArgs) {
for (auto Arg : CondBr->getTrueArgs())
TrueArgs.push_back(Arg);
}
SmallVector<SILValue, 8> FalseArgs;
if (OldDest == CondBr->getTrueBB() || PreserveArgs) {
for (auto Arg : CondBr->getFalseArgs())
FalseArgs.push_back(Arg);
}
SILBasicBlock *TrueDest = CondBr->getTrueBB();
SILBasicBlock *FalseDest = CondBr->getFalseBB();
if (OldDest == CondBr->getTrueBB()) {
TrueDest = NewDest;
} else {
assert(OldDest == CondBr->getFalseBB() && "wrong cond_br target");
FalseDest = NewDest;
}
B.createCondBranch(CondBr->getLoc(), CondBr->getCondition(), TrueDest,
TrueArgs, FalseDest, FalseArgs, CondBr->getTrueBBCount(),
CondBr->getFalseBBCount());
CondBr->dropAllReferences();
CondBr->eraseFromParent();
return;
}
case TermKind::SwitchValueInst: {
auto SII = cast<SwitchValueInst>(T);
SmallVector<std::pair<SILValue, SILBasicBlock *>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SII, Cases, OldDest, NewDest);
B.createSwitchValue(SII->getLoc(), SII->getOperand(), DefaultBB, Cases);
SII->eraseFromParent();
return;
}
case TermKind::SwitchEnumInst: {
auto SEI = cast<SwitchEnumInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, OldDest, NewDest);
B.createSwitchEnum(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::SwitchEnumAddrInst: {
auto SEI = cast<SwitchEnumAddrInst>(T);
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 8> Cases;
auto *DefaultBB = replaceSwitchDest(SEI, Cases, OldDest, NewDest);
B.createSwitchEnumAddr(SEI->getLoc(), SEI->getOperand(), DefaultBB, Cases);
SEI->eraseFromParent();
return;
}
case TermKind::DynamicMethodBranchInst: {
auto DMBI = cast<DynamicMethodBranchInst>(T);
assert(OldDest == DMBI->getHasMethodBB() || OldDest == DMBI->getNoMethodBB() && "Invalid edge index");
auto HasMethodBB = OldDest == DMBI->getHasMethodBB() ? NewDest : DMBI->getHasMethodBB();
auto NoMethodBB = OldDest == DMBI->getNoMethodBB() ? NewDest : DMBI->getNoMethodBB();
B.createDynamicMethodBranch(DMBI->getLoc(), DMBI->getOperand(),
DMBI->getMember(), HasMethodBB, NoMethodBB);
DMBI->eraseFromParent();
return;
}
case TermKind::CheckedCastBranchInst: {
auto CBI = cast<CheckedCastBranchInst>(T);
assert(OldDest == CBI->getSuccessBB() || OldDest == CBI->getFailureBB() && "Invalid edge index");
auto SuccessBB = OldDest == CBI->getSuccessBB() ? NewDest : CBI->getSuccessBB();
auto FailureBB = OldDest == CBI->getFailureBB() ? NewDest : CBI->getFailureBB();
B.createCheckedCastBranch(CBI->getLoc(), CBI->isExact(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB,
CBI->getTrueBBCount(), CBI->getFalseBBCount());
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastValueBranchInst: {
auto CBI = cast<CheckedCastValueBranchInst>(T);
assert(OldDest == CBI->getSuccessBB() ||
OldDest == CBI->getFailureBB() && "Invalid edge index");
auto SuccessBB =
OldDest == CBI->getSuccessBB() ? NewDest : CBI->getSuccessBB();
auto FailureBB =
OldDest == CBI->getFailureBB() ? NewDest : CBI->getFailureBB();
B.createCheckedCastValueBranch(CBI->getLoc(), CBI->getOperand(),
CBI->getCastType(), SuccessBB, FailureBB);
CBI->eraseFromParent();
return;
}
case TermKind::CheckedCastAddrBranchInst: {
auto CBI = cast<CheckedCastAddrBranchInst>(T);
assert(OldDest == CBI->getSuccessBB() || OldDest == CBI->getFailureBB() && "Invalid edge index");
auto SuccessBB = OldDest == CBI->getSuccessBB() ? NewDest : CBI->getSuccessBB();
auto FailureBB = OldDest == CBI->getFailureBB() ? NewDest : CBI->getFailureBB();
auto TrueCount = CBI->getTrueBBCount();
auto FalseCount = CBI->getFalseBBCount();
B.createCheckedCastAddrBranch(CBI->getLoc(), CBI->getConsumptionKind(),
CBI->getSrc(), CBI->getSourceType(),
CBI->getDest(), CBI->getTargetType(),
SuccessBB, FailureBB, TrueCount, FalseCount);
CBI->eraseFromParent();
return;
}
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::TryApplyInst:
case TermKind::UnreachableInst:
case TermKind::UnwindInst:
case TermKind::YieldInst:
llvm_unreachable("Branch target cannot be replaced for this terminator instruction!");
}
llvm_unreachable("Not yet implemented!");
}
/// \brief Check if the edge from the terminator is critical.
bool swift::isCriticalEdge(TermInst *T, unsigned EdgeIdx) {
assert(T->getSuccessors().size() > EdgeIdx && "Not enough successors");
auto SrcSuccs = T->getSuccessors();
if (SrcSuccs.size() <= 1)
return false;
SILBasicBlock *DestBB = SrcSuccs[EdgeIdx];
assert(!DestBB->pred_empty() && "There should be a predecessor");
if (DestBB->getSinglePredecessorBlock())
return false;
return true;
}
template<class SwitchInstTy>
SILBasicBlock *getNthEdgeBlock(SwitchInstTy *S, unsigned EdgeIdx) {
if (S->getNumCases() == EdgeIdx)
return S->getDefaultBB();
return S->getCase(EdgeIdx).second;
}
static void getEdgeArgs(TermInst *T, unsigned EdgeIdx, SILBasicBlock *NewEdgeBB,
SmallVectorImpl<SILValue> &Args) {
if (auto Br = dyn_cast<BranchInst>(T)) {
for (auto V : Br->getArgs())
Args.push_back(V);
return;
}
if (auto CondBr = dyn_cast<CondBranchInst>(T)) {
assert(EdgeIdx < 2);
auto OpdArgs = EdgeIdx ? CondBr->getFalseArgs() : CondBr->getTrueArgs();
for (auto V: OpdArgs)
Args.push_back(V);
return;
}
if (auto SEI = dyn_cast<SwitchValueInst>(T)) {
auto *SuccBB = getNthEdgeBlock(SEI, EdgeIdx);
assert(SuccBB->getNumArguments() == 0 && "Can't take an argument");
(void) SuccBB;
return;
}
// A switch_enum can implicitly pass the enum payload. We need to look at the
// destination block to figure this out.
if (auto SEI = dyn_cast<SwitchEnumInstBase>(T)) {
auto *SuccBB = getNthEdgeBlock(SEI, EdgeIdx);
assert(SuccBB->getNumArguments() < 2 && "Can take at most one argument");
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
// A dynamic_method_br passes the function to the first basic block.
if (auto DMBI = dyn_cast<DynamicMethodBranchInst>(T)) {
auto *SuccBB =
(EdgeIdx == 0) ? DMBI->getHasMethodBB() : DMBI->getNoMethodBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
/// A checked_cast_br passes the result of the cast to the first basic block.
if (auto CBI = dyn_cast<CheckedCastBranchInst>(T)) {
auto SuccBB = EdgeIdx == 0 ? CBI->getSuccessBB() : CBI->getFailureBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
if (auto CBI = dyn_cast<CheckedCastAddrBranchInst>(T)) {
auto SuccBB = EdgeIdx == 0 ? CBI->getSuccessBB() : CBI->getFailureBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
if (auto CBI = dyn_cast<CheckedCastValueBranchInst>(T)) {
auto SuccBB = EdgeIdx == 0 ? CBI->getSuccessBB() : CBI->getFailureBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
if (auto *TAI = dyn_cast<TryApplyInst>(T)) {
auto *SuccBB = EdgeIdx == 0 ? TAI->getNormalBB() : TAI->getErrorBB();
if (!SuccBB->getNumArguments())
return;
Args.push_back(NewEdgeBB->createPHIArgument(
SuccBB->getArgument(0)->getType(), ValueOwnershipKind::Owned));
return;
}
// For now this utility is only used to split critical edges involving
// cond_br.
llvm_unreachable("Not yet implemented");
}
/// Splits the basic block at the iterator with an unconditional branch and
/// updates the dominator tree and loop info.
SILBasicBlock *swift::splitBasicBlockAndBranch(SILBuilder &B,
SILInstruction *SplitBeforeInst,
DominanceInfo *DT,
SILLoopInfo *LI) {
auto *OrigBB = SplitBeforeInst->getParent();
auto *NewBB = OrigBB->split(SplitBeforeInst->getIterator());
B.setInsertionPoint(OrigBB);
B.createBranch(SplitBeforeInst->getLoc(), NewBB);
// Update the dominator tree.
if (DT) {
auto OrigBBDTNode = DT->getNode(OrigBB);
if (OrigBBDTNode) {
// Change the immediate dominators of the children of the block we
// splitted to the splitted block.
SmallVector<DominanceInfoNode *, 16> Adoptees(OrigBBDTNode->begin(),
OrigBBDTNode->end());
auto NewBBDTNode = DT->addNewBlock(NewBB, OrigBB);
for (auto *Adoptee : Adoptees)
DT->changeImmediateDominator(Adoptee, NewBBDTNode);
}
}
// Update loop info.
if (LI)
if (auto *OrigBBLoop = LI->getLoopFor(OrigBB)) {
OrigBBLoop->addBasicBlockToLoop(NewBB, LI->getBase());
}
return NewBB;
}
SILBasicBlock *swift::splitEdge(TermInst *T, unsigned EdgeIdx,
DominanceInfo *DT, SILLoopInfo *LI) {
auto *SrcBB = T->getParent();
auto *Fn = SrcBB->getParent();
SILBasicBlock *DestBB = T->getSuccessors()[EdgeIdx];
// Create a new basic block in the edge, and insert it after the SrcBB.
auto *EdgeBB = Fn->createBasicBlock(SrcBB);
SmallVector<SILValue, 16> Args;
getEdgeArgs(T, EdgeIdx, EdgeBB, Args);
SILBuilder(EdgeBB).createBranch(T->getLoc(), DestBB, Args);
// Strip the arguments and rewire the branch in the source block.
changeBranchTarget(T, EdgeIdx, EdgeBB, /*PreserveArgs=*/false);
if (!DT && !LI)
return EdgeBB;
// Update the dominator tree.
if (DT) {
auto *SrcBBNode = DT->getNode(SrcBB);
// Unreachable code could result in a null return here.
if (SrcBBNode) {
// The new block is dominated by the SrcBB.
auto *EdgeBBNode = DT->addNewBlock(EdgeBB, SrcBB);
// Are all predecessors of DestBB dominated by DestBB?
auto *DestBBNode = DT->getNode(DestBB);
bool OldSrcBBDominatesAllPreds = std::all_of(
DestBB->pred_begin(), DestBB->pred_end(), [=](SILBasicBlock *B) {
if (B == EdgeBB)
return true;
auto *PredNode = DT->getNode(B);
if (!PredNode)
return true;
if (DT->dominates(DestBBNode, PredNode))
return true;
return false;
});
// If so, the new bb dominates DestBB now.
if (OldSrcBBDominatesAllPreds)
DT->changeImmediateDominator(DestBBNode, EdgeBBNode);
}
}
if (!LI)
return EdgeBB;
// Update loop info. Both blocks must be in a loop otherwise the split block
// is outside the loop.
SILLoop *SrcBBLoop = LI->getLoopFor(SrcBB);
if (!SrcBBLoop)
return EdgeBB;
SILLoop *DstBBLoop = LI->getLoopFor(DestBB);
if (!DstBBLoop)
return EdgeBB;
// Same loop.
if (DstBBLoop == SrcBBLoop) {
DstBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Edge from inner to outer loop.
if (DstBBLoop->contains(SrcBBLoop)) {
DstBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Edge from outer to inner loop.
if (SrcBBLoop->contains(DstBBLoop)) {
SrcBBLoop->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
// Neither loop contains the other. The destination must be the header of its
// loop. Otherwise, we would be creating irreducible control flow.
assert(DstBBLoop->getHeader() == DestBB &&
"Creating irreducible control flow?");
// Add to outer loop if there is one.
if (auto *Parent = DstBBLoop->getParentLoop())
Parent->addBasicBlockToLoop(EdgeBB, LI->getBase());
return EdgeBB;
}
/// Split every edge between two basic blocks.
void swift::splitEdgesFromTo(SILBasicBlock *From, SILBasicBlock *To,
DominanceInfo *DT, SILLoopInfo *LI) {
for (unsigned EdgeIndex = 0, E = From->getSuccessors().size(); EdgeIndex != E;
++EdgeIndex) {
SILBasicBlock *SuccBB = From->getSuccessors()[EdgeIndex];
if (SuccBB != To)
continue;
splitEdge(From->getTerminator(), EdgeIndex, DT, LI);
}
}
/// Splits the n-th critical edge from the terminator and updates dominance and
/// loop info if set.
/// Returns the newly created basic block on success or nullptr otherwise (if
/// the edge was not critical.
SILBasicBlock *swift::splitCriticalEdge(TermInst *T, unsigned EdgeIdx,
DominanceInfo *DT, SILLoopInfo *LI) {
if (!isCriticalEdge(T, EdgeIdx))
return nullptr;
return splitEdge(T, EdgeIdx, DT, LI);
}
bool swift::hasCriticalEdges(SILFunction &F, bool OnlyNonCondBr) {
for (SILBasicBlock &BB : F) {
// Only consider critical edges for terminators that don't support block
// arguments.
if (OnlyNonCondBr && isa<CondBranchInst>(BB.getTerminator()))
continue;
if (isa<BranchInst>(BB.getTerminator()))
continue;
for (unsigned Idx = 0, e = BB.getSuccessors().size(); Idx != e; ++Idx)
if (isCriticalEdge(BB.getTerminator(), Idx))
return true;
}
return false;
}
/// Split all critical edges in the function updating the dominator tree and
/// loop information (if they are not set to null).
bool swift::splitAllCriticalEdges(SILFunction &F, bool OnlyNonCondBr,
DominanceInfo *DT, SILLoopInfo *LI) {
bool Changed = false;
for (SILBasicBlock &BB : F) {
// Only split critical edges for terminators that don't support block
// arguments.
if (OnlyNonCondBr && isa<CondBranchInst>(BB.getTerminator()))
continue;
if (isa<BranchInst>(BB.getTerminator()))
continue;
for (unsigned Idx = 0, e = BB.getSuccessors().size(); Idx != e; ++Idx)
Changed |=
(splitCriticalEdge(BB.getTerminator(), Idx, DT, LI) != nullptr);
}
return Changed;
}
/// Merge the basic block with its successor if possible. If dominance
/// information or loop info is non null update it. Return true if block was
/// merged.
bool swift::mergeBasicBlockWithSuccessor(SILBasicBlock *BB, DominanceInfo *DT,
SILLoopInfo *LI) {
auto *Branch = dyn_cast<BranchInst>(BB->getTerminator());
if (!Branch)
return false;
auto *SuccBB = Branch->getDestBB();
if (BB == SuccBB || !SuccBB->getSinglePredecessorBlock())
return false;
// If there are any BB arguments in the destination, replace them with the
// branch operands, since they must dominate the dest block.
for (unsigned i = 0, e = Branch->getArgs().size(); i != e; ++i)
SuccBB->getArgument(i)->replaceAllUsesWith(Branch->getArg(i));
Branch->eraseFromParent();
// Move the instruction from the successor block to the current block.
BB->spliceAtEnd(SuccBB);
if (DT)
if (auto *SuccBBNode = DT->getNode(SuccBB)) {
// Change the immediate dominator for children of the successor to be the
// current block.
auto *BBNode = DT->getNode(BB);
SmallVector<DominanceInfoNode *, 8> Children(SuccBBNode->begin(),
SuccBBNode->end());
for (auto *ChildNode : *SuccBBNode)
DT->changeImmediateDominator(ChildNode, BBNode);
DT->eraseNode(SuccBB);
}
if (LI)
LI->removeBlock(SuccBB);
SuccBB->eraseFromParent();
return true;
}
/// Splits the critical edges between from and to. This code assumes there is
/// only one edge between the two basic blocks.
SILBasicBlock *swift::splitIfCriticalEdge(SILBasicBlock *From,
SILBasicBlock *To,
DominanceInfo *DT,
SILLoopInfo *LI) {
auto *T = From->getTerminator();
for (unsigned i = 0, e = T->getSuccessors().size(); i != e; ++i) {
if (T->getSuccessors()[i] == To)
return splitCriticalEdge(T, i, DT, LI);
}
llvm_unreachable("Destination block not found");
}
void swift::completeJointPostDominanceSet(
ArrayRef<SILBasicBlock *> UserBlocks, ArrayRef<SILBasicBlock *> DefBlocks,
llvm::SmallVectorImpl<SILBasicBlock *> &Result) {
assert(!UserBlocks.empty() && "Must have at least 1 user block");
assert(!DefBlocks.empty() && "Must have at least 1 def block");
// If we have only one def block and one user block and they are the same
// block, then just return.
if (DefBlocks.size() == 1 && UserBlocks.size() == 1 &&
UserBlocks[0] == DefBlocks[0]) {
return;
}
// Some notes on the algorithm:
//
// 1. Our VisitedBlocks set just states that a value has been added to the
// worklist and should not be added to the worklist.
// 2. Our targets of the CFG block are DefBlockSet.
// 3. We find the missing post-domination blocks by finding successors of
// blocks on our walk that we have not visited by the end of the walk. For
// joint post-dominance to be true, no such successors should exist.
// Our set of target blocks where we stop walking.
llvm::SmallPtrSet<SILBasicBlock *, 8> DefBlockSet(DefBlocks.begin(),
DefBlocks.end());
// The set of successor blocks of blocks that we visit. Any blocks still in
// this set at the end of the walk act as a post-dominating closure around our
// UserBlock set.
llvm::SmallSetVector<SILBasicBlock *, 16> MustVisitSuccessorBlocks;
// Add our user and def blocks to the VisitedBlock set. We never want to find
// these in our worklist.
llvm::SmallPtrSet<SILBasicBlock *, 32> VisitedBlocks(UserBlocks.begin(),
UserBlocks.end());
// Finally setup our worklist by adding our user block predecessors. We only
// add the predecessors to the worklist once.
llvm::SmallVector<SILBasicBlock *, 32> Worklist;
for (auto *Block : UserBlocks) {
copy_if(Block->getPredecessorBlocks(), std::back_inserter(Worklist),
[&](SILBasicBlock *PredBlock) -> bool {
return VisitedBlocks.insert(PredBlock).second;
});
}
// Then until we reach a fix point.
while (!Worklist.empty()) {
// Grab the next block from the worklist.
auto *Block = Worklist.pop_back_val();
assert(VisitedBlocks.count(Block) && "All blocks from worklist should be "
"in the visited blocks set.");
// Since we are visiting this block now, we know that this block can not be
// apart of a the post-dominance closure of our UseBlocks.
MustVisitSuccessorBlocks.remove(Block);
// Then add each successor block of Block that has not been visited yet to
// the MustVisitSuccessorBlocks set.
for (auto *SuccBlock : Block->getSuccessorBlocks()) {
if (!VisitedBlocks.count(SuccBlock)) {
MustVisitSuccessorBlocks.insert(SuccBlock);
}
}
// If this is a def block, then do not add its predecessors to the
// worklist.
if (DefBlockSet.count(Block))
continue;
// Otherwise add all unvisited predecessors to the worklist.
copy_if(Block->getPredecessorBlocks(), std::back_inserter(Worklist),
[&](SILBasicBlock *Block) -> bool {
return VisitedBlocks.insert(Block).second;
});
}
// Now that we are done, add all remaining must visit blocks to our result
// list. These are the remaining parts of our joint post-dominance closure.
copy(MustVisitSuccessorBlocks, std::back_inserter(Result));
}
bool swift::splitAllCondBrCriticalEdgesWithNonTrivialArgs(SILFunction &Fn,
DominanceInfo *DT,
SILLoopInfo *LI) {
// Find our targets.
llvm::SmallVector<std::pair<SILBasicBlock *, unsigned>, 8> Targets;
for (auto &Block : Fn) {
auto *CBI = dyn_cast<CondBranchInst>(Block.getTerminator());
if (!CBI)
continue;
// See if our true index is a critical edge. If so, add block to the list
// and continue. If the false edge is also critical, we will handle it at
// the same time.
if (isCriticalEdge(CBI, CondBranchInst::TrueIdx)) {
Targets.emplace_back(&Block, CondBranchInst::TrueIdx);
}
if (!isCriticalEdge(CBI, CondBranchInst::FalseIdx)) {
continue;
}
Targets.emplace_back(&Block, CondBranchInst::FalseIdx);
}
if (Targets.empty())
return false;
for (auto P : Targets) {
SILBasicBlock *Block = P.first;
unsigned Index = P.second;
auto *Result = splitCriticalEdge(Block->getTerminator(), Index, DT, LI);
(void)Result;
assert(Result);
}
return true;
}
namespace {
class RemoveUnreachable {
SILFunction &Fn;
llvm::SmallSet<SILBasicBlock *, 8> Visited;
public:
RemoveUnreachable(SILFunction &Fn) : Fn(Fn) { }
void visit(SILBasicBlock *BB);
bool run();
};
} // end anonymous namespace
void RemoveUnreachable::visit(SILBasicBlock *BB) {
if (!Visited.insert(BB).second)
return;
for (auto &Succ : BB->getSuccessors())
visit(Succ);
}
bool RemoveUnreachable::run() {
bool Changed = false;
// Clear each time we run so that we can run multiple times.
Visited.clear();
// Visit all blocks reachable from the entry block of the function.
visit(&*Fn.begin());
// Remove the blocks we never reached.
for (auto It = Fn.begin(), End = Fn.end(); It != End; ) {
auto *BB = &*It++;
if (!Visited.count(BB)) {
removeDeadBlock(BB);
Changed = true;
}
}
return Changed;
}
bool swift::removeUnreachableBlocks(SILFunction &Fn) {
return RemoveUnreachable(Fn).run();
}
| 36.040354
| 106
| 0.642488
|
sysidos
|
4490a1959fb2cf7adabe2da0e9844b9f60973284
| 423
|
cpp
|
C++
|
codeforce2/236A. Boy or Girl.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce2/236A. Boy or Girl.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
codeforce2/236A. Boy or Girl.cpp
|
khaled-farouk/My_problem_solving_solutions
|
46ed6481fc9b424d0714bc717cd0ba050a6638ef
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int freq[26] = {0};
for(int i = 0; i < s.size(); i++)
freq[s[i] - 'a']++;
int c = 0;
for(int i = 0; i < 26; i++)
if(freq[i])
c++;
if(c % 2) cout << "IGNORE HIM!" << endl;
else cout << "CHAT WITH HER!" << endl;
return 0;
}
| 17.625
| 45
| 0.404255
|
khaled-farouk
|
44914cc9672ad8b0b5b61e29802ecd3c2382b43d
| 3,879
|
cpp
|
C++
|
3dparty/taglib/examples/framelist.cpp
|
olanser/uteg
|
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
|
[
"MIT"
] | 3,066
|
2016-06-10T09:23:40.000Z
|
2022-03-31T11:01:01.000Z
|
3dparty/taglib/examples/framelist.cpp
|
olanser/uteg
|
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
|
[
"MIT"
] | 414
|
2016-09-20T20:26:05.000Z
|
2022-03-29T00:43:13.000Z
|
3dparty/taglib/examples/framelist.cpp
|
olanser/uteg
|
c8c79a8e8e5d185253b415e67f7b6d9e37114da3
|
[
"MIT"
] | 310
|
2016-06-13T21:53:04.000Z
|
2022-03-18T14:36:38.000Z
|
/* Copyright (C) 2003 Scott Wheeler <wheeler@kde.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <stdlib.h>
#include <tbytevector.h>
#include <mpegfile.h>
#include <id3v2tag.h>
#include <id3v2frame.h>
#include <id3v2header.h>
#include <commentsframe.h>
#include <id3v1tag.h>
#include <apetag.h>
using namespace std;
using namespace TagLib;
int main(int argc, char *argv[])
{
// process the command line args
for(int i = 1; i < argc; i++) {
cout << "******************** \"" << argv[i] << "\"********************" << endl;
MPEG::File f(argv[i]);
ID3v2::Tag *id3v2tag = f.ID3v2Tag();
if(id3v2tag) {
cout << "ID3v2."
<< id3v2tag->header()->majorVersion()
<< "."
<< id3v2tag->header()->revisionNumber()
<< ", "
<< id3v2tag->header()->tagSize()
<< " bytes in tag"
<< endl;
ID3v2::FrameList::ConstIterator it = id3v2tag->frameList().begin();
for(; it != id3v2tag->frameList().end(); it++) {
cout << (*it)->frameID();
if(ID3v2::CommentsFrame *comment = dynamic_cast<ID3v2::CommentsFrame *>(*it))
if(!comment->description().isEmpty())
cout << " [" << comment->description() << "]";
cout << " - \"" << (*it)->toString() << "\"" << endl;
}
}
else
cout << "file does not have a valid id3v2 tag" << endl;
cout << endl << "ID3v1" << endl;
ID3v1::Tag *id3v1tag = f.ID3v1Tag();
if(id3v1tag) {
cout << "title - \"" << id3v1tag->title() << "\"" << endl;
cout << "artist - \"" << id3v1tag->artist() << "\"" << endl;
cout << "album - \"" << id3v1tag->album() << "\"" << endl;
cout << "year - \"" << id3v1tag->year() << "\"" << endl;
cout << "comment - \"" << id3v1tag->comment() << "\"" << endl;
cout << "track - \"" << id3v1tag->track() << "\"" << endl;
cout << "genre - \"" << id3v1tag->genre() << "\"" << endl;
}
else
cout << "file does not have a valid id3v1 tag" << endl;
APE::Tag *ape = f.APETag();
cout << endl << "APE" << endl;
if(ape) {
for(APE::ItemListMap::ConstIterator it = ape->itemListMap().begin();
it != ape->itemListMap().end(); ++it)
{
if((*it).second.type() != APE::Item::Binary)
cout << (*it).first << " - \"" << (*it).second.toString() << "\"" << endl;
else
cout << (*it).first << " - Binary data (" << (*it).second.binaryData().size() << " bytes)" << endl;
}
}
else
cout << "file does not have a valid APE tag" << endl;
cout << endl;
}
}
| 32.872881
| 109
| 0.576179
|
olanser
|
44914daa0eec6c16a3ae8198479558e4adf7f559
| 395
|
cpp
|
C++
|
Source/ex1.cpp
|
allhailthetail/cpp-itp-main
|
43a33a3df68feac3a600b3a51af3fbe893225277
|
[
"MIT"
] | null | null | null |
Source/ex1.cpp
|
allhailthetail/cpp-itp-main
|
43a33a3df68feac3a600b3a51af3fbe893225277
|
[
"MIT"
] | null | null | null |
Source/ex1.cpp
|
allhailthetail/cpp-itp-main
|
43a33a3df68feac3a600b3a51af3fbe893225277
|
[
"MIT"
] | null | null | null |
// Sample C++ program
#include <iostream>
using namespace std;
int main()
{
/* You have multiple options for doing new lines.
Either insert an escape character, as shown, or declare an end of line
*/
cout << "Hello, there! \n How about a new line??" << endl;
cout << "Now let's try some tabs!!\ttab\ttab..." << endl;
cout << "\n\tTab to new line...";
cout << "\n\tAgain..." << endl;
return 0;
}
| 26.333333
| 70
| 0.648101
|
allhailthetail
|
44918d79bdf02d8e273243b3f8f017a416cbc0c5
| 19,138
|
cpp
|
C++
|
tutorial02/main.cpp
|
taqu/RayTracing
|
b0727ef16c8252cd7d3d79ef94c0691a2b7a4387
|
[
"Unlicense"
] | null | null | null |
tutorial02/main.cpp
|
taqu/RayTracing
|
b0727ef16c8252cd7d3d79ef94c0691a2b7a4387
|
[
"Unlicense"
] | null | null | null |
tutorial02/main.cpp
|
taqu/RayTracing
|
b0727ef16c8252cd7d3d79ef94c0691a2b7a4387
|
[
"Unlicense"
] | null | null | null |
#define CPPIMG_IMPLEMENTATION
#include <cppimg/cppimg.h>
#define CPPGLTF_IMPLEMENTATION
#include <cppgltf/cppgltf.h>
#include "lray.h"
#include "Camera.h"
#include "core/LString.h"
#include "core/Array.h"
#include "math/Ray.h"
#include "math/RayTest.h"
#include "math/Matrix44.h"
#include "math/Quaternion.h"
#include "core/ReferenceCounted.h"
#include "shape/Mesh.h"
#include "shape/Node.h"
using namespace lray;
namespace lray
{
class Scene
{
public:
typedef lray::Array<Mesh> MeshArray;
typedef lray::Array<Node> NodeArray;
Scene();
Scene(Scene&& rhs);
explicit Scene(const Char* name, MeshArray&& meshes, NodeArray&& nodes);
void updateFrame();
Result test(Intersection& intersection, Ray& ray);
Scene& operator=(Scene&& rhs);
private:
Scene(const Scene&) = delete;
Scene& operator=(const Scene&) = delete;
String name_;
MeshArray meshes_;
MeshArray refinedMeshes_;
NodeArray nodes_;
};
}
namespace lray
{
//--- Scene
//-----------------------------------------------------
Scene::Scene()
{
}
Scene::Scene(Scene&& rhs)
:meshes_(move(rhs.meshes_))
,nodes_(move(rhs.nodes_))
{
}
Scene::Scene(const Char* name, MeshArray&& meshes, NodeArray&& nodes)
:meshes_(move(meshes))
,nodes_(move(nodes))
{
if(NULL != name){
name_.assign(name);
}
}
Scene& Scene::operator=(Scene&& rhs)
{
if(this == &rhs){
return *this;
}
name_ = move(rhs.name_);
meshes_ = move(rhs.meshes_);
nodes_ = move(rhs.nodes_);
return *this;
}
Result Scene::test(Intersection& intersection, Ray& ray)
{
for(s32 i=0; i<refinedMeshes_.size(); ++i){
Mesh& mesh = refinedMeshes_[i];
mesh.test(intersection, ray);
}
return intersection.result_;
}
void Scene::updateFrame()
{
refinedMeshes_.resize(meshes_.size());
//Update world matrices and meshes of root nodes
s32 inode=0;
for(; inode<nodes_.size(); ++inode){
Node& node = nodes_[inode];
if(0<=node.getParent()){
break;
}
node.getWorldMatrix() = node.getMatrix();
s32 imesh = node.getMesh();
if(0<=imesh){
refinedMeshes_[imesh].refine(meshes_[imesh], node.getWorldMatrix());
}
}
//Update descendant's
for(; inode<nodes_.size(); ++inode){
Node& node = nodes_[inode];
s32 iparent = node.getParent();
node.getWorldMatrix().mul(node.getMatrix(), nodes_[iparent].getWorldMatrix());
s32 imesh = node.getMesh();
if(0<=imesh){
refinedMeshes_[imesh].refine(meshes_[imesh], node.getWorldMatrix());
}
}
}
}
bool checkPrimitiveAttributes(cppgltf::Primitive& primitive)
{
s32 flags = 0;
s32 needs = (0x01U<<cppgltf::GLTF_ATTRIBUTE_POSITION
| 0x01U<<cppgltf::GLTF_ATTRIBUTE_NORMAL);
for(s32 i=0; i<primitive.attributes_.size(); ++i){
cppgltf::Attribute& attribute = primitive.attributes_[i];
switch(attribute.semanticType_){
case cppgltf::GLTF_ATTRIBUTE_POSITION:
flags |= (0x01U<<cppgltf::GLTF_ATTRIBUTE_POSITION);
break;
case cppgltf::GLTF_ATTRIBUTE_NORMAL:
flags |= (0x01U<<cppgltf::GLTF_ATTRIBUTE_NORMAL);
break;
case cppgltf::GLTF_ATTRIBUTE_TANGENT:
break;
case cppgltf::GLTF_ATTRIBUTE_TEXCOORD:
break;
case cppgltf::GLTF_ATTRIBUTE_COLOR:
break;
case cppgltf::GLTF_ATTRIBUTE_JOINTS:
break;
case cppgltf::GLTF_ATTRIBUTE_WEIGHTS:
break;
}
}
return 0 != (flags & needs);
}
cppgltf::Attribute* findPrimitiveAttributes(cppgltf::Primitive& primitive, s32 semanticType, s32 semanticIndex)
{
for(s32 i=0; i<primitive.attributes_.size(); ++i){
cppgltf::Attribute& attribute = primitive.attributes_[i];
if(semanticType == attribute.semanticType_
&& semanticIndex == attribute.semanticIndex_){
return &attribute;
}
}
return NULL;
}
void createPositions(s32& numPositions, Vector3** positions, cppgltf::glTF& gltf, cppgltf::Primitive& primitive)
{
numPositions = 0;
*positions = NULL;
//Check having position attribute
cppgltf::Attribute* attribute = findPrimitiveAttributes(primitive, cppgltf::GLTF_ATTRIBUTE_POSITION, 0);
if(NULL == attribute){
return;
}
if(attribute->accessor_<0 || gltf.accessors_.size()<=attribute->accessor_){
return;
}
cppgltf::Accessor& accessor = gltf.accessors_[attribute->accessor_];
//Check that component-type and type are VEC3 and FLOAT respectively.
if(accessor.componentType_ != cppgltf::GLTF_TYPE_FLOAT
|| accessor.type_ != cppgltf::GLTF_TYPE_VEC3){
return;
}
if(accessor.bufferView_<0 || gltf.bufferViews_.size()<=accessor.bufferView_){
return;
}
cppgltf::BufferView& bufferView = gltf.bufferViews_[accessor.bufferView_];
if(bufferView.buffer_<0 || gltf.buffers_.size()<=bufferView.buffer_){
return;
}
cppgltf::Buffer& buffer = gltf.buffers_[bufferView.buffer_];
s32 byteStride = (bufferView.byteStride_<=0)? sizeof(f32)*3 : bufferView.byteStride_;
numPositions = accessor.count_;
*positions = LNEW Vector3[numPositions];
Vector3 bmin(F32_INFINITY), bmax(-F32_INFINITY);
u8* data = buffer.data_ + bufferView.byteOffset_ + accessor.byteOffset_;
for(s32 i=0; i<numPositions; ++i, data+=byteStride){
Vector3* p = reinterpret_cast<Vector3*>(data);
bmin = minimum(*p, bmin);
bmax = maximum(*p, bmax);
(*positions)[i] = *p;
}
}
void createNormals(s32& numNormals, Vector3** normals, cppgltf::glTF& gltf, cppgltf::Primitive& primitive)
{
numNormals = 0;
*normals = NULL;
//Check having normal attribute
cppgltf::Attribute* attribute = findPrimitiveAttributes(primitive, cppgltf::GLTF_ATTRIBUTE_NORMAL, 0);
if(NULL == attribute){
return;
}
if(attribute->accessor_<0 || gltf.accessors_.size()<=attribute->accessor_){
return;
}
cppgltf::Accessor& accessor = gltf.accessors_[attribute->accessor_];
//Check that component-type and type are VEC3 and FLOAT respectively.
if(accessor.componentType_ != cppgltf::GLTF_TYPE_FLOAT
|| accessor.type_ != cppgltf::GLTF_TYPE_VEC3){
return;
}
if(accessor.bufferView_<0 || gltf.bufferViews_.size()<=accessor.bufferView_){
return;
}
cppgltf::BufferView& bufferView = gltf.bufferViews_[accessor.bufferView_];
if(bufferView.buffer_<0 || gltf.buffers_.size()<=bufferView.buffer_){
return;
}
cppgltf::Buffer& buffer = gltf.buffers_[bufferView.buffer_];
s32 byteStride = (bufferView.byteStride_<=0)? sizeof(f32)*3 : bufferView.byteStride_;
numNormals = accessor.count_;
*normals = LNEW Vector3[numNormals];
u8* data = buffer.data_ + bufferView.byteOffset_ + accessor.byteOffset_;
for(s32 i=0; i<numNormals; ++i, data+=byteStride){
Vector3* p = reinterpret_cast<Vector3*>(data);
(*normals)[i] = normalize(*p);
}
}
void generateTriangles(s32& numTriangles, Triangle** triangles, s32 primitiveMode, s32 numPositions)
{
switch(primitiveMode)
{
case cppgltf::GLTF_PRIMITIVE_TRIANGLES:
{
numTriangles = numPositions/3;
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
for(s32 i=0; i<numPositions; i+=3, ++tri){
tri->indices_[0] = i;
tri->indices_[1] = i+1;
tri->indices_[2] = i+2;
}
}
break;
case cppgltf::GLTF_PRIMITIVE_TRIANGLE_STRIP:
{
numTriangles = maximum(numPositions-2, 0);
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
for(s32 i=2; i<numPositions; ++i, ++tri){
tri->indices_[0] = i-2;
tri->indices_[1] = i-1;
tri->indices_[2] = i;
}
}
break;
case cppgltf::GLTF_PRIMITIVE_TRIANGLE_FAN:
{
numTriangles = maximum(numPositions-2, 0);
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
for(s32 i=2; i<numPositions; ++i, ++tri){
tri->indices_[0] = 0;
tri->indices_[1] = i-1;
tri->indices_[2] = i;
}
}
break;
default:
numTriangles = 0;
*triangles = NULL;
break;
}
}
template<class T>
void createTriangles(s32& numTriangles, Triangle** triangles, s32 primitiveMode, s32 numIndices, s32 byteStride, u8* data)
{
switch(primitiveMode)
{
case cppgltf::GLTF_PRIMITIVE_TRIANGLES:
{
numTriangles = numIndices/3;
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
for(s32 i=0; i<numIndices; i+=3, ++tri){
tri->indices_[0] = *reinterpret_cast<T*>(data);
data += byteStride;
tri->indices_[1] = *reinterpret_cast<T*>(data);
data += byteStride;
tri->indices_[2] = *reinterpret_cast<T*>(data);
data += byteStride;
}
}
break;
case cppgltf::GLTF_PRIMITIVE_TRIANGLE_STRIP:
{
numTriangles = maximum(numIndices-2, 0);
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
data += byteStride;
for(s32 i=2; i<numIndices; ++i, ++tri){
tri->indices_[0] = *reinterpret_cast<T*>(data-byteStride);
tri->indices_[1] = *reinterpret_cast<T*>(data);
tri->indices_[2] = *reinterpret_cast<T*>(data+byteStride);
data += byteStride;
}
}
break;
case cppgltf::GLTF_PRIMITIVE_TRIANGLE_FAN:
{
numTriangles = maximum(numIndices-2, 0);
*triangles = LNEW Triangle[numTriangles];
Triangle* tri = *triangles;
T index0 = *reinterpret_cast<T*>(data);
data += byteStride;
for(s32 i=2; i<numIndices; ++i, ++tri){
tri->indices_[0] = index0;
tri->indices_[1] = *reinterpret_cast<T*>(data);
tri->indices_[2] = *reinterpret_cast<T*>(data+byteStride);
data += byteStride;
}
}
break;
default:
numTriangles = 0;
*triangles = NULL;
break;
}
}
void createTriangles(s32& numTriangles, Triangle** triangles, cppgltf::glTF& gltf, cppgltf::Primitive& primitive)
{
numTriangles = 0;
*triangles = NULL;
//Check having position attribute
cppgltf::Attribute* attribute = findPrimitiveAttributes(primitive, cppgltf::GLTF_ATTRIBUTE_POSITION, 0);
if(NULL == attribute){
return;
}
if(attribute->accessor_<0 || gltf.accessors_.size()<=attribute->accessor_){
return;
}
cppgltf::Accessor& positionAccessor = gltf.accessors_[attribute->accessor_];
if(primitive.indices_<0 || gltf.accessors_.size()<=primitive.indices_){
//Don't have indices, then create indices
generateTriangles(numTriangles, triangles, primitive.mode_, positionAccessor.count_);
return;
}
cppgltf::Accessor& indexAccessor = gltf.accessors_[primitive.indices_];
//Check that component-type and type are VEC3 and FLOAT respectively.
if((indexAccessor.componentType_ != cppgltf::GLTF_TYPE_UNSIGNED_SHORT
&& indexAccessor.componentType_ != cppgltf::GLTF_TYPE_INT
&& indexAccessor.componentType_ != cppgltf::GLTF_TYPE_UNSIGNED_INT)
|| indexAccessor.type_ != cppgltf::GLTF_TYPE_SCALAR){
return;
}
if(indexAccessor.bufferView_<0 || gltf.bufferViews_.size()<=indexAccessor.bufferView_){
return;
}
cppgltf::BufferView& bufferView = gltf.bufferViews_[indexAccessor.bufferView_];
if(bufferView.buffer_<0 || gltf.buffers_.size()<=bufferView.buffer_){
return;
}
cppgltf::Buffer& buffer = gltf.buffers_[bufferView.buffer_];
s32 byteStride;
u8* data = buffer.data_ + bufferView.byteOffset_ + indexAccessor.byteOffset_;
switch(indexAccessor.componentType_){
case cppgltf::GLTF_TYPE_UNSIGNED_SHORT:
{
byteStride = (bufferView.byteStride_<=0)? 2 : bufferView.byteStride_;
createTriangles<u16>(numTriangles, triangles, primitive.mode_, indexAccessor.count_, byteStride, data);
}
break;
case cppgltf::GLTF_TYPE_INT:
{
byteStride = (bufferView.byteStride_<=0)? 4 : bufferView.byteStride_;
createTriangles<s32>(numTriangles, triangles, primitive.mode_, indexAccessor.count_, byteStride, data);
}
break;
case cppgltf::GLTF_TYPE_UNSIGNED_INT:
{
byteStride = (bufferView.byteStride_<=0)? 4 : bufferView.byteStride_;
createTriangles<u32>(numTriangles, triangles, primitive.mode_, indexAccessor.count_, byteStride, data);
}
break;
}
}
Primitive createPrimitive(cppgltf::glTF& gltf, cppgltf::Primitive& gltfPrimitive)
{
s32 numVertices;
Vector3* positions = NULL;
createPositions(numVertices, &positions, gltf, gltfPrimitive);
s32 numNormals;
Vector3* normals = NULL;
createNormals(numNormals, &normals, gltf, gltfPrimitive);
s32 numTriangles;
Triangle* triangles = NULL;
createTriangles(numTriangles, &triangles, gltf, gltfPrimitive);
return Primitive(numVertices, positions, normals, numTriangles, triangles);
}
void load(Scene& scene, const Char* filepath)
{
cppgltf::IFStream ifstream;
if(!ifstream.open(filepath)){
return;
}
s32 pathLength = strlen_s32(filepath);
Char* directoryPath = LNEW Char[pathLength+1];
extractDirectoryPath(directoryPath, pathLength, filepath);
cppgltf::glTFHandler gltfHandler(directoryPath);
cppgltf::JSONReader gltfJsonReader(ifstream, gltfHandler);
bool result = gltfJsonReader.read();
if(!result){
LDELETE_ARRAY(directoryPath);
return;
}
ifstream.close();
cppgltf::glTF& gltf = gltfHandler.get();
//asset
LASSERT("2.0" == gltf.asset_.version_);
//meshes
//--------------------------------------------
Scene::MeshArray meshArray;
for(s32 i=0; i<gltf.meshes_.size(); ++i){
cppgltf::Mesh& gltfMesh = gltf.meshes_[i];
Mesh::PrimitiveArray primitiveArray;
for(s32 j=0; j<gltfMesh.primitives_.size(); ++j){
cppgltf::Primitive& gltfPrim = gltfMesh.primitives_[j];
//check
if(gltfPrim.attributes_.size()<=0
|| gltfPrim.indices_<0){
continue;
}
if(gltfPrim.mode_<cppgltf::GLTF_PRIMITIVE_TRIANGLES){
continue;
}
Primitive primitive = createPrimitive(gltf, gltfPrim);
if(primitive.getNumVertices()<=0){
continue;
}
primitiveArray.push_back(move(primitive));
}
if(primitiveArray.size()<=0){
continue;
}
Mesh mesh(move(primitiveArray));
meshArray.push_back(move(mesh));
}
//nodes
//--------------------------------------------
Scene::NodeArray nodeArray;
if(0<gltf.sortedNodes_.size()){
nodeArray.reserve(gltf.sortedNodes_.size());
for(s32 i=0; i<gltf.sortedNodes_.size(); ++i){
const cppgltf::glTF::SortNode& sortNode = gltf.sortedNodes_[i];
const cppgltf::Node& gltfNode = gltf.nodes_[sortNode.oldId_];
Node node(gltfNode.name_.c_str(), sortNode.parent_, sortNode.numChildren_, sortNode.childrenStart_, gltfNode.mesh_);
lray::Matrix44& matrix = node.getMatrix();
if(gltfNode.flags_.check(cppgltf::Node::Flag_Matrix)){
for(s32 m=0; m<4; ++m){
for(s32 n=0; n<4; ++n){
matrix.m_[m][n] = gltfNode.matrix_[n*4+m]; //transpose glTF matrix
}
}
}else{
matrix.identity();
//Translate
matrix.setTranslate(gltfNode.translation_[0], gltfNode.translation_[1], gltfNode.translation_[2]);
//Rotate
lray::Quaternion rotation(gltfNode.rotation_[3], gltfNode.rotation_[0], gltfNode.rotation_[1], gltfNode.rotation_[2]);
lray::Matrix44 rotMatrix;
rotation.getMatrix(rotMatrix);
matrix *= rotMatrix;
//Scale
lray::Matrix44 scaleMatrix;
scaleMatrix.identity();
scaleMatrix.setScale(gltfNode.scale_[0], gltfNode.scale_[1], gltfNode.scale_[2]);
matrix *= scaleMatrix;
}
nodeArray.push_back(move(node));
}
}else{
nodeArray.reserve(meshArray.size());
for(s32 i=0; i<meshArray.size(); ++i){
Node node("", -1, 0, -1, i);
nodeArray.push_back(move(node));
}
}
const Char* name = (0<gltf.scenes_.size())? gltf.scenes_[0].name_.c_str() : "";
scene = move(Scene(name, move(meshArray), move(nodeArray)));
LDELETE_ARRAY(directoryPath);
}
int main(int , char** )
{
static const s32 Width = 800;
static const s32 Height = 600;
static const s32 Bpp = 3;
u8* image = new u8[Width*Height*Bpp];
Camera camera;
camera.setResolution(Width, Height);
camera.perspective(static_cast<f32>(Width)/Height, 60.0f*DEG_TO_RAD);
camera.lookAt(Vector3(0.0f, 3.0f, 10.0f), Vector3(0.0f, 3.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
//Add object
Scene scene;
load(scene, "../../data/hatsune_miku_chibi_w_stand/scene.gltf");
//Set light environment
Vector3 lightDirection = normalize(Vector3(0.5f, 0.5f, 0.0f));
//
scene.updateFrame();
//Loop over pixels
ClockType startTime = getPerformanceCounter();
for(s32 y=0; y<Height; ++y){
for(s32 x=0; x<Width; ++x){
Intersection intersection;
Ray ray = camera.generateRay(static_cast<f32>(x), static_cast<f32>(y));
u8 r,g,b;
Result result = scene.test(intersection, ray);
if(Result_Success & result){
f32 d = maximum(dot(intersection.shadingNormal_, lightDirection), 0.0f);
r = g = b = static_cast<u8>(minimum(clamp01(d)*256, 255.0f));
}else{
r = g = b = 128;
}
s32 pixel = (y*Width + x)*Bpp;
image[pixel+0] = r;
image[pixel+1] = g;
image[pixel+2] = b;
}
}
f64 elapsedTime = calcTime64(startTime, getPerformanceCounter());
//Output
cppimg::OFStream file;
if(file.open("out.bmp")){
cppimg::BMP::write(file, Width, Height, cppimg::ColorType_RGB, image);
file.close();
}
delete[] image;
printf("Render time %lf sec\n", elapsedTime);
return 0;
}
| 32.658703
| 134
| 0.601996
|
taqu
|
44984fb9ac3a27980de5b1d310db831404ca5818
| 1,044
|
hpp
|
C++
|
src/ParserError.hpp
|
rowanG077/InferExamAnswers
|
aedd537be0dc78ac6cc1face39302b3bd27ab007
|
[
"MIT"
] | 2
|
2018-12-22T12:19:31.000Z
|
2018-12-24T09:35:25.000Z
|
src/ParserError.hpp
|
rowanG077/InferExamAnswers
|
aedd537be0dc78ac6cc1face39302b3bd27ab007
|
[
"MIT"
] | 1
|
2019-10-28T09:38:06.000Z
|
2020-05-06T17:43:18.000Z
|
src/ParserError.hpp
|
rowanG077/InferExamAnswers
|
aedd537be0dc78ac6cc1face39302b3bd27ab007
|
[
"MIT"
] | null | null | null |
#pragma once
#include <exception>
#include <stdexcept>
#include <string>
/**
* @brief Contains code for the InferExamAnswers problem
*/
namespace InferExamAnswers
{
/**
* @brief Exception that is thrown when error occurs during parsing
*/
struct ParserError : public std::runtime_error
{
public:
/**
* @brief Construct a new Parser Exception object
*
* @param msg The message to set
* @return A new ParserError object
*/
explicit ParserError(const std::string& msg) : std::runtime_error(msg), innerException(nullptr)
{
}
/**
* @brief Construct a new Parser Exception object
*
* @param msg The message to set
* @param innerException innerException to set
* @return A new ParserError object
*/
ParserError(const std::string& msg, const std::exception& innerException) :
std::runtime_error(msg), innerException(std::make_exception_ptr(innerException))
{
}
/**
* @brief Contains the original exception if there was a caught exception
*/
const std::exception_ptr innerException;
};
} // InferExamAnswers
| 23.2
| 96
| 0.722222
|
rowanG077
|
44990748d1c84a2784d4f0a0f288054230804a96
| 21,151
|
cpp
|
C++
|
Sources/simdlib/SimdAvx512bwBackground.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | 6
|
2017-10-13T04:29:38.000Z
|
2018-05-10T13:52:20.000Z
|
Sources/simdlib/SimdAvx512bwBackground.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | null | null | null |
Sources/simdlib/SimdAvx512bwBackground.cpp
|
aestesis/Csimd
|
b333a8bb7e7f2707ed6167badb8002cfe3504bbc
|
[
"Apache-2.0"
] | null | null | null |
/*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Simd/SimdMemory.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdSet.h"
#include "Simd/SimdCompare.h"
namespace Simd
{
#ifdef SIMD_AVX512BW_ENABLE
namespace Avx512bw
{
template <bool align, bool mask> SIMD_INLINE void BackgroundGrowRangeSlow(const uint8_t * value, uint8_t * lo, uint8_t * hi, __mmask64 m = -1)
{
const __m512i _value = Load<align, mask>(value, m);
const __m512i _lo = Load<align, mask>(lo, m);
const __m512i _hi = Load<align, mask>(hi, m);
const __mmask64 inc = _mm512_cmpgt_epu8_mask(_value, _hi);
const __mmask64 dec = _mm512_cmplt_epu8_mask(_value, _lo);
Store<align, mask>(lo, _mm512_mask_subs_epu8(_lo, dec, _lo, K8_01), m);
Store<align, mask>(hi, _mm512_mask_adds_epu8(_hi, inc, _hi, K8_01), m);
}
template <bool align> void BackgroundGrowRangeSlow(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if(align)
{
assert(Aligned(value) && Aligned(valueStride));
assert(Aligned(lo) && Aligned(loStride));
assert(Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for(size_t row = 0; row < height; ++row)
{
size_t col = 0;
for(; col < alignedWidth; col += A)
BackgroundGrowRangeSlow<align, false>(value + col, lo + col, hi + col);
if(col < width)
BackgroundGrowRangeSlow<align, true>(value + col, lo + col, hi + col, tailMask);
value += valueStride;
lo += loStride;
hi += hiStride;
}
}
void BackgroundGrowRangeSlow(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if(Aligned(value) && Aligned(valueStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
BackgroundGrowRangeSlow<true>(value, valueStride, width, height, lo, loStride, hi, hiStride);
else
BackgroundGrowRangeSlow<false>(value, valueStride, width, height, lo, loStride, hi, hiStride);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundGrowRangeFast(const uint8_t * value, uint8_t * lo, uint8_t * hi, __mmask64 m = -1)
{
const __m512i _value = Load<align, mask>(value, m);
const __m512i _lo = Load<align, mask>(lo, m);
const __m512i _hi = Load<align, mask>(hi, m);
Store<align, mask>(lo, _mm512_min_epu8(_lo, _value), m);
Store<align, mask>(hi, _mm512_max_epu8(_hi, _value), m);
}
template <bool align> void BackgroundGrowRangeFast(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if (align)
{
assert(Aligned(value) && Aligned(valueStride));
assert(Aligned(lo) && Aligned(loStride));
assert(Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundGrowRangeFast<align, false>(value + col, lo + col, hi + col);
if (col < width)
BackgroundGrowRangeFast<align, true>(value + col, lo + col, hi + col, tailMask);
value += valueStride;
lo += loStride;
hi += hiStride;
}
}
void BackgroundGrowRangeFast(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if (Aligned(value) && Aligned(valueStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
BackgroundGrowRangeFast<true>(value, valueStride, width, height, lo, loStride, hi, hiStride);
else
BackgroundGrowRangeFast<false>(value, valueStride, width, height, lo, loStride, hi, hiStride);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundIncrementCount(const uint8_t * value,
const uint8_t * loValue, const uint8_t * hiValue, uint8_t * loCount, uint8_t * hiCount, size_t offset, __mmask64 m = -1)
{
const __m512i _value = Load<align, mask>(value + offset, m);
const __m512i _loValue = Load<align, mask>(loValue + offset, m);
const __m512i _loCount = Load<align, mask>(loCount + offset, m);
const __m512i _hiValue = Load<align, mask>(hiValue + offset, m);
const __m512i _hiCount = Load<align, mask>(hiCount + offset, m);
const __mmask64 incLo = _mm512_cmplt_epu8_mask(_value, _loValue);
const __mmask64 incHi = _mm512_cmpgt_epu8_mask(_value, _hiValue);
Store<align, mask>(loCount + offset, _mm512_mask_adds_epu8(_loCount, incLo, _loCount, K8_01), m);
Store<align, mask>(hiCount + offset, _mm512_mask_adds_epu8(_hiCount, incHi, _hiCount, K8_01), m);
}
template <bool align> void BackgroundIncrementCount(const uint8_t * value, size_t valueStride, size_t width, size_t height,
const uint8_t * loValue, size_t loValueStride, const uint8_t * hiValue, size_t hiValueStride,
uint8_t * loCount, size_t loCountStride, uint8_t * hiCount, size_t hiCountStride)
{
if (align)
{
assert(Aligned(value) && Aligned(valueStride));
assert(Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride));
assert(Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundIncrementCount<align, false>(value, loValue, hiValue, loCount, hiCount, col);
if (col < width)
BackgroundIncrementCount<align, true>(value, loValue, hiValue, loCount, hiCount, col, tailMask);
value += valueStride;
loValue += loValueStride;
hiValue += hiValueStride;
loCount += loCountStride;
hiCount += hiCountStride;
}
}
void BackgroundIncrementCount(const uint8_t * value, size_t valueStride, size_t width, size_t height,
const uint8_t * loValue, size_t loValueStride, const uint8_t * hiValue, size_t hiValueStride,
uint8_t * loCount, size_t loCountStride, uint8_t * hiCount, size_t hiCountStride)
{
if (Aligned(value) && Aligned(valueStride) &&
Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride) &&
Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride))
BackgroundIncrementCount<true>(value, valueStride, width, height,
loValue, loValueStride, hiValue, hiValueStride, loCount, loCountStride, hiCount, hiCountStride);
else
BackgroundIncrementCount<false>(value, valueStride, width, height,
loValue, loValueStride, hiValue, hiValueStride, loCount, loCountStride, hiCount, hiCountStride);
}
SIMD_INLINE __m512i AdjustLo(const __m512i & count, const __m512i & value, const __m512i & threshold)
{
const __mmask64 dec = _mm512_cmpgt_epu8_mask(count, threshold);
const __mmask64 inc = _mm512_cmplt_epu8_mask(count, threshold);
__m512i added = _mm512_mask_adds_epu8(value, inc, value, K8_01);
return _mm512_mask_subs_epu8(added, dec, added, K8_01);
}
SIMD_INLINE __m512i AdjustHi(const __m512i & count, const __m512i & value, const __m512i & threshold)
{
const __mmask64 inc = _mm512_cmpgt_epu8_mask(count, threshold);
const __mmask64 dec = _mm512_cmplt_epu8_mask(count, threshold);
__m512i added = _mm512_mask_adds_epu8(value, inc, value, K8_01);
return _mm512_mask_subs_epu8(added, dec, added, K8_01);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundAdjustRange(uint8_t * loCount, uint8_t * loValue,
uint8_t * hiCount, uint8_t * hiValue, const __m512i & threshold, __mmask64 m = -1)
{
const __m512i _loCount = Load<align, mask>(loCount, m);
const __m512i _loValue = Load<align, mask>(loValue, m);
const __m512i _hiCount = Load<align, mask>(hiCount, m);
const __m512i _hiValue = Load<align, mask>(hiValue, m);
Store<align, mask>(loValue, AdjustLo(_loCount, _loValue, threshold), m);
Store<align, mask>(hiValue, AdjustHi(_hiCount, _hiValue, threshold), m);
Store<align, mask>(loCount, K_ZERO, m);
Store<align, mask>(hiCount, K_ZERO, m);
}
template <bool align> void BackgroundAdjustRange(uint8_t * loCount, size_t loCountStride, size_t width, size_t height,
uint8_t * loValue, size_t loValueStride, uint8_t * hiCount, size_t hiCountStride,
uint8_t * hiValue, size_t hiValueStride, uint8_t threshold)
{
if (align)
{
assert(Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride));
assert(Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride));
}
const __m512i _threshold = _mm512_set1_epi8((char)threshold);
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundAdjustRange<align, false>(loCount + col, loValue + col, hiCount + col, hiValue + col, _threshold);
if (col < width)
BackgroundAdjustRange<align, true>(loCount + col, loValue + col, hiCount + col, hiValue + col, _threshold, tailMask);
loValue += loValueStride;
hiValue += hiValueStride;
loCount += loCountStride;
hiCount += hiCountStride;
}
}
void BackgroundAdjustRange(uint8_t * loCount, size_t loCountStride, size_t width, size_t height,
uint8_t * loValue, size_t loValueStride, uint8_t * hiCount, size_t hiCountStride,
uint8_t * hiValue, size_t hiValueStride, uint8_t threshold)
{
if (Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride) &&
Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride))
BackgroundAdjustRange<true>(loCount, loCountStride, width, height, loValue, loValueStride,
hiCount, hiCountStride, hiValue, hiValueStride, threshold);
else
BackgroundAdjustRange<false>(loCount, loCountStride, width, height, loValue, loValueStride,
hiCount, hiCountStride, hiValue, hiValueStride, threshold);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundAdjustRangeMasked(uint8_t * loCount, uint8_t * loValue, uint8_t * hiCount, uint8_t * hiValue,
const uint8_t * pmask, const __m512i & threshold, __mmask64 m = -1)
{
const __m512i _mask = Load<align, mask>(pmask, m);
const __mmask64 mm = _mm512_cmpneq_epu8_mask(_mask, K_ZERO) & m;
const __m512i _loCount = Load<align, mask>(loCount, m);
const __m512i _loValue = Load<align, mask>(loValue, m);
const __m512i _hiCount = Load<align, mask>(hiCount, m);
const __m512i _hiValue = Load<align, mask>(hiValue, m);
Store<align, true>(loValue, AdjustLo(_loCount, _loValue, threshold), mm);
Store<align, true>(hiValue, AdjustHi(_hiCount, _hiValue, threshold), mm);
Store<align, mask>(loCount, K_ZERO, m);
Store<align, mask>(hiCount, K_ZERO, m);
}
template <bool align> void BackgroundAdjustRangeMasked(uint8_t * loCount, size_t loCountStride, size_t width, size_t height,
uint8_t * loValue, size_t loValueStride, uint8_t * hiCount, size_t hiCountStride,
uint8_t * hiValue, size_t hiValueStride, uint8_t threshold, const uint8_t * mask, size_t maskStride)
{
if (align)
{
assert(Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride));
assert(Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride));
assert(Aligned(mask) && Aligned(maskStride));
}
const __m512i _threshold = _mm512_set1_epi8((char)threshold);
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundAdjustRangeMasked<align, false>(loCount + col, loValue + col, hiCount + col, hiValue + col, mask + col, _threshold);
if (col < width)
BackgroundAdjustRangeMasked<align, true>(loCount + col, loValue + col, hiCount + col, hiValue + col, mask + col, _threshold, tailMask);
loValue += loValueStride;
hiValue += hiValueStride;
loCount += loCountStride;
hiCount += hiCountStride;
mask += maskStride;
}
}
void BackgroundAdjustRangeMasked(uint8_t * loCount, size_t loCountStride, size_t width, size_t height,
uint8_t * loValue, size_t loValueStride, uint8_t * hiCount, size_t hiCountStride,
uint8_t * hiValue, size_t hiValueStride, uint8_t threshold, const uint8_t * mask, size_t maskStride)
{
if (Aligned(loValue) && Aligned(loValueStride) && Aligned(hiValue) && Aligned(hiValueStride) &&
Aligned(loCount) && Aligned(loCountStride) && Aligned(hiCount) && Aligned(hiCountStride) &&
Aligned(mask) && Aligned(maskStride))
BackgroundAdjustRangeMasked<true>(loCount, loCountStride, width, height, loValue, loValueStride,
hiCount, hiCountStride, hiValue, hiValueStride, threshold, mask, maskStride);
else
BackgroundAdjustRangeMasked<false>(loCount, loCountStride, width, height, loValue, loValueStride,
hiCount, hiCountStride, hiValue, hiValueStride, threshold, mask, maskStride);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundShiftRange(const uint8_t * value, uint8_t * lo, uint8_t * hi, __mmask64 m = -1)
{
const __m512i _value = Load<align, mask>(value, m);
const __m512i _lo = Load<align, mask>(lo, m);
const __m512i _hi = Load<align, mask>(hi, m);
const __m512i add = _mm512_subs_epu8(_value, _hi);
const __m512i sub = _mm512_subs_epu8(_lo, _value);
Store<align, mask>(lo, _mm512_subs_epu8(_mm512_adds_epu8(_lo, add), sub), m);
Store<align, mask>(hi, _mm512_subs_epu8(_mm512_adds_epu8(_hi, add), sub), m);
}
template <bool align> void BackgroundShiftRange(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if (align)
{
assert(Aligned(value) && Aligned(valueStride));
assert(Aligned(lo) && Aligned(loStride));
assert(Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundShiftRange<align, false>(value + col, lo + col, hi + col);
if (col < width)
BackgroundShiftRange<align, true>(value + col, lo + col, hi + col, tailMask);
value += valueStride;
lo += loStride;
hi += hiStride;
}
}
void BackgroundShiftRange(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride)
{
if (Aligned(value) && Aligned(valueStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
BackgroundShiftRange<true>(value, valueStride, width, height, lo, loStride, hi, hiStride);
else
BackgroundShiftRange<false>(value, valueStride, width, height, lo, loStride, hi, hiStride);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundShiftRangeMasked(const uint8_t * value, uint8_t * lo, uint8_t * hi,
const uint8_t * pmask, __mmask64 m = -1)
{
const __m512i _mask = Load<align, mask>(pmask, m);
const __mmask64 mm = _mm512_cmpneq_epu8_mask(_mask, K_ZERO) & m;
const __m512i _value = Load<align, mask>(value, m);
const __m512i _lo = Load<align, mask>(lo, m);
const __m512i _hi = Load<align, mask>(hi, m);
const __m512i add = _mm512_subs_epu8(_value, _hi);
const __m512i sub = _mm512_subs_epu8(_lo, _value);
Store<align, true>(lo, _mm512_subs_epu8(_mm512_adds_epu8(_lo, add), sub), mm);
Store<align, true>(hi, _mm512_subs_epu8(_mm512_adds_epu8(_hi, add), sub), mm);
}
template <bool align> void BackgroundShiftRangeMasked(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride, const uint8_t * mask, size_t maskStride)
{
if (align)
{
assert(Aligned(value) && Aligned(valueStride));
assert(Aligned(lo) && Aligned(loStride));
assert(Aligned(hi) && Aligned(hiStride));
assert(Aligned(mask) && Aligned(maskStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundShiftRangeMasked<align, false>(value + col, lo + col, hi + col, mask + col);
if (col < width)
BackgroundShiftRangeMasked<align, true>(value + col, lo + col, hi + col, mask + col, tailMask);
value += valueStride;
lo += loStride;
hi += hiStride;
mask += maskStride;
}
}
void BackgroundShiftRangeMasked(const uint8_t * value, size_t valueStride, size_t width, size_t height,
uint8_t * lo, size_t loStride, uint8_t * hi, size_t hiStride, const uint8_t * mask, size_t maskStride)
{
if (Aligned(value) && Aligned(valueStride) && Aligned(lo) && Aligned(loStride) &&
Aligned(hi) && Aligned(hiStride) && Aligned(mask) && Aligned(maskStride))
BackgroundShiftRangeMasked<true>(value, valueStride, width, height, lo, loStride, hi, hiStride, mask, maskStride);
else
BackgroundShiftRangeMasked<false>(value, valueStride, width, height, lo, loStride, hi, hiStride, mask, maskStride);
}
template <bool align, bool mask> SIMD_INLINE void BackgroundInitMask(const uint8_t * src, uint8_t * dst, const __m512i & index, const __m512i & value, __mmask64 m = -1)
{
__m512i _src = Load<align, mask>(src, m);
__mmask64 mm = _mm512_cmpeq_epu8_mask(_src, index) & m;
Store<align, true>(dst, value, mm);
}
template <bool align> void BackgroundInitMask(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t index, uint8_t value, uint8_t * dst, size_t dstStride)
{
if (align)
{
assert(Aligned(src) && Aligned(srcStride));
assert(Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
__mmask64 tailMask = TailMask64(width - alignedWidth);
__m512i _index = _mm512_set1_epi8(index);
__m512i _value = _mm512_set1_epi8(value);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += A)
BackgroundInitMask<align, false>(src + col, dst + col, _index, _value);
if (col < width)
BackgroundInitMask<align, true>(src + col, dst + col, _index, _value, tailMask);
src += srcStride;
dst += dstStride;
}
}
void BackgroundInitMask(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t index, uint8_t value, uint8_t * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
BackgroundInitMask<true>(src, srcStride, width, height, index, value, dst, dstStride);
else
BackgroundInitMask<false>(src, srcStride, width, height, index, value, dst, dstStride);
}
}
#endif// SIMD_AVX512BW_ENABLE
}
| 46.282276
| 171
| 0.678597
|
aestesis
|
449c7154ca945846417d9f3cd49227380218180d
| 18,771
|
cpp
|
C++
|
XDKSamples/Audio/SimpleSpatialPlaySoundXDK/SimpleSpatialPlaySoundXDK.cpp
|
dephora/Xbox-ATG-Samples
|
31e482c9e23def36073542ce614a0f0b145d7112
|
[
"MIT"
] | null | null | null |
XDKSamples/Audio/SimpleSpatialPlaySoundXDK/SimpleSpatialPlaySoundXDK.cpp
|
dephora/Xbox-ATG-Samples
|
31e482c9e23def36073542ce614a0f0b145d7112
|
[
"MIT"
] | null | null | null |
XDKSamples/Audio/SimpleSpatialPlaySoundXDK/SimpleSpatialPlaySoundXDK.cpp
|
dephora/Xbox-ATG-Samples
|
31e482c9e23def36073542ce614a0f0b145d7112
|
[
"MIT"
] | 1
|
2020-07-30T11:13:23.000Z
|
2020-07-30T11:13:23.000Z
|
//--------------------------------------------------------------------------------------
// SimpleSpatialPlaySoundXDK.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleSpatialPlaySoundXDK.h"
#include "ATGColors.h"
#include "ControllerFont.h"
#include "WAVFileReader.h"
namespace
{
const LPCWSTR g_FileList[] =
{
L"Jungle_RainThunder_mix714.wav",
L"ChannelIDs714.wav",
};
const int numFiles = _countof(g_FileList);
}
extern void ExitSample() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
VOID CALLBACK SpatialWorkCallback(_Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _Inout_ PTP_WORK Work)
{
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
Sample * Sink = (Sample *)Context;
Work;
Instance;
while (Sink->m_bThreadActive)
{
while (Sink->m_bPlayingSound && Sink->m_Renderer->IsActive())
{
// Wait for a signal from the audio-engine to start the next processing pass
if (WaitForSingleObject(Sink->m_Renderer->m_bufferCompletionEvent, 100) != WAIT_OBJECT_0)
{
//make a call to stream to see why we didn't get a signal after 100ms
hr = Sink->m_Renderer->m_SpatialAudioStream->Reset();
//if we have a stream error, set the renderer state to reset
if (hr != S_OK)
{
Sink->m_Renderer->Reset();
}
continue;
}
UINT32 frameCount;
UINT32 availableObjectCount;
// Begin the process of sending object data and metadata
// Get the number of active object that can be used to send object-data
// Get the number of frame count that each buffer be filled with
hr = Sink->m_Renderer->m_SpatialAudioStream->BeginUpdatingAudioObjects(
&availableObjectCount,
&frameCount);
//if we have a stream error, set the renderer state to reset
if (hr != S_OK)
{
Sink->m_Renderer->Reset();
}
Sink->m_availableObjects = availableObjectCount;
for (int chan = 0; chan < MAX_CHANNELS; chan++)
{
//Activate the object if not yet done
if (Sink->WavChannels[chan].object == nullptr)
{
// If this method called more than activeObjectCount times
// It will fail with this error HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)
hr = Sink->m_Renderer->m_SpatialAudioStream->ActivateSpatialAudioObject(
Sink->WavChannels[chan].objType,
&Sink->WavChannels[chan].object);
if (FAILED(hr))
{
continue;
}
}
//Get the object buffer
BYTE* buffer = nullptr;
UINT32 bytecount;
hr = Sink->WavChannels[chan].object->GetBuffer(&buffer, &bytecount);
if (FAILED(hr))
{
continue;
}
Sink->WavChannels[chan].object->SetVolume(Sink->WavChannels[chan].volume);
UINT32 readsize = bytecount;
for (UINT32 i = 0; i < readsize; i++)
{
UINT32 fileLoc = Sink->WavChannels[chan].curBufferLoc;
if (chan < Sink->m_numChannels)
{
buffer[i] = Sink->WavChannels[chan].wavBuffer[fileLoc];
}
else
{
buffer[i] = 0;
}
Sink->WavChannels[chan].curBufferLoc++;
if (Sink->WavChannels[chan].curBufferLoc == Sink->WavChannels[chan].buffersize)
{
Sink->WavChannels[chan].curBufferLoc = 0;
}
}
}
// Let the audio-engine know that the object data are available for processing now
hr = Sink->m_Renderer->m_SpatialAudioStream->EndUpdatingAudioObjects();
if (FAILED(hr))
{
Sink->m_Renderer->Reset();
continue;
}
}
}
}
}
Sample::Sample() :
m_numChannels(0),
WavChannels{},
m_bThreadActive(false),
m_bPlayingSound(false),
m_availableObjects(0),
m_frame(0),
m_fileLoaded(false),
m_curFile(0),
m_workThread(nullptr)
{
m_deviceResources = std::make_unique<DX::DeviceResources>();
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(IUnknown* window)
{
m_gamePad = std::make_unique<GamePad>();
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
InitializeSpatialStream();
SetChannelPosVolumes();
for (UINT32 i = 0; i < MAX_CHANNELS; i++)
{
WavChannels[i].buffersize = 0;
WavChannels[i].curBufferLoc = 0;
WavChannels[i].object = nullptr;
}
m_fileLoaded = LoadFile(g_FileList[m_curFile]);
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %I64u", m_frame);
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
PIXEndEvent();
m_frame++;
}
// Updates the world.
void Sample::Update(DX::StepTimer const&)
{
PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update");
//Are we resetting the renderer? This will happen if we get an invalid stream
// which can happen when render mode changes or device changes
if (m_Renderer->IsResetting())
{
//clear out renderer
m_Renderer.Reset();
// Create a new ISAC instance
m_Renderer = Microsoft::WRL::Make<ISACRenderer>();
// Initialize Default Audio Device
m_Renderer->InitializeAudioDeviceAsync();
//Reset all the Objects that were being used
for (int chan = 0; chan < MAX_CHANNELS; chan++)
{
WavChannels[chan].object = nullptr;
}
}
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
m_gamePadButtons.Update(pad);
if (pad.IsViewPressed())
{
ExitSample();
}
if (m_gamePadButtons.a == m_gamePadButtons.RELEASED)
{
//if we have an active renderer
if (m_Renderer && m_Renderer->IsActive())
{
//Start spatial worker thread
if (!m_bThreadActive)
{
//reload file to start again
m_fileLoaded = LoadFile(g_FileList[m_curFile]);
//startup spatial thread
m_bThreadActive = true;
m_bPlayingSound = true;
m_workThread = CreateThreadpoolWork(SpatialWorkCallback, this, nullptr);
SubmitThreadpoolWork(m_workThread);
}
else
{
//stop and shutdown spatial worker thread
m_bThreadActive = false;
m_bPlayingSound = false;
WaitForThreadpoolWorkCallbacks(m_workThread, FALSE);
CloseThreadpoolWork(m_workThread);
m_workThread = nullptr;
}
}
}
else if (m_gamePadButtons.b == m_gamePadButtons.RELEASED)
{
//if we have an active renderer
if (m_Renderer && m_Renderer->IsActive())
{
//if spatial thread active and playing, shutdown and start new file
if (m_bThreadActive && m_bPlayingSound)
{
m_bThreadActive = false;
m_bPlayingSound = false;
WaitForThreadpoolWorkCallbacks(m_workThread, FALSE);
CloseThreadpoolWork(m_workThread);
m_workThread = nullptr;
//load next file
m_curFile++;
if (m_curFile == numFiles) m_curFile = 0;
m_fileLoaded = LoadFile(g_FileList[m_curFile]);
//if successfully loaded, start up thread and playing new file
if (m_fileLoaded)
{
m_bThreadActive = true;
m_bPlayingSound = true;
m_workThread = CreateThreadpoolWork(SpatialWorkCallback, this, nullptr);
SubmitThreadpoolWork(m_workThread);
}
}
else
{
//if thread active but paused, shutdown thread to load new file
if (m_bThreadActive)
{
m_bThreadActive = false;
m_bPlayingSound = false;
WaitForThreadpoolWorkCallbacks(m_workThread, FALSE);
CloseThreadpoolWork(m_workThread);
m_workThread = nullptr;
}
//load next file
m_curFile++;
if (m_curFile == numFiles) m_curFile = 0;
m_fileLoaded = LoadFile(g_FileList[m_curFile]);
}
}
}
}
else
{
m_gamePadButtons.Reset();
}
PIXEndEvent();
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the render target to render a new frame.
m_deviceResources->Prepare();
Clear();
auto context = m_deviceResources->GetD3DDeviceContext();
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Render");
auto rect = m_deviceResources->GetOutputSize();
auto safeRect = SimpleMath::Viewport::ComputeTitleSafeArea(rect.right, rect.bottom);
XMFLOAT2 pos(float(safeRect.left), float(safeRect.top));
m_spriteBatch->Begin();
float spacing = m_font->GetLineSpacing();
m_font->DrawString(m_spriteBatch.get(), L"Simple Spatial Playback:", pos, ATG::Colors::White);
pos.y += spacing * 1.5f;
if (!m_Renderer->IsActive())
{
m_font->DrawString(m_spriteBatch.get(), L"Spatial Renderer Not Available", pos, ATG::Colors::Orange);
pos.y += spacing * 2.f;
}
else
{
wchar_t str[256] = {};
swprintf_s(str, L" File: %ls", g_FileList[m_curFile]);
m_font->DrawString(m_spriteBatch.get(), str, pos, ATG::Colors::White);
pos.y += spacing;
swprintf_s(str, L" State: %ls", ((m_bPlayingSound) ? L"Playing" : L"Stopped"));
m_font->DrawString(m_spriteBatch.get(), str, pos, ATG::Colors::White);
pos.y += spacing * 1.5f;
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Use [A] to start/stop playback", pos, ATG::Colors::White);
pos.y += spacing;
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Use [B] to change to next file", pos, ATG::Colors::White);
pos.y += spacing;
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Use [View] to exit", pos, ATG::Colors::White);
}
m_spriteBatch->End();
PIXEndEvent(context);
// Show the new frame.
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Present");
m_deviceResources->Present();
m_graphicsMemory->Commit();
PIXEndEvent(context);
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto context = m_deviceResources->GetD3DDeviceContext();
PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Clear");
// Clear the views.
auto renderTarget = m_deviceResources->GetRenderTargetView();
auto depthStencil = m_deviceResources->GetDepthStencilView();
context->ClearRenderTargetView(renderTarget, ATG::Colors::Background);
context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
context->OMSetRenderTargets(1, &renderTarget, depthStencil);
// Set the viewport.
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
PIXEndEvent(context);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnSuspending()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Suspend(0);
}
void Sample::OnResuming()
{
auto context = m_deviceResources->GetD3DDeviceContext();
context->Resume();
m_timer.ResetElapsedTime();
m_gamePadButtons.Reset();
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount());
auto context = m_deviceResources->GetD3DDeviceContext();
m_spriteBatch = std::make_unique<SpriteBatch>(context);
m_font = std::make_unique<SpriteFont>(device, L"SegoeUI_18.spritefont");
m_ctrlFont = std::make_unique<SpriteFont>(device, L"XboxOneControllerSmall.spritefont");
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
}
#pragma endregion
HRESULT Sample::InitializeSpatialStream(void)
{
HRESULT hr = S_OK;
if (!m_Renderer)
{
// Create a new ISAC instance
m_Renderer = Microsoft::WRL::Make<ISACRenderer>();
// Selects the Default Audio Device
hr = m_Renderer->InitializeAudioDeviceAsync();
}
return hr;
}
bool Sample::LoadFile(LPCWSTR inFile)
{
//clear and reset wavchannels
for (UINT32 i = 0; i < MAX_CHANNELS; i++)
{
if (WavChannels[i].buffersize)
{
delete[] WavChannels[i].wavBuffer;
}
WavChannels[i].buffersize = 0;
WavChannels[i].curBufferLoc = 0;
WavChannels[i].object = nullptr;
}
HRESULT hr = S_OK;
std::unique_ptr<uint8_t[]> m_waveFile;
DX::WAVData WavData;
hr = DX::LoadWAVAudioFromFileEx(inFile, m_waveFile, WavData);
if (FAILED(hr))
{
return false;
}
if ((WavData.wfx->wFormatTag == 1 || WavData.wfx->wFormatTag == 65534) && WavData.wfx->nSamplesPerSec == 48000)
{
m_numChannels = WavData.wfx->nChannels;
int numSamples = WavData.audioBytes / (2 * m_numChannels);
for (int i = 0; i < m_numChannels; i++)
{
WavChannels[i].wavBuffer = new char[numSamples * 4];
WavChannels[i].buffersize = numSamples * 4;
}
float * tempnew;
short * tempdata = (short *)WavData.startAudio;
for (int i = 0; i < numSamples; i++)
{
for (int j = 0; j < m_numChannels; j++)
{
int chan = j;
tempnew = (float *)WavChannels[chan].wavBuffer;
int sample = (i * m_numChannels) + chan;
tempnew[i] = (float)tempdata[sample] / 32768;
}
}
}
else if ((WavData.wfx->wFormatTag == 3) && WavData.wfx->nSamplesPerSec == 48000)
{
m_numChannels = WavData.wfx->nChannels;
int numSamples = WavData.audioBytes / (4 * m_numChannels);
for (int i = 0; i < m_numChannels; i++)
{
WavChannels[i].wavBuffer = new char[numSamples * 4];
WavChannels[i].buffersize = numSamples * 4;
}
float * tempnew;
float * tempdata = (float *)WavData.startAudio;
for (int i = 0; i < numSamples; i++)
{
for (int j = 0; j < m_numChannels; j++)
{
int chan = j;
tempnew = (float *)WavChannels[chan].wavBuffer;
int sample = (i * m_numChannels) + chan;
tempnew[i] = (float)tempdata[sample];
}
}
}
else
{
return false;
}
return true;
}
void Sample::SetChannelPosVolumes(void)
{
WavChannels[0].volume = 1.f;
WavChannels[0].objType = AudioObjectType_FrontLeft;
WavChannels[1].volume = 1.f;
WavChannels[1].objType = AudioObjectType_FrontRight;
WavChannels[2].volume = 1.f;
WavChannels[2].objType = AudioObjectType_FrontCenter;
WavChannels[3].volume = 1.f;
WavChannels[3].objType = AudioObjectType_LowFrequency;
WavChannels[4].volume = 1.f;
WavChannels[4].objType = AudioObjectType_BackLeft;
WavChannels[5].volume = 1.f;
WavChannels[5].objType = AudioObjectType_BackRight;
WavChannels[6].volume = 1.f;
WavChannels[6].objType = AudioObjectType_SideLeft;
WavChannels[7].volume = 1.f;
WavChannels[7].objType = AudioObjectType_SideRight;
WavChannels[8].volume = 1.f;
WavChannels[8].objType = AudioObjectType_TopFrontLeft;
WavChannels[9].volume = 1.f;
WavChannels[9].objType = AudioObjectType_TopFrontRight;
WavChannels[10].volume = 1.f;
WavChannels[10].objType = AudioObjectType_TopBackLeft;
WavChannels[11].volume = 1.f;
WavChannels[11].objType = AudioObjectType_TopBackRight;
}
| 32.363793
| 147
| 0.544883
|
dephora
|
449d53cb90ea98c78591551c0671486171fef3ed
| 10,993
|
hpp
|
C++
|
glx_parse.hpp
|
degarashi/resonant
|
f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a
|
[
"MIT"
] | null | null | null |
glx_parse.hpp
|
degarashi/resonant
|
f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a
|
[
"MIT"
] | null | null | null |
glx_parse.hpp
|
degarashi/resonant
|
f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a
|
[
"MIT"
] | null | null | null |
#pragma once
#define BOOST_NO_CXX11_DECLTYPE_N3276
#include "glhead.hpp"
#include "glx_macro.hpp"
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/optional.hpp>
#include <iostream>
#include <string>
#define TRANSFORM_STRUCT_MEMBER(ign, name, member) (decltype(name::member), member)
#define FUSION_ADAPT_STRUCT_AUTO(name, members) \
BOOST_FUSION_ADAPT_STRUCT(name, BOOST_PP_SEQ_FOR_EACH(TRANSFORM_STRUCT_MEMBER, name, members))
#define DEF_TYPE(typ, name, seq) struct typ##_ : x3::symbols<unsigned> { \
enum TYPE { BOOST_PP_SEQ_FOR_EACH(PPFUNC_ENUM, T, seq) }; \
const static char* cs_typeStr[BOOST_PP_SEQ_SIZE(seq)]; \
typ##_(): x3::symbols<unsigned>(std::string(name)) { \
add \
BOOST_PP_SEQ_FOR_EACH(PPFUNC_ADD, T, seq); } }; \
extern const typ##_ typ;
namespace rs {
enum class VSem : unsigned int {
BOOST_PP_SEQ_ENUM(SEQ_VSEM),
NUM_SEMANTIC
};
}
using namespace boost::spirit;
namespace rs {
// ---------------- GLXシンボルリスト ----------------
//! GLSL変数型
DEF_TYPE(GLType, "GLSL-ValueType", SEQ_GLTYPE)
//! GLSL変数入出力フラグ
DEF_TYPE(GLInout, "InOut-Flag", SEQ_INOUT)
//! GLSL頂点セマンティクス
DEF_TYPE(GLSem, "VertexSemantics", SEQ_VSEM)
//! GLSL浮動小数点数精度
DEF_TYPE(GLPrecision, "PrecisionFlag", SEQ_PRECISION)
//! boolでフラグを切り替える項目
struct GLBoolsetting_ : x3::symbols<unsigned> {
GLBoolsetting_(): x3::symbols<unsigned>(std::string("BooleanSettingName")) {
add("cullface", GL_CULL_FACE)
("polyoffsetfill", GL_POLYGON_OFFSET_FILL)
("scissortest", GL_SCISSOR_TEST)
("samplealphatocoverage", GL_SAMPLE_ALPHA_TO_COVERAGE)
("samplecoverage", GL_SAMPLE_COVERAGE)
("stenciltest", GL_STENCIL_TEST)
("depthtest", GL_DEPTH_TEST)
("blend", GL_BLEND)
("dither", GL_DITHER);
}
};
struct GLFillMode_ : x3::symbols<unsigned> {
GLFillMode_(): x3::symbols<unsigned>(std::string("FillMode")) {
add("point", GL_POINT)
("line", GL_LINE)
("fill", GL_FILL);
}
};
//! 数値指定するタイプの設定項目フラグ
struct GLSetting_ : x3::symbols<unsigned> {
enum TYPE : unsigned { BOOST_PP_SEQ_FOR_EACH(PPFUNC_GLSET_ENUM, T, SEQ_GLSETTING) };
const static char* cs_typeStr[BOOST_PP_SEQ_SIZE(SEQ_GLSETTING)];
GLSetting_(): x3::symbols<unsigned>(std::string("SettingName")) {
add
BOOST_PP_SEQ_FOR_EACH(PPFUNC_GLSET_ADD, T, SEQ_GLSETTING);
}
};
//! 設定項目毎に用意したほうがいい?
struct GLStencilop_ : x3::symbols<unsigned> {
GLStencilop_(): x3::symbols<unsigned>(std::string("StencilOperator")) {
add("keep", GL_KEEP)
("zero", GL_ZERO)
("replace", GL_REPLACE)
("increment", GL_INCR)
("decrement", GL_DECR)
("invert", GL_INVERT)
("incrementwrap", GL_INCR_WRAP)
("decrementwrap", GL_DECR_WRAP);
}
};
struct GLFunc_ : x3::symbols<unsigned> {
GLFunc_(): x3::symbols<unsigned>(std::string("CompareFunction")) {
add("never", GL_NEVER)
("always", GL_ALWAYS)
("less", GL_LESS)
("lessequal", GL_LEQUAL)
("equal", GL_EQUAL)
("greater", GL_GREATER)
("greaterequal", GL_GEQUAL)
("notequal", GL_NOTEQUAL);
}
};
struct GLEq_ : x3::symbols<unsigned> {
GLEq_(): x3::symbols<unsigned>(std::string("BlendEquation")) {
add("add", GL_FUNC_ADD)
("subtract", GL_FUNC_SUBTRACT)
("invsubtract", GL_FUNC_REVERSE_SUBTRACT);
}
};
struct GLBlend_ : x3::symbols<unsigned> {
GLBlend_(): x3::symbols<unsigned>(std::string("BlendOperator")) {
add("zero", GL_ZERO)
("one", GL_ONE)
("invsrccolor", GL_ONE_MINUS_SRC_COLOR)
("invdstcolor", GL_ONE_MINUS_DST_COLOR)
("srccolor", GL_SRC_COLOR)
("dstcolor", GL_DST_COLOR)
("invsrcalpha", GL_ONE_MINUS_SRC_ALPHA)
("invdstalpha", GL_ONE_MINUS_DST_ALPHA)
("srcalpha", GL_SRC_ALPHA)
("dstalpha", GL_DST_ALPHA)
("invconstantalpha", GL_ONE_MINUS_CONSTANT_ALPHA)
("constantalpha", GL_CONSTANT_ALPHA)
("srcalphasaturate", GL_SRC_ALPHA_SATURATE);
}
};
struct GLFace_ : x3::symbols<unsigned> {
GLFace_(): x3::symbols<unsigned>(std::string("Face(Front or Back)")) {
add("front", GL_FRONT)
("back", GL_BACK)
("frontandback", GL_FRONT_AND_BACK);
}
};
struct GLFacedir_ : x3::symbols<unsigned> {
GLFacedir_(): x3::symbols<unsigned>(std::string("FaceDir")) {
add("ccw", GL_CCW)
("cw", GL_CW);
}
};
struct GLColormask_ : x3::symbols<unsigned> {
GLColormask_(): x3::symbols<unsigned>(std::string("ColorMask")) {
add("r", 0x08)
("g", 0x04)
("b", 0x02)
("a", 0x01);
}
};
struct GLShadertype_ : x3::symbols<unsigned> {
GLShadertype_(): x3::symbols<unsigned>(std::string("ShaderType")) {
add("vertexshader", (unsigned)rs::ShType::VERTEX)
("fragmentshader", (unsigned)rs::ShType::FRAGMENT)
("geometryshader", (unsigned)rs::ShType::GEOMETRY);
}
};
//! 変数ブロックタイプ
DEF_TYPE(GLBlocktype, "BlockType", SEQ_BLOCK)
extern const GLSetting_ GLSetting;
extern const GLBoolsetting_ GLBoolsetting;
extern const GLFillMode_ GLFillMode;
extern const GLStencilop_ GLStencilop;
extern const GLFunc_ GLFunc;
extern const GLEq_ GLEq;
extern const GLBlend_ GLBlend;
extern const GLFace_ GLFace;
extern const GLFacedir_ GLFacedir;
extern const GLColormask_ GLColormask;
extern const GLShadertype_ GLShadertype;
// ---------------- GLX構文解析データ ----------------
struct EntryBase {
boost::optional<unsigned> prec;
int type;
std::string name;
};
std::ostream& operator << (std::ostream& os, const EntryBase& e);
//! Attribute宣言エントリ
struct AttrEntry : EntryBase {
unsigned sem;
};
std::ostream& operator << (std::ostream& os, const AttrEntry& e);
//! Varying宣言エントリ
struct VaryEntry : EntryBase {
boost::optional<int> arraySize;
};
std::ostream& operator << (std::ostream& os, const VaryEntry& e);
//! Uniform宣言エントリ
struct UnifEntry : EntryBase {
boost::optional<int> arraySize;
boost::optional<boost::variant<std::vector<float>, float, bool>> defStr;
};
std::ostream& operator << (std::ostream& os, const UnifEntry& e);
//! Const宣言エントリ
struct ConstEntry : EntryBase {
boost::variant<bool, float, std::vector<float>> defVal;
};
std::ostream& operator << (std::ostream& os, const ConstEntry& e);
//! Bool設定項目エントリ
struct BoolSetting {
GLuint type; //!< 設定項目ID
bool value; //!< 設定値ID or 数値
};
std::ostream& operator << (std::ostream& os, const BoolSetting& s);
//! 数値設定エントリ
struct ValueSetting {
using ValueT = boost::variant<boost::blank, unsigned int,float,bool>;
unsigned type;
std::vector<ValueT> value;
};
std::ostream& operator << (std::ostream& os, const ValueSetting& s);
//! 変数ブロック使用宣言
struct BlockUse {
unsigned type; // Attr,Vary,Unif,Const
bool bAdd;
std::vector<std::string> name;
};
std::ostream& operator << (std::ostream& os, const BlockUse& b);
//! シェーダー設定エントリ
struct ShSetting {
int type;
std::string shName;
// 引数指定
std::vector<boost::variant<std::vector<float>, float, bool>> args;
};
std::ostream& operator << (std::ostream& os, const ShSetting& s);
//! マクロ宣言エントリ
struct MacroEntry {
std::string fromStr;
boost::optional<std::string> toStr;
};
std::ostream& operator << (std::ostream& os, const MacroEntry& e);
template <class Ent>
struct Struct {
std::string name;
std::vector<std::string> derive;
std::vector<Ent> entry;
Struct() = default;
Struct(const Struct& a) = default;
Struct(Struct&& a): Struct() { swap(a); }
Struct& operator = (const Struct& a) {
this->~Struct();
new(this) Struct(a);
return *this;
}
void swap(Struct& a) noexcept {
std::swap(name, a.name);
std::swap(derive, a.derive);
std::swap(entry, a.entry);
}
void iterate(std::function<void (const Ent&)> cb) const {
for(const auto& e : entry)
cb(e);
}
void output(std::ostream& os) const {
using std::endl;
// print name
os << '"' << name << '"' << endl;
// print derives
os << "derives: ";
for(auto& d : derive)
os << d << ", ";
os << endl;
// print entries
for(auto& e : entry) {
os << e << endl;
}
}
};
using AttrStruct = Struct<AttrEntry>;
using VaryStruct = Struct<VaryEntry>;
using UnifStruct = Struct<UnifEntry>;
using ConstStruct = Struct<ConstEntry>;
template <class T>
std::ostream& operator << (std::ostream& os, const Struct<T>& s) {
s.output(os);
return os;
}
struct ArgItem {
int type;
std::string name;
};
using StrV = std::vector<std::string>;
struct ShStruct {
//! シェーダータイプ
uint32_t type;
//! バージョン文字列
std::string version_str;
//! 組み込みコードブロック名
StrV code;
//! シェーダー名
std::string name;
//! 引数群(型ID + 名前)
std::vector<ArgItem> args;
//! シェーダーの中身(文字列)
std::string info;
mutable std::string info_str; //!< シェーダー文字列を1つに纏めた物
const std::string& getShaderString() const;
};
struct CodeStruct {
//! コードブロック名
std::string name;
//! シェーダーコード文字列
std::string info;
};
std::ostream& operator << (std::ostream& os, const CodeStruct& t);
template <typename T>
using NameMap = std::map<std::string, T>;
//! Tech,Pass
struct TPStruct;
struct TPStruct {
std::string name;
std::vector<BlockUse> blkL;
std::vector<BoolSetting> bsL;
std::vector<MacroEntry> mcL;
std::vector<ShSetting> shL;
std::vector<boost::recursive_wrapper<TPStruct>> tpL;
std::vector<ValueSetting> vsL;
std::vector<std::string> derive;
};
std::ostream& operator << (std::ostream& os, const TPStruct& t);
//! エフェクト全般
struct GLXStruct {
NameMap<AttrStruct> atM;
NameMap<ConstStruct> csM;
NameMap<ShStruct> shM;
std::vector<TPStruct> tpL;
NameMap<UnifStruct> uniM;
NameMap<VaryStruct> varM;
NameMap<CodeStruct> codeM;
std::vector<std::string> incl;
};
std::ostream& operator << (std::ostream& os, const GLXStruct& glx);
GLXStruct ParseGlx(std::string str);
}
FUSION_ADAPT_STRUCT_AUTO(rs::AttrEntry, (prec)(type)(name)(sem))
FUSION_ADAPT_STRUCT_AUTO(rs::VaryEntry, (prec)(type)(name)(arraySize))
FUSION_ADAPT_STRUCT_AUTO(rs::UnifEntry, (prec)(type)(name)(arraySize)(defStr))
FUSION_ADAPT_STRUCT_AUTO(rs::ConstEntry, (prec)(type)(name)(defVal))
FUSION_ADAPT_STRUCT_AUTO(rs::BoolSetting, (type)(value))
FUSION_ADAPT_STRUCT_AUTO(rs::ValueSetting, (type)(value))
FUSION_ADAPT_STRUCT_AUTO(rs::ShSetting, (type)(shName)(args))
FUSION_ADAPT_STRUCT_AUTO(rs::MacroEntry, (fromStr)(toStr))
FUSION_ADAPT_STRUCT_AUTO(rs::AttrStruct, (name)(derive)(entry))
FUSION_ADAPT_STRUCT_AUTO(rs::VaryStruct, (name)(derive)(entry))
FUSION_ADAPT_STRUCT_AUTO(rs::UnifStruct, (name)(derive)(entry))
FUSION_ADAPT_STRUCT_AUTO(rs::ConstStruct, (name)(derive)(entry))
FUSION_ADAPT_STRUCT_AUTO(rs::ShStruct, (type)(version_str)(name)(args)(info))
FUSION_ADAPT_STRUCT_AUTO(rs::TPStruct, (name)(blkL)(bsL)(mcL)(shL)(tpL)(vsL)(derive))
FUSION_ADAPT_STRUCT_AUTO(rs::GLXStruct, (atM)(csM)(shM)(tpL)(uniM)(varM)(incl))
FUSION_ADAPT_STRUCT_AUTO(rs::ArgItem, (type)(name))
FUSION_ADAPT_STRUCT_AUTO(rs::BlockUse, (type)(bAdd)(name))
| 30.62117
| 95
| 0.67825
|
degarashi
|
449fed2a69fe430949e7d60839d6d000354b2387
| 1,127
|
cpp
|
C++
|
dev/dll/MUXControlsFactory.cpp
|
micahl/microsoft-ui-xaml
|
75ea41ee0847af715aa2ddad5dd2027f393b1e6b
|
[
"MIT"
] | 2
|
2019-08-26T17:16:26.000Z
|
2020-04-30T20:31:20.000Z
|
dev/dll/MUXControlsFactory.cpp
|
chingucoding/microsoft-ui-xaml
|
9c623fec308f1c081afbff2563e2acdff92729c3
|
[
"MIT"
] | null | null | null |
dev/dll/MUXControlsFactory.cpp
|
chingucoding/microsoft-ui-xaml
|
9c623fec308f1c081afbff2563e2acdff92729c3
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include "XamlMetadataProvider.h"
#include "MUXControlsFactory.h"
#ifdef MATERIALS_INCLUDED
#include "RevealBrush.h"
#endif
bool MUXControlsFactory::s_initialized{ false };
void MUXControlsFactory::EnsureInitialized()
{
if (!s_initialized)
{
// Need to register here the DPs of types which are not referenced in our XAML but whose attached properties are.
#ifdef MATERIALS_INCLUDED
if (SharedHelpers::IsXamlCompositionBrushBaseAvailable())
{
// These are only needed on RS2+.
RevealBrush::EnsureProperties();
}
#endif
s_initialized = true;
}
}
void MUXControlsFactory::VerifyInitialized()
{
if (!s_initialized)
{
throw winrt::hresult_error(E_FAIL, L"ERROR: You must put an instance of " MUXCONTROLSROOT_NAMESPACE_STR ".XamlControlsResources in your Application.Resources.MergedDictionaries.");
}
}
| 29.657895
| 189
| 0.692103
|
micahl
|
44a36b42047385d80544a250dec84cbf129c391a
| 200
|
hpp
|
C++
|
book/cpp_templates/tmplbook/inherit/person.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
book/cpp_templates/tmplbook/inherit/person.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
book/cpp_templates/tmplbook/inherit/person.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
struct Person {
std::string firstName;
std::string lastName;
friend std::ostream& operator<<(std::ostream& strm, Person const& p) {
return strm << p.lastName << ", " << p.firstName;
}
};
| 22.222222
| 72
| 0.63
|
houruixiang
|
44a69a20b8594d30a187b8835b2249035fcaa1f8
| 558
|
hpp
|
C++
|
headers/CameraComponent.hpp
|
bDiazCentro/AlchemyFramework
|
6b55cdef1d0b9ddb4248382e44bbbfdb8320f062
|
[
"MIT"
] | null | null | null |
headers/CameraComponent.hpp
|
bDiazCentro/AlchemyFramework
|
6b55cdef1d0b9ddb4248382e44bbbfdb8320f062
|
[
"MIT"
] | null | null | null |
headers/CameraComponent.hpp
|
bDiazCentro/AlchemyFramework
|
6b55cdef1d0b9ddb4248382e44bbbfdb8320f062
|
[
"MIT"
] | null | null | null |
#ifndef CAMERA_COMPONENT_H
#define CAMERA_COMPONENT_H
enum Projection {ORTHOGRAPHIC, PERSPECTIVE};
class Object;
class TransformComponent;
class CameraComponent
{
private:
Object *father;
TransformComponent *lookTarget;
public:
Projection projection = Projection::ORTHOGRAPHIC;
float fov;
float near;
float far;
int cameraId;
bool active;
void Debug();
void Update();
Object Father();
void Father(Object *obj);
void LookAt(TransformComponent *target);
CameraComponent();
CameraComponent(Object *obj);
};
#endif
| 18.6
| 51
| 0.731183
|
bDiazCentro
|
44a881af02f2d62098b57b043f35fa22f4e6bfb1
| 13,167
|
cpp
|
C++
|
libs/math/test/test_bessel_j_prime.cpp
|
Abce/boost
|
2d7491a27211aa5defab113f8e2d657c3d85ca93
|
[
"BSL-1.0"
] | 85
|
2015-02-08T20:36:17.000Z
|
2021-11-14T20:38:31.000Z
|
libs/boost/libs/math/test/test_bessel_j_prime.cpp
|
flingone/frameworks_base_cmds_remoted
|
4509d9f0468137ed7fd8d100179160d167e7d943
|
[
"Apache-2.0"
] | 9
|
2015-01-28T16:33:19.000Z
|
2020-04-12T23:03:28.000Z
|
libs/boost/libs/math/test/test_bessel_j_prime.cpp
|
flingone/frameworks_base_cmds_remoted
|
4509d9f0468137ed7fd8d100179160d167e7d943
|
[
"Apache-2.0"
] | 27
|
2015-01-28T16:33:30.000Z
|
2021-08-12T05:04:39.000Z
|
// Copyright (c) 2013 Anton Bikineev
// Use, modification and distribution are subject to 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)
#include "pch_light.hpp"
#include "test_bessel_j_prime.hpp"
//
// DESCRIPTION:
// ~~~~~~~~~~~~
//
// This file tests the bessel functions derivatives. There are two sets of tests, spot
// tests which compare our results with selected values computed
// using the online special function calculator at
// functions.wolfram.com, while the bulk of the accuracy tests
// use values generated with Boost.Multiprecision at 50 precision
// and our generic versions of these functions.
//
// Note that when this file is first run on a new platform many of
// these tests will fail: the default accuracy is 1 epsilon which
// is too tight for most platforms. In this situation you will
// need to cast a human eye over the error rates reported and make
// a judgement as to whether they are acceptable. Either way please
// report the results to the Boost mailing list. Acceptable rates of
// error are marked up below as a series of regular expressions that
// identify the compiler/stdlib/platform/data-type/test-data/test-function
// along with the maximum expected peek and RMS mean errors for that
// test.
//
void expected_results()
{
//
// Define the max and mean errors expected for
// various compilers and platforms.
//
const char* largest_type;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())
{
largest_type = "(long\\s+)?double|real_concept";
}
else
{
largest_type = "long double|real_concept";
}
#else
largest_type = "(long\\s+)?double";
#endif
//
// HP-UX specific rates:
//
// Error rate for double precision are limited by the accuracy of
// the approximations use, which bracket rather than preserve the root.
//
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
".*J0'.*Tricky.*", // test data group
".*", 80000000000LL, 80000000000LL); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
".*J1'.*Tricky.*", // test data group
".*", 3000000, 2000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
"double", // test type(s)
".*Tricky.*", // test data group
".*", 100000, 100000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"HP-UX", // platform
largest_type, // test type(s)
".*J'.*Tricky.*", // test data group
".*", 3000, 500); // test function
//
// HP Tru64:
//
add_expected_result(
".*Tru64.*", // compiler
".*", // stdlib
".*", // platform
"double", // test type(s)
".*Tricky.*", // test data group
".*", 100000, 100000); // test function
add_expected_result(
".*Tru64.*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*Tricky large.*", // test data group
".*", 3000, 1000); // test function
//
// Solaris specific rates:
//
// Error rate for double precision are limited by the accuracy of
// the approximations use, which bracket rather than preserve the root.
//
add_expected_result(
".*", // compiler
".*", // stdlib
"Sun Solaris", // platform
largest_type, // test type(s)
"Bessel J': Random Data.*Tricky.*", // test data group
".*", 3000, 500); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Sun Solaris", // platform
"double", // test type(s)
".*Tricky.*", // test data group
".*", 200000, 100000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Sun Solaris", // platform
largest_type, // test type(s)
".*J'.*tricky.*", // test data group
".*", 400000000, 200000000); // test function
//
// Mac OS X:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"Mac OS", // platform
largest_type, // test type(s)
".*J0'.*Tricky.*", // test data group
".*", 400000000, 400000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Mac OS", // platform
largest_type, // test type(s)
".*J1'.*Tricky.*", // test data group
".*", 3000000, 2000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Mac OS", // platform
largest_type, // test type(s)
"Bessel JN'.*", // test data group
".*", 60000, 20000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
"Mac OS", // platform
largest_type, // test type(s)
"Bessel J':.*", // test data group
".*", 60000, 20000); // test function
//
// Linux specific results:
//
// sin and cos appear to have only double precision for large
// arguments on some linux distros:
//
add_expected_result(
".*", // compiler
".*", // stdlib
"linux", // platform
largest_type, // test type(s)
".*J':.*", // test data group
".*", 60000, 30000); // test function
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
if((std::numeric_limits<double>::digits != std::numeric_limits<long double>::digits)
&& (std::numeric_limits<long double>::digits < 90))
{
// some errors spill over into type double as well:
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"double", // test type(s)
".*J0'.*Tricky.*", // test data group
".*", 400000, 400000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"double", // test type(s)
".*J1'.*Tricky.*", // test data group
".*", 5000, 5000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"double", // test type(s)
".*(JN'|j').*|.*Tricky.*", // test data group
".*", 50, 50); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"double", // test type(s)
".*", // test data group
".*", 30, 30); // test function
//
// and we have a few cases with higher limits as well:
//
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*J0'.*Tricky.*", // test data group
".*", 400000000, 400000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*J1'.*Tricky.*", // test data group
".*", 5000000, 5000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*(JN'|j').*|.*Tricky.*", // test data group
".*", 60000, 40000); // test function
}
#endif
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*J0'.*Tricky.*", // test data group
".*", 400000000, 400000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*J1'.*Tricky.*", // test data group
".*", 5000000, 5000000); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
"Bessel j':.*|Bessel JN': Mathworld.*|.*Tricky.*", // test data group
".*", 1500, 700); // test function
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
largest_type, // test type(s)
".*", // test data group
".*", 40, 20); // test function
//
// One set of float tests has inexact input values, so there is a slight error:
//
add_expected_result(
".*", // compiler
".*", // stdlib
".*", // platform
"float", // test type(s)
"Bessel J': Mathworld Data", // test data group
".*", 30, 20); // test function
//
// Finish off by printing out the compiler/stdlib/platform names,
// we do this to make it easier to mark up expected error rates.
//
std::cout << "Tests run with " << BOOST_COMPILER << ", "
<< BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}
BOOST_AUTO_TEST_CASE( test_main )
{
#ifdef TEST_GSL
gsl_set_error_handler_off();
#endif
expected_results();
BOOST_MATH_CONTROL_FP;
test_bessel_prime(0.1F, "float");
test_bessel_prime(0.1, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
test_bessel_prime(0.1L, "long double");
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
test_bessel_prime(boost::math::concepts::real_concept(0.1), "real_concept");
#endif
#else
std::cout << "<note>The long double tests have been disabled on this platform "
"either because the long double overloads of the usual math functions are "
"not available at all, or because they are too inaccurate for these tests "
"to pass.</note>" << std::cout;
#endif
}
| 42.474194
| 163
| 0.422116
|
Abce
|
44ac457f50baea79aae03e03037c6a508dbe5c66
| 32,268
|
cpp
|
C++
|
bbs/lilo.cpp
|
dotelpenguin/wwiv
|
58d651fea6a5287da3282f9afb05e43ff3012fee
|
[
"Apache-2.0"
] | null | null | null |
bbs/lilo.cpp
|
dotelpenguin/wwiv
|
58d651fea6a5287da3282f9afb05e43ff3012fee
|
[
"Apache-2.0"
] | null | null | null |
bbs/lilo.cpp
|
dotelpenguin/wwiv
|
58d651fea6a5287da3282f9afb05e43ff3012fee
|
[
"Apache-2.0"
] | null | null | null |
/**************************************************************************/
/* */
/* WWIV Version 5.x */
/* Copyright (C)1998-2020, WWIV Software Services */
/* */
/* 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 "bbs/automsg.h"
#include "bbs/basic.h"
#include "bbs/batch.h"
#include "bbs/bbs.h"
#include "bbs/bbsutl.h"
#include "bbs/bbsutl1.h"
#include "bbs/com.h"
#include "bbs/confutil.h"
#include "bbs/connect1.h"
#include "bbs/datetime.h"
#include "bbs/defaults.h"
#include "bbs/dropfile.h"
#include "bbs/email.h"
#include "bbs/execexternal.h"
#include "bbs/finduser.h"
#include "bbs/inetmsg.h"
#include "bbs/input.h"
#include "bbs/instmsg.h"
#include "bbs/menusupp.h"
#include "bbs/msgbase1.h"
#include "bbs/newuser.h"
#include "bbs/pause.h"
#include "bbs/printfile.h"
#include "bbs/readmail.h"
#include "bbs/remote_io.h"
#include "bbs/shortmsg.h"
#include "bbs/stuffin.h"
#include "bbs/sysoplog.h"
#include "bbs/trashcan.h"
#include "bbs/utility.h"
#include "bbs/wqscn.h"
#include "core/datafile.h"
#include "core/file.h"
#include "core/inifile.h"
#include "core/os.h"
#include "core/scope_exit.h"
#include "core/stl.h"
#include "core/strings.h"
#include "core/version.h"
#include "fmt/printf.h"
#include "local_io/wconstants.h"
#include "sdk/config.h"
#include "sdk/filenames.h"
#include "sdk/names.h"
#include "sdk/status.h"
#include <chrono>
#include <limits>
#include <memory>
#include <string>
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::seconds;
using std::string;
using std::unique_ptr;
using std::vector;
using namespace wwiv::core;
using namespace wwiv::os;
using namespace wwiv::sdk;
using namespace wwiv::stl;
using namespace wwiv::strings;
#define SECS_PER_DAY 86400L
static char g_szLastLoginDate[9];
static void CleanUserInfo() {
if (okconf(a()->user())) {
setuconf(ConferenceType::CONF_SUBS, a()->user()->GetLastSubConf(), 0);
setuconf(ConferenceType::CONF_DIRS, a()->user()->GetLastDirConf(), 0);
}
if (a()->user()->GetLastSubNum() > a()->config()->max_subs()) {
a()->user()->SetLastSubNum(0);
}
if (a()->user()->GetLastDirNum() > a()->config()->max_dirs()) {
a()->user()->SetLastDirNum(0);
}
if (a()->usub[a()->user()->GetLastSubNum()].subnum != -1) {
a()->set_current_user_sub_num(a()->user()->GetLastSubNum());
}
if (a()->udir[a()->user()->GetLastDirNum()].subnum != -1) {
a()->set_current_user_dir_num(a()->user()->GetLastDirNum());
}
}
bool IsPhoneNumberUSAFormat(User *pUser) {
string country = pUser->GetCountry();
return (country == "USA" || country == "CAN" || country == "MEX");
}
static int GetAnsiStatusAndShowWelcomeScreen() {
bout << "\r\nWWIV " << wwiv_version << beta_version << wwiv::endl;
bout << "Copyright (c) 1998-2020, WWIV Software Services." << wwiv::endl;
bout << "All Rights Reserved." << wwiv::endl;
int ans = check_ansi();
if (ans > 0) {
a()->user()->SetStatusFlag(User::ansi);
a()->user()->SetStatusFlag(User::status_color);
}
bout.nl();
if (!printfile_random(WELCOME_NOEXT)) {
printfile(WELCOME_NOEXT);
}
if (bout.curatr() != 7) {
bout.ResetColors();
}
return ans;
}
static uint16_t FindUserByRealName(const std::string& user_name) {
if (user_name.empty()) {
return 0;
}
bout << "Searching...";
bool abort = false;
int current_count = 0;
for (const auto& n : a()->names()->names_vector()) {
if (a()->hangup_ || abort) { break; }
if (++current_count % 25 == 0) {
// changed from 15 since computers are faster now-a-days
bout << ".";
}
auto current_user = n.number;
a()->ReadCurrentUser(current_user);
string temp_user_name(a()->user()->GetRealName());
StringUpperCase(&temp_user_name);
if (user_name == temp_user_name && !a()->user()->IsUserDeleted()) {
bout << "|#5Do you mean " << a()->names()->UserName(n.number) << "? ";
if (yesno()) {
return current_user;
}
}
checka(&abort);
}
return 0;
}
static int ShowLoginAndGetUserNumber(string remote_username) {
bout.nl();
bout << "Enter number or name or 'NEW'\r\n";
bout << "NN: ";
string user_name;
if (remote_username.empty()) {
user_name = input_upper(30);
} else {
bout << remote_username << wwiv::endl;
user_name = remote_username;
}
StringTrim(&user_name);
Trashcan trashcan(*a()->config());
if (trashcan.IsTrashName(user_name)) {
LOG(INFO) << "Trashcan name entered from IP: " << a()->remoteIO()->remote_info().address
<< "; name: " << user_name;
hang_it_up();
Hangup();
return 0;
}
auto user_number = finduser(user_name);
if (user_number != 0) {
return user_number;
}
return FindUserByRealName(user_name);
}
bool IsPhoneRequired() {
IniFile ini(PathFilePath(a()->bbsdir(), WWIV_INI),
{StrCat("WWIV-", a()->instance_number()), INI_TAG});
if (ini.IsOpen()) {
if (ini.value<bool>("NEWUSER_MIN")) {
return false;
}
if (!ini.value<bool>("LOGON_PHONE")) {
return false;
}
}
return true;
}
bool VerifyPhoneNumber() {
if (IsPhoneNumberUSAFormat(a()->user()) || !a()->user()->GetCountry()[0]) {
string phoneNumber = input_password("PH: ###-###-", 4);
if (phoneNumber != &a()->user()->GetVoicePhoneNumber()[8]) {
if (phoneNumber.length() == 4 && phoneNumber[3] == '-') {
bout << "\r\n!! Enter the LAST 4 DIGITS of your phone number ONLY !!\r\n\n";
}
return false;
}
}
return true;
}
static bool VerifyPassword(string remote_password) {
a()->UpdateTopScreen();
if (!remote_password.empty() && remote_password == a()->user()->GetPassword()) {
return true;
}
string password = input_password("PW: ", 8);
return (password == a()->user()->GetPassword());
}
static bool VerifySysopPassword() {
string password = input_password("SY: ", 20);
return (password == a()->config()->system_password()) ? true : false;
}
static void DoFailedLoginAttempt() {
a()->user()->SetNumIllegalLogons(a()->user()->GetNumIllegalLogons() + 1);
a()->WriteCurrentUser();
bout << "\r\n\aILLEGAL LOGON\a\r\n\n";
const string logline = StrCat("### ILLEGAL LOGON for ",
a()->names()->UserName(a()->usernum));
sysoplog(false) << "";
sysoplog(false) << logline;
sysoplog(false) << "";
a()->usernum = 0;
}
static void LeaveBadPasswordFeedback(int ans) {
ScopeExit at_exit([] {
a()->usernum = 0;
});
if (ans > 0) {
a()->user()->SetStatusFlag(User::ansi);
} else {
a()->user()->ClearStatusFlag(User::ansi);
}
bout << "|#6Too many logon attempts!!\r\n\n";
bout << "|#9Would you like to leave Feedback to " << a()->config()->sysop_name() << "? ";
if (!yesno()) {
return;
}
bout.nl();
bout << "What is your NAME or HANDLE? ";
auto tempName = input_proper("", 31);
if (tempName.empty()) {
return;
}
bout.nl();
a()->usernum = 1;
a()->user()->set_name(tempName.c_str());
a()->user()->SetMacro(0, "");
a()->user()->SetMacro(1, "");
a()->user()->SetMacro(2, "");
a()->user()->SetSl(a()->config()->newuser_sl());
a()->user()->SetScreenChars(80);
if (ans > 0) {
select_editor();
} else {
a()->user()->SetDefaultEditor(0);
}
a()->user()->SetNumEmailSent(0);
bool bSaveAllowCC = a()->IsCarbonCopyEnabled();
a()->SetCarbonCopyEnabled(false);
auto title = StrCat("** Illegal logon feedback from ", tempName);
email(title, 1, 0, true, 0, true);
a()->SetCarbonCopyEnabled(bSaveAllowCC);
if (a()->user()->GetNumEmailSent() > 0) {
ssm(1) << "Check your mailbox. Someone forgot their password again!";
}
}
static void CheckCallRestrictions() {
if (a()->usernum > 0 && a()->user()->IsRestrictionLogon() &&
date() == a()->user()->GetLastOn() &&
a()->user()->GetTimesOnToday() > 0) {
bout.nl();
bout << "|#6Sorry, you can only logon once per day.\r\n";
Hangup();
}
}
static void logon_guest() {
a()->SetUserOnline(true);
bout.nl(2);
input_ansistat();
printfile(GUEST_NOEXT);
pausescr();
string userName, reason;
int count = 0;
do {
bout << "\r\n|#5Enter your real name : ";
userName = input_upper(25);
bout << "\r\n|#5Purpose of your call?\r\n";
reason = input_text(79);
if (!userName.empty() && !reason.empty()) {
break;
}
count++;
} while (count < 3);
if (count >= 3) {
printfile(REJECT_NOEXT);
ssm(1) << "Guest Account failed to enter name and purpose";
Hangup();
} else {
ssm(1) << "Guest Account accessed by " << userName << " on " << times() << " for" << reason;
}
}
void getuser() {
// Reset the key timeout to 30 seconds while trying to log in a user.
ScopeExit at_exit([] { a()->context().okmacro(true); bout.reset_key_timeout(); });
a()->context().okmacro(false);
// TODO(rushfan): uncomment this
//bout.set_logon_key_timeout();
// Let's set this to 0 here since we don't have a user yet.
a()->usernum = 0;
a()->SetCurrentConferenceMessageArea(0);
a()->SetCurrentConferenceFileArea(0);
a()->effective_sl(a()->config()->newuser_sl());
a()->user()->SetStatus(0);
const auto& ip = a()->remoteIO()->remote_info().address;
const auto& hostname = a()->remoteIO()->remote_info().address_name;
if (!ip.empty()) {
bout << "Client Address: " << hostname << " (" << ip << ")" << wwiv::endl;
bout.nl();
}
write_inst(INST_LOC_GETUSER, 0, INST_FLAGS_NONE);
int count = 0;
bool ok = false;
int ans = GetAnsiStatusAndShowWelcomeScreen();
bool first_time = true;
do {
string remote_username;
string remote_password;
if (first_time) {
remote_username = ToStringUpperCase(a()->remoteIO()->remote_info().username);
remote_password = ToStringUpperCase(a()->remoteIO()->remote_info().password);
first_time = false;
}
auto usernum = ShowLoginAndGetUserNumber(remote_username);
if (usernum > 0) {
a()->usernum = static_cast<uint16_t>(usernum);
a()->ReadCurrentUser();
read_qscn(a()->usernum, a()->context().qsc, false);
if (!set_language(a()->user()->GetLanguage())) {
a()->user()->SetLanguage(0);
set_language(0);
}
int nInstanceNumber;
if (a()->user()->GetSl() < 255 && user_online(a()->usernum, &nInstanceNumber)) {
bout << "\r\n|#6You are already online on instance " << nInstanceNumber << "!\r\n\n";
continue;
}
ok = true;
if (a()->context().guest_user()) {
logon_guest();
} else {
a()->effective_sl(a()->config()->newuser_sl());
if (!VerifyPassword(remote_password)) {
ok = false;
}
if ((a()->config()->sysconfig_flags() & sysconfig_free_phone) == 0 && IsPhoneRequired()) {
if (!VerifyPhoneNumber()) {
ok = false;
}
}
if (a()->user()->GetSl() == 255 && a()->context().incom() && ok) {
if (!VerifySysopPassword()) {
ok = false;
}
}
}
if (ok) {
a()->reset_effective_sl();
changedsl();
} else {
DoFailedLoginAttempt();
}
} else if (usernum == 0) {
bout.nl();
bout << "|#6Unknown user.\r\n";
a()->usernum = static_cast<uint16_t>(usernum);
} else if (usernum == -1) {
write_inst(INST_LOC_NEWUSER, 0, INST_FLAGS_NONE);
play_sdf(NEWUSER_NOEXT, false);
newuser();
ok = true;
}
} while (!ok && ++count < 3);
if (count >= 3) {
LeaveBadPasswordFeedback(ans);
}
CheckCallRestrictions();
if (!ok) {
Hangup();
}
}
static void FixUserLinesAndColors() {
if (a()->user()->GetNumExtended() > a()->max_extend_lines) {
a()->user()->SetNumExtended(a()->max_extend_lines);
}
if (a()->user()->GetColor(8) == 0 || a()->user()->GetColor(9) == 0) {
a()->user()->SetColor(8, a()->newuser_colors[8]);
a()->user()->SetColor(9, a()->newuser_colors[9]);
}
}
static void UpdateUserStatsForLogin() {
to_char_array(g_szLastLoginDate, date());
if (a()->user()->GetLastOn() == g_szLastLoginDate) {
a()->user()->SetTimesOnToday(a()->user()->GetTimesOnToday() + 1);
} else {
a()->user()->SetTimesOnToday(1);
a()->user()->SetTimeOnToday(0.0);
a()->user()->SetExtraTime(0.0);
a()->user()->SetNumPostsToday(0);
a()->user()->SetNumEmailSentToday(0);
a()->user()->SetNumFeedbackSentToday(0);
}
a()->user()->SetNumLogons(a()->user()->GetNumLogons() + 1);
a()->set_current_user_sub_num(0);
a()->SetNumMessagesReadThisLogon(0);
if (a()->udir[0].subnum == 0 && a()->udir[1].subnum > 0) {
a()->set_current_user_dir_num(1);
} else {
a()->set_current_user_dir_num(0);
}
if (a()->effective_sl() != 255 && !a()->context().guest_user()) {
a()->status_manager()->Run([](WStatus& s) {
s.IncrementCallerNumber();
s.IncrementNumCallsToday();
});
}
}
static void PrintLogonFile() {
if (!a()->context().incom()) {
return;
}
play_sdf(LOGON_NOEXT, false);
if (!printfile(LOGON_NOEXT)) {
pausescr();
}
}
static void PrintUserSpecificFiles() {
const User* user = a()->user(); // not-owned
printfile(fmt::format("sl{}", user->GetSl()));
printfile(fmt::format("dsl{}", user->GetDsl()));
const int short_size = std::numeric_limits<uint16_t>::digits - 1;
for (int i=0; i < short_size; i++) {
if (user->HasArFlag(1 << i)) {
printfile(fmt::format("ar{}", static_cast<char>('A' + i)));
}
}
for (int i=0; i < short_size; i++) {
if (user->HasDarFlag(1 << i)) {
printfile(fmt::format("dar{}", static_cast<char>('A' + i)));
}
}
}
static std::string CreateLastOnLogLine(const WStatus& status) {
string log_line;
if (a()->HasConfigFlag(OP_FLAGS_SHOW_CITY_ST) &&
(a()->config()->sysconfig_flags() & sysconfig_extended_info)) {
const string username_num = a()->names()->UserName(a()->usernum);
const string t = times();
const string f = fulldate();
log_line = fmt::sprintf(
"|#1%-6ld %-25.25s %-5.5s %-5.5s %-15.15s %-2.2s %-3.3s %-8.8s %2d\r\n",
status.GetCallerNumber(),
username_num,
t,
f,
a()->user()->GetCity(),
a()->user()->GetState(),
a()->user()->GetCountry(),
a()->GetCurrentSpeed(),
a()->user()->GetTimesOnToday());
} else {
const string username_num = a()->names()->UserName(a()->usernum);
const string t = times();
const string f = fulldate();
log_line = fmt::sprintf(
"|#1%-6ld %-25.25s %-10.10s %-5.5s %-5.5s %-20.20s %2d\r\n",
status.GetCallerNumber(),
username_num,
a()->cur_lang_name,
t,
f,
a()->GetCurrentSpeed(),
a()->user()->GetTimesOnToday());
}
return log_line;
}
static void UpdateLastOnFile() {
const auto laston_txt_filename = PathFilePath(a()->config()->gfilesdir(), LASTON_TXT);
vector<string> lines;
{
TextFile laston_file(laston_txt_filename, "r");
lines = laston_file.ReadFileIntoVector();
}
if (!lines.empty()) {
bool needs_header = true;
for (const auto& line : lines) {
if (line.empty()) {
continue;
}
if (needs_header) {
bout.nl(2);
bout << "|#1Last few callers|#7: |#0";
bout.nl(2);
if (a()->HasConfigFlag(OP_FLAGS_SHOW_CITY_ST) &&
(a()->config()->sysconfig_flags() & sysconfig_extended_info)) {
bout << "|#2Number Name/Handle Time Date City ST Cty Speed ##" << wwiv::endl;
} else {
bout << "|#2Number Name/Handle Language Time Date Speed ##" << wwiv::endl;
}
char chLine = (okansi()) ? static_cast<char>('\xCD') : '=';
bout << "|#7" << std::string(79, chLine) << wwiv::endl;
needs_header = false;
}
bout << line << wwiv::endl;
}
bout.nl(2);
pausescr();
}
auto status = a()->status_manager()->GetStatus();
{
const string username_num = a()->names()->UserName(a()->usernum);
string t = times();
string f = fulldate();
const string sysop_log_line = fmt::sprintf("%ld: %s %s %s %s - %d (%u)",
status->GetCallerNumber(),
username_num,
t,
f,
a()->GetCurrentSpeed(),
a()->user()->GetTimesOnToday(),
a()->instance_number());
sysoplog(false) << "";
sysoplog(false) << stripcolors(sysop_log_line);
sysoplog(false) << "";
}
if (a()->context().incom()) {
const auto remote_address = a()->remoteIO()->remote_info().address;
if (!remote_address.empty()) {
sysoplog() << "Remote IP: " << remote_address;
}
}
if (a()->effective_sl() == 255 && !a()->context().incom()) {
return;
}
// add line to laston.txt. We keep 8 lines
if (a()->effective_sl() != 255) {
TextFile lastonFile(laston_txt_filename, "w");
if (lastonFile.IsOpen()) {
auto it = lines.begin();
// skip over any lines over 7
while (lines.size() - std::distance(lines.begin(), it) >= 8) {
it++;
}
while (it != lines.end()) {
lastonFile.WriteLine(*it++);
}
lastonFile.Write(CreateLastOnLogLine(*status.get()));
lastonFile.Close();
}
}
}
static void CheckAndUpdateUserInfo() {
if (a()->user()->GetBirthdayYear() == 0) {
bout << "\r\nPlease enter the following information:\r\n";
do {
bout.nl();
input_age(a()->user());
bout.nl();
bout << fmt::sprintf("%02d/%02d/%02d -- Correct? ",
a()->user()->GetBirthdayMonth(),
a()->user()->GetBirthdayDay(),
a()->user()->GetBirthdayYear());
if (!yesno()) {
a()->user()->SetBirthdayYear(0);
}
} while (a()->user()->GetBirthdayYear() == 0);
}
if (!a()->user()->GetRealName()[0]) {
input_realname();
}
if (!(a()->config()->sysconfig_flags() & sysconfig_extended_info)) {
return;
}
if (!a()->user()->GetStreet()[0]) {
input_street();
}
if (!a()->user()->GetCity()[0]) {
input_city();
}
if (!a()->user()->GetState()[0]) {
input_state();
}
if (!a()->user()->GetCountry()[0]) {
input_country();
}
if (!a()->user()->GetZipcode()[0]) {
input_zipcode();
}
if (!a()->user()->GetDataPhoneNumber()[0]) {
input_dataphone();
}
if (a()->user()->GetComputerType() == -1) {
input_comptype();
}
}
static void DisplayUserLoginInformation() {
bout.nl();
const string username_num = a()->names()->UserName(a()->usernum);
bout << "|#9Name/Handle|#0....... |#2" << username_num << wwiv::endl;
bout << "|#9Internet Address|#0.. |#2";
if (check_inet_addr(a()->user()->GetEmailAddress())) {
bout << a()->user()->GetEmailAddress() << wwiv::endl;
} else if (!a()->internetEmailName.empty()) {
bout << (a()->IsInternetUseRealNames() ? a()->user()->GetRealName() :
a()->user()->GetName())
<< "<" << a()->internetFullEmailAddress << ">\r\n";
} else {
bout << "None.\r\n";
}
bout << "|#9Time allowed on|#0... |#2" << (nsl() + 30) / SECONDS_PER_MINUTE
<< wwiv::endl;
if (a()->user()->GetNumIllegalLogons() > 0) {
bout << "|#9Illegal logons|#0.... |#2" << a()->user()->GetNumIllegalLogons()
<< wwiv::endl;
}
if (a()->user()->GetNumMailWaiting() > 0) {
bout << "|#9Mail waiting|#0...... |#2" << a()->user()->GetNumMailWaiting()
<< wwiv::endl;
}
if (a()->user()->GetTimesOnToday() == 1) {
bout << "|#9Date last on|#0...... |#2" << a()->user()->GetLastOn() << wwiv::endl;
} else {
bout << "|#9Times on today|#0.... |#2" << a()->user()->GetTimesOnToday() << wwiv::endl;
}
bout << "|#9Sysop currently|#0... |#2";
if (sysop2()) {
bout << "Available\r\n";
} else {
bout << "NOT Available\r\n";
}
bout << "|#9System is|#0......... |#2WWIV " << wwiv_version << beta_version << " " << wwiv::endl;
/////////////////////////////////////////////////////////////////////////
a()->status_manager()->RefreshStatusCache();
for (int i = 0; i < wwiv::stl::ssize(a()->net_networks); i++) {
if (a()->net_networks[i].sysnum) {
std::ostringstream ss;
const auto& n = a()->net_networks[i];
ss << "|#9" << n.name << " node|#0" << std::string(13 - strlen(n.name), ' ') << "|#2 @" << n.sysnum;
auto s1 = ss.str();
if (i) {
bout << s1;
bout.nl();
} else {
int i1;
for (i1 = s1.size(); i1 < 26; i1++) {
s1[i1] = ' ';
}
s1[i1] = '\0';
auto status = a()->status_manager()->GetStatus();
bout << s1 << "(net" << status->GetNetworkVersion() << ")\r\n";
}
}
}
bout << "|#9OS|#0................ |#2" << wwiv::os::os_version_string() << wwiv::endl;
bout << "|#9Instance|#0.......... |#2" << a()->instance_number() << "\r\n\n";
if (a()->user()->GetForwardUserNumber()) {
if (a()->user()->GetForwardSystemNumber() != 0) {
set_net_num(a()->user()->GetForwardNetNumber());
if (!valid_system(a()->user()->GetForwardSystemNumber())) {
a()->user()->ClearMailboxForward();
bout << "Forwarded to unknown system; forwarding reset.\r\n";
} else {
bout << "Mail set to be forwarded to ";
if (wwiv::stl::ssize(a()->net_networks) > 1) {
bout << "#" << a()->user()->GetForwardUserNumber()
<< " @"
<< a()->user()->GetForwardSystemNumber()
<< "." << a()->network_name() << "."
<< wwiv::endl;
} else {
bout << "#" << a()->user()->GetForwardUserNumber() << " @"
<< a()->user()->GetForwardSystemNumber() << "." << wwiv::endl;
}
}
} else {
if (a()->user()->IsMailboxClosed()) {
bout << "Your mailbox is closed.\r\n\n";
} else {
bout << "Mail set to be forwarded to #"
<< a()->user()->GetForwardUserNumber() << wwiv::endl;
}
}
} else if (a()->user()->GetForwardSystemNumber() != 0) {
string internet_addr;
read_inet_addr(internet_addr, a()->usernum);
bout << "Mail forwarded to Internet " << internet_addr << ".\r\n";
}
if (a()->IsTimeOnlineLimited()) {
bout << "\r\n|#3Your on-line time is limited by an external event.\r\n\n";
}
}
static void LoginCheckForNewMail() {
bout << "|#9Scanning for new mail... ";
if (a()->user()->GetNumMailWaiting() > 0) {
int nNumNewMessages = check_new_mail(a()->usernum);
if (nNumNewMessages) {
bout << "|#9You have |#2" << nNumNewMessages
<< "|#9 new message(s).\r\n\r\n"
<< "|#9Read your mail now? ";
if (noyes()) {
readmail(1);
}
} else {
bout << "|#9You have |#2" << a()->user()->GetNumMailWaiting()
<< "|#9 old message(s) in your mailbox.\r\n";
}
} else {
bout << " |#9No mail found.\r\n";
}
}
static vector<bool> read_voting() {
vector<votingrec> votes;
DataFile<votingrec> file(PathFilePath(a()->config()->datadir(), VOTING_DAT));
vector<bool> questused(20);
if (file) {
file.ReadVector(votes);
int cur = 0;
for (const auto& v : votes) {
if (v.numanswers != 0) {
questused[cur] = true;
}
++cur;
}
}
return questused;
}
static void CheckUserForVotingBooth() {
vector<bool> questused = read_voting();
if (!a()->user()->IsRestrictionVote() && a()->effective_sl() > a()->config()->newuser_sl()) {
for (int i = 0; i < 20; i++) {
if (questused[i] && a()->user()->GetVote(i) == 0) {
bout.nl();
bout << "|#9You haven't voted yet.\r\n";
return;
}
}
}
}
void logon() {
if (a()->usernum < 1) {
Hangup();
return;
}
a()->SetUserOnline(true);
write_inst(INST_LOC_LOGON, 0, INST_FLAGS_NONE);
get_user_ppp_addr();
bout.ResetColors();
bout.Color(0);
bout.cls();
FixUserLinesAndColors();
UpdateUserStatsForLogin();
PrintLogonFile();
UpdateLastOnFile();
PrintUserSpecificFiles();
read_automessage();
a()->SetLogonTime();
a()->UpdateTopScreen();
bout.nl(2);
pausescr();
if (!a()->logon_cmd.empty()) {
if (a()->logon_cmd.front() == '@') {
// Let's see if we need to run a basic script.
const string BASIC_PREFIX = "@basic:";
if (starts_with(a()->logon_cmd, BASIC_PREFIX)) {
const auto cmd = a()->logon_cmd.substr(BASIC_PREFIX.size());
LOG(INFO) << "Running basic script: " << cmd;
wwiv::bbs::RunBasicScript(cmd);
}
}
else {
bout.nl();
const auto cmd = stuff_in(a()->logon_cmd, create_chain_file(), "", "", "", "");
ExecuteExternalProgram(cmd, a()->spawn_option(SPAWNOPT_LOGON));
}
bout.nl(2);
}
DisplayUserLoginInformation();
CheckAndUpdateUserInfo();
a()->UpdateTopScreen();
a()->read_subs();
// Is this needed? Doesn't read_subs do it?
a()->subs().Load();
rsm(a()->usernum, a()->user(), true);
LoginCheckForNewMail();
if (a()->user()->GetNewScanDateNumber()) {
a()->context().nscandate(a()->user()->GetNewScanDateNumber());
} else {
a()->context().nscandate(a()->user()->GetLastOnDateNumber());
}
a()->batch().clear();
CheckUserForVotingBooth();
if ((a()->context().incom() || sysop1()) && a()->user()->GetSl() < 255) {
broadcast(fmt::format("{} Just logged on!", a()->user()->GetName()));
}
setiia(std::chrono::seconds(5));
// New Message Scan
if (a()->IsNewScanAtLogin()) {
bout << "\r\n|#5Scan All Message Areas For New Messages? ";
if (yesno()) {
NewMsgsAllConfs();
}
}
// Handle case of first conf with no subs avail
if (a()->usub[0].subnum == -1 && okconf(a()->user())) {
for (a()->SetCurrentConferenceMessageArea(0);
(a()->GetCurrentConferenceMessageArea() < ssize(a()->subconfs))
&& (a()->uconfsub[a()->GetCurrentConferenceMessageArea()].confnum != -1);
a()->SetCurrentConferenceMessageArea(a()->GetCurrentConferenceMessageArea() + 1)) {
setuconf(ConferenceType::CONF_SUBS, a()->GetCurrentConferenceMessageArea(), -1);
if (a()->usub[0].subnum != -1) {
break;
}
}
if (a()->usub[0].subnum == -1) {
a()->SetCurrentConferenceMessageArea(0);
setuconf(ConferenceType::CONF_SUBS, a()->GetCurrentConferenceMessageArea(), -1);
}
}
if (a()->HasConfigFlag(OP_FLAGS_USE_FORCESCAN)) {
bool nextsub = false;
if (a()->user()->GetSl() < 255) {
a()->context().forcescansub(true);
qscan(a()->GetForcedReadSubNumber(), nextsub);
a()->context().forcescansub(false);
} else {
qscan(a()->GetForcedReadSubNumber(), nextsub);
}
}
CleanUserInfo();
}
void logoff() {
mailrec m;
if (a()->context().incom()) {
play_sdf(LOGOFF_NOEXT, false);
}
if (a()->usernum > 0) {
if ((a()->context().incom() || sysop1()) && a()->user()->GetSl() < 255) {
broadcast(fmt::format("{} Just logged off!", a()->user()->GetName()));
}
}
setiia(std::chrono::seconds(5));
a()->remoteIO()->disconnect();
// Don't need to a()->hangup_ here, but *do* want to ensure that a()->hangup_ is true.
a()->hangup_ = true;
VLOG(1) << "Setting a()->hangup_=true in logoff";
if (a()->usernum < 1) {
return;
}
string text = " Logged Off At ";
text += times();
if (a()->effective_sl() != 255 || a()->context().incom()) {
sysoplog(false) << "";
sysoplog(false) << stripcolors(text);
}
a()->user()->SetLastBaudRate(a()->modem_speed_);
// put this back here where it belongs... (not sure why it te
a()->user()->SetLastOn(g_szLastLoginDate);
a()->user()->SetNumIllegalLogons(0);
auto seconds_used_duration = duration_cast<seconds>(
std::chrono::system_clock::now() - a()->system_logon_time() - a()->extratimecall());
a()->user()->add_timeon(seconds_used_duration);
a()->user()->add_timeon_today(seconds_used_duration);
a()->status_manager()->Run([=](WStatus& s) {
int active_today = s.GetMinutesActiveToday();
auto minutes_used_now = std::chrono::duration_cast<std::chrono::minutes>(seconds_used_duration).count();
s.SetMinutesActiveToday(active_today + minutes_used_now);
});
if (a()->context().scanned_files()) {
a()->user()->SetNewScanDateNumber(a()->user()->GetLastOnDateNumber());
}
a()->user()->SetLastOnDateNumber(daten_t_now());
auto used_this_session = (std::chrono::system_clock::now() - a()->system_logon_time());
auto min_used = std::chrono::duration_cast<std::chrono::minutes>(used_this_session);
sysoplog(false) << "Read: " << a()->GetNumMessagesReadThisLogon()
<< " Time on: " << min_used.count() << " minutes.";
{
unique_ptr<File> pFileEmail(OpenEmailFile(true));
if (pFileEmail->IsOpen()) {
a()->user()->SetNumMailWaiting(0);
auto num_records = static_cast<int>(pFileEmail->length() / sizeof(mailrec));
int r = 0;
int w = 0;
while (r < num_records) {
pFileEmail->Seek(static_cast<long>(sizeof(mailrec)) * static_cast<long>(r), File::Whence::begin);
pFileEmail->Read(&m, sizeof(mailrec));
if (m.tosys != 0 || m.touser != 0) {
if (m.tosys == 0 && m.touser == a()->usernum) {
if (a()->user()->GetNumMailWaiting() != 255) {
a()->user()->SetNumMailWaiting(a()->user()->GetNumMailWaiting() + 1);
}
}
if (r != w) {
pFileEmail->Seek(static_cast<long>(sizeof(mailrec)) * static_cast<long>(w), File::Whence::begin);
pFileEmail->Write(&m, sizeof(mailrec));
}
++w;
}
++r;
}
if (r != w) {
m.tosys = 0;
m.touser = 0;
for (int w1 = w; w1 < r; w1++) {
pFileEmail->Seek(static_cast<long>(sizeof(mailrec)) * static_cast<long>(w1), File::Whence::begin);
pFileEmail->Write(&m, sizeof(mailrec));
}
}
pFileEmail->set_length(static_cast<long>(sizeof(mailrec)) * static_cast<long>(w));
a()->status_manager()->Run([](WStatus& s) {
s.IncrementFileChangedFlag(WStatus::fileChangeEmail);
});
pFileEmail->Close();
}
}
if (a()->received_short_message_) {
File smwFile(PathFilePath(a()->config()->datadir(), SMW_DAT));
if (smwFile.Open(File::modeReadWrite | File::modeBinary | File::modeCreateFile)) {
auto num_records = static_cast<int>(smwFile.length() / sizeof(shortmsgrec));
int r = 0;
int w = 0;
while (r < num_records) {
shortmsgrec sm;
smwFile.Seek(r * sizeof(shortmsgrec), File::Whence::begin);
smwFile.Read(&sm, sizeof(shortmsgrec));
if (sm.tosys != 0 || sm.touser != 0) {
if (sm.tosys == 0 && sm.touser == a()->usernum) {
a()->user()->SetStatusFlag(User::SMW);
}
if (r != w) {
smwFile.Seek(w * sizeof(shortmsgrec), File::Whence::begin);
smwFile.Write(&sm, sizeof(shortmsgrec));
}
++w;
}
++r;
}
smwFile.set_length(w * sizeof(shortmsgrec));
smwFile.Close();
}
}
a()->WriteCurrentUser();
write_qscn(a()->usernum, a()->context().qsc, false);
}
| 31.086705
| 117
| 0.556775
|
dotelpenguin
|
44ae758972bebb36226c9b9f99def329ac8e1949
| 15,661
|
cpp
|
C++
|
Source/Ilum/Editor/Panels/Inspector.cpp
|
LavenSun/IlumEngine
|
94841e56af3c5214f04e7a94cb7369f4935c5788
|
[
"MIT"
] | 1
|
2021-11-20T15:39:09.000Z
|
2021-11-20T15:39:09.000Z
|
Source/Ilum/Editor/Panels/Inspector.cpp
|
LavenSun/IlumEngine
|
94841e56af3c5214f04e7a94cb7369f4935c5788
|
[
"MIT"
] | null | null | null |
Source/Ilum/Editor/Panels/Inspector.cpp
|
LavenSun/IlumEngine
|
94841e56af3c5214f04e7a94cb7369f4935c5788
|
[
"MIT"
] | null | null | null |
#include "Inspector.hpp"
#include "Editor/Editor.hpp"
#include "Scene/Component/DirectionalLight.hpp"
#include "Scene/Component/Hierarchy.hpp"
#include "Scene/Component/Light.hpp"
#include "Scene/Component/MeshRenderer.hpp"
#include "Scene/Component/PointLight.hpp"
#include "Scene/Component/SpotLight.hpp"
#include "Scene/Component/Tag.hpp"
#include "Scene/Component/Transform.hpp"
#include "Material/DisneyPBR.h"
#include "Material/Material.h"
#include "Renderer/Renderer.hpp"
#include "Loader/ImageLoader/ImageLoader.hpp"
#include "Loader/ResourceCache.hpp"
#include "ImGui/ImGuiContext.hpp"
#include "File/FileSystem.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <imgui.h>
#include <imgui_internal.h>
namespace Ilum::panel
{
inline bool draw_vec3_control(const std::string &label, glm::vec3 &values, float resetValue = 0.0f, float columnWidth = 100.0f)
{
ImGuiIO &io = ImGui::GetIO();
auto bold_font = io.Fonts->Fonts[0];
bool update = false;
ImGui::PushID(label.c_str());
ImGui::Columns(2);
ImGui::SetColumnWidth(0, columnWidth);
ImGui::Text(label.c_str());
ImGui::NextColumn();
ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{0, 0});
float line_height = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImVec2 button_size = {line_height + 3.0f, line_height};
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.8f, 0.1f, 0.15f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.9f, 0.2f, 0.2f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.8f, 0.1f, 0.15f, 1.0f});
ImGui::PushFont(bold_font);
if (ImGui::Button("X", button_size))
{
values.x = resetValue;
update = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
update = update | ImGui::DragFloat("##X", &values.x, 0.1f, 0.0f, 0.0f, "%.3f");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.2f, 0.7f, 0.2f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.3f, 0.8f, 0.3f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.2f, 0.7f, 0.2f, 1.0f});
ImGui::PushFont(bold_font);
if (ImGui::Button("Y", button_size))
{
values.y = resetValue;
update = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
update = update | ImGui::DragFloat("##Y", &values.y, 0.1f, 0.0f, 0.0f, "%.3f");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.1f, 0.25f, 0.8f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.2f, 0.35f, 0.9f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.1f, 0.25f, 0.8f, 1.0f});
ImGui::PushFont(bold_font);
if (ImGui::Button("Z", button_size))
{
values.z = resetValue;
update = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
update = update | ImGui::DragFloat("##Z", &values.z, 0.1f, 0.0f, 0.0f, "%.3f");
ImGui::PopItemWidth();
ImGui::PopStyleVar();
ImGui::Columns(1);
ImGui::PopID();
return update;
}
template <typename T>
void select_material(scope<IMaterial> &material)
{
if ((!material || (material && material->type() != typeid(T))) && ImGui::MenuItem(typeid(T).name()))
{
material = createScope<T>();
}
}
template <typename T1, typename T2, typename... Tn>
inline void select_material()
{
select_material<T1>();
select_material<T2, Tn...>();
}
template <typename T, typename Callback>
inline void draw_component(const std::string &name, Entity entity, Callback callback, bool static_mode = false)
{
const ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_FramePadding;
if (entity.hasComponent<T>())
{
auto & component = entity.getComponent<T>();
ImVec2 content_region_available = ImGui::GetContentRegionAvail();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2{4, 4});
float line_height = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImGui::Separator();
bool open = ImGui::TreeNodeEx((void *) typeid(T).hash_code(), tree_node_flags, name.c_str());
ImGui::PopStyleVar();
bool remove_component = false;
if (!static_mode)
{
ImGui::SameLine(content_region_available.x - line_height * 0.5f);
if (ImGui::Button("-", ImVec2{line_height, line_height}))
{
remove_component = true;
}
}
if (open)
{
callback(component);
ImGui::TreePop();
}
if (remove_component)
{
entity.removeComponent<T>();
}
}
}
template <typename T>
inline void draw_material(T &material)
{
ASSERT(false);
}
void draw_texture(std::string &texture)
{
if (ImGui::ImageButton(Renderer::instance()->getResourceCache().hasImage(texture) ?
ImGuiContext::textureID(Renderer::instance()->getResourceCache().loadImage(texture), Renderer::instance()->getSampler(Renderer::SamplerType::Trilinear_Clamp)) :
ImGuiContext::textureID(Renderer::instance()->getDefaultTexture(), Renderer::instance()->getSampler(Renderer::SamplerType::Trilinear_Clamp)),
ImVec2{100.f, 100.f}))
{
texture = "";
}
if (ImGui::BeginDragDropTarget())
{
if (const auto *pay_load = ImGui::AcceptDragDropPayload("Texture2D"))
{
ASSERT(pay_load->DataSize == sizeof(std::string));
if (texture != *static_cast<std::string *>(pay_load->Data))
{
texture = *static_cast<std::string *>(pay_load->Data);
}
}
ImGui::EndDragDropTarget();
}
}
template <>
inline void draw_material<material::DisneyPBR>(material::DisneyPBR &material)
{
ImGui::ColorEdit4("Base Color", glm::value_ptr(material.base_color));
ImGui::ColorEdit3("Emissive Color", glm::value_ptr(material.emissive_color));
ImGui::DragFloat("Metallic Factor", &material.metallic_factor, 0.01f, 0.f, 1.f, "%.3f");
ImGui::DragFloat("Emissive Intensity", &material.emissive_intensity, 0.01f, 0.f, std::numeric_limits<float>::max(), "%.3f");
ImGui::DragFloat("Roughness Factor", &material.roughness_factor, 0.01f, 0.f, 1.f, "%.3f");
ImGui::DragFloat("Height Factor", &material.displacement_height, 0.01f, 0.f, std::numeric_limits<float>::max(), "%.3f");
ImGui::Text("Albedo Map");
draw_texture(material.albedo_map);
ImGui::Text("Normal Map");
draw_texture(material.normal_map);
ImGui::Text("Metallic Map");
draw_texture(material.metallic_map);
ImGui::Text("Roughness Map");
draw_texture(material.roughness_map);
ImGui::Text("Emissive Map");
draw_texture(material.emissive_map);
ImGui::Text("AO Map");
draw_texture(material.ao_map);
ImGui::Text("Displacement Map");
draw_texture(material.displacement_map);
}
template <typename T>
inline void draw_material(scope<IMaterial> &material)
{
if (material->type() == typeid(T))
{
draw_material<T>(*static_cast<T *>(material.get()));
}
}
template <typename T1, typename T2, typename... Tn>
inline void draw_material(scope<IMaterial> &material)
{
draw_material<T1>(material);
draw_material<T2, Tn...>(material);
}
inline void draw_material(scope<IMaterial> &material)
{
if (!material)
{
return;
}
draw_material<material::DisneyPBR>(material);
}
template <typename T>
inline void add_component()
{
if (!Editor::instance()->getSelect().hasComponent<T>() && ImGui::MenuItem(typeid(T).name()))
{
Editor::instance()->getSelect().addComponent<T>();
ImGui::CloseCurrentPopup();
}
}
template <typename T1, typename T2, typename... Tn>
inline void add_component()
{
add_component<T1>();
add_component<T2, Tn...>();
}
template <typename T>
inline void draw_component(Entity entity)
{
}
template <typename T1, typename T2, typename... Tn>
inline void draw_component(Entity entity)
{
draw_component<T1>(entity);
draw_component<T2, Tn...>(entity);
}
template <>
inline void draw_component<cmpt::Tag>(Entity entity)
{
if (entity.hasComponent<cmpt::Tag>())
{
ImGui::Text("Tag");
ImGui::SameLine();
auto &tag = entity.getComponent<cmpt::Tag>().name;
char buffer[64];
memset(buffer, 0, sizeof(buffer));
std::memcpy(buffer, tag.data(), sizeof(buffer));
ImGui::PushItemWidth(150.f);
if (ImGui::InputText("##Tag", buffer, sizeof(buffer)))
{
tag = std::string(buffer);
}
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::Checkbox("Active", &entity.getComponent<cmpt::Tag>().active);
}
}
template <>
inline void draw_component<cmpt::Transform>(Entity entity)
{
draw_component<cmpt::Transform>(
"Transform", entity, [](auto &component) {
component.update = draw_vec3_control("Translation", component.translation, 0.f);
component.update |= draw_vec3_control("Rotation", component.rotation, 0.f);
component.update |= draw_vec3_control("Scale", component.scale, 1.f);
},
true);
}
template <>
inline void draw_component<cmpt::Hierarchy>(Entity entity)
{
draw_component<cmpt::Hierarchy>(
"Hierarchy", entity, [](auto &component) {
ImGui::Text("Parent: %s", component.parent == entt::null ? "false" : "true");
ImGui::Text("Children: %s", component.first == entt::null ? "false" : "true");
ImGui::Text("Siblings: %s", component.next == entt::null && component.prev == entt::null ? "false" : "true");
},
true);
}
template <>
inline void draw_component<cmpt::MeshRenderer>(Entity entity)
{
draw_component<cmpt::MeshRenderer>(
"MeshRenderer", entity, [](cmpt::MeshRenderer &component) {
ImGui::Text("Model: ");
ImGui::SameLine();
ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.f, 0.f));
if (ImGui::Button(component.model.c_str(), component.model.empty() ? ImVec2(250.f, 0.f) : ImVec2(0.f, 0.f)))
{
component.model = "";
component.materials.clear();
}
ImGui::PopStyleVar();
if (ImGui::BeginDragDropTarget())
{
if (const auto *pay_load = ImGui::AcceptDragDropPayload("Model"))
{
ASSERT(pay_load->DataSize == sizeof(std::string));
std::string new_model = *static_cast<std::string *>(pay_load->Data);
if (component.model != new_model)
{
component.model = new_model;
auto &model = Renderer::instance()->getResourceCache().loadModel(component.model);
for (auto &submesh : model.get().submeshes)
{
component.materials.emplace_back(createScope<material::DisneyPBR>());
*static_cast<material::DisneyPBR *>(component.materials.back().get()) = submesh.material;
}
}
}
ImGui::EndDragDropTarget();
}
if (Renderer::instance()->getResourceCache().hasModel(component.model))
{
auto &model = Renderer::instance()->getResourceCache().loadModel(component.model);
uint32_t idx = 0;
for (uint32_t i = 0; i < model.get().submeshes.size(); i++)
{
auto &submesh = model.get().submeshes[i];
if (component.materials.size() <= i)
{
component.materials.emplace_back(createScope<material::DisneyPBR>());
}
auto &material = component.materials[i];
if (ImGui::TreeNode((std::string("Submesh #") + std::to_string(idx++)).c_str()))
{
// Submesh attributes
if (ImGui::TreeNode("Mesh Attributes"))
{
ImGui::Text("vertices count: %d", submesh.vertices.size());
ImGui::Text("indices count: %d", submesh.indices.size());
ImGui::Text("index offset: %d", submesh.index_offset);
ImGui::Text("AABB bounding box:");
ImGui::BulletText("min (%f, %f, %f)", submesh.bounding_box.min_.x, submesh.bounding_box.min_.y, submesh.bounding_box.min_.z);
ImGui::BulletText("max (%f, %f, %f)", submesh.bounding_box.max_.x, submesh.bounding_box.max_.y, submesh.bounding_box.max_.z);
ImGui::TreePop();
}
// Material attributes
if (ImGui::TreeNode("Material Attributes"))
{
// Switch material type
if (ImGui::Button(material ? material->type().name() : "Select Material"))
{
ImGui::OpenPopup("Material Type");
}
if (ImGui::BeginPopup("Material Type"))
{
select_material<material::DisneyPBR>(material);
ImGui::EndPopup();
}
draw_material(material);
ImGui::TreePop();
}
ImGui::TreePop();
}
}
}
});
}
template <>
inline void draw_component<cmpt::Light>(Entity entity)
{
draw_component<cmpt::Light>(
"Light", entity, [](cmpt::Light &component) {
const char *const LightNames[] = {"None", "Directional", "Point", "Spot"};
int current = static_cast<int>(component.type);
ImGui::Combo("Type", ¤t, LightNames, 4);
if (component.type != cmpt::LightType::None && !component.impl)
{
return;
}
if (component.type == cmpt::LightType::Directional)
{
auto light = static_cast<cmpt::DirectionalLight *>(component.impl.get());
ImGui::DragFloat("Intensity", &light->data.intensity, 0.01f, 0.f, std::numeric_limits<float>::max(), "%.3f");
ImGui::ColorEdit3("Color", glm::value_ptr(light->data.color));
ImGui::DragFloat3("Direction", glm::value_ptr(light->data.direction), 0.1f, 0.0f, 0.0f, "%.3f");
}
else if (component.type == cmpt::LightType::Spot)
{
auto light = static_cast<cmpt::SpotLight *>(component.impl.get());
ImGui::DragFloat("Intensity", &light->data.intensity, 0.01f, 0.f, std::numeric_limits<float>::max(), "%.3f");
ImGui::ColorEdit3("Color", glm::value_ptr(light->data.color));
ImGui::DragFloat3("Direction", glm::value_ptr(light->data.direction), 0.1f, 0.0f, 0.0f, "%.3f");
ImGui::DragFloat("Cut off", &light->data.cut_off, 0.0001f, 0.f, std::numeric_limits<float>::max(), "%.5f");
ImGui::DragFloat("Outer cut off", &light->data.outer_cut_off, 0.0001f, 0.f, std::numeric_limits<float>::max(), "%.5f");
}
else if (component.type == cmpt::LightType::Point)
{
auto light = static_cast<cmpt::PointLight *>(component.impl.get());
ImGui::DragFloat("Intensity", &light->data.intensity, 0.01f, 0.f, std::numeric_limits<float>::max(), "%.3f");
ImGui::ColorEdit3("Color", glm::value_ptr(light->data.color));
ImGui::DragFloat("Constant", &light->data.constant, 0.0001f, 0.f, std::numeric_limits<float>::max(), "%.5f");
ImGui::DragFloat("Linear", &light->data.linear, 0.0001f, 0.f, std::numeric_limits<float>::max(), "%.5f");
ImGui::DragFloat("Quadratic", &light->data.quadratic, 0.0001f, 0.f, std::numeric_limits<float>::max(), "%.5f");
}
else if (component.type == cmpt::LightType::Area)
{
ImGui::Text("Area");
}
component.type = static_cast<cmpt::LightType>(current);
});
}
Inspector::Inspector()
{
m_name = "Inspector";
}
void Inspector::draw(float delta_time)
{
ImGui::Begin("Inspector", &active);
auto entity = Editor::instance()->getSelect();
if (!entity.valid())
{
ImGui::End();
return;
}
// Editable tag
draw_component<cmpt::Tag>(entity);
ImGui::SameLine();
ImGui::PushItemWidth(-1);
// Add components popup
if (ImGui::Button("Add Component"))
{
ImGui::OpenPopup("AddComponent");
}
if (ImGui::BeginPopup("AddComponent"))
{
add_component<cmpt::MeshRenderer, cmpt::Light>();
ImGui::EndPopup();
}
ImGui::PopItemWidth();
draw_component<cmpt::Transform, cmpt::Hierarchy, cmpt::MeshRenderer, cmpt::Light>(entity);
ImGui::End();
}
} // namespace Ilum::panel
| 30.889546
| 211
| 0.655961
|
LavenSun
|
44b2af13c4693fd56ed378502edc9b95c73f56b9
| 1,482
|
cc
|
C++
|
bench/SpConvI8Benchmark.cc
|
wuhuikx/FBGEMM
|
672beabd4c315a020adf07a1b8bd2018a18e0dd1
|
[
"BSD-3-Clause"
] | null | null | null |
bench/SpConvI8Benchmark.cc
|
wuhuikx/FBGEMM
|
672beabd4c315a020adf07a1b8bd2018a18e0dd1
|
[
"BSD-3-Clause"
] | null | null | null |
bench/SpConvI8Benchmark.cc
|
wuhuikx/FBGEMM
|
672beabd4c315a020adf07a1b8bd2018a18e0dd1
|
[
"BSD-3-Clause"
] | null | null | null |
#include "bench/BenchUtils.h"
#include "fbgemm/FbgemmSpConv.h"
#include <iostream>
using namespace std;
using namespace fbgemm;
int main(int, char**) {
vector<char> llc(128 * 1024 * 1024);
// clang-format off
vector<vector<unsigned>> shapes = {
{128, 128, 28, 28}
};
// clang-format on
// C is MxN -> CT is NxM
// A is MxK -> BT is KxM
// B is KxN -> AT is NxK
for (auto const& s : shapes) {
int Cout = s[0];
int Cin = s[1];
int IY = s[2];
int IX = s[3];
for (float fnz = 0.99; fnz >= 0.009999; fnz -= 0.01) {
constexpr int KY = 3;
constexpr int KX = 3;
auto kData = getRandomSparseVector(KY * KX * Cout * Cin / 4, fnz);
auto bData = getRandomSparseVector(Cin * IY * IX / 4);
auto cData = getRandomSparseVector(Cout * IY * IX);
auto kptr = reinterpret_cast<const int8_t*>(kData.data());
auto bptr = reinterpret_cast<uint8_t*>(bData.data());
for (int i = 0; i < bData.size() * 4; ++i) {
bptr[i] &= 0x7F;
}
auto cptr = reinterpret_cast<int32_t*>(cData.data());
auto fn = generateSpConv<int32_t>(Cin, Cout, IY, IX, kptr);
double effective_flop = IY * IX * Cin * Cout * KY * KX * 2;
auto secs =
fbgemm::measureWithWarmup([&]() { fn(bptr, cptr); }, 5, 10, &llc);
double effective_gflops = effective_flop / secs / 1e9;
cout << fnz << "," << effective_gflops << "," << fnz * effective_gflops
<< endl;
}
}
}
| 25.551724
| 77
| 0.566127
|
wuhuikx
|
44b43fa6dbfdca8589f6eedd3ea24335d6cb48df
| 1,749
|
cpp
|
C++
|
10002.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
10002.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
10002.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
PDD t[110];
int N,x,y,z;
double Ax,Ay,A;
vector<PDD> ch;
stack<PDD> s;
double det(PDD p,PDD q,PDD r)
{
return(p.fi*(q.se-r.se)+q.fi*(r.se-p.se)+r.fi*(p.se-q.se));
}
double dis(PDD i)
{
double x=t[0].fi-i.fi;
double y=t[0].se-i.se;
return(x*x+y*y);
}
bool cf(PDD i,PDD j)
{
if(fabs(det(t[0],i,j))<eps) return(dis(i)<dis(j));
return(det(t[0],i,j)>0);
}
int main()
{
while(1)
{
scanf("%d",&N);
if(N<3) break;
int PO=0;
for(x=0;x<N;x++)
{
scanf("%lf %lf",&t[x].fi,&t[x].se);
if((t[PO].se>t[x].se)||((fabs(t[PO].se-t[x].se)<eps)&&(t[PO].fi<t[x].fi))) PO=x;
}
swap(t[PO],t[0]);
sort(t+1,t+N,cf);
s.push(t[N-1]);
s.push(t[0]);
x=1;
PDD now,prev;
while(x<N)
{
now=s.top();s.pop();
prev=s.top();s.push(now);
if(det(prev,now,t[x])>0) s.push(t[x++]); else s.pop();
}
ch.clear();
while(!s.empty())
{
ch.pb(s.top());
s.pop();
}ch.pop_back();
Ax=Ay=A=0;
for(x=2;x<ch.size();x++)
{
double L=0.5*fabs(det(ch[0],ch[x-1],ch[x]));
Ax+=(ch[0].fi+ch[x-1].fi+ch[x].fi)*L/(double)3.0;
Ay+=(ch[0].se+ch[x-1].se+ch[x].se)*L/(double)3.0;
A+=L;
}
Ax/=A;
Ay/=A;
printf("%.3lf %.3lf\n",Ax,Ay);
}
return 0;
}
| 16.980583
| 84
| 0.523728
|
felikjunvianto
|
44b51a507ec5e8bb63bd86383598b502d03c7e43
| 30,138
|
cpp
|
C++
|
BE_Supporter/MtnAlgo/MtnAFT/dllsrc/MotDLL_LoadWbDefSpeedServo.cpp
|
ZHAOZhengyi-tgx/BE-Supporter_2016
|
88bb9c7b1c16afeaff4855aa0dd3b316c394e68a
|
[
"MIT"
] | null | null | null |
BE_Supporter/MtnAlgo/MtnAFT/dllsrc/MotDLL_LoadWbDefSpeedServo.cpp
|
ZHAOZhengyi-tgx/BE-Supporter_2016
|
88bb9c7b1c16afeaff4855aa0dd3b316c394e68a
|
[
"MIT"
] | null | null | null |
BE_Supporter/MtnAlgo/MtnAFT/dllsrc/MotDLL_LoadWbDefSpeedServo.cpp
|
ZHAOZhengyi-tgx/BE-Supporter_2016
|
88bb9c7b1c16afeaff4855aa0dd3b316c394e68a
|
[
"MIT"
] | null | null | null |
//The MIT License (MIT)
//
//Copyright (c) 2016 ZHAOZhengyi-tgx
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
// (c)All right reserved, sg.LongRenE@gmail.com
#include "stdafx.h"
#include "MtnApi.h"
#include "MtnInitAcs.h"
#include "MotAlgo_DLL.h"
#include "MtnAlgo_Private.h"
#include "mtndefin.h"
#include "MtnWbDef.h" // 20130305
extern COMM_SETTINGS stServoControllerCommSet;
// Defined local
extern void mtnapi_wb_LoadDefaultMotionPara(SERVO_MOTION_PARAMETER *pSpeedPara);
extern void mtnapi_wb_LoadDefaultControlProfile(SERVO_CONTROL_PARAMETER *pControlProfile);
extern void mtnapi_dll_InitWireBondServoAxisName();
extern void mtnapi_init_static_vaj_unit_factor();
#ifdef __INIT_ACS_BUFF__
extern short acs_buff_prog_init_comm(HANDLE stCommHandle);
#endif // __INIT_ACS_BUFF__
char cFlag_ConnectACS_SC_UDI;
char sys_acs_communication_get_flag_sc_udi()
{
return cFlag_ConnectACS_SC_UDI;
}
char aAxisList_BndZ_ACS[256] = {APP_Z_BOND_ACS_PCI_ID, APP_Z_BOND_ACS_SC_UDI_ID};
char aAxisList_BndWireClamp_ACS[256] = {APP_WIRE_CLAMP_ACS_PCI_ID, APP_WIRE_CLAMP_ACS_SC_UDI_ID};
void sys_acs_communication_set_flag_sc_udi(char cTempFlag)
{
cFlag_ConnectACS_SC_UDI = cTempFlag;
}
char sys_get_acs_communication_flag_udi()
{
return cFlag_ConnectACS_SC_UDI;
}
char sys_get_acs_axis_id_bnd_z()
{
return aAxisList_BndZ_ACS[cFlag_ConnectACS_SC_UDI];
}
char sys_get_acs_axis_id_wire_clamp()
{
return aAxisList_BndWireClamp_ACS[cFlag_ConnectACS_SC_UDI];
}
///// static variables
static HANDLE hLocalDllInitAcsHandle; static int iFlagInitByLocalAcsComm = 0;
static double dTableX_EncRes_mm;
static double dTableY_EncRes_mm;
static double dBndHeadZ_EncRes_mm;
static double dFactorBH_Z_Acc_Fr_cnt_sec_to_si;
static double dFactorTbl_X_Acc_Fr_cnt_sec_to_si;
static double dFactorTbl_Y_Acc_Fr_cnt_sec_to_si;
static double dFactorBH_Z_Jerk_Fr_cnt_sec_to_si;
static double dFactorTbl_X_Jerk_Fr_cnt_sec_to_si;
static double dFactorTbl_Y_Jerk_Fr_cnt_sec_to_si;
static double dFactorBH_Z_Vel_Fr_cnt_sec_to_mmps;
static double dFactorTbl_X_Vel_Fr_cnt_sec_to_mmps;
static double dFactorTbl_Y_Vel_Fr_cnt_sec_to_mmps;
char *strDeBugServoWb = "C:\\WbData\\ParaBase\\Test1.000";
FILE *fpDebugServoIni = NULL;
extern SERVO_AXIS_BLK stServoAxis_ACS[MAX_CTRL_AXIS_PER_SERVO_BOARD];
#define MOT_ALGO_DLL_VERSION_MINOR 2
#define MOT_ALGO_DLL_VERSION_MAJOR 1
#define MOT_ALGO_DLL_VERSION_DATE 27
#define MOT_ALGO_DLL_VERSION_MONTH 2
#define MOT_ALGO_DLL_VERSION_YEAR 2012
int mtnapi_dll_init_get_version(VERSION_INFO *stpVersion)
{
stpVersion->usVerMajor = MOT_ALGO_DLL_VERSION_MAJOR;
stpVersion->usVerMinor = MOT_ALGO_DLL_VERSION_MINOR;
////
stpVersion->usVerDate = MOT_ALGO_DLL_VERSION_DATE;
stpVersion->usVerMonth = MOT_ALGO_DLL_VERSION_MONTH;
stpVersion->usVerYear = MOT_ALGO_DLL_VERSION_YEAR;
return MTN_API_OK_ZERO;
}
static int iFlagDonePointerInitialization;
// Save speed and servo parameter for wb application
char *strDefaultSaveFilename_SpeedServoWb = "C:\\WbData\\ParaBase\\ServoMaster.ini";
char *strDefaultReadDownloadFilename_SpeedServoWb = "C:\\WbData\\DefParaBase\\ServoMaster.ini";
// Init default parameter
// it is important to initialize the memory in the dll
void mtnapi_dll_init_master_struct_ptr()
{
if( iFlagDonePointerInitialization == 0)
{
unsigned int ii;
stServoACS.uiTotalNumAxis = MAX_CTRL_AXIS_PER_SERVO_BOARD;
for( ii = 0; ii<stServoACS.uiTotalNumAxis; ii++)
{
stServoACS.stpServoAxis_ACS[ii] = &stServoAxis_ACS[ii];
stServoACS.stpSafetyAxis_ACS[ii] = &stSafetyParaAxis_ACS[ii];
stServoACS.stpBasicAxis_ACS[ii] = &stBasicParaAxis_ACS[ii];
}
iFlagDonePointerInitialization = 1;
}
sprintf_s(&stServoACS.strFilename[0], MTN_API_MAX_STRLEN_FILENAME, "%s", strDefaultSaveFilename_SpeedServoWb);
}
#include "MtnWbDef.h"
extern char *astrWireBondServoAxisNameEn[];
extern char *astrWireBondServoAxisNameCn[];
extern double afRatioRMS_DrvCmd[MAX_SERVO_AXIS_WIREBOND];
extern AXIS_INFO_WIRE_BOND astAxisInfoWireBond[MAX_SERVO_AXIS_WIREBOND];
void mtnapi_dll_InitWireBondServoAxisName_VerLED_ACS()
{
astAxisInfoWireBond[WB_AXIS_TABLE_X].iAxisInCtrlCardACS = ACS_CARD_AXIS_X;
astAxisInfoWireBond[WB_AXIS_TABLE_Y].iAxisInCtrlCardACS = ACS_CARD_AXIS_Y;
astAxisInfoWireBond[WB_AXIS_BOND_Z].iAxisInCtrlCardACS = ACS_CARD_AXIS_A;
astAxisInfoWireBond[WB_AXIS_WIRE_CLAMP].iAxisInCtrlCardACS = ACS_CARD_AXIS_B;
for(int ii=0; ii<MAX_SERVO_AXIS_WIREBOND; ii++)
{
astAxisInfoWireBond[ii].strAxisNameCn = astrWireBondServoAxisNameCn[ii];
astAxisInfoWireBond[ii].strAxisNameEn = astrWireBondServoAxisNameEn[ii];
}
astAxisInfoWireBond[WB_AXIS_TABLE_X].afEncoderResolution_cnt_p_mm = 2000;
astAxisInfoWireBond[WB_AXIS_TABLE_Y].afEncoderResolution_cnt_p_mm = 2000;
astAxisInfoWireBond[WB_AXIS_BOND_Z].afEncoderResolution_cnt_p_mm = 1000;
astAxisInfoWireBond[WB_AXIS_WIRE_CLAMP].afEncoderResolution_cnt_p_mm = 0;
afRatioRMS_DrvCmd[WB_AXIS_TABLE_X] = 0.27;
afRatioRMS_DrvCmd[WB_AXIS_TABLE_Y] = 0.25;
afRatioRMS_DrvCmd[WB_AXIS_BOND_Z] = 0.25;
afRatioRMS_DrvCmd[WB_AXIS_WIRE_CLAMP] = 0.3;
}
void mtnapi_dll_InitWireBondServoAxisName_YZ_1SP_ACS()
{
astAxisInfoWireBond[WB_AXIS_TABLE_X].iAxisInCtrlCardACS = ACS_CARD_AXIS_Y;
astAxisInfoWireBond[WB_AXIS_TABLE_Y].iAxisInCtrlCardACS = ACS_CARD_AXIS_X;
astAxisInfoWireBond[WB_AXIS_BOND_Z].iAxisInCtrlCardACS = ACS_CARD_AXIS_A;
astAxisInfoWireBond[WB_AXIS_WIRE_CLAMP].iAxisInCtrlCardACS = ACS_CARD_AXIS_B;
for(int ii=0; ii<MAX_SERVO_AXIS_WIREBOND; ii++)
{
astAxisInfoWireBond[ii].strAxisNameCn = astrWireBondServoAxisNameCn[ii];
astAxisInfoWireBond[ii].strAxisNameEn = astrWireBondServoAxisNameEn[ii];
}
astAxisInfoWireBond[WB_AXIS_TABLE_X].afEncoderResolution_cnt_p_mm = 2000;
astAxisInfoWireBond[WB_AXIS_TABLE_Y].afEncoderResolution_cnt_p_mm = 2000;
astAxisInfoWireBond[WB_AXIS_BOND_Z].afEncoderResolution_cnt_p_mm = 1000;
astAxisInfoWireBond[WB_AXIS_WIRE_CLAMP].afEncoderResolution_cnt_p_mm = 0;
afRatioRMS_DrvCmd[WB_AXIS_TABLE_X] = 0.27;
afRatioRMS_DrvCmd[WB_AXIS_TABLE_Y] = 0.25;
afRatioRMS_DrvCmd[WB_AXIS_BOND_Z] = 0.25;
afRatioRMS_DrvCmd[WB_AXIS_WIRE_CLAMP] = 0.3;
}
void mtnapi_dll_InitWireBondServoAxisName()
{
int iTempMachTypeFlag = get_sys_machine_type_flag();
if(iTempMachTypeFlag == WB_MACH_TYPE_VLED_FORK ||
iTempMachTypeFlag == WB_MACH_TYPE_ONE_TRACK_13V_LED ||
iTempMachTypeFlag == WB_MACH_TYPE_VLED_MAGAZINE ) // machine type dependency Item-2.
{
mtnapi_dll_InitWireBondServoAxisName_VerLED_ACS();
}
else if(iTempMachTypeFlag == WB_MACH_TYPE_HORI_LED || iTempMachTypeFlag == WB_STATION_XY_TOP|| iTempMachTypeFlag == BE_WB_HORI_20T_LED
|| iTempMachTypeFlag == BE_WB_ONE_TRACK_18V_LED)
{
mtnapi_dll_InitWireBondServoAxisName_YZ_1SP_ACS();
}
else
{
mtnapi_dll_InitWireBondServoAxisName_VerLED_ACS();
}
}
void mtnapi_dll_init_all()
{
// 1. Machine config
int iTempMachCfg;
if(mtn_api_load_machine_config(&iTempMachCfg) == MTN_API_OK_ZERO)
{
mtn_wb_dll_set_sys_machine_type(iTempMachCfg); //iFlagSysMachineType = iTempMachCfg;
}
// 2. initialize with default parameter
mtnapi_dll_init_master_struct_ptr(); // mtnapi_init_master_struct_ptr();
mtnapi_init_def_servo_acs();
// 3. WireBonder Application related
// mtnapi_dll_InitWireBondServoAxisName(); // InitWireBondServoAxisName(); //
if(iTempMachCfg == WB_MACH_TYPE_VLED_FORK || iTempMachCfg == WB_MACH_TYPE_ONE_TRACK_13V_LED ||
iTempMachCfg == WB_MACH_TYPE_VLED_MAGAZINE ) // machine type dependency Item-2.
{
mtnapi_dll_InitWireBondServoAxisName_VerLED_ACS();
}
else if(iTempMachCfg == WB_MACH_TYPE_HORI_LED || iTempMachCfg == WB_STATION_XY_TOP || iTempMachCfg == BE_WB_HORI_20T_LED
|| iTempMachCfg == BE_WB_ONE_TRACK_18V_LED)
{
mtnapi_dll_InitWireBondServoAxisName_YZ_1SP_ACS();
}
else
{
mtnapi_dll_InitWireBondServoAxisName_VerLED_ACS();
}
mtnapi_init_static_vaj_unit_factor();
// 4 Tuning Related
mtn_tune_init_wb_bondhead_tuning_position_set();
mtn_tune_init_wb_table_x_tuning_position_set();
mtn_dll_wb_tune_initialization(); // 20120117
// 5. Home Related
iTempMachCfg = get_sys_machine_type_flag();
if(iTempMachCfg == WB_MACH_TYPE_VLED_FORK || iTempMachCfg == WB_STATION_XY_VERTICAL ||
iTempMachCfg == WB_MACH_TYPE_VLED_MAGAZINE ) // machine type dependency Item-3.
{
mtn_dll_init_def_para_search_index_vled_bonder_xyz(APP_X_TABLE_ACS_ID, APP_Y_TABLE_ACS_ID, sys_get_acs_axis_id_bnd_z());
mtn_tune_init_wb_table_y_tuning_vled_position_set();
}
else if(iTempMachCfg == WB_MACH_TYPE_HORI_LED || iTempMachCfg == WB_STATION_XY_TOP|| iTempMachCfg == BE_WB_HORI_20T_LED
|| iTempMachCfg == BE_WB_ONE_TRACK_18V_LED)
{
mtn_dll_init_def_para_search_index_hori_bonder_xyz(APP_X_TABLE_ACS_ID, APP_Y_TABLE_ACS_ID, sys_get_acs_axis_id_bnd_z());
if(iTempMachCfg == BE_WB_ONE_TRACK_18V_LED)
{
mtn_tune_init_wb_table_y_tuning_vled_position_set();
}
else
{
mtn_tune_init_wb_table_y_tuning_hori_led_position_set();
}
}
else // if (get_sys_machine_type_flag() == WB_MACH_TYPE_ONE_TRACK_13V_LED) // default
{
mtn_dll_init_def_para_search_index_13v_vled_bonder_xyz(APP_X_TABLE_ACS_ID, APP_Y_TABLE_ACS_ID, sys_get_acs_axis_id_bnd_z());
mtn_tune_init_wb_table_y_tuning_vled_position_set();
}
}
extern short acs_init_buffer_prog_prbs_prof_cfg_move();
short acs_clear_buffer_prog_prbs_prof_cfg_move();
// Update Last saved parameter for next time of loading
// Check path
// modify the READONLY mode to R/W
// delete
// Copy
// Set mode to READONLY
// 20110404, to write to para, with protection if no such folder
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <direct.h>
int mtnapi_create_para_base_master_template()
{
int iRet = MTN_API_OK_ZERO;
// unsigned int ii;
FILE *fptr;
char strPathBuffer[_MAX_PATH];
char strPathCurrBakBuffer[_MAX_PATH];
_getcwd(strPathCurrBakBuffer, _MAX_PATH);
if(_chdir("C:\\WbData\\ParaBase\\"))
{
_mkdir("C:\\WbData"); // 20120522
_mkdir("C:\\WbData\\ParaBase\\");
}
_chdir(strPathCurrBakBuffer);
_makepath(strPathBuffer, "C", "\\WbData\\ParaBase\\", "ServoMaster", "ini");
fopen_s(&fptr, strDefaultSaveFilename_SpeedServoWb, "w");
if(fptr != NULL)
{
fprintf(fptr, "## BE-WB Servo Control Parameter dataBase\n");
fprintf(fptr, "## Under GNU license, (c) All right reserved\n");
fprintf(fptr, "## efsika@gmail.com\n");
fprintf(fptr, "\n\n[SERVO_MASTER_CONFIG]\n");
fprintf(fptr, "TOTAL_AXIS = %d\n", 4);
fprintf(fptr, "CONTROLLER_BOARD = A3S\n\n"); // just for security
// Table-X 0
fprintf(fptr, "[SERVO_SETTING_AXIS_1]\n");
fprintf(fptr, "APPLICATION_NAME = X_TBL\n");
fprintf(fptr, "PARA_FILE_PATH = C:\\WbData\\ParaBase\\ctrl_acsc_x.ini\n");
fprintf(fptr, "MTN_TUNE_AXIS = C:\\WbData\\ParaBase\\MtnTune_acs_x.ini\n");
fprintf(fptr, "AXIS_ON_SERVO_BOARD = 1\n\n");
// Table-Y 1
fprintf(fptr, "[SERVO_SETTING_AXIS_2]\n");
fprintf(fptr, "APPLICATION_NAME = Y_TBL\n");
fprintf(fptr, "PARA_FILE_PATH = C:\\WbData\\ParaBase\\ctrl_acsc_y.ini\n");
fprintf(fptr, "MTN_TUNE_AXIS = C:\\WbData\\ParaBase\\MtnTune_acs_y.ini\n");
fprintf(fptr, "AXIS_ON_SERVO_BOARD = 0\n\n");
// Bnd-Z, 4-ACS
fprintf(fptr, "[SERVO_SETTING_AXIS_3]\n");
fprintf(fptr, "APPLICATION_NAME = Z_BONDHEAD\n");
fprintf(fptr, "PARA_FILE_PATH = C:\\WbData\\ParaBase\\ctrl_acsc_z.ini\n");
fprintf(fptr, "MTN_TUNE_AXIS = C:\\WbData\\ParaBase\\MtnTune_acs_z.ini\n");
fprintf(fptr, "AXIS_ON_SERVO_BOARD = 4\n\n");
// WireClamp, 5
fprintf(fptr, "[SERVO_SETTING_AXIS_4]\n");
fprintf(fptr, "APPLICATION_NAME = WireClamp\n");
fprintf(fptr, "PARA_FILE_PATH = C:\\WbData\\ParaBase\\ctrl_acsc_w.ini\n");
fprintf(fptr, "MTN_TUNE_AXIS = C:\\WbData\\ParaBase\\MtnTune_acs_z.ini\n");
fprintf(fptr, "AXIS_ON_SERVO_BOARD = 5\n\n");
//for(int ii = 0; ii <NUM_TOTAL_PROGRAM_BUFFER; ii ++) // // 20090508
//{
// fprintf(fptr, "\n\n[ACS_PROG_CONFIG-%d]\n", ii);
// fprintf(fptr, "0x%x\n", stServoACS.stGlobalParaACS.aiProgramFlags[ii]); // ProgramFlags
// fprintf(fptr, "%d\n", stServoACS.stGlobalParaACS.aiProgramRate[ii]); // ProgramRate
// fprintf(fptr, "%d\n", stServoACS.stGlobalParaACS.aiProgramAutoRoutineRate[ii]); // ProgramAutoRoutineRate
//}
fclose(fptr);
}
else
{
iRet = MTN_API_ERR_FILE_PTR;
}
return iRet;
}
// Save to c:\\WbData\\ParaBase
int mtnapi_dll_save_wb_speed_servo_parameter_acs(HANDLE hAcsHandle)
{
int iRet = MTN_API_OK_ZERO;
mtnapi_dll_init_master_struct_ptr();
// mtnapi_test_write_file_1();
if((iRet =sys_init_acs_communication()) == MTN_API_OK_ZERO)
{
hLocalDllInitAcsHandle = stServoControllerCommSet.Handle;
// Buffer Program
#ifdef __INIT_ACS_BUFF__
acs_buff_prog_init_comm(stServoControllerCommSet.Handle);
mtn_api_clear_acs_buffer_prof(); // Each time stop and clean the buffer program, before downloading
Sleep(200);
mtn_api_init_acs_buffer_prog();
#endif // __INIT_ACS_BUFF__
iFlagInitByLocalAcsComm = 1;
}
else
{
hLocalDllInitAcsHandle = hAcsHandle;
}
// Initialize buffer program
#ifdef __INIT_ACS_BUFF__
acs_buff_prog_init_comm(hLocalDllInitAcsHandle);
acs_init_buffer_prog_prbs_prof_cfg_move(); // must initialize buffer program
#endif // __INIT_ACS_BUFF__
mtnapi_confirm_para_base_path_exist(); // 20110404, Protection to handle
iRet = mtnapi_init_master_config_acs(strDefaultSaveFilename_SpeedServoWb, hLocalDllInitAcsHandle); // NOT, mtnapi_init_servo_control_para_acs
iRet = mtnapi_upload_wb_servo_speed_parameter_acs(hLocalDllInitAcsHandle);
// mtnapi_test_write_file_2(hAcsHandle);
if(iRet == MTN_API_OK_ZERO)
{
iRet = mtnapi_save_servo_parameter_acs();
}
// acs_clear_buffer_prog_prbs_prof_cfg_move();
if(iFlagInitByLocalAcsComm == 1)
{
#ifdef __INIT_ACS_BUFF__
mtn_api_clear_acs_buffer_prof();
#endif // __INIT_ACS_BUFF__
acsc_CloseComm(stServoControllerCommSet.Handle);
iFlagInitByLocalAcsComm = 0; // Protection, 20110121
}
// mtnapi_test_close_file();
return iRet;
}
//#define __DEBUG__
int mtnapi_dll_init_wb_speed_parameter_acs(HANDLE hAcsHandle, SERVO_MOTION_PARAMETER *pSpeedPara)
{
mtnapi_dll_init_all(); // mtnapi_dll_init_master_struct_ptr();
int iRet = MTN_API_OK_ZERO;
#ifdef __DEBUG__
mtnapi_test_write_file_1();
#endif
mtnapi_init_wb_def_servo_control_para_acs(hAcsHandle);
if( iRet == MTN_API_OK_ZERO)
{
mtnapi_wb_LoadDefaultMotionPara(pSpeedPara);
}
else
{
mtnapi_wb_LoadDefaultMotionPara(pSpeedPara);
iRet = MTN_API_ERROR_INIT_WB_MOTION;
}
#ifdef __DEBUG__
mtnapi_test_write_file_3(pSpeedPara);
mtnapi_test_close_file();
#endif
return iRet;
}
int mtnapi_dll_init_wb_servo_parameter_acs(HANDLE hAcsHandle, SERVO_CONTROL_PARAMETER *pControlProfile)
{
mtnapi_dll_init_master_struct_ptr();
int iRet = MTN_API_OK_ZERO;
mtnapi_init_wb_def_servo_control_para_acs(hAcsHandle); // call mtnapi_init_servo_control_para_acs
if( iRet == MTN_API_OK_ZERO)
{
mtnapi_wb_LoadDefaultControlProfile(pControlProfile);
}
else
{
mtnapi_wb_LoadDefaultControlProfile(pControlProfile);
iRet = MTN_API_ERROR_INIT_WB_MOTION;
}
return iRet;
}
extern AXIS_INFO_WIRE_BOND astAxisInfoWireBond[MAX_SERVO_AXIS_WIREBOND];
void mtnapi_init_static_vaj_unit_factor()
{
dTableX_EncRes_mm = astAxisInfoWireBond[WB_AXIS_TABLE_X].afEncoderResolution_cnt_p_mm;
dTableY_EncRes_mm = astAxisInfoWireBond[WB_AXIS_TABLE_Y].afEncoderResolution_cnt_p_mm;
dBndHeadZ_EncRes_mm = astAxisInfoWireBond[WB_AXIS_BOND_Z].afEncoderResolution_cnt_p_mm;
dFactorBH_Z_Acc_Fr_cnt_sec_to_si = 1.0/dBndHeadZ_EncRes_mm/1000;
dFactorTbl_X_Acc_Fr_cnt_sec_to_si = 1.0/dTableX_EncRes_mm/1000;
dFactorTbl_Y_Acc_Fr_cnt_sec_to_si = 1.0/dTableY_EncRes_mm/1000;
dFactorBH_Z_Jerk_Fr_cnt_sec_to_si = 1.0/dBndHeadZ_EncRes_mm/1000;
dFactorTbl_X_Jerk_Fr_cnt_sec_to_si = 1.0/dTableX_EncRes_mm/1000;
dFactorTbl_Y_Jerk_Fr_cnt_sec_to_si = 1.0/dTableY_EncRes_mm/1000;
dFactorBH_Z_Vel_Fr_cnt_sec_to_mmps = 1.0/dBndHeadZ_EncRes_mm;
dFactorTbl_X_Vel_Fr_cnt_sec_to_mmps = 1.0/dTableX_EncRes_mm;
dFactorTbl_Y_Vel_Fr_cnt_sec_to_mmps = 1.0/dTableY_EncRes_mm;
}
void mtnapi_wb_LoadDefaultMotionPara(SERVO_MOTION_PARAMETER *pSpeedPara)
{
int ii;
// X
// pSpeedPara->stSpeedProfileX[0].nMaxVel = 950; //mm/s
// pSpeedPara->stSpeedProfileX[0].nMaxAcc = 25; //m/s^2 //@3
// pSpeedPara->stSpeedProfileX[0].lJerk = 6000; //m/s^3
//pSpeedPara->stSpeedProfileX[1].nMaxVel = 950; //mm/s
//pSpeedPara->stSpeedProfileX[1].nMaxAcc = 22; //m/s^2
//pSpeedPara->stSpeedProfileX[1].lJerk = 3000; //m/s^3
// pSpeedPara->stSpeedProfileX[2].nMaxVel = 950; //mm/s
// pSpeedPara->stSpeedProfileX[2].nMaxAcc = 15; //m/s^2
// pSpeedPara->stSpeedProfileX[2].lJerk = 1500; //m/s^3
//pSpeedPara->stSpeedProfileX[3].nMaxVel = 950; //mm/s
//pSpeedPara->stSpeedProfileX[3].nMaxAcc = 10; //m/s^2
//pSpeedPara->stSpeedProfileX[3].lJerk = 500; //m/s^3
for(ii = 0; ii<=3; ii++) // hard-code from WireBonder.exe
{
pSpeedPara->stSpeedProfileX[ii].nMaxVel = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_X]->stSpeedProfile[ii].dMaxVelocity * dFactorTbl_X_Vel_Fr_cnt_sec_to_mmps);
pSpeedPara->stSpeedProfileX[ii].nMaxAcc = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_X]->stSpeedProfile[ii].dMaxAcceleration * dFactorTbl_X_Acc_Fr_cnt_sec_to_si);
pSpeedPara->stSpeedProfileX[ii].lJerk = (long)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_X]->stSpeedProfile[ii].dMaxJerk * dFactorTbl_X_Jerk_Fr_cnt_sec_to_si);
}
// stServoACS.stpServoAxis_ACS[ii]->stSpeedProfile[0].dMaxAcceleration
for(ii = 0; ii<=3; ii++) // hard-code from WireBonder.exe
{
pSpeedPara->stSpeedProfileY[ii].nMaxVel = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_Y]->stSpeedProfile[ii].dMaxVelocity * dFactorTbl_Y_Vel_Fr_cnt_sec_to_mmps);
pSpeedPara->stSpeedProfileY[ii].nMaxAcc = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_Y]->stSpeedProfile[ii].dMaxAcceleration * dFactorTbl_Y_Acc_Fr_cnt_sec_to_si);
pSpeedPara->stSpeedProfileY[ii].lJerk = (long)(stServoACS.stpServoAxis_ACS[WB_AXIS_TABLE_Y]->stSpeedProfile[ii].dMaxJerk * dFactorTbl_Y_Jerk_Fr_cnt_sec_to_si);
}
for(ii = 0; ii<=4; ii++) // hard-code from WireBonder.exe
{ // WB_AXIS_BOND_Z
pSpeedPara->stSpeedProfileZ[ii].nMaxVel = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[ii+1].dMaxVelocity * dFactorBH_Z_Vel_Fr_cnt_sec_to_mmps); //mm/s
pSpeedPara->stSpeedProfileZ[ii].nMaxAcc = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[ii+1].dMaxAcceleration * dFactorBH_Z_Acc_Fr_cnt_sec_to_si); //m/s^2
pSpeedPara->stSpeedProfileZ[ii].lJerk = (long)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[ii+1].dMaxJerk * dFactorBH_Z_Jerk_Fr_cnt_sec_to_si); //m/s^3
}
ii = 5;
pSpeedPara->stSpeedProfileZ[ii].nMaxVel = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxVelocity * dFactorBH_Z_Vel_Fr_cnt_sec_to_mmps); //mm/s
pSpeedPara->stSpeedProfileZ[ii].nMaxAcc = (short)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxAcceleration * dFactorBH_Z_Acc_Fr_cnt_sec_to_si); //m/s^2
pSpeedPara->stSpeedProfileZ[ii].lJerk = (long)(stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxJerk * dFactorBH_Z_Jerk_Fr_cnt_sec_to_si); //m/s^3
}
void mtnapi_wb_LoadDefaultControlProfile(SERVO_CONTROL_PARAMETER *pControlProfile)
{
int ii;
// Table - X
for(ii = 0; ii < X_MOTOR_CONTROL_PROFILE_NUM; ii++)
{
pControlProfile->stControlProfileX[ii].lVelGain = (long)(stServoACS.stpServoAxis_ACS[0]->stServoParaACS[ii].dVelocityLoopProportionalGain); // 350;
pControlProfile->stControlProfileX[ii].lVelIntegrator = (long)(stServoACS.stpServoAxis_ACS[0]->stServoParaACS[ii].dVelocityLoopIntegratorGain);
pControlProfile->stControlProfileX[ii].lPosGain = (long)(stServoACS.stpServoAxis_ACS[0]->stServoParaACS[ii].dPositionLoopProportionalGain); // 150;
pControlProfile->stControlProfileX[ii].lAccFeedFwd = (long)(stServoACS.stpServoAxis_ACS[0]->stServoParaACS[ii].dAccelerationFeedforward); // 7250;
}
//Y
for(ii = 0; ii < Y_MOTOR_CONTROL_PROFILE_NUM; ii++)
{
pControlProfile->stControlProfileY[ii].lVelGain = (long)(stServoACS.stpServoAxis_ACS[1]->stServoParaACS[ii].dVelocityLoopProportionalGain); // 400;
pControlProfile->stControlProfileY[ii].lVelIntegrator = (long)(stServoACS.stpServoAxis_ACS[1]->stServoParaACS[ii].dVelocityLoopIntegratorGain); // 320;
pControlProfile->stControlProfileY[ii].lPosGain = (long)(stServoACS.stpServoAxis_ACS[1]->stServoParaACS[ii].dPositionLoopProportionalGain); // 50;
pControlProfile->stControlProfileY[ii].lAccFeedFwd = (long)(stServoACS.stpServoAxis_ACS[1]->stServoParaACS[ii].dAccelerationFeedforward); // 11250;
}
//Z=9
for(ii = 0; ii < Z_MOTOR_CONTROL_PROFILE_NUM; ii++)
{
pControlProfile->stControlProfileZ[ii].lVelGain = (long)(stServoACS.stpServoAxis_ACS[2]->stServoParaACS[ii].dVelocityLoopProportionalGain); // 30;
pControlProfile->stControlProfileZ[ii].lVelIntegrator = (long)(stServoACS.stpServoAxis_ACS[2]->stServoParaACS[ii].dVelocityLoopIntegratorGain); // 200;
pControlProfile->stControlProfileZ[ii].lPosGain = (long)(stServoACS.stpServoAxis_ACS[2]->stServoParaACS[ii].dPositionLoopProportionalGain); // 100;
pControlProfile->stControlProfileZ[ii].lAccFeedFwd = (long)(stServoACS.stpServoAxis_ACS[2]->stServoParaACS[ii].dAccelerationFeedforward); // 650;
}
}
int mtnapi_dll_init_servo_control_para_acs(HANDLE hAcsHandle, SERVO_MOTION_PARAMETER *pSpeedPara, SERVO_CONTROL_PARAMETER *pControlProfile)
{
mtnapi_dll_init_master_struct_ptr();
int iRet = mtnapi_init_wb_def_servo_control_para_acs(hAcsHandle);
if( iRet == MTN_API_OK_ZERO)
{
mtnapi_wb_LoadDefaultMotionPara(pSpeedPara);
mtnapi_wb_LoadDefaultControlProfile(pControlProfile);
}
else
{
mtnapi_wb_LoadDefaultMotionPara(pSpeedPara);
mtnapi_wb_LoadDefaultControlProfile(pControlProfile);
iRet = MTN_API_ERROR_INIT_WB_MOTION;
}
return iRet;
}
#include "MTN_WB_INTERFACE.h"
static SERVO_MOTION_PARAMETER stSpeedPara;
static SERVO_CONTROL_PARAMETER stControlProfile;
int _mtnapi_dll_init_wb_servo_parameter_acs(HANDLE hAcsHandle)
{
return mtnapi_dll_init_wb_servo_parameter_acs(hAcsHandle, &stControlProfile);
}
int _mtnapi_dll_init_servo_speed_para_acs(HANDLE hAcsHandle)
{
return mtnapi_dll_init_servo_control_para_acs(stServoControllerCommSet.Handle,
&stSpeedPara, &stControlProfile);
}
///////////////////////////////////// Download Parameter to WB structure Ctrl, Speed, in ACS
extern int mtn_wb_download_acs_servo_speed_parameter_acs(HANDLE hCommunicationHandle);
int mtn_wb_dll_download_acs_servo_speed_parameter_acs(HANDLE hCommunicationHandle)
{
int iRet = MTN_API_OK_ZERO;
mtnapi_dll_init_master_struct_ptr();
// mtnapi_test_write_file_1();
if(hCommunicationHandle != ACSC_INVALID)
{
hLocalDllInitAcsHandle = hCommunicationHandle;
}
else
{
if((iRet =sys_init_acs_communication()) == MTN_API_OK_ZERO)
{
hLocalDllInitAcsHandle = stServoControllerCommSet.Handle;
iFlagInitByLocalAcsComm = 1;
}
}
// Initialize buffer program
mtnapi_confirm_para_base_path_exist(); // 20110404, Protection to handle
iRet = mtnapi_init_master_config_acs(strDefaultReadDownloadFilename_SpeedServoWb, hLocalDllInitAcsHandle);
iRet = _mtnapi_dll_init_servo_speed_para_acs(hLocalDllInitAcsHandle);
// Sleep(100);
iRet = mtn_wb_download_acs_servo_speed_parameter_acs(hLocalDllInitAcsHandle);
Sleep(100);
if(iFlagInitByLocalAcsComm == 1)
{
acsc_CloseComm(stServoControllerCommSet.Handle);
iFlagInitByLocalAcsComm = 0; // Protection, 20110121
}
return iRet;
}
int mtnapi_confirm_para_base_path_exist()
{
int iRet = MTN_API_OK_ZERO;
mtnapi_dll_init_master_struct_ptr();
iRet = _access(strDefaultSaveFilename_SpeedServoWb, 0);
if(iRet)
{
iRet = mtnapi_create_para_base_master_template(); // create default
// MTN_API_ERR_FILE_PTR;
}
return iRet;
}
// Servo Parameter Tuning, Motion between 2 points
static CWinThread* m_pWinThread_ServoTuning;
//extern int iFlagStopThread_ServoTuning;
int iFlagStopThread_ServoTuning = TRUE;
int mtn_dll_wb_servo_tune_get_stop_flag()
{
return iFlagStopThread_ServoTuning;
}
void mtn_dll_wb_servo_tune_set_stop_flag(int iFlag)
{
iFlagStopThread_ServoTuning = iFlag;
}
static char cFlagDlgParaServoTuningThreadRunning;
char mtn_wb_tune_thread_get_flag_running()
{
return cFlagDlgParaServoTuningThreadRunning;
}
void mtn_wb_tune_thread_set_flag_running(char cFlag)
{
cFlagDlgParaServoTuningThreadRunning = cFlag;
}
extern UINT uiBitComboFlag_ServoTuning;
extern UINT mtn_dll_wb_tune_servo_start_move_2points_thread( LPVOID pParam );
void mtn_dll_wb_tune_servo_trigger_move_2points_thread(UINT uiBitFlagComboTuningThread)
{
if(iFlagStopThread_ServoTuning == TRUE)
{
// Set global variable flag
iFlagStopThread_ServoTuning = FALSE;
uiBitComboFlag_ServoTuning = uiBitFlagComboTuningThread;
//
m_pWinThread_ServoTuning = AfxBeginThread(mtn_dll_wb_tune_servo_start_move_2points_thread, 0); // mtn_dll_wb_tune_servo_move_2points_thread
SetPriorityClass(m_pWinThread_ServoTuning->m_hThread, REALTIME_PRIORITY_CLASS);
m_pWinThread_ServoTuning->m_bAutoDelete = FALSE;
}
}
int mtn_dll_wb_tune_servo_get_flag_stopping_thread()
{
return iFlagStopThread_ServoTuning;
}
void mtn_dll_wb_tune_servo_stop_thread()
{
if (m_pWinThread_ServoTuning)
{
iFlagStopThread_ServoTuning = TRUE;
WaitForSingleObject(m_pWinThread_ServoTuning->m_hThread, 5000);
// delete m_pWinThreadSpecTest;
m_pWinThread_ServoTuning = NULL;
}
}
#ifdef __DEBUG__
void mtnapi_test_write_file_1()
{
fopen_s(&fpDebugServoIni, strDeBugServoWb, "w");
// fprintf(fpDebugServoIni, "%% ACSC Controller, %s\n\n", strACSC_VarName);
if(fpDebugServoIni != NULL)
{
fprintf(fpDebugServoIni, "%% Debug-1\n");
}
}
void mtnapi_test_write_file_2(HANDLE hAcsHandle)
{
int iAxisTuningACS = 0;
CTRL_PARA_ACS stAxisServoCtrlParaBak;
mtnapi_upload_servo_parameter_acs_per_axis(hAcsHandle, iAxisTuningACS, &stAxisServoCtrlParaBak);
if(fpDebugServoIni != NULL)
{
fprintf(fpDebugServoIni, "%%Z Servo-BLK0: %6.1f, %6.1f, %6.1f\n",
stServoAxis_ACS[2].stServoParaACS[0].dAccelerationFeedforward,
stServoAxis_ACS[2].stServoParaACS[0].dVelocityLoopProportionalGain,
stServoAxis_ACS[2].stServoParaACS[0].dVelocityLoopIntegratorGain);
fprintf(fpDebugServoIni, "%%Z Servo-ACS: %6.1f, %6.1f, %6.1f\n",
stAxisServoCtrlParaBak.dAccelerationFeedforward,
stAxisServoCtrlParaBak.dVelocityLoopProportionalGain,
stAxisServoCtrlParaBak.dVelocityLoopIntegratorGain
);
}
}
void mtnapi_test_write_file_3(SERVO_MOTION_PARAMETER *pSpeedPara)
{
if(fpDebugServoIni != NULL)
{
fprintf(fpDebugServoIni, "%%Z Motion-BLK0: %d, %d, %d\n",
pSpeedPara->stSpeedProfileZ[0].nMaxVel, pSpeedPara->stSpeedProfileZ[0].nMaxAcc, pSpeedPara->stSpeedProfileZ[0].lJerk);
fprintf(fpDebugServoIni, "%%X Motion-BLK0: %d, %d, %d\n",
pSpeedPara->stSpeedProfileX[0].nMaxVel, pSpeedPara->stSpeedProfileX[0].nMaxAcc, pSpeedPara->stSpeedProfileX[0].lJerk);
fprintf(fpDebugServoIni, "%%Y Motion-BLK0: %d, %d, %d\n",
pSpeedPara->stSpeedProfileY[0].nMaxVel, pSpeedPara->stSpeedProfileY[0].nMaxAcc, pSpeedPara->stSpeedProfileY[0].lJerk);
fprintf(fpDebugServoIni, "%%Factors-Table-X-[V, A, J]: %6.8f, %6.8f, %6.8f\n",
dFactorTbl_X_Vel_Fr_cnt_sec_to_mmps, dFactorTbl_X_Acc_Fr_cnt_sec_to_si, dFactorTbl_X_Jerk_Fr_cnt_sec_to_si);
fprintf(fpDebugServoIni, "%%Factors-Table-Y-[V, A, J]: %6.8f, %6.8f, %6.8f\n",
dFactorTbl_Y_Vel_Fr_cnt_sec_to_mmps, dFactorTbl_Y_Acc_Fr_cnt_sec_to_si, dFactorTbl_Y_Jerk_Fr_cnt_sec_to_si);
fprintf(fpDebugServoIni, "%%Factors-Bond-Z-[V, A, J]: %6.8f, %6.8f, %6.8f\n",
dFactorBH_Z_Vel_Fr_cnt_sec_to_mmps, dFactorBH_Z_Acc_Fr_cnt_sec_to_si, dFactorBH_Z_Jerk_Fr_cnt_sec_to_si);
fprintf(fpDebugServoIni, "%%EncRes_mm-[X, Y, Z]: %6.8f, %6.8f, %6.8f\n",
dTableX_EncRes_mm, dTableY_EncRes_mm, dBndHeadZ_EncRes_mm);
fprintf(fpDebugServoIni, "%%Blk0-Speed-Bond-Z-[V, A, J]: %6.8f, %6.8f, %6.8f\n",
stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxVelocity,
stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxAcceleration,
stServoACS.stpServoAxis_ACS[WB_AXIS_BOND_Z]->stSpeedProfile[0].dMaxJerk);
}
}
void mtnapi_test_close_file()
{
if(fpDebugServoIni != NULL)
{
fclose(fpDebugServoIni);
}
}
#endif // __DEBUG__
| 38.197719
| 182
| 0.769693
|
ZHAOZhengyi-tgx
|
44b5df20667816f2f1155dcb84c7690555a09f9e
| 4,735
|
cpp
|
C++
|
samples/hot-triangle/hot_wasm.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | 29
|
2021-11-19T11:28:22.000Z
|
2022-03-29T00:26:51.000Z
|
samples/hot-triangle/hot_wasm.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | null | null | null |
samples/hot-triangle/hot_wasm.cpp
|
SakuraEngine/Sakura.Runtime
|
5a397fb2b1285326c4216f522fe10e347bd566f7
|
[
"MIT"
] | 1
|
2022-03-05T08:14:40.000Z
|
2022-03-05T08:14:40.000Z
|
#include "cgpu/api.h"
#include "utils.h"
#include "platform/thread.h"
#include <filesystem>
#include <fstream>
#include "filewatch.hpp"
// Watch triangle_module32.wasm file automatically
struct WasmWatcher {
WasmWatcher()
{
auto cpath = std::filesystem::absolute("triangle_module32.wasm");
watcher = new filewatch::FileWatch<std::filesystem::path>(cpath,
[this](const std::filesystem::path& path, const filewatch::Event change_type) {
if (change_type == filewatch::Event::renamed_new)
{
skr_thread_sleep(50);
std::ifstream ifs(path.c_str());
this->content = std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
updated = true;
}
});
std::ifstream ifs(cpath.c_str());
content = std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
updated = true;
}
~WasmWatcher()
{
if (wa_module) swa_free_module(wa_module);
if (wa_runtime) swa_free_runtime(wa_runtime);
if (wa_instance) swa_free_instance(wa_instance);
delete watcher;
}
SWAModuleId glob_latest_available()
{
if (updated)
{
if (wa_module) swa_free_module(wa_module);
wa_module = nullptr;
if (wa_runtime) swa_free_runtime(wa_runtime);
wa_runtime = nullptr;
if (wa_instance) swa_free_instance(wa_instance);
wa_instance = nullptr;
SWAInstanceDescriptor inst_desc = { ESWA_BACKEND_WASM3 };
wa_instance = swa_create_instance(&inst_desc);
SWARuntimeDescriptor runtime_desc = { "wa_runtime", 64 * 1024 };
wa_runtime = swa_create_runtime(wa_instance, &runtime_desc);
SWAModuleDescriptor module_desc;
module_desc.name = "raster_cmd";
module_desc.wasm = (const uint8_t*)content.c_str();
module_desc.wasm_size = (uint32_t)content.size();
module_desc.bytes_pinned_outside = true;
module_desc.strong_stub = false;
wa_module = swa_create_module(wa_runtime, &module_desc);
swa::utilx::link(wa_module, "env", "cgpu_render_encoder_set_viewport", cgpu_render_encoder_set_viewport);
swa::utilx::link(wa_module, "env", "cgpu_render_encoder_set_scissor", cgpu_render_encoder_set_scissor);
swa::utilx::link(wa_module, "env", "cgpu_render_encoder_bind_pipeline", cgpu_render_encoder_bind_pipeline);
swa::utilx::link(wa_module, "env", "cgpu_render_encoder_draw", cgpu_render_encoder_draw);
updated = false;
}
return wa_module;
}
std::atomic_bool updated = false;
filewatch::FileWatch<std::filesystem::path>* watcher = nullptr;
std::string content;
SWAInstanceId wa_instance = nullptr;
SWARuntimeId wa_runtime = nullptr;
SWAModuleId wa_module = nullptr;
};
SWAModuleId get_available_wasm(void* watcher)
{
WasmWatcher* W = (WasmWatcher*)watcher;
return W->glob_latest_available();
}
void* watch_wasm()
{
return new WasmWatcher();
}
void unwatch_wasm(void* watcher)
{
delete (WasmWatcher*)watcher;
}
struct SourceWatcher {
void Compile()
{
auto bat_dir = watch_path / "compile_32.bat";
auto dirstr = bat_dir.string();
std::string cmdstr;
{
std::filesystem::path valid = dirstr;
cmdstr = cmdstr.append(valid.string());
system(cmdstr.c_str());
std::cout << "Recompiled with " << cmdstr << "\n";
}
}
SourceWatcher(std::filesystem::path path)
: watch_path(path)
{
watcher = new filewatch::FileWatch<std::filesystem::path>(path,
[this](const std::filesystem::path& path, const filewatch::Event change_type) {
if (change_type == filewatch::Event::modified)
{
auto pathstr = path.string();
if (pathstr.find(".wa.") != std::string::npos)
{
Compile();
}
}
});
Compile();
}
~SourceWatcher()
{
delete watcher;
}
filewatch::FileWatch<std::filesystem::path>* watcher;
std::filesystem::path watch_path;
};
void* watch_source()
{
try
{
std::filesystem::path watch_path = __FILE__;
watch_path = watch_path.parent_path();
return new SourceWatcher(watch_path);
} //
catch (std::system_error err)
{
std::cout << err.what() << std::endl;
}
return nullptr;
}
void unwatch_source(void* watcher)
{
delete (SourceWatcher*)watcher;
}
| 32.655172
| 119
| 0.608659
|
SakuraEngine
|
44b7c175f87157a0c864a2a66653d688f42cfb1d
| 10,997
|
cpp
|
C++
|
examples/headless/main.cpp
|
WebKitForWayland/wpe-mesa
|
3f9f87d5f42c27a22273d67db072bd7f2cba6135
|
[
"BSD-2-Clause"
] | 2
|
2019-09-17T04:49:55.000Z
|
2021-01-09T18:24:58.000Z
|
examples/headless/main.cpp
|
WebKitForWayland/wpe-mesa
|
3f9f87d5f42c27a22273d67db072bd7f2cba6135
|
[
"BSD-2-Clause"
] | 3
|
2017-11-02T13:08:03.000Z
|
2018-09-27T13:10:56.000Z
|
examples/headless/main.cpp
|
WebKitForWayland/wpe-mesa
|
3f9f87d5f42c27a22273d67db072bd7f2cba6135
|
[
"BSD-2-Clause"
] | 10
|
2017-05-03T21:15:46.000Z
|
2020-03-18T13:58:42.000Z
|
#include <cairo.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <WebKit/WKContext.h>
#include <WebKit/WKFramePolicyListener.h>
#include <WebKit/WKPage.h>
#include <WebKit/WKPageGroup.h>
#include <WebKit/WKPageConfigurationRef.h>
#include <WebKit/WKRetainPtr.h>
#include <WebKit/WKString.h>
#include <WebKit/WKURL.h>
#include <WebKit/WKView.h>
#include <cassert>
#include <cstdio>
#include <glib.h>
#include <unordered_map>
#include <wpe-mesa/view-backend-exportable-dma-buf.h>
class GLContext {
public:
GLContext();
bool initialized() const { return m_initialized; }
EGLDisplay eglDisplay() const { return m_eglDisplay; }
bool makeCurrent();
bool readImage(EGLImageKHR, uint32_t, uint32_t, uint8_t*);
PFNEGLCREATEIMAGEKHRPROC createImage;
PFNEGLDESTROYIMAGEKHRPROC destroyImage;
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC imageTargetTexture2DOES;
private:
EGLDisplay m_eglDisplay;
EGLConfig m_eglConfig;
EGLContext m_eglContext;
bool m_initialized { false };
};
GLContext::GLContext()
{
m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (m_eglDisplay == EGL_NO_DISPLAY)
return;
if (!eglInitialize(m_eglDisplay, nullptr, nullptr))
return;
if (!eglBindAPI(EGL_OPENGL_ES_API))
return;
static const EGLint configAttributes[13] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 1,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
EGLint numConfigs;
EGLBoolean ret = eglChooseConfig(m_eglDisplay, configAttributes, &m_eglConfig, 1, &numConfigs);
if (!ret || !numConfigs)
return;
static const EGLint contextAttributes[3] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, EGL_NO_CONTEXT, contextAttributes);
if (m_eglContext == EGL_NO_CONTEXT)
return;
if (!eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, m_eglContext))
return;
createImage = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
destroyImage = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
imageTargetTexture2DOES = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));
fprintf(stderr, "GLContext: initialized!\n");
m_initialized = true;
}
bool GLContext::makeCurrent()
{
return eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, m_eglContext);
}
bool GLContext::readImage(EGLImageKHR image, uint32_t width, uint32_t height, uint8_t* buffer)
{
makeCurrent();
GLuint imageTexture;
glGenTextures(1, &imageTexture);
glBindTexture(GL_TEXTURE_2D, imageTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, nullptr);
imageTargetTexture2DOES(GL_TEXTURE_2D, image);
glBindTexture(GL_TEXTURE_2D, 0);
GLuint imageFramebuffer;
glGenFramebuffers(1, &imageFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, imageFramebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, imageTexture, 0);
glFlush();
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &imageFramebuffer);
glDeleteTextures(1, &imageTexture);
return false;
}
glReadPixels(0, 0, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, buffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &imageFramebuffer);
glDeleteTextures(1, &imageTexture);
return true;
}
class View {
public:
View(GLContext&);
void load(const char*);
void snapshot();
private:
static struct wpe_mesa_view_backend_exportable_dma_buf_client s_exportableClient;
static WKPageNavigationClientV0 s_pageNavigationClient;
GLContext& m_glContext;
WKContextRef m_context;
WKPageConfigurationRef m_pageConfiguration;
struct wpe_mesa_view_backend_exportable_dma_buf* m_exportable;
WKViewRef m_view;
std::unordered_map<uint32_t, std::pair<int32_t, EGLImageKHR>> m_imageMap;
std::pair<uint32_t, std::tuple<EGLImageKHR, uint32_t, uint32_t>> m_pendingImage { };
std::pair<uint32_t, std::tuple<EGLImageKHR, uint32_t, uint32_t>> m_lockedImage { };
void performUpdate();
GSource* m_updateSource;
gint64 m_frameRate { G_USEC_PER_SEC / 60 };
};
View::View(GLContext& glContext)
: m_glContext(glContext)
{
m_context = WKContextCreate();
m_pageConfiguration = WKPageConfigurationCreate();
{
auto pageGroupIdentifier = adoptWK(WKStringCreateWithUTF8CString("WPEPageGroup"));
auto pageGroup = adoptWK(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));
WKPageConfigurationSetContext(m_pageConfiguration, m_context);
WKPageConfigurationSetPageGroup(m_pageConfiguration, pageGroup.get());
}
m_exportable = wpe_mesa_view_backend_exportable_dma_buf_create(&s_exportableClient, this);
auto* backend = wpe_mesa_view_backend_exportable_dma_buf_get_view_backend(m_exportable);
m_view = WKViewCreateWithViewBackend(backend, m_pageConfiguration);
WKPageSetPageNavigationClient(WKViewGetPage(m_view), &s_pageNavigationClient.base);
m_updateSource = g_timeout_source_new(m_frameRate / 1000);
g_source_set_callback(m_updateSource,
[](gpointer data) -> gboolean {
auto& view = *static_cast<View*>(data);
view.performUpdate();
return TRUE;
}, this, nullptr);
g_source_attach(m_updateSource, g_main_context_default());
}
void View::load(const char* url)
{
auto shellURL = adoptWK(WKURLCreateWithUTF8CString(url));
WKPageLoadURL(WKViewGetPage(m_view), shellURL.get());
}
void View::snapshot()
{
EGLImageKHR image = std::get<0>(m_lockedImage.second);
if (!image)
return;
uint32_t width = std::get<1>(m_lockedImage.second);
uint32_t height = std::get<2>(m_lockedImage.second);
uint8_t* buffer = new uint8_t[4 * width * height];
if (!m_glContext.readImage(image, width, height, buffer)) {
fprintf(stderr, "View::snapshot(): failed\n");
delete[] buffer;
return;
}
cairo_surface_t* imageSurface = cairo_image_surface_create_for_data(buffer,
CAIRO_FORMAT_ARGB32, width, height, width * 4);
cairo_surface_write_to_png(imageSurface, "/tmp/wpe-snapshot.png");
cairo_surface_destroy(imageSurface);
delete[] buffer;
}
void View::performUpdate()
{
if (!m_pendingImage.first)
return;
wpe_mesa_view_backend_exportable_dma_buf_dispatch_frame_complete(m_exportable);
if (m_lockedImage.first) {
wpe_mesa_view_backend_exportable_dma_buf_dispatch_release_buffer(m_exportable, m_lockedImage.first);
m_glContext.destroyImage(m_glContext.eglDisplay(), std::get<0>(m_lockedImage.second));
}
m_lockedImage = m_pendingImage;
m_pendingImage = std::pair<uint32_t, std::tuple<EGLImageKHR, uint32_t, uint32_t>> { };
}
struct wpe_mesa_view_backend_exportable_dma_buf_client View::s_exportableClient = {
// export_dma_buf
[](void* data, struct wpe_mesa_view_backend_exportable_dma_buf_data* imageData)
{
auto& view = *static_cast<View*>(data);
auto it = view.m_imageMap.end();
if (imageData->fd >= 0) {
assert(view.m_imageMap.find(imageData->handle) == view.m_imageMap.end());
it = view.m_imageMap.insert({ imageData->handle, { imageData->fd, nullptr }}).first;
} else {
assert(view.m_imageMap.find(imageData->handle) != view.m_imageMap.end());
it = view.m_imageMap.find(imageData->handle);
}
assert(it != view.m_imageMap.end());
uint32_t handle = it->first;
int32_t fd = it->second.first;
view.m_glContext.makeCurrent();
EGLint attributes[] = {
EGL_WIDTH, static_cast<EGLint>(imageData->width),
EGL_HEIGHT, static_cast<EGLint>(imageData->height),
EGL_LINUX_DRM_FOURCC_EXT, static_cast<EGLint>(imageData->format),
EGL_DMA_BUF_PLANE0_FD_EXT, fd,
EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0,
EGL_DMA_BUF_PLANE0_PITCH_EXT, static_cast<EGLint>(imageData->stride),
EGL_NONE,
};
EGLImageKHR image = view.m_glContext.createImage(view.m_glContext.eglDisplay(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, attributes);
view.m_pendingImage = { imageData->handle, std::make_tuple(image, imageData->width, imageData->height) };
},
};
WKPageNavigationClientV0 View::s_pageNavigationClient = {
{ 0, nullptr },
// decidePolicyForNavigationAction
[](WKPageRef, WKNavigationActionRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) {
WKFramePolicyListenerUse(listener);
},
// decidePolicyForNavigationResponse
[](WKPageRef, WKNavigationResponseRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) {
WKFramePolicyListenerUse(listener);
},
nullptr, // decidePolicyForPluginLoad
nullptr, // didStartProvisionalNavigation
nullptr, // didReceiveServerRedirectForProvisionalNavigation
nullptr, // didFailProvisionalNavigation
nullptr, // didCommitNavigation
nullptr, // didFinishNavigation
nullptr, // didFailNavigation
nullptr, // didFailProvisionalLoadInSubframe
nullptr, // didFinishDocumentLoad
nullptr, // didSameDocumentNavigation
nullptr, // renderingProgressDidChange
nullptr, // canAuthenticateAgainstProtectionSpace
nullptr, // didReceiveAuthenticationChallenge
nullptr, // webProcessDidCrash
nullptr, // copyWebCryptoMasterKey
nullptr, // didBeginNavigationGesture
nullptr, // willEndNavigationGesture
nullptr, // didEndNavigationGesture
nullptr, // didRemoveNavigationGestureSnapshot
};
int main(int argc, char* argv[])
{
GLContext glContext;
if (!glContext.initialized())
return 1;
GMainLoop* loop = g_main_loop_new(g_main_context_default(), FALSE);
View view(glContext);
view.load("http://www.webkit.org/blog-files/3d-transforms/poster-circle.html");
g_timeout_add(10 * 1000,
[](gpointer data) -> gboolean {
auto& view = *static_cast<View*>(data);
view.snapshot();
return TRUE;
}, &view);
g_main_loop_run(loop);
g_main_loop_unref(loop);
return 0;
}
| 33.629969
| 148
| 0.71765
|
WebKitForWayland
|
44bb335564831dcab945d1d801e2b3ac69da9f8f
| 2,763
|
cpp
|
C++
|
source/Kai/Kai.cpp
|
ioquatix/kai
|
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
|
[
"Unlicense",
"MIT"
] | 4
|
2016-07-19T08:53:09.000Z
|
2021-08-03T10:06:41.000Z
|
source/Kai/Kai.cpp
|
ioquatix/kai
|
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
|
[
"Unlicense",
"MIT"
] | null | null | null |
source/Kai/Kai.cpp
|
ioquatix/kai
|
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
|
[
"Unlicense",
"MIT"
] | null | null | null |
//
// Kai.cpp
// This file is part of the "Kai" project, and is released under the MIT license.
//
// Created by Samuel Williams on 24/06/09.
// Copyright 2009 Samuel Williams. All rights reserved.
//
//
#include "Kai.hpp"
#include <ctime>
#include <sys/time.h>
#include <cmath>
#include "Ensure.hpp"
namespace Kai {
bool close_enough (double a, double b) {
double d = a - b;
if (d < 0) d *= -1;
if (d < 0.001)
return true;
else
return false;
}
Time::Time()
{
struct timeval time_value;
gettimeofday (&time_value, (struct timezone*)0);
_seconds = time_value.tv_sec;
_fraction = (FractionT)time_value.tv_usec / 1000000.0;
}
Time::Time(FractionT time)
{
_seconds = 0;
_fraction = time;
normalize();
}
void Time::normalize()
{
if (_fraction < 0) {
FractionT seconds = std::floor(_fraction);
_fraction -= seconds;
_seconds += seconds;
} else if (_fraction > 1) {
FractionT seconds = std::floor(_fraction);
_fraction -= seconds;
_seconds += seconds;
}
}
Time Time::operator+(const Time & other)
{
Time time(*this);
time._seconds += other._seconds;
time._fraction += other._fraction;
time.normalize();
KAI_ENSURE(close_enough(this->total() + other.total(), time.total()));
return time;
}
Time Time::operator-(const Time & other)
{
Time time(*this);
time._seconds -= other._seconds;
time._fraction -= other._fraction;
time.normalize();
KAI_ENSURE(close_enough(this->total() - other.total(), time.total()));
return time;
}
Time & Time::operator+=(const Time & other)
{
_seconds += other._seconds;
_fraction += other._fraction;
normalize();
return *this;
}
Time & Time::operator-=(const Time & other)
{
_seconds -= other._seconds;
_fraction -= other._fraction;
normalize();
return *this;
}
Time Time::operator*(FractionT other)
{
Time time(*this);
time._seconds *= other;
time._fraction *= other;
time.normalize();
KAI_ENSURE(close_enough(this->total() * other, time.total()));
return time;
}
Time Time::operator/(FractionT other)
{
Time time(*this);
FractionT current = this->total();
time._seconds = 0;
time._fraction = current / other;
time.normalize();
KAI_ENSURE(close_enough(this->total() / other, time.total()));
return time;
}
std::ostream & operator<<(std::ostream & output, const Time & time)
{
if (time.seconds()) {
output << time.total() << "s";
} else {
const char * postfix[] = {"s", "ms", "µs", "ns"};
Time::FractionT f = time.fraction();
std::size_t k = 0;
while (f < 1.0 && k < 3) {
k++;
f *= 1000.0;
}
output << f << postfix[k];
}
return output;
}
}
| 17.487342
| 82
| 0.608035
|
ioquatix
|
44bbff8144dc025ab63103ad8dee8c2501895795
| 7,938
|
cpp
|
C++
|
asio-basic/src/main.cpp
|
kovdan01/cosec-examples
|
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
|
[
"MIT"
] | 2
|
2021-03-03T08:40:39.000Z
|
2021-06-15T15:32:28.000Z
|
asio-basic/src/main.cpp
|
kovdan01/cosec-examples
|
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
|
[
"MIT"
] | 3
|
2021-01-04T17:47:48.000Z
|
2021-03-17T05:54:00.000Z
|
asio-basic/src/main.cpp
|
kovdan01/cosec-examples
|
bf19f2e2db8962d80ee7ce237be1c8af9e901cc9
|
[
"MIT"
] | 3
|
2020-12-17T20:10:56.000Z
|
2021-04-28T09:03:16.000Z
|
#include <ce/asio-main.hpp>
#include <ce/charconv.hpp>
#include <ce/format.hpp>
#include <ce/io_context_signal_interrupter.hpp>
#include <ce/socket_session.hpp>
#include <ce/tcp_listener.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <memory>
#include <stdexcept>
namespace ce
{
namespace
{
using bigint = boost::multiprecision::cpp_int;
// We don't need type-erased executor for our socket,
// which boost::asio::ip::tcp::socket provides.
using tcp_socket = ba::basic_stream_socket<ba::ip::tcp,ba::io_context::executor_type>;
class calc_session final : public socket_session<calc_session,tcp_socket>
{
public:
using socket_session<calc_session,tcp_socket>::socket_session;
void start_protocol()
{
// We are going to handle every source of exception explicitly for this
// example to precisely log the source. Usually this is overkill.
using namespace boost::log::trivial;
// At the point of call to process(), there is a shared_ptr
// outside this function that will be destroyed after the call.
// We take another ownership by the callback by capturing another
// shared_ptr to this.
// If async_read_until fails to initiate allocation, out handler
// and its shared ownership of this will be destroyed.
// After logging the exception and returning from this function,
// session will be destroyed with the last shared_ptr owner.
// Otherwise ownership will be held by the shared_ptr inside
// callback and carried until the callback is invoced.
try{
async_read_until(stream_,ba::dynamic_string_buffer{in_buf_},'\n',
[s=shared_from_this()](boost::system::error_code ec,std::size_t n) mutable {
// Both `this` and s refer to our session, we should use s
// everywhere to avoid an extra capture of `this`.
if(ec){
// If we didn't read any data at all due to end of stream,
// this is not an error, but a graceful disconnect.
if(ec!=boost::asio::error::eof||n)
BOOST_LOG_SEV(s->log(),error) << "Failed to read a: " << ec.message();
else
BOOST_LOG_SEV(s->log(),info) << "Connection closed";
// In either case, we return from the callback.
// Since callback owns calc_session through captured shared_ptr,
// it will be cleaned up properly.
return;
}
try{
s->a_ = s->read_buffered_number(n);
}
catch(const std::exception& e){
BOOST_LOG_SEV(s->log(),error) << "Failed to parse a: " << e.what();
return;
}
try{
// Copy shared_ptr that owns our session to the next callback.
// We can't move ownership, since we might need it in exception
// handler in case initiating function throws.
async_read_until(s->stream_,ba::dynamic_string_buffer{s->in_buf_},'\n',
[s](boost::system::error_code ec,std::size_t n) mutable {
if(ec){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to read b: " << ec.message();
return;
}
bigint b;
try{
b = s->read_buffered_number(n);
}
catch(const std::exception& e){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to parse b: " << e.what();
return;
}
try{
s->a_ *= b;
s->out_buf_ = s->a_.str()+'\n';
}
catch(const std::exception& e){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to compute result: " << e.what();
return;
}
try{
async_write(s->stream_,ba::buffer(s->out_buf_),[s]
(boost::system::error_code ec,std::size_t /*n*/) mutable {
if(ec){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to write result: " << ec.message();
return;
}
// Start our callback chain from the beginning.
// It will pick up our ownership.
s->start_protocol();
});
}
catch(const std::exception& e){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to initiate write: " << e.what();
}
});
}
catch(const std::exception& e){
BOOST_LOG_SEV(s->log(),error)
<< "Failed to initiate read of b: " << e.what();
}
});
}
catch(const std::exception& e){
BOOST_LOG_SEV(log(),error) << "Failed to initiate read of a: " << e.what();
}
}
private:
std::string in_buf_,out_buf_;
bigint a_;
bigint read_buffered_number(std::size_t n)
{
// boost::multiprecision can only indicate string to number
// conversion failure with exceptions.
// There is no string_view-like constructor, but null-terminated
// strings are accepted. To avoid copy, replace '\n' with '\0'.
// -1 is to account for \n at end.
in_buf_[n-1] = '\0';
bigint x{in_buf_.data()};
in_buf_.erase(0,n);
return x;
}
};
}
int main(std::span<const char* const> args)
{
if(args.size()!=2)
throw std::runtime_error(format("Usage: ",args[0]," <listen-port>"));
auto port = from_chars<std::uint16_t>(args[1]);
if(!port||!*port)
throw std::runtime_error("Port must be in [1;65535]");
// Infor io_context it can apply single-threaded-optimizations.
ba::io_context ctx{1};
io_context_signal_interrupter iosi{ctx};
tcp_listener<calc_session,ba::io_context::executor_type> tl{ctx.get_executor(),*port};
ctx.run();
return 0;
}
}
| 48.699387
| 104
| 0.434492
|
kovdan01
|
44bf949e3966b4cbcfb69a1b6abaa4be59679694
| 2,390
|
hpp
|
C++
|
core/src/utils/MeshUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | 1
|
2019-04-04T14:20:37.000Z
|
2019-04-04T14:20:37.000Z
|
core/src/utils/MeshUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | null | null | null |
core/src/utils/MeshUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | null | null | null |
#ifndef UTILS_MESHUTILS_HPP_DEFINED
#define UTILS_MESHUTILS_HPP_DEFINED
#include "math/Mesh.hpp"
#include "math/Vector3.hpp"
namespace utymap { namespace utils {
/// Copies mesh into existing one adjusting position.
inline void copyMesh(const utymap::math::Vector3& position, const utymap::math::Mesh& source, utymap::math::Mesh& destination)
{
int startIndex = static_cast<int>(destination.vertices.size() / 3);
// copy adjusted vertices
for (std::size_t i = 0; i < source.vertices.size();) {
destination.vertices.push_back(source.vertices[i++] + position.x);
destination.vertices.push_back(source.vertices[i++] + position.z);
destination.vertices.push_back(source.vertices[i++] + position.y);
}
// copy adjusted triangles
std::transform(source.triangles.begin(), source.triangles.end(), std::back_inserter(destination.triangles), [&](int value) {
return value + startIndex;
});
// copy colors
std::copy(source.colors.begin(), source.colors.end(), std::back_inserter(destination.colors));
// copy adjusted uvs
std::copy(source.uvs.begin(), source.uvs.end(), std::back_inserter(destination.uvs));
std::copy(source.uvMap.begin(), source.uvMap.end(), std::back_inserter(destination.uvMap));
startIndex = static_cast<int>(destination.uvs.size() - source.uvs.size());
for (std::size_t i = destination.uvMap.size() - source.uvMap.size(); i < destination.uvMap.size(); i += 8) {
destination.uvMap[i] += startIndex;
}
}
/// Copies mesh along two coordinates.
inline void copyMeshAlong(const utymap::QuadKey& quadKey, const utymap::GeoCoordinate& p1, const utymap::GeoCoordinate& p2,
const utymap::math::Mesh& source, utymap::math::Mesh& destination, double stepInMeters,
const utymap::heightmap::ElevationProvider& eleProvider)
{
double distanceInMeters = GeoUtils::distance(p1, p2);
int count = static_cast<int>(distanceInMeters / stepInMeters);
for (int j = 0; j < count; ++j) {
GeoCoordinate position = GeoUtils::newPoint(p1, p2, static_cast<double>(j) / count);
double elevation = eleProvider.getElevation(quadKey, position);
utymap::utils::copyMesh(utymap::math::Vector3(position.longitude, elevation, position.latitude), source, destination);
}
}
}}
#endif // UTILS_GEOUTILS_HPP_DEFINED
| 41.929825
| 128
| 0.689121
|
lonnibesancon
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.