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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce5dddb0c36256a9bb6b19dc69deed45b70ea86d | 5,524 | cpp | C++ | resource/src/monitoring_thread.cpp | md-w/httpserver | 41645e5632f17dd931ee3ba4f1947e78ae9f3172 | [
"MIT"
] | null | null | null | resource/src/monitoring_thread.cpp | md-w/httpserver | 41645e5632f17dd931ee3ba4f1947e78ae9f3172 | [
"MIT"
] | null | null | null | resource/src/monitoring_thread.cpp | md-w/httpserver | 41645e5632f17dd931ee3ba4f1947e78ae9f3172 | [
"MIT"
] | null | null | null | #include "monitoring_thread.hpp"
#include <Poco/Net/NetException.h>
#include <Poco/Net/SocketAddress.h>
#include <Poco/Net/SocketStream.h>
#include <Poco/Net/StreamSocket.h>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include "interfaces/status.pb.h"
#define FUNC_TYPE_DATA 1
#define FUNC_TYPE_EOF 2
MonitoringThread* MonitoringThread::instance_ = nullptr;
MonitoringThread::MonitoringThread() : _is_shutdown_command(false), _is_already_shutting_down(false) {
_this_thread = std::thread(&MonitoringThread::run, this);
}
MonitoringThread::~MonitoringThread() {
shutDown();
// TODO: delete _p_machine_status etc.
}
MonitoringThread* MonitoringThread::createInstance() {
if (!instance_) {
instance_ = new MonitoringThread();
}
return instance_;
}
MonitoringThread* MonitoringThread::getInstance() { return createInstance(); }
void MonitoringThread::deleteInstance() {
if (instance_) {
delete instance_;
}
instance_ = NULL;
}
void MonitoringThread::shutDown() {
if (_is_already_shutting_down) return;
_is_already_shutting_down = true;
_is_shutdown_command = true;
_this_thread.join();
for (auto&& it : _resource_map) {
it.second.reset();
it.second = nullptr;
}
}
uint64_t getCurrentTimeInMs() {
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
auto duration = now.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
return millis;
}
void MonitoringThread::setStatus(uint64_t id) {
if (_is_already_shutting_down) return;
std::map<uint64_t, std::unique_ptr<Status>>::iterator it = _resource_map.find(id);
if (it != _resource_map.end()) {
it->second->value++;
it->second->last_update_time_in_ms.store(getCurrentTimeInMs());
} else {
_resource_map.insert(std::make_pair(id, std::move(std::make_unique<Status>())));
}
}
void MonitoringThread::run() {
std::cout << "Started monitoring thread" << std::endl;
int sleep_upto_sec = 10;
int iteration_counter = 0;
while (!_is_shutdown_command) {
if (sleep_upto_sec > 0) {
sleep_upto_sec--;
} else {
sleep_upto_sec = 10;
try {
std::cout << "Trying to connect" << std::endl;
std::unique_ptr<Poco::Net::StreamSocket> s = std::make_unique<Poco::Net::StreamSocket>();
s->connect(Poco::Net::SocketAddress("127.0.0.1", 23000), Poco::Timespan(2, 0));
s->setSendTimeout(Poco::Timespan(2, 0));
Poco::Net::SocketStream ss(*s);
sleep_upto_sec = 10;
while (!_is_shutdown_command) {
std::this_thread::sleep_for(std::chrono::seconds(1));
if (sleep_upto_sec > 0) {
sleep_upto_sec--;
} else {
sleep_upto_sec = 10;
::resource::MachineStatus machine_status;
machine_status.set_id(1);
machine_status.set_channel_id(iteration_counter++);
::resource::ProcessStatus* p_process_status = machine_status.add_process_status();
p_process_status->set_id(1);
p_process_status->set_channel_id(1);
for (auto&& it : _resource_map) {
float diff = (float)(it.second->value - it.second->last_value) / 10;
std::stringstream ss1;
ss1 << "FPS : " << std::setfill('0') << std::setw(5) << it.first << " : " << std::setfill('0')
<< std::setw(5) << diff;
std::cout << ss1.str() << std::endl;
::resource::ThreadStatus* l_p_th = p_process_status->add_thread_status();
l_p_th->set_id(it.first);
l_p_th->set_channel_id(it.first);
l_p_th->set_value(it.second->value);
l_p_th->set_last_value(it.second->last_value);
l_p_th->set_last_updated_in_ms(it.second->last_update_time_in_ms);
it.second->last_value.store(it.second->value);
}
int func_type = (int)FUNC_TYPE_DATA;
int64_t data_timestamp = getCurrentTimeInMs();
int64_t data_len = machine_status.ByteSizeLong();
try {
ss.write((char*)&func_type, 4);
ss.write((char*)&data_timestamp, 8);
ss.write((char*)&data_len, 8);
if (machine_status.SerializeToOstream(&ss) == false) {
std::cout << "SerializeToOstream exception: " << std::endl;
break;
}
std::cout << machine_status.DebugString() << std::endl;
ss.flush();
} catch (const Poco::Net::NetException& e) {
std::cout << "flush NetException : " << e.what() << std::endl;
break;
}
}
}
sleep_upto_sec = 10;
try {
s->shutdown();
} catch (const Poco::Net::NetException& e) {
}
try {
s->close();
} catch (const Poco::Net::NetException& e) {
}
} catch (const Poco::Net::NetException& e) {
sleep_upto_sec = 10;
std::cout << "Unable to connect NetException retrying in " << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
} catch (const Poco::TimeoutException& e) {
sleep_upto_sec = 10;
std::cout << "Unable to connect TimeoutException retrying in " << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
std::cout << "Ended monitoring thread" << std::endl;
} | 34.742138 | 108 | 0.611513 | md-w |
ce5e5b360cc77d1344241da7b9b49753b5bd2451 | 8,855 | cpp | C++ | tests/proofnetwork/restclient_test.cpp | dkormalev/proofbase | 0b45c190e53fe71bfdd22670e89c97ba90b006c8 | [
"BSD-3-Clause"
] | null | null | null | tests/proofnetwork/restclient_test.cpp | dkormalev/proofbase | 0b45c190e53fe71bfdd22670e89c97ba90b006c8 | [
"BSD-3-Clause"
] | null | null | null | tests/proofnetwork/restclient_test.cpp | dkormalev/proofbase | 0b45c190e53fe71bfdd22670e89c97ba90b006c8 | [
"BSD-3-Clause"
] | null | null | null | // clazy:skip
#include "proofseed/future.h"
#include "proofnetwork/restclient.h"
#include "gtest/proof/test_global.h"
#include <QNetworkReply>
#include <QRegExp>
#include <QScopedPointer>
#include <functional>
#include <tuple>
using testing::Test;
using testing::TestWithParam;
using HttpMethodCall =
std::function<Proof::CancelableFuture<QNetworkReply *>(Proof::RestClient &, const QByteArray & /*body*/)>;
using HttpMethodsTestParam = std::tuple<HttpMethodCall, QString /*fileOfBody*/, QString /*contentType*/>;
class RestClientTest : public TestWithParam<HttpMethodsTestParam>
{
public:
RestClientTest() {}
protected:
void SetUp() override
{
serverRunner = new FakeServerRunner();
serverRunner->runServer();
QTime timer;
timer.start();
while (!serverRunner->serverIsRunning() && timer.elapsed() < 10000)
QThread::msleep(50);
ASSERT_TRUE(serverRunner->serverIsRunning());
restClient = Proof::RestClientSP::create();
restClient->setAuthType(Proof::RestAuthType::NoAuth);
restClient->setHost("127.0.0.1");
restClient->setPort(9091);
restClient->setScheme("http");
restClient->setClientName("Proof-test");
}
void TearDown() override { delete serverRunner; }
protected:
FakeServerRunner *serverRunner;
Proof::RestClientSP restClient;
};
using namespace std::placeholders;
INSTANTIATE_TEST_CASE_P(
RestClientTestInstance, RestClientTest,
testing::Values(
// Without vendor, without body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QString &)>(&Proof::RestClient::get),
_1, QStringLiteral("/"), QUrlQuery(), QString()),
"", "text/plain"),
HttpMethodsTestParam(
std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(const QUrl &)>(
&Proof::RestClient::get),
_1, QUrl("http://127.0.0.1:9091/")),
"", "text/plain"),
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, QString()),
"", "text/plain"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, QString()), "", "text/plain"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, QString()), "", "text/plain"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::deleteResource, _1, "/", QUrlQuery(), QString()), "",
"text/plain"),
// With vendor, without body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QString &)>(&Proof::RestClient::get),
_1, QStringLiteral("/"), QUrlQuery(), "opensoft"),
"", "application/vnd.opensoft"),
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, "opensoft"),
"", "application/vnd.opensoft"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, "opensoft"), "",
"application/vnd.opensoft"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, "opensoft"), "",
"application/vnd.opensoft"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::deleteResource, _1, "/", QUrlQuery(), "opensoft"), "",
"application/vnd.opensoft"),
// Without vendor, with json body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.json", "application/json"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.json", "application/json"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.json", "application/json"),
// Without vendor, with xml body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.xml", "text/xml"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.xml", "text/xml"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, QString()),
":/data/vendor_test_body.xml", "text/xml"),
// With vendor, with json body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.json", "application/vnd.opensoft+json"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.json", "application/vnd.opensoft+json"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.json", "application/vnd.opensoft+json"),
// With vendor, with xml body
HttpMethodsTestParam(std::bind(static_cast<Proof::CancelableFuture<QNetworkReply *> (Proof::RestClient::*)(
const QString &, const QUrlQuery &, const QByteArray &, const QString &)>(
&Proof::RestClient::post),
_1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.xml", "application/vnd.opensoft+xml"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::put, _1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.xml", "application/vnd.opensoft+xml"),
HttpMethodsTestParam(std::bind(&Proof::RestClient::patch, _1, "/", QUrlQuery(), _2, "opensoft"),
":/data/vendor_test_body.xml", "application/vnd.opensoft+xml")));
TEST_P(RestClientTest, vendorTest)
{
const auto methodCall = std::get<0>(GetParam());
const auto file = std::get<1>(GetParam());
const auto expected = std::get<2>(GetParam());
const QRegExp expectedRegExp(QString("Content-Type:(\\s*)([^\r\n]*)\\r\\n"));
QByteArray body;
if (!file.isEmpty()) {
body = dataFromFile(file);
ASSERT_FALSE(body.isEmpty());
}
QScopedPointer<QNetworkReply> reply(methodCall(*restClient, body)->result());
ASSERT_NE(nullptr, reply);
QTime timer;
timer.start();
while (!reply->isFinished() && timer.elapsed() < 10000)
QThread::msleep(5);
ASSERT_TRUE(reply->isFinished());
const auto query = QString::fromLatin1(serverRunner->lastQueryRaw());
const int position = expectedRegExp.indexIn(query);
ASSERT_NE(-1, position);
EXPECT_EQ(expected, expectedRegExp.cap(2));
}
| 53.993902 | 122 | 0.557538 | dkormalev |
ce5ef92419eec3c0333f37d56613d51aae29e124 | 1,594 | cpp | C++ | leetcode/MergeTwoSortedLists/MergeTwoSortedLists.cpp | lizhenghn123/myAlgorithmStudy | 1917d48debeab33436c705bf9bc2fe9cf49f95cf | [
"MIT"
] | 2 | 2015-08-30T04:45:24.000Z | 2015-08-30T04:45:36.000Z | leetcode/MergeTwoSortedLists/MergeTwoSortedLists.cpp | lizhenghn123/myAlgorithmStudy | 1917d48debeab33436c705bf9bc2fe9cf49f95cf | [
"MIT"
] | null | null | null | leetcode/MergeTwoSortedLists/MergeTwoSortedLists.cpp | lizhenghn123/myAlgorithmStudy | 1917d48debeab33436c705bf9bc2fe9cf49f95cf | [
"MIT"
] | 4 | 2015-07-15T08:43:58.000Z | 2021-04-10T12:55:29.000Z | // Source : https://oj.leetcode.com/problems/merge-two-sorted-lists/
// Author : lizhenghn@gmail.com
// Date : 2014-11-26
/**********************************************************************************
*
* Merge two sorted linked lists and return it as a new list. The new list should be
* made by splicing together the nodes of the first two lists.
*
**********************************************************************************/
#include <iostream>
#include <stdio.h>
#include "../common/single_list.hpp"
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
ListNode dummy(0);
ListNode *head = &dummy;
while (l1 && l2)
{
if (l1->val < l2->val)
{
head->next = l1;
head = l1;
l1 = l1->next;
}
else
{
head->next = l2;
head = l2;
l2 = l2->next;
}
}
if (l1)
head->next = l1;
else if (l2)
head->next = l2;
return dummy.next;
}
ListNode *mergeTwoLists2(ListNode* head1, ListNode* head2)
{
ListNode *p1 = head1, *p2 = head2;
ListNode dummy(0);
dummy.next = p1;
ListNode *prev = &dummy;
while (p1 && p2)
{
if (p1->val < p2->val){
prev->next = p1;
p1 = p1->next;
prev = prev->next;
}
else
{
prev->next = p2;
p2 = p2->next;
prev = prev->next;
}
}
if (p2){
prev->next = p2;
}
if (p1){
prev->next = p1;
}
return dummy.next;
}
int main()
{
int a[] = { 2, 2, 3, 4 };
int b[] = { 0, 1, 3, 5 };
ListNode *p1 = createList(a, sizeof(a) / sizeof(a[0]));
ListNode *p2 = createList(b, sizeof(b) / sizeof(b[0]));
ListNode *p = mergeTwoLists(p1, p2);
printList(p);
freeList(p);
system("pause");
} | 17.910112 | 83 | 0.524467 | lizhenghn123 |
ce61cbdd658b88af3befd614273d8bd2c3eff28a | 926 | cpp | C++ | firmware/examples/SystemClock/source/main.cpp | nicoleb1661/SJSU-Dev2 | c2f2ac92e12390e2da4a6598dcc8afbdbd7626d4 | [
"Apache-2.0"
] | null | null | null | firmware/examples/SystemClock/source/main.cpp | nicoleb1661/SJSU-Dev2 | c2f2ac92e12390e2da4a6598dcc8afbdbd7626d4 | [
"Apache-2.0"
] | null | null | null | firmware/examples/SystemClock/source/main.cpp | nicoleb1661/SJSU-Dev2 | c2f2ac92e12390e2da4a6598dcc8afbdbd7626d4 | [
"Apache-2.0"
] | 1 | 2018-09-19T01:58:48.000Z | 2018-09-19T01:58:48.000Z | #include <project_config.hpp>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include "L1_Drivers/pin_configure.hpp"
#include "L1_Drivers/system_clock.hpp"
#include "L2_Utilities/debug_print.hpp"
int main(void)
{
SystemClock clock;
PinConfigure clock_pin(1, 25);
clock_pin.SetPinFunction(0b101); // set clock to putput mode
clock_pin.SetPinMode(clock_pin.PinConfigureInterface::kInactive);
clock_pin.EnableHysteresis(false);
clock_pin.SetAsActiveLow(false);
clock_pin.EnableFastMode(false);
clock_pin.SetAsOpenDrain(false);
LPC_SC->CLKOUTCFG |= (1<<8);
LPC_SC->CLKOUTCFG &= ~(0xFF << 0);
while (true)
{
uint32_t speed;
clock.SetClockFrequency(12);
Delay(5000);
clock.SetClockFrequency(48);
Delay(5000);
speed = clock.GetClockFrequency();
DEBUG_PRINT("Speed is %" PRIu32, speed);
}
return 0;
}
| 25.722222 | 69 | 0.673866 | nicoleb1661 |
ce64eefacf4dec631e253409dcc92edeae4e58ad | 1,426 | cpp | C++ | sources/src/structure/include.cpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | sources/src/structure/include.cpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | sources/src/structure/include.cpp | sydelity-net/EDACurry | 20cbf9835827e42efeb0b3686bf6b3e9d72417e9 | [
"MIT"
] | null | null | null | /// @file include.cpp
/// @author Enrico Fraccaroli (enrico.fraccaroli@gmail.com)
/// @copyright Copyright (c) 2021 sydelity.net (info@sydelity.com)
/// Distributed under the MIT License (MIT) (See accompanying LICENSE file or
/// copy at http://opensource.org/licenses/MIT)
#include "structure/include.hpp"
#include "features/named_object.hpp"
#include "utility/utility.hpp"
namespace edacurry::structure
{
Include::Include()
: Object(),
parameters(this),
_include_type(),
_path()
{
// Nothing to do.
}
Include::Include(IncludeType include_type,
const std::string &path,
const features::ObjectList<Parameter>::base_type ¶ms)
: Object(),
parameters(this, params),
_include_type(include_type),
_path(path)
{
// Nothing to do.
}
Include::~Include()
{
}
IncludeType Include::getIncludeType() const
{
return _include_type;
}
void Include::setIncludeType(IncludeType include_type)
{
_include_type = include_type;
}
void Include::setPath(const std::string &path)
{
_path = path;
}
std::string Include::getPath() const
{
return _path;
}
std::string Include::toString() const
{
std::stringstream ss;
ss << "Include("
<< include_type_to_plain_string(_include_type) << ", "
<< _path << ", "
<< parameters.toString()
<< ")";
return ss.str();
}
} // namespace edacurry::structure | 20.970588 | 77 | 0.650771 | sydelity-net |
ce659c5fac5fec84096a424867614e25206844e6 | 21,198 | cpp | C++ | src/core/lib/math/cpu_int/binvect.cpp | marcelmon/PALISADE_capstone | 2cfd1626b26576f8fe93bb3a424f934ef700c5b2 | [
"BSD-2-Clause"
] | null | null | null | src/core/lib/math/cpu_int/binvect.cpp | marcelmon/PALISADE_capstone | 2cfd1626b26576f8fe93bb3a424f934ef700c5b2 | [
"BSD-2-Clause"
] | null | null | null | src/core/lib/math/cpu_int/binvect.cpp | marcelmon/PALISADE_capstone | 2cfd1626b26576f8fe93bb3a424f934ef700c5b2 | [
"BSD-2-Clause"
] | null | null | null | /*
* @file binvect.cpp This file contains the vector manipulation functionality.
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* 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.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
This code provides basic arithmetic functionality.
*/
#include "../../utils/serializable.h"
#include "../cpu_int/binvect.h"
#include "../nbtheory.h"
#include "../../utils/debug.h"
namespace cpu_int {
//CTORS
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(){
this->m_length = 0;
//this->m_modulus;
m_data = NULL;
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length){
this->m_length = length;
//this->m_modulus;
this->m_data = new IntegerType[m_length] ();
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType& modulus){
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length] ();
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType& modulus, std::initializer_list<usint> rhs){
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length] ();
usint len = rhs.size();
for (usint i=0;i<m_length;i++){ // this loops over each entry
if(i<len) {
m_data[i] = IntegerType(*(rhs.begin()+i));
} else {
m_data[i] = IntegerType::ZERO;
}
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType& modulus, std::initializer_list<std::string> rhs){
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length] ();
usint len = rhs.size();
for(usint i=0;i<m_length;i++){ // this loops over each entry
if(i<len) {
m_data[i] = IntegerType(*(rhs.begin()+i));
} else {
m_data[i] = IntegerType::ZERO;
}
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(const BigVectorImpl &bigVector){
m_length = bigVector.m_length;
m_modulus = bigVector.m_modulus;
m_data = new IntegerType[m_length];
for(usint i=0;i<m_length;i++){
m_data[i] = bigVector.m_data[i];
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(BigVectorImpl &&bigVector){
m_data = bigVector.m_data;
m_length = bigVector.m_length;
m_modulus = bigVector.m_modulus;
bigVector.m_data = NULL;
}
//ASSIGNMENT OPERATOR
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(const BigVectorImpl &rhs){
if(this!=&rhs){
if(this->m_length==rhs.m_length){
for (usint i = 0; i < m_length; i++){
this->m_data[i] = rhs.m_data[i];
}
}
else{
//throw std::logic_error("Trying to copy vectors of different size");
delete [] m_data;
m_length = rhs.m_length;
m_modulus = rhs.m_modulus;
m_data = new IntegerType[m_length];
for (usint i = 0; i < m_length; i++){
m_data[i] = rhs.m_data[i];
}
}
this->m_modulus = rhs.m_modulus;
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(std::initializer_list<sint> rhs){
usint len = rhs.size();
for(usint i=0;i<m_length;i++){ // this loops over each tower
if(i<len) {
m_data[i] = IntegerType(*(rhs.begin()+i));
} else {
m_data[i] = 0;
}
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(std::initializer_list<std::string> rhs){
bool dbg_flag = false;
usint len = rhs.size();
for(usint i=0;i<m_length;i++){ // this loops over each tower
if(i<len) {
m_data[i] = IntegerType(*(rhs.begin()+i));
} else {
m_data[i] = 0;
}
DEBUG("in op= i.l. m_data["<<i<<"] = "<<m_data[i]);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(BigVectorImpl &&rhs){
if(this!=&rhs){
delete [] m_data;
m_data = rhs.m_data;
m_length = rhs.m_length;
m_modulus = rhs.m_modulus;
rhs.m_data = NULL;
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType>::~BigVectorImpl(){
//std::cout<<"destructor called for vector of size: "<<this->m_length<<" "<<std::endl;
delete [] m_data;
}
//ACCESSORS
template<class IntegerType_c>
std::ostream& operator<<(std::ostream& os, const BigVectorImpl<IntegerType_c> &ptr_obj){
auto len = ptr_obj.m_length;
os<<"[";
for(usint i=0;i<len;i++){
os<< ptr_obj.m_data[i];
os << ((i == (len-1))?"]":" ");
}
return os;
}
template<class IntegerType>
void BigVectorImpl<IntegerType>::SetModulus(const IntegerType& value){
this->m_modulus = value;
}
/**Switches the integers in the vector to values corresponding to the new modulus
* Algorithm: Integer i, Old Modulus om, New Modulus nm, delta = abs(om-nm):
* Case 1: om < nm
* if i > i > om/2
* i' = i + delta
* Case 2: om > nm
* i > om/2
* i' = i-delta
*/
template<class IntegerType>
void BigVectorImpl<IntegerType>::SwitchModulus(const IntegerType& newModulus) {
bool dbg_flag = false;
DEBUG("Switch modulus old mod :"<<this->m_modulus);
DEBUG("Switch modulus old this :"<<*this);
IntegerType oldModulus(this->m_modulus);
IntegerType n;
IntegerType oldModulusByTwo(oldModulus>>1);
IntegerType diff ((oldModulus > newModulus) ? (oldModulus-newModulus) : (newModulus - oldModulus));
DEBUG("Switch modulus diff :"<<diff);
for(usint i=0; i< this->m_length; i++) {
n = this->GetValAtIndex(i);
DEBUG("i,n "<<i<<" "<< n);
if(oldModulus < newModulus) {
if(n > oldModulusByTwo) {
DEBUG("s1 "<<n.ModAdd(diff, newModulus));
this->SetValAtIndex(i, n.ModAdd(diff, newModulus));
} else {
DEBUG("s2 "<<n.Mod(newModulus));
this->SetValAtIndex(i, n.Mod(newModulus));
}
} else {
if(n > oldModulusByTwo) {
DEBUG("s3 "<<n.ModSub(diff, newModulus));
this->SetValAtIndex(i, n.ModSub(diff, newModulus));
} else {
DEBUG("s4 "<<n.Mod(newModulus));
this->SetValAtIndex(i, n.Mod(newModulus));
}
}
}
DEBUG("Switch modulus this before set :"<<*this);
this->SetModulus(newModulus);
DEBUG("Switch modulus new modulus :"<<this->m_modulus);
DEBUG("Switch modulus new this :"<<*this);
}
template<class IntegerType>
const IntegerType& BigVectorImpl<IntegerType>::GetModulus() const{
return this->m_modulus;
}
template<class IntegerType>
usint BigVectorImpl<IntegerType>::GetLength() const{
return this->m_length;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::Mod(const IntegerType& modulus) const{
//BigVectorImpl ans(*this);
//for(usint i=0;i<this->m_length;i++){
// ans.m_data[i] = ans.m_data[i].Mod(modulus);
//}
//return ans;
if (modulus==2)
return this->ModByTwo();
else
{
BigVectorImpl ans(this->GetLength(),this->GetModulus());
IntegerType halfQ(this->GetModulus() >> 1);
for (usint i = 0; i<ans.GetLength(); i++) {
if (this->GetValAtIndex(i)>halfQ) {
ans.SetValAtIndex(i,this->GetValAtIndex(i).ModSub(this->GetModulus(),modulus));
}
else {
ans.SetValAtIndex(i,this->GetValAtIndex(i).Mod(modulus));
}
}
return ans;
}
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAddAtIndex(usint i, const IntegerType &b) const{
if(i > this->GetLength()-1) {
std::string errMsg = "binvect::ModAddAtIndex. Index is out of range. i = " + std::to_string(i);
throw std::runtime_error(errMsg);
}
BigVectorImpl ans(*this);
ans.m_data[i] = ans.m_data[i].ModAdd(b, this->m_modulus);
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAdd(const IntegerType &b) const{
BigVectorImpl ans(*this);
for(usint i=0;i<this->m_length;i++){
ans.m_data[i] = ans.m_data[i].ModAdd(b, this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModSub(const IntegerType &b) const{
BigVectorImpl ans(*this);
for(usint i=0;i<this->m_length;i++){
ans.m_data[i] = ans.m_data[i].ModSub(b,this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::MultiplyAndRound(const IntegerType &p, const IntegerType &q) const {
//BigVectorImpl ans(this->GetLength(), this->GetModulus());
//IntegerType halfQ(this->GetModulus() >> 1);
//for (usint i = 0; i<ans.GetLength(); i++) {
// if (this->GetValAtIndex(i)>halfQ) {
// ans.SetValAtIndex(i, this->GetValAtIndex(i).ModSub(this->GetModulus(), modulus));
// }
// else {
// ans.SetValAtIndex(i, this->GetValAtIndex(i).Mod(modulus));
// }
//}
//return ans;
BigVectorImpl ans(*this);
IntegerType halfQ(this->m_modulus >> 1);
for(usint i=0;i<this->m_length;i++){
if (ans.m_data[i] > halfQ) {
IntegerType temp = this->m_modulus - ans.m_data[i];
ans.m_data[i] = this->m_modulus - temp.MultiplyAndRound(p, q);
}
else
ans.m_data[i] = ans.m_data[i].MultiplyAndRound(p, q).Mod(this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::DivideAndRound(const IntegerType &q) const {
BigVectorImpl ans(*this);
for(usint i=0;i<this->m_length;i++){
ans.m_data[i] = ans.m_data[i].DivideAndRound(q);
}
return ans;
}
/*
Source: http://homes.esat.kuleuven.be/~fvercaut/papers/bar_mont.pdf
@article{knezevicspeeding,
title={Speeding Up Barrett and Montgomery Modular Multiplications},
author={Knezevic, Miroslav and Vercauteren, Frederik and Verbauwhede, Ingrid}
}
We use the Generalized Barrett modular reduction algorithm described in Algorithm 2 of the Source. The algorithm was originally
proposed in J.-F. Dhem. Modified version of the Barrett algorithm. Technical report, 1994 and described in more detail
in the PhD thesis of the author published at
http://users.belgacom.net/dhem/these/these_public.pdf (Section 2.2.4).
We take \alpha equal to n + 3. So in our case, \mu = 2^(n + \alpha) = 2^(2*n + 3).
Generally speaking, the value of \alpha should be \ge \gamma + 1, where \gamma + n is the number of digits in the dividend.
We use the upper bound of dividend assuming that none of the dividends will be larger than 2^(2*n + 3).
Potential improvements:
1. When working with MATHBACKEND = 1, we tried to compute an evenly distributed array of \mu (the number is approximately equal
to the number BARRET_LEVELS) but that did not give any performance improvement. So using one pre-computed value of
\mu was the most efficient option at the time.
2. We also tried "Interleaved digit-serial modular multiplication with generalized Barrett reduction" Algorithm 3 in the Source but it
was slower with MATHBACKEND = 1.
3. Our implementation makes the modulo operation essentially equivalent to two multiplications. If sparse moduli are selected, it can be replaced
with a single multiplication. The interleaved version of modular multiplication for this case is listed in Algorithm 6 of the source.
This algorithm would most like give the biggest improvement but it sets constraints on moduli.
*/
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModMul(const IntegerType &b) const{
//std::cout<< "Printing Modulus: "<< m_modulus<< std::endl;
BigVectorImpl ans(*this);
//Precompute the Barrett mu parameter
IntegerType mu = lbcrypto::ComputeMu<IntegerType>(m_modulus);
for(usint i=0;i<this->m_length;i++){
//std::cout<< "before data: "<< ans.m_data[i]<< std::endl;
ans.m_data[i].ModBarrettMulInPlace(b,this->m_modulus,mu);
//std::cout<< "after data: "<< ans.m_data[i]<< std::endl;
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModExp(const IntegerType &b) const{
BigVectorImpl ans(*this);
for(usint i=0;i<this->m_length;i++){
ans.m_data[i] = ans.m_data[i].ModExp(b,this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModInverse() const{
BigVectorImpl ans(*this);
//std::cout << ans << std::endl;
for(usint i=0;i<this->m_length;i++){
//std::cout << ans.m_data[i] << std::endl;
//ans.m_data[i].PrintValueInDec();
ans.m_data[i] = ans.m_data[i].ModInverse(this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAdd(const BigVectorImpl &b) const{
if((this->m_length!=b.m_length) || this->m_modulus!=b.m_modulus ){
throw std::logic_error("ModAdd called on BigVectorImpl's with different parameters.");
}
BigVectorImpl ans(*this);
for(usint i=0;i<ans.m_length;i++){
ans.m_data[i] = ans.m_data[i].ModAdd(b.m_data[i],this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModSub(const BigVectorImpl &b) const{
if((this->m_length!=b.m_length) || this->m_modulus!=b.m_modulus ){
throw std::logic_error("ModSub called on BigVectorImpl's with different parameters.");
}
BigVectorImpl ans(*this);
for(usint i=0;i<ans.m_length;i++){
ans.m_data[i] = ans.m_data[i].ModSub(b.m_data[i],this->m_modulus);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModByTwo() const {
BigVectorImpl ans(this->GetLength(),this->GetModulus());
IntegerType halfQ(this->GetModulus() >> 1);
for (usint i = 0; i<ans.GetLength(); i++) {
if (this->GetValAtIndex(i)>halfQ) {
if (this->GetValAtIndex(i).Mod(2) == 1)
ans.SetValAtIndex(i, IntegerType(0));
else
ans.SetValAtIndex(i, 1);
}
else {
if (this->GetValAtIndex(i).Mod(2) == 1)
ans.SetValAtIndex(i, 1);
else
ans.SetValAtIndex(i, IntegerType(0));
}
}
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator+=(const BigVectorImpl &b) {
if((this->m_length!=b.m_length) || this->m_modulus!=b.m_modulus ){
throw std::logic_error("operator+= called on BigVectorImpl's with different parameters.");
}
for(usint i=0;i<this->m_length;i++){
this->m_data[i] = this->m_data[i].ModAdd(b.m_data[i],this->m_modulus);
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator-=(const BigVectorImpl &b) {
if((this->m_length!=b.m_length) || this->m_modulus!=b.m_modulus ){
throw std::logic_error("operator-= called on BigVectorImpl's with different parameters.");
}
for(usint i=0;i<this->m_length;i++){
this->m_data[i] = this->m_data[i].ModSub(b.m_data[i],this->m_modulus);
}
return *this;
}
/*
Source: http://homes.esat.kuleuven.be/~fvercaut/papers/bar_mont.pdf
@article{knezevicspeeding,
title={Speeding Up Barrett and Montgomery Modular Multiplications},
author={Knezevic, Miroslav and Vercauteren, Frederik and Verbauwhede, Ingrid}
}
We use the Generalized Barrett modular reduction algorithm described in Algorithm 2 of the Source. The algorithm was originally
proposed in J.-F. Dhem. Modified version of the Barrett algorithm. Technical report, 1994 and described in more detail
in the PhD thesis of the author published at
http://users.belgacom.net/dhem/these/these_public.pdf (Section 2.2.4).
We take \alpha equal to n + 3. So in our case, \mu = 2^(n + \alpha) = 2^(2*n + 3).
Generally speaking, the value of \alpha should be \ge \gamma + 1, where \gamma + n is the number of digits in the dividend.
We use the upper bound of dividend assuming that none of the dividends will be larger than 2^(2*n + 3).
Potential improvements:
1. When working with MATHBACKEND = 1, we tried to compute an evenly distributed array of \mu (the number is approximately equal
to the number BARRET_LEVELS) but that did not give any performance improvement. So using one pre-computed value of
\mu was the most efficient option at the time.
2. We also tried "Interleaved digit-serial modular multiplication with generalized Barrett reduction" Algorithm 3 in the Source but it
was slower with MATHBACKEND = 1.
3. Our implementation makes the modulo operation essentially equivalent to two multiplications. If sparse moduli are selected, it can be replaced
with a single multiplication. The interleaved version of modular multiplication for this case is listed in Algorithm 6 of the source.
This algorithm would most like give the biggest improvement but it sets constraints on moduli.
*/
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModMul(const BigVectorImpl &b) const{
if((this->m_length!=b.m_length) || this->m_modulus!=b.m_modulus ){
throw std::logic_error("ModMul called on BigVectorImpl's with different parameters.");
}
BigVectorImpl ans(*this);
//Precompute the Barrett mu parameter
IntegerType mu = lbcrypto::ComputeMu<IntegerType>(this->GetModulus());
for(usint i=0;i<ans.m_length;i++){
//ans.m_data[i] = ans.m_data[i].ModMul(b.m_data[i],this->m_modulus);
ans.m_data[i].ModBarrettMulInPlace(b.m_data[i],this->m_modulus,mu);
}
return ans;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::MultWithOutMod(const BigVectorImpl &b) const {
if ((this->m_length != b.m_length) || this->m_modulus != b.m_modulus) {
throw std::logic_error("ModMul called on BigVectorImpl's with different parameters.");
}
BigVectorImpl ans(*this);
for (usint i = 0; i<ans.m_length; i++) {
ans.m_data[i] = ans.m_data[i] * b.m_data[i];
}
return ans;
}
//Gets the ind
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::GetDigitAtIndexForBase(usint index, usint base) const{
BigVectorImpl ans(*this);
for(usint i=0;i<this->m_length;i++){
ans.m_data[i] = IntegerType(ans.m_data[i].GetDigitAtIndexForBase(index,base));
}
return ans;
}
// Serialize Operation
template<class IntegerType>
bool BigVectorImpl<IntegerType>::Serialize(lbcrypto::Serialized* serObj) const {
if( !serObj->IsObject() )
return false;
lbcrypto::SerialItem bbvMap(rapidjson::kObjectType);
bbvMap.AddMember("Modulus", this->GetModulus().ToString(), serObj->GetAllocator());
bbvMap.AddMember("IntegerType", IntegerType::IntegerTypeName(), serObj->GetAllocator());
usint pkVectorLength = this->GetLength();
bbvMap.AddMember("Length", std::to_string(pkVectorLength), serObj->GetAllocator());
if( pkVectorLength > 0 ) {
std::string pkBufferString = "";
for (size_t i = 0; i < pkVectorLength; i++) {
pkBufferString += GetValAtIndex(i).Serialize(this->GetModulus());
}
bbvMap.AddMember("VectorValues", pkBufferString, serObj->GetAllocator());
}
serObj->AddMember("BigVectorImpl", bbvMap, serObj->GetAllocator());
return true;
}
// Deserialize Operation
template<class IntegerType>
bool BigVectorImpl<IntegerType>::Deserialize(const lbcrypto::Serialized& serObj) {
lbcrypto::Serialized::ConstMemberIterator mIter = serObj.FindMember("BigVectorImpl");
if( mIter == serObj.MemberEnd() )
return false;
lbcrypto::SerialItem::ConstMemberIterator vIt;
if( (vIt = mIter->value.FindMember("IntegerType")) == mIter->value.MemberEnd() )
return false;
if( IntegerType::IntegerTypeName() != vIt->value.GetString() )
return false;
if( (vIt = mIter->value.FindMember("Modulus")) == mIter->value.MemberEnd() )
return false;
IntegerType bbiModulus(vIt->value.GetString());
if( (vIt = mIter->value.FindMember("Length")) == mIter->value.MemberEnd() )
return false;
usint vectorLength = std::stoi(vIt->value.GetString());
if( (vIt = mIter->value.FindMember("VectorValues")) == mIter->value.MemberEnd() )
return false;
BigVectorImpl<IntegerType> newVec(vectorLength, bbiModulus);
IntegerType vectorElem;
const char *vp = vIt->value.GetString();
for( usint ePos = 0; ePos < vectorLength; ePos++ ) {
if( *vp == '\0' ) {
return false; // premature end of vector
}
vp = vectorElem.Deserialize(vp, bbiModulus);
newVec[ePos] = vectorElem;
}
*this = std::move(newVec);
return true;
}
} // namespace lbcrypto ends
| 32.363359 | 145 | 0.716577 | marcelmon |
ce66c15030f3b50317775ca4168ecf9e38630a76 | 589 | hpp | C++ | C-PhotoDeal_framework/CannyPhoto.hpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 8 | 2016-03-12T08:39:56.000Z | 2021-07-12T01:48:20.000Z | C-PhotoDeal_framework/CannyPhoto.hpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | null | null | null | C-PhotoDeal_framework/CannyPhoto.hpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 2 | 2016-03-15T09:48:38.000Z | 2017-02-04T23:53:32.000Z | //
// CannyPhoto.hpp
// cameraDeal
//
// Created by numberwolf on 16/9/10.
// Copyright © 2016年 numberwolf. All rights reserved.
//
#ifndef CannyPhoto_hpp
#define CannyPhoto_hpp
#include <stdio.h>
#include "Pixels.hpp"
#include "Common.hpp"
#include <math.h>
class CannyPhoto {
Pixels *CannyPixels = NULL;
public:
CannyPhoto(Pixels *p_Pixels) {
this->CannyPixels = p_Pixels;
}
~CannyPhoto() {
CannyPixels = NULL;
}
void sobelCanny(int width, int height);
private:
protected:
};
#endif /* CannyPhoto_hpp */
| 15.102564 | 54 | 0.62309 | numberwolf |
ce676938c5e95a8ada062323b7a881172a62844c | 1,445 | cpp | C++ | luogu/1519.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | luogu/1519.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | luogu/1519.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
char nextchar(){
char ch = getchar();
while(ch != '|' && ch != '+' && ch != ' ' && ch != '-') ch=getchar();
return ch;
}
char mp[250][250];
int f[250][250], ans;
int qx[N], qy[N], n, m;
int px[] = {0, 1, 0, -1};
int py[] = {1, 0, -1, 0};
void bfs(int sx, int sy){
int l = 0, r = 1;
qx[1] = sx; qy[1] = sy;
f[sx][sy] = 0;
while(l < r){
int tx = qx[++l], ty = qy[l];
for(int i = 0; i < 4; i++){
int xx = tx+px[i], yy = ty+py[i];
if(mp[xx][yy] != ' ' || xx > m || xx < 1 || yy > n || yy < 1) continue;
xx += px[i]; yy += py[i];
if(f[tx][ty]+1 < f[xx][yy]){
f[xx][yy] = f[tx][ty]+1;
qx[++r] = xx; qy[r] = yy;
}
}
}
}
int main(int argc, char const *argv[]){
n = read()<<1|1; m = read()<<1|1;
memset(f, 63, sizeof(int)*62500);
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++) mp[i][j] = nextchar();
for(int i = 2; i <= m; i += 2){
if(mp[i][1] == ' ') bfs(i, 0);
if(mp[i][n] == ' ') bfs(i, n+1);
}
for(int i = 2; i <= n; i += 2){
if(mp[1][i] == ' ') bfs(0, i);
if(mp[m][i] == ' ') bfs(m+1, i);
}
for(int i = 2; i <= m; i += 2)
for(int j = 2; j <= n; j += 2)
ans = max(ans, f[i][j]);
printf("%d\n", ans);
return 0;
} | 25.803571 | 74 | 0.447751 | swwind |
ce6e0552e3f08e7331b199f853ab25225566fe13 | 3,874 | hpp | C++ | headers/Font.hpp | edwinacunav/gosu-edwinacunav | 24919d1ac3055d365f97fcf5628864b6f937991a | [
"MIT"
] | null | null | null | headers/Font.hpp | edwinacunav/gosu-edwinacunav | 24919d1ac3055d365f97fcf5628864b6f937991a | [
"MIT"
] | null | null | null | headers/Font.hpp | edwinacunav/gosu-edwinacunav | 24919d1ac3055d365f97fcf5628864b6f937991a | [
"MIT"
] | null | null | null | //! \file Font.hpp
//! Interface of the Font class.
#pragma once
#include "Fwd.hpp"
#include "Color.hpp"
#include "GraphicsBase.hpp"
#include "Platform.hpp"
#include "Text.hpp"
#include <memory>
#include <string>
namespace Gosu
{
//! Fonts are ideal for drawing short, dynamic strings.
//! For large, static texts you should use Gosu::layout_text and turn the result into an image.
class Font
{
struct Impl;//std::ptr<Impl> pimpl;
public:
//! Constructs a font that can be drawn onto the graphics object.
//! \param font_name Name of a system font, or a filename to a TTF
//! file (must contain '/', does not work on Linux).
//! \param font_height Height of the font, in pixels.
//! \param font_flags Flags used to render individual characters of
//! the font.
Font(int height, const std::string& name = default_font_name(), unsigned flags = 0);
~Font();
//! Returns the name of the font that was used to create it.
const std::string& name() const;
//! Returns the height of the font, in pixels.
int height() const;
//! Returns the flags used to create the font characters.
unsigned flags() const;
const std::string& text() const;
Gosu::Color* color() const;
bool visible() const;
void set_text(const std::string& text);
void set_color(Gosu::Color* color);
void set_visible(bool seen);
double set_text_width() const;
//! Returns the width, in pixels, the given text would occupy if drawn.
double text_width(const std::string& text) const;
//! Returns the width, in pixels, the given text would occupy if drawn.
double markup_width(const std::string& markup) const;
//! Draws text so the top left corner of the text is at (x; y).
void draw_text(const std::string& text, double x, double y, ZPos z,
double scale_x = 1, double scale_y = 1, Color c = Color::WHITE,
AlphaMode mode = AM_DEFAULT) const;
//! Draws markup so the top left corner of the text is at (x; y).
void draw_markup(const std::string& markup, double x, double y, ZPos z,
double scale_x = 1, double scale_y = 1, Color c = Color::WHITE,
AlphaMode mode = AM_DEFAULT) const;
//! Draws text at a position relative to (x; y).
//! \param rel_x Determines where the text is drawn horizontally. If
//! rel_x is 0.0, the text will be to the right of x, if it is 1.0,
//! the text will be to the left of x, if it is 0.5, it will be
//! centered on x. All real numbers are possible values.
//! \param rel_y See rel_x.
void draw_text_rel(const std::string& text, double x, double y, ZPos z,
double rel_x, double rel_y, double scale_x = 1, double scale_y = 1,
Color c = Color::WHITE, AlphaMode mode = AM_DEFAULT) const;
//! Draws text at a position relative to (x; y).
//! \param rel_x Determines where the text is drawn horizontally. If
//! rel_x is 0.0, the text will be to the right of x, if it is 1.0,
//! the text will be to the left of x, if it is 0.5, it will be
//! centered on x. All real numbers are possible values.
//! \param rel_y See rel_x.
void draw_markup_rel(const std::string& markup, double x, double y, ZPos z,
double rel_x, double rel_y, double scale_x = 1, double scale_y = 1,
Color c = Color::WHITE, AlphaMode mode = AM_DEFAULT) const;
//! Maps a letter to a specific image, instead of generating one using
//! Gosu's built-in text rendering.
void set_image(std::string codepoint, unsigned font_flags, const Gosu::Image& image);
//! A shortcut for mapping a character to an image regardless of font_flags.
void set_image(std::string codepoint, const Gosu::Image& image);
private:
Impl *pimpl;
};
}
| 47.243902 | 97 | 0.647651 | edwinacunav |
ce700eae42d32a6c6ef61066fe20cfb758206dac | 1,921 | cpp | C++ | Modules/Core/src/Interactions/mitkMouseMoveEvent.cpp | ZP-Hust/MITK | ca11353183c5ed4bc30f938eae8bde43a0689bf6 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/Core/src/Interactions/mitkMouseMoveEvent.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/Core/src/Interactions/mitkMouseMoveEvent.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2019-01-09T08:20:18.000Z | 2019-01-09T08:20:18.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkMouseMoveEvent.h"
#include "mitkException.h"
mitk::MouseMoveEvent::MouseMoveEvent(mitk::BaseRenderer *baseRenderer,
const mitk::Point2D &mousePosition,
MouseButtons buttonStates,
ModifierKeys modifiers)
: InteractionPositionEvent(baseRenderer, mousePosition), m_ButtonStates(buttonStates), m_Modifiers(modifiers)
{
}
mitk::InteractionEvent::ModifierKeys mitk::MouseMoveEvent::GetModifiers() const
{
return m_Modifiers;
}
mitk::InteractionEvent::MouseButtons mitk::MouseMoveEvent::GetButtonStates() const
{
return m_ButtonStates;
}
void mitk::MouseMoveEvent::SetModifiers(ModifierKeys modifiers)
{
m_Modifiers = modifiers;
}
void mitk::MouseMoveEvent::SetButtonStates(MouseButtons buttons)
{
m_ButtonStates = buttons;
}
mitk::MouseMoveEvent::~MouseMoveEvent()
{
}
bool mitk::MouseMoveEvent::IsEqual(const mitk::InteractionEvent &interactionEvent) const
{
const auto &mpe = static_cast<const mitk::MouseMoveEvent &>(interactionEvent);
return (this->GetModifiers() == mpe.GetModifiers() && this->GetButtonStates() == mpe.GetButtonStates() &&
Superclass::IsEqual(interactionEvent));
}
bool mitk::MouseMoveEvent::IsSuperClassOf(const InteractionEvent::Pointer &baseClass) const
{
return (dynamic_cast<MouseMoveEvent *>(baseClass.GetPointer()) != nullptr);
}
| 30.492063 | 111 | 0.679334 | ZP-Hust |
ce70f2e6a83aa04b236312d47de1bbb1b29c9441 | 554 | cc | C++ | util/src/ifile.cc | k3ll3x/tetra_sand | c590a4ca5cc988c552532a6f17f213c70f492a4c | [
"MIT"
] | null | null | null | util/src/ifile.cc | k3ll3x/tetra_sand | c590a4ca5cc988c552532a6f17f213c70f492a4c | [
"MIT"
] | null | null | null | util/src/ifile.cc | k3ll3x/tetra_sand | c590a4ca5cc988c552532a6f17f213c70f492a4c | [
"MIT"
] | null | null | null | #include "ifile.h"
#include <fstream>
#include <iostream>
#include <sstream>
bool ifile::read(const std::string& filename)
{
if (filename.empty())
{
std::cout << "No filename provided" << std::endl;
return false;
}
std::fstream input_file(filename, std::fstream::in);
if (!input_file.is_open())
{
std::cout << "Could not open file " << filename << std::endl;
return false;
}
std::stringstream ss;
ss << input_file.rdbuf();
_contents = ss.str();
return true;
}
const std::string ifile::get_contents() const
{
return _contents;
} | 16.787879 | 63 | 0.66065 | k3ll3x |
ce70f6346cef4f79cd3dc708fd6881b617f3d4ea | 3,997 | cpp | C++ | HelloWorldAlmost.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | HelloWorldAlmost.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | HelloWorldAlmost.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | // ch3vector.cpp
//
// Examples to show how sequence containers (vector) work.
//
// Last modificaton dates:
//
// 2006-3-22 DD new code for algorithms
//
// (C) Datasim Education BV 2003-2006
//
//
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
string UpperCase(string s)
{ // Convert a string to upper case
for (int j = 0; j < s.length(); j++)
{
if (s[j] >= 'a' && s[j] <= 'z')
{
s[j] -= 'a' - 'A';
}
}
return s;
}
class Join
{
public:
// Overloading of operator ()
string operator () (const string& s1, const string& s2)
{
return s1 + " and " +s2;
}
};
bool myGreater(double x, double y)
{
return x > y;
}
template <class T> void print(const vector<T>& l, string s = string("data"))
{ // A generic print function for vectors
cout << endl << s << ", size of vector is " << l.size() << "\n[";
// We must use a const iterator here, otherwise we get a compiler error.
vector<T>::const_iterator i;
for (i = l.begin(); i != l.end(); i++)
{
cout << *i << ",";
}
cout << "]\n";
}
int main()
{
size_t n = 10;
double val = 3.14;
vector<double> myVec(n, val); // Create n copies of val
print(myVec);
// Access elements of the vector by using the indexing operator []
// Change some values here and there
myVec[0] = 2.0;
myVec[1] = 456.76;
int last_element= myVec.size() - 1;
myVec[last_element] = 55.66;
print(myVec);
// Now some algorithms
vector<double> myVec2(myVec.size());
list<double> myList;
// Copy source range of type T1 into target range of type T2
copy(myVec.begin(), myVec.end(), myVec2.begin());
print(myVec2, string("copy to a vector"));
copy(myVec.begin(), myVec.end(), myList.begin());
// Copying and transformation at the same time
vector<string> First(3);
First[0] = "Bill";
First[1] = "Abbott";
First[2] = "Bassie";
vector<string> Second(3);
Second[0] = "Ben";
Second[1] = "Costello";
Second[2] = "Adriaan";
vector<string> Couples(3);
// Now convert the First names to upper case
transform (First.begin(), First.end(), First.begin(), UpperCase);
print(First, string("An upper case vector"));
// Now join to make a team
transform (First.begin(), First.end(), Second.begin(), Couples.begin(),
Join());
print(Couples, string("Joined couples"));
// Shift the elements of a vector to the left; those that fall off
// are inserted at the end
int N = 6;
vector<double> myVec3(N);
for (int i = 0; i < myVec3.size(); i++)
{
myVec3[i] = double (i);
}
int shiftFactor = 2;
rotate(myVec3.begin(), myVec3.begin() + shiftFactor, myVec3.end());
print(myVec3, string("Rotated vector by 2 units"));
// Now reverse the order of elements in the vector; the first becomes
// last and vice versa
reverse(myVec3.begin(), myVec3.end());
print(myVec3, string("Reversed vector vec3"));
// Now replace each occurrence of one value by a new value
double oldVal = 2;
double newVal = 999;
replace(myVec3.begin(), myVec3.end(), oldVal, newVal);
print(myVec3, string("Modified value of vec3"));
// Now remove this element
remove(myVec3.begin(), myVec3.end(), newVal);
print(myVec3, string("Removed element from vec3"));
// Sort the random access container vector<T> class
myVec3[myVec3.size() - 1] = 9999.0;
stable_sort(myVec3.begin(), myVec3.end()); // Using < as comparitor
print(myVec3, string("Sorted vec3 with '<' ASCENDING "));
stable_sort(myVec3.begin(), myVec3.end(), myGreater);
print(myVec3, string("Sorted vec3 with DESCENDING comparitor function "));
// Merge two sorted vectors
vector<double> myVec4(N, 2.41);
vector<double> myVec5(myVec3.size() + myVec4.size()); // Output
merge(myVec3.begin(), myVec3.end(), myVec4.begin(), myVec4.end(),
myVec5.begin());
print(myVec5, string("Merged vector"));
return 0;
}
| 23.374269 | 77 | 0.621466 | talibe84 |
ce71715e14aba50c584045a45f76a0a50b6cc43e | 1,178 | cpp | C++ | src/Template/VideoTemplate.cpp | Inlife/video-cube | 1caefa2b2cda7c1386c3b75796086cb7201f5e8d | [
"MIT"
] | 2 | 2015-08-19T13:52:43.000Z | 2016-09-02T23:12:32.000Z | src/Template/VideoTemplate.cpp | Inlife/video-cube | 1caefa2b2cda7c1386c3b75796086cb7201f5e8d | [
"MIT"
] | null | null | null | src/Template/VideoTemplate.cpp | Inlife/video-cube | 1caefa2b2cda7c1386c3b75796086cb7201f5e8d | [
"MIT"
] | 1 | 2018-05-25T11:29:45.000Z | 2018-05-25T11:29:45.000Z | using namespace Cooper;
// Video template grid
class VideoTemplate : public Template {
public:
void grid(std::string name, std::vector<Video> videos) {
this->set(name, "");
double _l = videos.size() / 3.0;
std::size_t length = std::ceil(_l);
for(std::size_t i = 0; i < length; i++) {
Template line("main/_index-video-line");
for(std::size_t j = 0; j < 3; j++) {
int id = ( i * 3 ) + j;
if (id < videos.size()) {
Template box("main/_index-video-box");
box.set("id", videos[id].getId());
box.set("title", videos[id].getTitle());
box.set("preview", videos[id].getPreview());
line.add("videoline", box.render(false));
}
}
this->add(name, line.render(false));
}
}
void list(std::string name, std::vector<Video> videos) {
this->set(name, "");
std::size_t length = videos.size();
for(std::size_t i = 0; i < length; i++) {
Template line("main/_video-video-line");
line.set("id", videos[i].getId());
line.set("title", videos[i].getTitle());
line.set("preview", videos[i].getPreview());
this->add(name, line.render(false));
}
}
VideoTemplate(std::string name) : Template(name) {}
}; | 24.040816 | 57 | 0.594228 | Inlife |
ce7345b1dedd067a62905aee366b66addd2e2212 | 1,047 | cpp | C++ | penet/callbacks.cpp | organicpencil/gdnet3 | b4b951e0cffc0c594ea58de52d3b1eee2222f325 | [
"MIT"
] | null | null | null | penet/callbacks.cpp | organicpencil/gdnet3 | b4b951e0cffc0c594ea58de52d3b1eee2222f325 | [
"MIT"
] | null | null | null | penet/callbacks.cpp | organicpencil/gdnet3 | b4b951e0cffc0c594ea58de52d3b1eee2222f325 | [
"MIT"
] | null | null | null | /**
@file callbacks.c
@brief PENet callback functions
*/
#define PENET_BUILDING_LIB 1
#include "penet/penet.h"
#include "os/memory.h"
static PENetCallbacks callbacks = { malloc, free, abort };
int
penet_initialize_with_callbacks (PENetVersion version, const PENetCallbacks * inits)
{
if (version < PENET_VERSION_CREATE (1, 3, 0))
return -1;
if (inits -> malloc != NULL || inits -> free != NULL)
{
if (inits -> malloc == NULL || inits -> free == NULL)
return -1;
callbacks.malloc = inits -> malloc;
callbacks.free = inits -> free;
}
if (inits -> no_memory != NULL)
callbacks.no_memory = inits -> no_memory;
return penet_initialize ();
}
PENetVersion
penet_linked_version (void)
{
return PENET_VERSION;
}
void *
penet_malloc (size_t size)
{
return memalloc(size);
/*void * memory = callbacks.malloc (size);
if (memory == NULL)
callbacks.no_memory ();
return memory;*/
}
void
penet_free (void * memory)
{
return memfree(memory);
//callbacks.free (memory);
}
| 18.368421 | 84 | 0.65043 | organicpencil |
ce73dd4eb51033c1822248bd852a743fa19fe846 | 964 | cpp | C++ | src/build/hibf/bin_size_in_bits.cpp | SGSSGene/raptor | 76189b4b941525f8da05821146a840c1d666e430 | [
"BSD-3-Clause"
] | null | null | null | src/build/hibf/bin_size_in_bits.cpp | SGSSGene/raptor | 76189b4b941525f8da05821146a840c1d666e430 | [
"BSD-3-Clause"
] | null | null | null | src/build/hibf/bin_size_in_bits.cpp | SGSSGene/raptor | 76189b4b941525f8da05821146a840c1d666e430 | [
"BSD-3-Clause"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/raptor/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <cmath>
#include <raptor/build/hibf/bin_size_in_bits.hpp>
namespace raptor::hibf
{
size_t bin_size_in_bits(build_arguments const & arguments, size_t const number_of_kmers_to_be_stored)
{
return std::ceil( - static_cast<double>(number_of_kmers_to_be_stored * arguments.hash) /
std::log(1 - std::exp(std::log(arguments.fpr) / arguments.hash)));
}
} // namespace raptor::hibf
| 43.818182 | 104 | 0.578838 | SGSSGene |
ce7637a0f9ee90f2fc0f8aeb896fd305095cb7cd | 4,937 | cpp | C++ | Base/PLScene/src/Scene/SceneNodes/SNPoint.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLScene/src/Scene/SceneNodes/SNPoint.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 19 | 2018-08-24T08:10:13.000Z | 2018-11-29T06:39:08.000Z | Base/PLScene/src/Scene/SceneNodes/SNPoint.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: SNPoint.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLRenderer/RendererContext.h>
#include <PLRenderer/Renderer/DrawHelpers.h>
#include <PLRenderer/Effect/EffectManager.h>
#include "PLScene/Visibility/VisNode.h"
#include "PLScene/Scene/SceneNodes/SNPoint.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
using namespace PLMath;
using namespace PLRenderer;
namespace PLScene {
//[-------------------------------------------------------]
//[ RTTI interface ]
//[-------------------------------------------------------]
pl_implement_class(SNPoint)
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Default constructor
*/
SNPoint::SNPoint() :
Size(this),
Color(this),
Flags(this)
{
// Set draw function flags
SetDrawFunctionFlags(static_cast<uint8>(GetDrawFunctionFlags() | UseDrawSolid | UseDrawTransparent));
}
/**
* @brief
* Destructor
*/
SNPoint::~SNPoint()
{
}
//[-------------------------------------------------------]
//[ Public virtual SceneNode functions ]
//[-------------------------------------------------------]
void SNPoint::DrawSolid(Renderer &cRenderer, const VisNode *pVisNode)
{
// Call base implementation
SceneNode::DrawSolid(cRenderer, pVisNode);
// Perform depth test?
if (!(GetFlags() & NoDepthTest)) {
// Draw the point
cRenderer.GetRendererContext().GetEffectManager().Use();
cRenderer.SetRenderState(RenderState::BlendEnable, Color.Get().a != 1.0f);
// 3D position or screen space position?
DrawHelpers &cDrawHelpers = cRenderer.GetDrawHelpers();
if (GetFlags() & No3DPosition) {
// Begin 2D mode
cDrawHelpers.Begin2DMode();
// Draw the point
cDrawHelpers.DrawPoint(Color.Get(), GetTransform().GetPosition(), Size);
// End 2D mode
cDrawHelpers.End2DMode();
} else {
// Draw the point
cDrawHelpers.DrawPoint(Color.Get(), Vector3::Zero, pVisNode->GetWorldViewProjectionMatrix(), Size);
}
}
}
void SNPoint::DrawTransparent(Renderer &cRenderer, const VisNode *pVisNode)
{
// Perform depth test?
if (GetFlags() & NoDepthTest) {
// Draw the point
cRenderer.GetRendererContext().GetEffectManager().Use();
cRenderer.SetRenderState(RenderState::ZEnable, false);
cRenderer.SetRenderState(RenderState::ZWriteEnable, false);
cRenderer.SetRenderState(RenderState::BlendEnable, Color.Get().a != 1.0f);
// 3D position or screen space position?
DrawHelpers &cDrawHelpers = cRenderer.GetDrawHelpers();
if (GetFlags() & No3DPosition) {
// Begin 2D mode
cDrawHelpers.Begin2DMode();
// Draw the point
cDrawHelpers.DrawPoint(Color.Get(), GetTransform().GetPosition(), Size);
// End 2D mode
cDrawHelpers.End2DMode();
} else {
// Draw the point
cDrawHelpers.DrawPoint(Color.Get(), Vector3::Zero, pVisNode->GetWorldViewProjectionMatrix(), Size);
}
}
// Call base implementation
SceneNode::DrawTransparent(cRenderer, pVisNode);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLScene
| 34.524476 | 102 | 0.564513 | ktotheoz |
7069f5efca27124859292124e24a62a636575466 | 1,510 | cpp | C++ | non_guaranteed_nanolog_benchmark.cpp | styac/NanoLog-- | b99a5e992f171a9bdbdc3a0d971c3651d8e701e6 | [
"MIT"
] | 1 | 2019-06-03T09:04:47.000Z | 2019-06-03T09:04:47.000Z | non_guaranteed_nanolog_benchmark.cpp | styac/NanoLog-- | b99a5e992f171a9bdbdc3a0d971c3651d8e701e6 | [
"MIT"
] | null | null | null | non_guaranteed_nanolog_benchmark.cpp | styac/NanoLog-- | b99a5e992f171a9bdbdc3a0d971c3651d8e701e6 | [
"MIT"
] | null | null | null | #include "NanoLog.hpp"
#include <chrono>
#include <thread>
#include <vector>
#include <atomic>
#include <cstdio>
constexpr int32_t iterExp = 25;
uint64_t timestamp_now()
{
constexpr int32_t sec2nsec = 1000*1000*1000LL;
timespec t;
clock_gettime( CLOCK_REALTIME, &t);
return t.tv_sec * sec2nsec + t.tv_nsec;
}
void nanolog_benchmark()
{
char const * const benchmark = "benchmark";
uint64_t begin = timestamp_now();
for (int i = 0; i < 1<<iterExp; ++i)
LOG_INFO << "Logging " << benchmark << " " << i << " " << 0 << " " << 'K' << " " << -42.42;
long int avg_latency = (timestamp_now() - begin)>>iterExp;
printf("\tAverage NanoLog Latency = %ld nanoseconds\n", avg_latency);
}
template < typename Function >
void run_benchmark(Function && f, int thread_count)
{
printf("Thread count: %d cycle: %d\n", thread_count, 1<<iterExp);
std::vector < std::thread > threads;
for (int i = 0; i < thread_count; ++i)
{
threads.emplace_back(f);
}
for (int i = 0; i < thread_count; ++i)
{
threads[i].join();
}
}
int main()
{
// Ring buffer size is passed as 10 mega bytes.
// Since each log line = 256 bytes, thats 40960 slots.
nanolog::initialize(nanolog::NonGuaranteedLogger(100), "/tmp/", "nanolog", 100);
nanolog::set_logLevel(nanolog::LogLevel::TRACE);
for (auto threads : { 1, 2, 3, 4, 5 })
run_benchmark(nanolog_benchmark, threads);
return 0;
}
| 25.59322 | 127 | 0.601987 | styac |
706c0482d67cdb0b8ee6d0fc8278621b20b32cb4 | 306 | hpp | C++ | src/stan/lang/ast/node/int_literal_def.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/node/int_literal_def.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/node/int_literal_def.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2020-07-14T11:36:09.000Z | 2020-07-14T11:36:09.000Z | #ifndef STAN_LANG_AST_NODE_INT_LITERAL_DEF_HPP
#define STAN_LANG_AST_NODE_INT_LITERAL_DEF_HPP
#include <stan/lang/ast.hpp>
namespace stan {
namespace lang {
int_literal::int_literal() : type_(int_type()) { }
int_literal::int_literal(int val) : val_(val), type_(int_type()) { }
}
}
#endif
| 19.125 | 73 | 0.728758 | drezap |
7070819b7db49b99e3edbb151e97705034440929 | 4,547 | hpp | C++ | hpx/util/static.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/util/static.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/util/static.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2006 Joao Abecasis
//
// 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)
#if !defined(HPX_UTIL_STATIC_JUN_12_2008_0934AM)
#define HPX_UTIL_STATIC_JUN_12_2008_0934AM
#include <hpx/hpx_fwd.hpp>
#include <boost/noncopyable.hpp>
#include <boost/call_traits.hpp>
#include <boost/aligned_storage.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/utility/addressof.hpp>
#include <boost/type_traits/add_pointer.hpp>
#include <boost/type_traits/alignment_of.hpp>
#if HPX_GCC_VERSION < 40300 && \
!(BOOST_INTEL_CXX_VERSION > 1200 && !defined(BOOST_WINDOWS)) && \
(HPX_CLANG_VERSION < 20900) && \
(_MSC_FULL_VER < 180021114) // NovCTP_2013
#include <boost/thread/once.hpp>
#include <boost/bind.hpp>
#include <boost/static_assert.hpp>
#include <memory> // for placement new
#endif
#if !defined(BOOST_WINDOWS)
# define HPX_EXPORT_STATIC_ HPX_EXPORT
#else
# define HPX_EXPORT_STATIC_
#endif
namespace hpx { namespace util
{
#if HPX_GCC_VERSION >= 40300 || \
(BOOST_INTEL_CXX_VERSION > 1200 && !defined(BOOST_WINDOWS)) || \
(HPX_CLANG_VERSION >= 20900) || \
(_MSC_FULL_VER >= 180021114) // NovCTP_2013
//
// C++11 requires thread-safe initialization of function-scope statics.
// For conforming compilers, we utilize this feature.
//
template <typename T, typename Tag = T>
struct HPX_EXPORT_STATIC_ static_ : boost::noncopyable
{
public:
typedef T value_type;
typedef typename boost::call_traits<T>::reference reference;
typedef typename boost::call_traits<T>::const_reference const_reference;
static_()
{
get_reference();
}
operator reference()
{
return get();
}
operator const_reference() const
{
return get();
}
reference get()
{
return get_reference();
}
const_reference get() const
{
return get_reference();
}
private:
static reference get_reference()
{
static T t;
return t;
}
};
#else
//
// Provides thread-safe initialization of a single static instance of T.
//
// This instance is guaranteed to be constructed on static storage in a
// thread-safe manner, on the first call to the constructor of static_.
//
// Requirements:
// T is default constructible or has one argument
// T::T() MUST not throw!
// this is a requirement of boost::call_once.
//
template <typename T, typename Tag = T>
struct HPX_EXPORT_STATIC_ static_ : boost::noncopyable
{
public:
typedef T value_type;
private:
struct destructor
{
~destructor()
{
static_::get_address()->~value_type();
}
};
struct default_constructor
{
static void construct()
{
new (static_::get_address()) value_type();
static destructor d;
}
};
public:
typedef typename boost::call_traits<T>::reference reference;
typedef typename boost::call_traits<T>::const_reference const_reference;
static_()
{
boost::call_once(&default_constructor::construct, constructed_);
}
operator reference()
{
return this->get();
}
operator const_reference() const
{
return this->get();
}
reference get()
{
return *this->get_address();
}
const_reference get() const
{
return *this->get_address();
}
private:
typedef typename boost::add_pointer<value_type>::type pointer;
static pointer get_address()
{
return static_cast<pointer>(data_.address());
}
typedef boost::aligned_storage<sizeof(value_type),
boost::alignment_of<value_type>::value> storage_type;
static storage_type data_;
static boost::once_flag constructed_;
};
template <typename T, typename Tag>
typename static_<T, Tag>::storage_type static_<T, Tag>::data_;
template <typename T, typename Tag>
boost::once_flag static_<T, Tag>::constructed_ = BOOST_ONCE_INIT;
#endif
}}
#endif // include guard
| 25.121547 | 80 | 0.602815 | Titzi90 |
70723fee6840f89af327d0ac8e57e636ecfaaf00 | 1,160 | cpp | C++ | Hooks.cpp | HeIIoween/revelation-mod-plugin | ea36a2ff0636718b19f900504aab2ea42d1161de | [
"Unlicense"
] | 2 | 2020-07-21T02:40:19.000Z | 2021-06-22T14:36:27.000Z | Hooks.cpp | HeIIoween/revelation-mod-plugin | ea36a2ff0636718b19f900504aab2ea42d1161de | [
"Unlicense"
] | null | null | null | Hooks.cpp | HeIIoween/revelation-mod-plugin | ea36a2ff0636718b19f900504aab2ea42d1161de | [
"Unlicense"
] | 1 | 2021-05-26T08:36:07.000Z | 2021-05-26T08:36:07.000Z | #include "Hooks.h"
#include "Client.h"
#include "Header.h"
using namespace raincious::FLHookPlugin::Revelation;
namespace HkIServerImpl
{
static int timerSkips = 0, timerSkiper = 10;
static uint onlinePlayers = 0;
void __stdcall Timer()
{
PluginReturnCode = DEFAULT_RETURNCODE;
if ((++timerSkips % timerSkiper) == 0)
{
Clients::Clients::Get().renew();
timerSkips = 0;
onlinePlayers = Clients::Clients::Get().size();
if (onlinePlayers > 10)
{
timerSkiper = onlinePlayers;
}
}
}
void __stdcall SystemSwitchOutComplete(uint iShip, uint iClientID)
{
PluginReturnCode = DEFAULT_RETURNCODE;
Clients::Clients::Get().renew(iClientID);
}
void __stdcall BaseEnter_AFTER(uint iBaseID, uint iClientID)
{
PluginReturnCode = DEFAULT_RETURNCODE;
Clients::Clients::Get().renew(iClientID);
}
void __stdcall PlayerLaunch_AFTER(uint iShip, uint iClientID)
{
PluginReturnCode = DEFAULT_RETURNCODE;
Clients::Clients::Get().renew(iClientID);
}
void __stdcall DisConnect_AFTER(uint iClientID, enum EFLConnection p2)
{
PluginReturnCode = DEFAULT_RETURNCODE;
Clients::Clients::Get().remove(iClientID);
}
} | 19.661017 | 71 | 0.718966 | HeIIoween |
70747430f360f89fbd8fadf733d2e5f0cd42712e | 226 | cpp | C++ | 2234/2174556_AC_0MS_32K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 2234/2174556_AC_0MS_32K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 2234/2174556_AC_0MS_32K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #include<iostream.h>
void main()
{
int iPileNum,iResult,iTemp;
while(cin>>iPileNum)
{
cin>>iResult;
while(--iPileNum)
{
cin>>iTemp;
iResult^=iTemp;
}
cout<<(iResult!=0?"Yes":"No")<<endl;
}
} | 14.125 | 39 | 0.561947 | vandreas19 |
70761e15007f253ca7819a806b1a4d77953e7d53 | 7,171 | cpp | C++ | sdk/physx/2.8.3/TrainingPrograms/Programs/Chap5/Lesson503/source/Lesson503.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | 1 | 2018-09-20T10:01:30.000Z | 2018-09-20T10:01:30.000Z | sdk/physx/2.8.3/TrainingPrograms/Programs/Chap5/Lesson503/source/Lesson503.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | null | null | null | sdk/physx/2.8.3/TrainingPrograms/Programs/Chap5/Lesson503/source/Lesson503.cpp | daher-alfawares/xr.desktop | 218a7cff7a9be5865cf786d7cad31da6072f7348 | [
"Apache-2.0"
] | null | null | null | // ===============================================================================
// NVIDIA PHYSX SDK TRAINING PROGRAMS
// LESSON 503: CORE DUMP
//
// Written by Bob Schade, 5-1-06
// ===============================================================================
#include <GL/glut.h>
#include <stdio.h>
#include "NxPhysics.h"
#include "CommonCode.h"
#include "Actors.h"
#include "Lesson503.h"
#include "MediaPath.h"
// Physics SDK globals
extern NxPhysicsSDK* gPhysicsSDK;
extern NxScene* gScene;
extern NxVec3 gDefaultGravity;
// User report globals
extern DebugRenderer gDebugRenderer;
extern UserAllocator* gAllocator;
// HUD globals
extern HUD hud;
// Force globals
extern NxVec3 gForceVec;
extern NxReal gForceStrength;
extern bool bForceMode;
// Simulation globals
extern bool bHardwareScene;
extern bool bPause;
extern bool bShadows;
extern bool bDebugWireframeMode;
// Data file
char*fnameCD="MyCoreDump.xml";
// Actor globals
extern NxActor* gSelectedActor;
bool bCoreDump = false;
bool bLoadCore = false;
bool bInstantiateCore = false;
NXU::NxuPhysicsCollection* gPhysicsCollection = NULL;
// Core dump globals
NxPhysicsSDK* CreatePhysics()
{
NxPhysicsSDK* pSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, gAllocator);
if (!pSDK) return NULL;
// Set the physics parameters
pSDK->setParameter(NX_SKIN_WIDTH, 0.01);
// Set the debug visualization parameters
pSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
pSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
pSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);
pSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS, 1);
return pSDK;
}
NXU::NxuPhysicsCollection* LoadCoreDump(const char * strFileName, NXU::NXU_FileType fileType = NXU::FT_XML)
{
return NXU::loadCollection(strFileName, fileType);
}
bool InstantiateCoreDump(NxPhysicsSDK* pSDK, NXU::NxuPhysicsCollection* c)
{
class MyNotify : public NXU_userNotify
{
};
bool success = false;
MyNotify notify;
success = NXU::instantiateCollection( c, *pSDK, NULL, NULL, ¬ify );
//NXU::releaseCollection(c);
return success;
}
void PrintControls()
{
printf("\n Flight Controls:\n ----------------\n w = forward, s = back\n a = strafe left, d = strafe right\n q = up, z = down\n");
printf("\n Force Controls:\n ---------------\n i = +z, k = -z\n j = +x, l = -x\n u = +y, m = -y\n");
printf("\n Miscellaneous:\n --------------\n p = Pause\n r = Select Next Actor\n f = Toggle Force Mode\n b = Toggle Debug Wireframe Mode\n x = Toggle Shadows\n t = Move Focus Actor to (0,5,0)\n");
printf("\n Special:\n --------\n c = Save Core Dump\n v = Load Core Dump into container\n n = Instantiate Core Dump\n");
}
void RenderActors(bool shadows)
{
// Render all the actors in the scene
NxU32 nbActors = gScene->getNbActors();
NxActor** actors = gScene->getActors();
while (nbActors--)
{
NxActor* actor = *actors++;
DrawActor(actor, gSelectedActor, true);
// Handle shadows
if (shadows)
{
DrawActorShadow(actor, true);
}
}
}
void ProcessInputs()
{
ProcessForceKeys();
// Core dump
if (bCoreDump)
{
bool ok = NXU::coreDump(gPhysicsSDK, fnameCD, NXU::FT_XML, true, false);
if(ok) {
printf("Output core dump successfully!\n");
} else {
printf("Output core dump failed!\n");
}
bCoreDump = false;
}
// Load core to core container
if (bLoadCore)
{
if(gPhysicsCollection) {
NXU::releaseCollection(gPhysicsCollection);
gPhysicsCollection = NULL;
}
gPhysicsCollection = LoadCoreDump(fnameCD);
if(!gPhysicsCollection) {
printf("Unable to load the core dump, please first save a core dump.\n");
}
else
{
printf("Core dump has been loaded into container.\n");
}
bLoadCore = false;
}
// instantiate a core dump
if(bInstantiateCore) {
if(gPhysicsCollection) {
if(gPhysicsSDK) {
ReleasePhysicsSDK(gPhysicsSDK);
gPhysicsSDK = CreatePhysics();
}
if(InstantiateCoreDump(gPhysicsSDK, gPhysicsCollection)) {
if(gPhysicsSDK->getNbScenes()) {
gScene = gPhysicsSDK->getScene(0);
AddUserDataToActors(gScene);
NxActor** actors = gScene->getActors();
gSelectedActor = *actors;
while(!IsSelectable(gSelectedActor))
{
gSelectedActor = *actors++;
}
}
printf("Core dump instantiated\n");
}
else
{
printf("Error in instantiating the core dump\n");
}
}
else
{
printf("Unable to instantiate the core dump with an empty container\n");
}
bInstantiateCore = false;
}
// Show debug wireframes
if (bDebugWireframeMode)
{
if (gScene) gDebugRenderer.renderData(*gScene->getDebugRenderable());
}
}
void RenderCallback()
{
// Clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ProcessCameraKeys();
SetupCamera();
if (gScene && !bPause)
{
GetPhysicsResults();
ProcessInputs();
StartPhysics();
}
// Display scene
RenderActors(bShadows);
if (bForceMode)
DrawForce(gSelectedActor, gForceVec, NxVec3(1,1,0));
else
DrawForce(gSelectedActor, gForceVec, NxVec3(0,1,1));
gForceVec = NxVec3(0,0,0);
// Render HUD
hud.Render();
glFlush();
glutSwapBuffers();
}
void SpecialKeys(unsigned char key, int x, int y)
{
switch (key)
{
case 'c': { printf("Coredumping...\n"); bCoreDump = true; break; }
case 'v': { printf("Loading Core Dump to Container...\n"); bLoadCore = true; break; }
case 'n': { printf("Instantiating Core...\n"); bInstantiateCore = true; break; }
}
}
void InitNx()
{
// Create a memory allocator
gAllocator = new UserAllocator;
// Create the physics SDK
gPhysicsSDK = CreatePhysics();
// Create the scene
NxSceneDesc sceneDesc;
sceneDesc.gravity = gDefaultGravity;
sceneDesc.simType = NX_SIMULATION_HW;
gScene = gPhysicsSDK->createScene(sceneDesc);
if(!gScene){
sceneDesc.simType = NX_SIMULATION_SW;
gScene = gPhysicsSDK->createScene(sceneDesc);
if(!gScene) return;
}
// Create the default material
NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0);
defaultMaterial->setRestitution(0.5);
defaultMaterial->setStaticFriction(0.5);
defaultMaterial->setDynamicFriction(0.5);
// Set Core Dump directory
char buff[512];
FindMediaFile(fnameCD, buff);
#ifdef WIN32
SetCurrentDirectory(buff);
#elif LINUX
chdir(buff);
#endif
// Create the objects in the scene
NxActor* groundPlane = CreateGroundPlane();
NxActor* box = CreateBox(NxVec3(5,0,0), NxVec3(0.5,1,0.5), 20);
NxActor* sphere = CreateSphere(NxVec3(0,0,0), 1, 10);
NxActor* capsule = CreateCapsule(NxVec3(-5,0,0), 2, 0.5, 10);
// pyramid = CreatePyramid(NxVec3(0,0,0), NxVec3(1,0.5,1.5), 10);
AddUserDataToActors(gScene);
gSelectedActor = capsule;
// gSelectedActor = pyramid;
// Initialize HUD
InitializeHUD();
// Get the current time
getElapsedTime();
// Start the first frame of the simulation
if (gScene) StartPhysics();
}
int main(int argc, char** argv)
{
PrintControls();
InitGlut(argc, argv, "Lesson 503: Core Dump");
InitNx();
glutMainLoop();
ReleaseNx();
return 0;
}
| 24.063758 | 197 | 0.660717 | daher-alfawares |
70795ddc256b1ad70a4d31ea0db0e6081df098cb | 20,322 | cpp | C++ | SDKs/CryCode/3.7.0/GameDll/VehicleMovementHelicopterArcade.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | SDKs/CryCode/3.7.0/GameDll/VehicleMovementHelicopterArcade.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | null | null | null | SDKs/CryCode/3.7.0/GameDll/VehicleMovementHelicopterArcade.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2005.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Implements a standard helicopter movements
-------------------------------------------------------------------------
History:
- Created by Stan Fichele
*************************************************************************/
#include "StdAfx.h"
#if 0
#include "Game.h"
#include "GameCVars.h"
#include "IMovementController.h"
#include "IVehicleSystem.h"
#include "VehicleMovementHelicopterArcade.h"
#include "VehicleActionLandingGears.h"
#include "ICryAnimation.h"
#include "GameUtils.h"
#include "Vehicle/VehicleUtils.h"
#include "IRenderAuxGeom.h"
#include "Utility/CryWatch.h"
//------------------------------------------------------------------------
// CVehicleMovementHelicopterArcade
//------------------------------------------------------------------------
CVehicleMovementHelicopterArcade::CVehicleMovementHelicopterArcade()
{
m_pRotorHelper=NULL;
m_damageActual=0.0f;
m_steeringDamage=0.0f;
m_turbulence=0.0f;
m_pLandingGears=NULL;
m_isTouchingGround=false;
m_timeOnTheGround=50.0f;
m_netActionSync.PublishActions( CNetworkMovementHelicopterArcade(this) );
}
//------------------------------------------------------------------------
bool CVehicleMovementHelicopterArcade::Init(IVehicle* pVehicle, const CVehicleParams& table)
{
if (!CVehicleMovementBase::Init(pVehicle, table))
return false;
MOVEMENT_VALUE("engineWarmupDelay", m_engineWarmupDelay);
MOVEMENT_VALUE("altitudeMax", m_altitudeMax);
m_pRotorAnim = NULL;
m_enginePower = 0.0f;
m_isTouchingGround = false;
m_timeOnTheGround = 50.0f;
if (table.haveAttr("rotorPartName"))
m_pRotorPart = m_pVehicle->GetPart(table.getAttr("rotorPartName"));
else
m_pRotorPart = NULL;
ResetActions();
//==============
// Handling
//==============
CVehicleParams handlingParams = table.findChild("HandlingArcade");
if (!handlingParams)
return false;
if (!m_arcade.Init(pVehicle, handlingParams))
return false;
m_maxSpeed = m_arcade.m_handling.maxSpeedForward;
return true;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::PostInit()
{
CVehicleMovementBase::PostInit();
m_pRotorAnim = m_pVehicle->GetAnimation("rotor");
m_pRotorHelper = m_pVehicle->GetHelper("rotorSmokeOut");
for (int i = 0; i < m_pVehicle->GetActionCount(); i++)
{
IVehicleAction* pAction = m_pVehicle->GetAction(i);
m_pLandingGears = CAST_VEHICLEOBJECT(CVehicleActionLandingGears, pAction);
if (m_pLandingGears)
break;
}
// This needs to be called from two places due to the init order on server and client
Reset();
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::Release()
{
CVehicleMovementBase::Release();
delete this;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::Physicalize()
{
CVehicleMovementBase::Physicalize();
pe_simulation_params simParams;
simParams.dampingFreefall = 0.01f;
GetPhysics()->SetParams(&simParams);
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::PostPhysicalize()
{
CVehicleMovementBase::PostPhysicalize();
// This needs to be called from two places due to the init order on server and client
if(!gEnv->pSystem->IsSerializingFile()) //don't do this while loading a savegame, it will overwrite the engine
Reset();
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::Reset()
{
CVehicleMovementBase::Reset();
m_isEnginePowered = false;
m_steeringDamage = 0.0f;
m_damageActual = 0.0f;
m_turbulence = 0.0f;
ResetActions();
m_enginePower = 0.0f;
m_isTouchingGround = false;
m_timeOnTheGround = 50.0f;
m_arcade.Reset(m_pVehicle, m_pEntity);
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::ResetActions()
{
m_inputAction.Reset();
}
//------------------------------------------------------------------------
bool CVehicleMovementHelicopterArcade::StartEngine(EntityId driverId)
{
if (!CVehicleMovementBase::StartEngine(driverId))
{
return false;
}
if (m_pRotorAnim)
m_pRotorAnim->StartAnimation();
return true;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::StopEngine()
{
if(m_enginePower > 0.0f)
{
m_isEngineGoingOff = true;
}
CVehicleMovementBase::StopEngine();
ResetActions();
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::OnEvent(EVehicleMovementEvent event, const SVehicleMovementEventParams& params)
{
CVehicleMovementBase::OnEvent(event, params);
if (event == eVME_DamageSteering)
{
float newSteeringDamage = (((float(cry_rand()) / float(CRY_RAND_MAX)) * 2.5f ) + 0.5f);
m_steeringDamage = max(m_steeringDamage, newSteeringDamage);
}
else if (event == eVME_Repair)
{
m_steeringDamage = min(m_steeringDamage, params.fValue);
if(params.fValue < 0.25)
{
m_damageActual = 0.0f;
m_damage = 0.0f;
}
}
else if (event == eVME_GroundCollision)
{
const float stopOver = 1.0f;
m_isTouchingGround = true;
}
else if (event == eVME_Damage)
{
const float stopOver = 1.0f;
m_damage = params.fValue;
}
else if (event == eVME_WarmUpEngine)
{
m_enginePower = 1.0f;
}
else if (event == eVME_PlayerSwitchView)
{
}
else if (event == eVME_Turbulence)
{
m_turbulence = max(m_turbulence, params.fValue);
}
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::OnAction(const TVehicleActionId actionId, int activationMode, float value)
{
CryAutoCriticalSection netlk(m_networkLock);
CryAutoCriticalSection lk(m_lock);
CVehicleMovementBase::OnAction(actionId, activationMode, value);
m_inputAction.forwardBack = m_movementAction.power;
if (actionId==eVAI_StrafeLeft)
{
m_inputAction.leftRight = -value;
}
else if (actionId==eVAI_StrafeRight)
{
m_inputAction.leftRight = +value;
}
else if (actionId==eVAI_MoveUp)
{
m_inputAction.rawInputUp = min(1.f, sqr(value));
m_inputAction.upDown = m_inputAction.rawInputUp + m_inputAction.rawInputDown;
}
else if (actionId==eVAI_MoveDown)
{
m_inputAction.rawInputDown = max(-1.f, -sqr(value));
m_inputAction.upDown = m_inputAction.rawInputUp + m_inputAction.rawInputDown;
}
else if (actionId==eVAI_RotateYaw)
{
m_inputAction.yaw = value;
}
const float eps = 0.05f;
if(fabs(m_inputAction.upDown) > eps || fabs(m_inputAction.leftRight) > eps)
{
m_pVehicle->NeedsUpdate(IVehicle::eVUF_AwakePhysics);
}
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::ProcessActions(const float deltaTime)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
UpdateDamages(deltaTime);
UpdateEngine(deltaTime);
if (!m_pVehicle->GetStatus().doingNetPrediction)
{
if (m_netActionSync.PublishActions( CNetworkMovementHelicopterArcade(this) ))
m_pVehicle->GetGameObject()->ChangedNetworkState(CNetworkMovementHelicopterArcade::CONTROLLED_ASPECT);
}
}
//===================================================================
// ProcessAI
// This treats the helicopter as able to move in any horizontal direction
// by tilting in any direction. Yaw control is thus secondary. Throttle
// control is also secondary since it is adjusted to maintain or change
// the height, and the amount needed depends on the tilt.
//===================================================================
//////////////////////////////////////////////////////////////////////////
// NOTE: This function must be thread-safe. Before adding stuff contact MarcoC.
void CVehicleMovementHelicopterArcade::ProcessAI(const float deltaTime)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
// it's useless to progress further if the engine has yet to be turned on
if (!m_isEnginePowered)
return;
//========================
// TODO !
//========================
}
//////////////////////////////////////////////////////////////////////////
// NOTE: This function must be thread-safe. Before adding stuff contact MarcoC.
void CVehicleMovementHelicopterArcade::ProcessMovement(const float dt)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
IPhysicalEntity* pPhysics = GetPhysics();
if (!pPhysics)
return;
CryAutoCriticalSection lk(m_lock);
m_netActionSync.UpdateObject(this);
if (!m_isEnginePowered)
return;
CVehicleMovementBase::ProcessMovement(dt);
const bool haveDriver=(m_actorId!=0);
/////////////////////////////////////////////////////////////
// Pass on the movement request to the active physics handler
// NB: m_physStatus is update by this call
SVehiclePhysicsHelicopterProcessParams params;
params.pPhysics = pPhysics;
params.pPhysStatus = &m_physStatus[k_physicsThread];
params.pInputAction = &m_inputAction;
params.dt = dt;
params.haveDriver = haveDriver;
params.isAI = m_movementAction.isAI;
params.aiRequiredVel = Vec3(0.f);
m_arcade.ProcessMovement(params);
//===============================================
// Commit the velocity back to the physics engine
//===============================================
// if (fabsf(m_movementAction.rotateYaw)>0.05f || vel.GetLengthSquared()>0.001f || m_chassis.vel.GetLengthSquared()>0.001f || angVel.GetLengthSquared()>0.001f || angVel.GetLengthSquared()>0.001f)
{
pe_action_set_velocity setVelocity;
setVelocity.v = m_physStatus[k_physicsThread].v;
setVelocity.w = m_physStatus[k_physicsThread].w;
pPhysics->Action(&setVelocity, 1);
}
/////////////////////////////////////////////////////////////
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::UpdateDamages(float deltaTime)
{
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::UpdateEngine(float deltaTime)
{
// will update the engine power up to the maximum according to the ignition time
if (m_isEnginePowered && !m_isEngineGoingOff)
{
if (m_enginePower < 1.f)
{
m_enginePower += deltaTime * (1.f / m_engineWarmupDelay);
m_enginePower = min(m_enginePower, 1.f);
}
}
else
{
if (m_enginePower >= 0.0f)
{
m_enginePower -= deltaTime * (1.f / m_engineWarmupDelay);
if (m_damageActual > 0.0f)
m_enginePower *= 1.0f - min(1.0f, m_damageActual);
}
}
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::Update(const float deltaTime)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
CVehicleMovementBase::Update(deltaTime);
CryAutoCriticalSection lk(m_lock);
if (m_isTouchingGround)
{
m_timeOnTheGround += deltaTime;
m_isTouchingGround = false;
}
else
{
m_timeOnTheGround = 0.0f;
}
// update animation
if(m_isEngineGoingOff)
{
if(m_enginePower > 0.0f)
{
UpdateEngine(deltaTime);
}
else
{
if(m_pRotorAnim)
{
m_pRotorAnim->StopAnimation();
}
m_isEngineGoingOff = false;
}
}
if(m_pRotorAnim)
{
m_pRotorAnim->SetSpeed(m_enginePower);
}
IActor* pActor = m_pActorSystem->GetActor(m_actorId);
#if ENABLE_VEHICLE_DEBUG
int profile = g_pGameCVars->v_profileMovement;
if ((profile == 1 && pActor && pActor->IsClient()) || profile == 2)
{
IRenderer* pRenderer = gEnv->pRenderer;
float color[4] = {1,1,1,1};
Ang3 localAngles = m_pEntity->GetWorldAngles();
const Vec3& velocity = m_physStatus[k_mainThread].v;
const Vec3& angVelocity = m_physStatus[k_mainThread].w;
SVehiclePhysicsStatus* physStatus = &m_physStatus[k_mainThread];
const Vec3 xAxis = physStatus->q.GetColumn0();
const Vec3 yAxis = physStatus->q.GetColumn1();
const Vec3 zAxis = physStatus->q.GetColumn2();
const Vec3 pos = physStatus->centerOfMass;
float x=30.f, y=30.f, dy=30.f;
pRenderer->Draw2dLabel(x, y, 2.0f, color, false, "Helicopter movement"); y+=dy;
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Action: forwardBack: %.2f", m_inputAction.forwardBack);
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Action: upDown: %.2f", m_inputAction.upDown);
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Action: yaw: %.2f", m_inputAction.yaw);
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Action: leftRight: %.2f", m_inputAction.leftRight);
// Forward, and left-right vectors in the xy plane
const Vec3 up(0.f, 0.f, 1.f);
Vec3 forward(yAxis.x, yAxis.y, 0.f);
forward.normalize();
Vec3 right(forward.y, -forward.x, 0.f);
Vec3 f = forward;
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Forward: %.2f, %.2f, %.2f ", f.x, f.y, f.z);
f = right;
pRenderer->Draw2dLabel(x, y+=dy, 2.0f, color, false, "Right: %.2f, %.2f, %.2f ", f.x, f.y, f.z);
// Aux Renderer
IRenderAuxGeom* pAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom();
SAuxGeomRenderFlags flags = pAuxGeom->GetRenderFlags();
SAuxGeomRenderFlags oldFlags = pAuxGeom->GetRenderFlags();
flags.SetDepthWriteFlag(e_DepthWriteOff);
flags.SetDepthTestFlag(e_DepthTestOff);
pAuxGeom->SetRenderFlags(flags);
ColorB colRed(255,0,0,255);
ColorB colGreen(0,255,0,255);
ColorB colBlue(0,0,255,255);
ColorB col1(255,255,0,255);
pAuxGeom->DrawSphere(pos, 0.1f, colGreen);
pAuxGeom->DrawLine(pos, colGreen, pos + forward, colGreen);
pAuxGeom->DrawLine(pos, colGreen, pos + right, colBlue);
}
#endif
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::OnEngineCompletelyStopped()
{
CVehicleMovementBase::OnEngineCompletelyStopped();
RemoveSurfaceEffects();
}
//------------------------------------------------------------------------
float CVehicleMovementHelicopterArcade::GetEnginePedal()
{
return fabsf(m_inputAction.forwardBack);
}
//------------------------------------------------------------------------
float CVehicleMovementHelicopterArcade::GetEnginePower()
{
float enginePower = (m_enginePower) * (1.0f - min(1.0f, m_damageActual));
return enginePower;
}
//------------------------------------------------------------------------
SVehicleMovementAction CVehicleMovementHelicopterArcade::GetMovementActions()
{
// This is used for vehicle client prediction, the mapping of SHelicopterAction variables to SVehicleMovementAction isn't important
// but it must be consistent with the RequestActions function
SVehicleMovementAction actions;
actions.power = m_inputAction.upDown;
actions.rotatePitch = m_inputAction.forwardBack;
actions.rotateRoll = m_inputAction.leftRight;
actions.rotateYaw = m_inputAction.yaw;
return actions;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::RequestActions(const SVehicleMovementAction& movementAction)
{
m_inputAction.upDown = movementAction.power;
m_inputAction.forwardBack = movementAction.rotatePitch;
m_inputAction.leftRight = movementAction.rotateRoll;
m_inputAction.yaw = movementAction.rotateYaw;
}
//------------------------------------------------------------------------
bool CVehicleMovementHelicopterArcade::RequestMovement(CMovementRequest& movementRequest)
{
FUNCTION_PROFILER( gEnv->pSystem, PROFILE_GAME );
m_movementAction.isAI = true;
if (!m_isEnginePowered)
return false;
CryAutoCriticalSection lk(m_lock);
if (movementRequest.HasLookTarget())
m_aiRequest.SetLookTarget(movementRequest.GetLookTarget());
else
m_aiRequest.ClearLookTarget();
if (movementRequest.HasMoveTarget())
{
Vec3 entityPos = m_pEntity->GetWorldPos();
Vec3 start(entityPos);
Vec3 end( movementRequest.GetMoveTarget() );
Vec3 pos = ( end - start ) * 100.0f;
pos +=start;
m_aiRequest.SetMoveTarget( pos );
}
else
m_aiRequest.ClearMoveTarget();
if (movementRequest.HasDesiredSpeed())
m_aiRequest.SetDesiredSpeed(movementRequest.GetDesiredSpeed());
else
m_aiRequest.ClearDesiredSpeed();
if (movementRequest.HasForcedNavigation())
{
Vec3 entityPos = m_pEntity->GetWorldPos();
m_aiRequest.SetForcedNavigation(movementRequest.GetForcedNavigation());
m_aiRequest.SetDesiredSpeed(movementRequest.GetForcedNavigation().GetLength());
m_aiRequest.SetMoveTarget(entityPos+movementRequest.GetForcedNavigation().GetNormalizedSafe()*100.0f);
}
else
m_aiRequest.ClearForcedNavigation();
return true;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::Serialize(TSerialize ser, EEntityAspects aspects)
{
CVehicleMovementBase::Serialize(ser, aspects);
if ((ser.GetSerializationTarget() == eST_Network) &&(aspects & CNetworkMovementHelicopterArcade::CONTROLLED_ASPECT))
{
m_netActionSync.Serialize(ser, aspects);
if (ser.IsReading())
{
IPhysicalEntity *pPhysics = GetPhysics();
if (pPhysics)
{
pe_action_awake awake;
pPhysics->Action(&awake);
}
}
}
else if (ser.GetSerializationTarget() != eST_Network)
{
ser.Value("enginePower", m_enginePower);
ser.Value("timeOnTheGround", m_timeOnTheGround);
ser.Value("turbulence", m_turbulence);
ser.Value("steeringDamage",m_steeringDamage);
ser.Value("upDown", m_inputAction.upDown);
ser.Value("forwardBack", m_inputAction.forwardBack);
ser.Value("leftRight", m_inputAction.leftRight);
ser.Value("yaw", m_inputAction.yaw);
ser.Value("timer", m_arcade.m_chassis.timer);
if (ser.IsReading())
m_isTouchingGround = m_timeOnTheGround > 0.0f;
}
};
//------------------------------------------------------------------------
SVehicleNetState CVehicleMovementHelicopterArcade::GetVehicleNetState()
{
SVehicleNetState state;
COMPILE_TIME_ASSERT(sizeof(m_pArcade->m_chassis) <= sizeof(SVehicleNetState));
memcpy(&state, &m_pArcade->m_chassis, sizeof(m_pArcade->m_chassis));
return state;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::SetVehicleNetState(const SVehicleNetState& state)
{
memcpy(&m_pArcade->m_chassis, &state, sizeof(m_pArcade->m_chassis));
}
//------------------------------------------------------------------------
float CVehicleMovementHelicopterArcade::GetDamageMult()
{
float damageMult = (1.0f - min(1.0f, m_damage)) * 0.75f;
damageMult += 0.25f;
return damageMult;
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::GetMemoryUsage( ICrySizer * pSizer ) const
{
pSizer->AddObject(this, sizeof(*this));
GetMemoryUsageInternal(pSizer);
}
//------------------------------------------------------------------------
void CVehicleMovementHelicopterArcade::GetMemoryUsageInternal( ICrySizer * pSizer ) const
{
CVehicleMovementBase::GetMemoryUsageInternal(pSizer);
}
//------------------------------------------------------------------------
// CNetworkMovementHelicopterArcade
//------------------------------------------------------------------------
CNetworkMovementHelicopterArcade::CNetworkMovementHelicopterArcade()
{
action.Reset();
}
//------------------------------------------------------------------------
CNetworkMovementHelicopterArcade::CNetworkMovementHelicopterArcade(CVehicleMovementHelicopterArcade *pMovement)
{
action = pMovement->m_inputAction;
}
//------------------------------------------------------------------------
void CNetworkMovementHelicopterArcade::UpdateObject(CVehicleMovementHelicopterArcade *pMovement)
{
pMovement->m_inputAction = action;
}
//------------------------------------------------------------------------
void CNetworkMovementHelicopterArcade::Serialize(TSerialize ser, EEntityAspects aspects)
{
if (ser.GetSerializationTarget()==eST_Network && aspects&CONTROLLED_ASPECT)
{
NET_PROFILE_SCOPE("NetMovementHelicopterArcade", ser.IsReading());
ser.Value("upDown", action.upDown, 'vPow');
ser.Value("forwardBack", action.forwardBack, 'vPow');
ser.Value("leftRight", action.leftRight, 'vPow');
ser.Value("yaw", action.yaw, 'vPow');
}
}
#endif //0
| 29.754026 | 197 | 0.626612 | amrhead |
707ac1dd48fa3bf4260d432939b8e2550652f375 | 1,044 | cpp | C++ | clibalgserver/code/exe/loop.cpp | bajdcc/clibalgserver | 0a464b1657c70244d18345ab8b2a4f222b32c18a | [
"MIT"
] | 12 | 2019-09-25T09:28:40.000Z | 2022-01-24T05:24:35.000Z | clibalgserver/code/exe/loop.cpp | bajdcc/clibalgserver | 0a464b1657c70244d18345ab8b2a4f222b32c18a | [
"MIT"
] | 3 | 2020-02-22T04:00:36.000Z | 2020-03-19T07:42:03.000Z | clibalgserver/code/exe/loop.cpp | bajdcc/clibalgserver | 0a464b1657c70244d18345ab8b2a4f222b32c18a | [
"MIT"
] | 2 | 2020-03-06T07:59:28.000Z | 2020-08-17T07:34:48.000Z | #include "/include/shell"
#include "/include/memory"
#include "/include/proc"
struct string {
char* text;
int capacity;
int length;
};
string new_string() {
string s;
s.text = malloc(16);
s.capacity = 16;
s.length = 0;
return s;
}
void append_char(string* s, char c) {
if (s->length >= s->capacity - 1) {
s->capacity <<= 1;
char* new_text = malloc(s->capacity);
strcpy(new_text, s->text);
free(s->text);
s->text = new_text;
}
(s->text)[s->length++] = c;
(s->text)[s->length] = 0;
}
int main(int argc, char **argv) {
if (argc <= 1) {
set_fg(240, 0, 0);
put_string("[Error] Missing argument.");
restore_fg();
return;
}
int i;
string s = new_string();
for (i = 1; i < argc; ++i) {
char* c = argv[i];
while (*c)
append_char(&s, *c++);
if (i < argc - 1)
append_char(&s, ' ');
}
for (;;) {
shell(s.text);
sleep(500);
}
return 0;
} | 21.75 | 48 | 0.482759 | bajdcc |
707e0f71cb3d54acd88a63a8f5f94428bc24fda9 | 2,868 | cc | C++ | src/Vehicle/ADSBVehicle.cc | harisankerPradeep/qgroundcontrol | 449ee8ffd3b165a220cb6ebfd8b94cc9b2daf49f | [
"Apache-2.0"
] | 12 | 2020-04-19T17:36:34.000Z | 2022-02-02T01:42:06.000Z | src/Vehicle/ADSBVehicle.cc | Myweik/MMC_qgroundcontrol | 3aa97928d30fc9de56fde2a0d37a49245de83da4 | [
"Apache-2.0"
] | 30 | 2019-07-10T02:21:58.000Z | 2019-08-15T02:17:42.000Z | src/Vehicle/ADSBVehicle.cc | Myweik/MMC_qgroundcontrol | 3aa97928d30fc9de56fde2a0d37a49245de83da4 | [
"Apache-2.0"
] | 39 | 2020-04-18T00:45:45.000Z | 2022-03-21T10:41:46.000Z | /****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "ADSBVehicle.h"
#include <QDebug>
#include <QtMath>
ADSBVehicle::ADSBVehicle(mavlink_adsb_vehicle_t& adsbVehicle, QObject* parent)
: QObject (parent)
, _icaoAddress (adsbVehicle.ICAO_address)
, _callsign (adsbVehicle.callsign)
, _altitude (NAN)
, _heading (NAN)
, _alert (false)
{
if (!(adsbVehicle.flags & ADSB_FLAGS_VALID_COORDS)) {
qWarning() << "At least coords must be valid";
return;
}
update(adsbVehicle);
}
ADSBVehicle::ADSBVehicle(const QGeoCoordinate& location, float heading, bool alert, QObject* parent)
: QObject(parent)
, _icaoAddress(0)
, _alert(alert)
{
update(alert, location, heading);
}
void ADSBVehicle::update(bool alert, const QGeoCoordinate& location, float heading)
{
_coordinate = location;
_altitude = location.altitude();
_heading = heading;
_alert = alert;
emit coordinateChanged();
emit altitudeChanged();
emit headingChanged();
emit alertChanged();
_lastUpdateTimer.restart();
}
void ADSBVehicle::update(mavlink_adsb_vehicle_t& adsbVehicle)
{
if (_icaoAddress != adsbVehicle.ICAO_address) {
qWarning() << "ICAO address mismatch expected:actual" << _icaoAddress << adsbVehicle.ICAO_address;
return;
}
if (!(adsbVehicle.flags & ADSB_FLAGS_VALID_COORDS)) {
return;
}
QString currCallsign(adsbVehicle.callsign);
if (currCallsign != _callsign) {
_callsign = currCallsign;
emit callsignChanged();
}
QGeoCoordinate newCoordinate(adsbVehicle.lat / 1e7, adsbVehicle.lon / 1e7);
if (newCoordinate != _coordinate) {
_coordinate = newCoordinate;
emit coordinateChanged();
}
double newAltitude = NAN;
if (adsbVehicle.flags & ADSB_FLAGS_VALID_ALTITUDE) {
newAltitude = (double)adsbVehicle.altitude / 1e3;
}
if (!(qIsNaN(newAltitude) && qIsNaN(_altitude)) && !qFuzzyCompare(newAltitude, _altitude)) {
_altitude = newAltitude;
emit altitudeChanged();
}
double newHeading = NAN;
if (adsbVehicle.flags & ADSB_FLAGS_VALID_HEADING) {
newHeading = (double)adsbVehicle.heading / 100.0;
}
if (!(qIsNaN(newHeading) && qIsNaN(_heading)) && !qFuzzyCompare(newHeading, _heading)) {
_heading = newHeading;
emit headingChanged();
}
_lastUpdateTimer.restart();
}
bool ADSBVehicle::expired()
{
return _lastUpdateTimer.hasExpired(expirationTimeoutMs);
}
| 28.969697 | 106 | 0.62901 | harisankerPradeep |
707f3d573d0a784dc8a64370d6e56696c1e310a8 | 36,299 | cpp | C++ | Source/hydro/riemann_solvers.cpp | nmford20/Castro | ad98e9f756dc4f8832da14b70ff17234dae4dad3 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/hydro/riemann_solvers.cpp | nmford20/Castro | ad98e9f756dc4f8832da14b70ff17234dae4dad3 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/hydro/riemann_solvers.cpp | nmford20/Castro | ad98e9f756dc4f8832da14b70ff17234dae4dad3 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include <Castro.H>
#include <Castro_F.H>
#include <Castro_util.H>
#ifdef RADIATION
#include <Radiation.H>
#endif
#include <cmath>
#include <eos.H>
#include <riemann.H>
using namespace amrex;
void
Castro::riemanncg(const Box& bx,
Array4<Real> const& ql,
Array4<Real> const& qr,
Array4<Real const> const& qaux_arr,
Array4<Real> const& qint,
const int idir) {
// this implements the approximate Riemann solver of Colella & Glaz
// (1985)
//
constexpr Real weakwv = 1.e-3_rt;
#ifndef AMREX_USE_GPU
if (cg_maxiter > HISTORY_SIZE) {
amrex::Error("error in riemanncg: cg_maxiter > HISTORY_SIZE");
}
#endif
#ifndef AMREX_USE_GPU
if (cg_blend == 2 && cg_maxiter < 5) {
amrex::Error("Error: need cg_maxiter >= 5 to do a bisection search on secant iteration failure.");
}
#endif
const auto domlo = geom.Domain().loVect3d();
const auto domhi = geom.Domain().hiVect3d();
int iu, iv1, iv2;
int sx, sy, sz;
if (idir == 0) {
iu = QU;
iv1 = QV;
iv2 = QW;
sx = 1;
sy = 0;
sz = 0;
} else if (idir == 1) {
iu = QV;
iv1 = QU;
iv2 = QW;
sx = 0;
sy = 1;
sz = 0;
} else {
iu = QW;
iv1 = QU;
iv2 = QV;
sx = 0;
sy = 0;
sz = 1;
}
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
// do we want to force the flux to zero at the boundary?
const bool special_bnd_lo = (lo_bc[idir] == Symmetry ||
lo_bc[idir] == SlipWall ||
lo_bc[idir] == NoSlipWall);
const bool special_bnd_hi = (hi_bc[idir] == Symmetry ||
hi_bc[idir] == SlipWall ||
hi_bc[idir] == NoSlipWall);
const Real lsmall_dens = small_dens;
const Real lsmall_pres = small_pres;
const Real lsmall_temp = small_temp;
const Real lsmall = riemann_constants::small;
amrex::ParallelFor(bx,
[=] AMREX_GPU_HOST_DEVICE (int i, int j, int k)
{
#ifndef AMREX_USE_GPU
GpuArray<Real, HISTORY_SIZE> pstar_hist;
#endif
// deal with hard walls
Real bnd_fac = 1.0_rt;
if (idir == 0) {
if ((i == domlo[0] && special_bnd_lo) ||
(i == domhi[0]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else if (idir == 1) {
if ((j == domlo[1] && special_bnd_lo) ||
(j == domhi[1]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else {
if ((k == domlo[2] && special_bnd_lo) ||
(k == domhi[2]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
}
// left state
Real rl = amrex::max(ql(i,j,k,QRHO), lsmall_dens);
Real pl = ql(i,j,k,QPRES);
Real rel = ql(i,j,k,QREINT);
Real gcl = qaux_arr(i-sx,j-sy,k-sz,QGAMC);
#ifdef TRUE_SDC
if (use_reconstructed_gamma1 == 1) {
gcl = ql(i,j,k,QGC);
}
#endif
// pick left velocities based on direction
Real ul = ql(i,j,k,iu);
Real v1l = ql(i,j,k,iv1);
Real v2l = ql(i,j,k,iv2);
// sometime we come in here with negative energy or pressure
// note: reset both in either case, to remain thermo
// consistent
if (rel <= 0.0_rt || pl < lsmall_pres) {
#ifndef AMREX_USE_GPU
std::cout << "WARNING: (rho e)_l < 0 or pl < small_pres in Riemann: " << rel << " " << pl << " " << lsmall_pres << std::endl;
#endif
eos_t eos_state;
eos_state.T = lsmall_temp;
eos_state.rho = rl;
for (int n = 0; n < NumSpec; n++) {
eos_state.xn[n] = ql(i,j,k,QFS+n);
}
#if NAUX_NET > 0
for (int n = 0; n < NumAux; n++) {
eos_state.aux[n] = ql(i,j,k,QFX+n);
}
#endif
eos(eos_input_rt, eos_state);
rel = rl*eos_state.e;
pl = eos_state.p;
gcl = eos_state.gam1;
}
// right state
Real rr = amrex::max(qr(i,j,k,QRHO), lsmall_dens);
Real pr = qr(i,j,k,QPRES);
Real rer = qr(i,j,k,QREINT);
Real gcr = qaux_arr(i,j,k,QGAMC);
#ifdef TRUE_SDC
if (use_reconstructed_gamma1 == 1) {
gcr = qr(i,j,k,QGC);
}
#endif
// pick right velocities based on direction
Real ur = qr(i,j,k,iu);
Real v1r = qr(i,j,k,iv1);
Real v2r = qr(i,j,k,iv2);
if (rer <= 0.0_rt || pr < lsmall_pres) {
#ifndef AMREX_USE_GPU
std::cout << "WARNING: (rho e)_r < 0 or pr < small_pres in Riemann: " << rer << " " << pr << " " << lsmall_pres << std::endl;
#endif
eos_t eos_state;
eos_state.T = lsmall_temp;
eos_state.rho = rr;
for (int n = 0; n < NumSpec; n++) {
eos_state.xn[n] = qr(i,j,k,QFS+n);
}
#if NAUX_NET > 0
for (int n = 0; n < NumAux; n++) {
eos_state.aux[n] = qr(i,j,k,QFX+n);
}
#endif
eos(eos_input_rt, eos_state);
rer = rr*eos_state.e;
pr = eos_state.p;
gcr = eos_state.gam1;
}
// common quantities
Real taul = 1.0_rt/rl;
Real taur = 1.0_rt/rr;
// lagrangian sound speeds
Real clsql = gcl*pl*rl;
Real clsqr = gcr*pr*rr;
Real csmall = amrex::max(lsmall, amrex::max(lsmall * qaux_arr(i,j,k,QC),
lsmall * qaux_arr(i-sx,j-sy,k-sz,QC)));
Real cavg = 0.5_rt*(qaux_arr(i,j,k,QC) + qaux_arr(i-sx,j-sy,k-sz,QC));
// Note: in the original Colella & Glaz paper, they predicted
// gamma_e to the interfaces using a special (non-hyperbolic)
// evolution equation. In Castro, we instead bring (rho e)
// to the edges, so we construct the necessary gamma_e here from
// what we have on the interfaces.
Real gamel = pl/rel + 1.0_rt;
Real gamer = pr/rer + 1.0_rt;
// these should consider a wider average of the cell-centered
// gammas
Real gmin = amrex::min(amrex::min(gamel, gamer), 1.0_rt);
Real gmax = amrex::max(amrex::max(gamel, gamer), 2.0_rt);
Real game_bar = 0.5_rt*(gamel + gamer);
Real gamc_bar = 0.5_rt*(gcl + gcr);
Real gdot = 2.0_rt*(1.0_rt - game_bar/gamc_bar)*(game_bar - 1.0_rt);
Real wsmall = lsmall_dens*csmall;
Real wl = amrex::max(wsmall, std::sqrt(std::abs(clsql)));
Real wr = amrex::max(wsmall, std::sqrt(std::abs(clsqr)));
// make an initial guess for pstar -- this is a two-shock
// approximation
//pstar = ((wr*pl + wl*pr) + wl*wr*(ul - ur))/(wl + wr)
Real pstar = pl + ( (pr - pl) - wr*(ur - ul) )*wl/(wl+wr);
pstar = amrex::max(pstar, lsmall_pres);
// get the shock speeds -- this computes W_s from CG Eq. 34
Real gamstar = 0.0;
Real wlsq = 0.0;
wsqge(pl, taul, gamel, gdot, gamstar,
gmin, gmax, clsql, pstar, wlsq);
Real wrsq = 0.0;
wsqge(pr, taur, gamer, gdot, gamstar,
gmin, gmax, clsqr, pstar, wrsq);
Real pstar_old = pstar;
wl = std::sqrt(wlsq);
wr = std::sqrt(wrsq);
// R-H jump conditions give ustar across each wave -- these
// should be equal when we are done iterating. Our notation
// here is a little funny, comparing to CG, ustar_l = u*_L and
// ustar_r = u*_R.
Real ustar_l = ul - (pstar-pl)/wl;
Real ustar_r = ur + (pstar-pr)/wr;
// revise our pstar guess
// pstar = ((wr*pl + wl*pr) + wl*wr*(ul - ur))/(wl + wr)
pstar = pl + ( (pr - pl) - wr*(ur - ul) )*wl/(wl+wr);
pstar = amrex::max(pstar, lsmall_pres);
// secant iteration
bool converged = false;
int iter = 0;
while ((iter < cg_maxiter && !converged) || iter < 2) {
wsqge(pl, taul, gamel, gdot, gamstar,
gmin, gmax, clsql, pstar, wlsq);
wsqge(pr, taur, gamer, gdot, gamstar,
gmin, gmax, clsqr, pstar, wrsq);
// NOTE: these are really the inverses of the wave speeds!
wl = 1.0_rt / std::sqrt(wlsq);
wr = 1.0_rt / std::sqrt(wrsq);
Real ustar_r_old = ustar_r;
Real ustar_l_old = ustar_l;
ustar_r = ur - (pr-pstar)*wr;
ustar_l = ul + (pl-pstar)*wl;
Real dpditer = std::abs(pstar_old-pstar);
// Here we are going to do the Secant iteration version in
// CG. Note that what we call zp and zm here are not
// actually the Z_p = |dp*/du*_p| defined in CG, by rather
// simply |du*_p| (or something that looks like dp/Z!).
Real zp = std::abs(ustar_l - ustar_l_old);
if (zp - weakwv*cavg <= 0.0_rt) {
zp = dpditer*wl;
}
Real zm = std::abs(ustar_r - ustar_r_old);
if (zm - weakwv*cavg <= 0.0_rt) {
zm = dpditer*wr;
}
// the new pstar is found via CG Eq. 18
Real denom = dpditer/amrex::max(zp+zm, lsmall*cavg);
pstar_old = pstar;
pstar = pstar - denom*(ustar_r - ustar_l);
pstar = amrex::max(pstar, lsmall_pres);
Real err = std::abs(pstar - pstar_old);
if (err < cg_tol*pstar) {
converged = true;
}
#ifndef AMREX_USE_GPU
pstar_hist[iter] = pstar;
#endif
iter++;
}
// If we failed to converge using the secant iteration, we
// can either stop here; or, revert to the original
// two-shock estimate for pstar; or do a bisection root
// find using the bounds established by the most recent
// iterations.
if (!converged) {
if (cg_blend == 0) {
#ifndef AMREX_USE_GPU
std::cout << "pstar history: " << std::endl;
for (int iter_l=0; iter_l < cg_maxiter; iter_l++) {
std::cout << iter_l << " " << pstar_hist[iter_l] << std::endl;
}
std::cout << std::endl;
std::cout << "left state (r,u,p,re,gc): " << rl << " " << ul << " " << pl << " " << rel << " " << gcl << std::endl;
std::cout << "right state (r,u,p,re,gc): " << rr << " " << ur << " " << pr << " " << rer << " " << gcr << std::endl;
std::cout << "cavg, smallc: " << cavg << " " << csmall;
amrex::Error("ERROR: non-convergence in the Riemann solver");
#endif
} else if (cg_blend == 1) {
pstar = pl + ( (pr - pl) - wr*(ur - ul) )*wl/(wl+wr);
} else if (cg_blend == 2) {
// we don't store the history if we are in CUDA, so
// we can't do this
#ifndef AMREX_USE_GPU
// first try to find a reasonable bounds
Real pstarl = 1.e200;
Real pstaru = -1.e200;
for (int n = cg_maxiter-6; n < cg_maxiter; n++) {
pstarl = amrex::min(pstarl, pstar_hist[n]);
pstaru = amrex::max(pstaru, pstar_hist[n]);
}
pstarl = amrex::max(pstarl, lsmall_pres);
pstaru = amrex::max(pstaru, lsmall_pres);
GpuArray<Real, PSTAR_BISECT_FACTOR*HISTORY_SIZE> pstar_hist_extra;
pstar_bisection(pstarl, pstaru,
ul, pl, taul, gamel, clsql,
ur, pr, taur, gamer, clsqr,
gdot, gmin, gmax,
cg_maxiter, cg_tol,
pstar, gamstar, converged, pstar_hist_extra);
if (!converged) {
std::cout << "pstar history: " << std::endl;
for (int iter_l = 0; iter_l < cg_maxiter; iter_l++) {
std::cout << iter_l << " " << pstar_hist[iter_l] << std::endl;
}
std::cout << "pstar extra history: " << std::endl;
for (int iter_l = 0; iter_l < PSTAR_BISECT_FACTOR*cg_maxiter; iter_l++) {
std::cout << iter_l << " " << pstar_hist_extra[iter_l] << std::endl;
}
std::cout << std::endl;
std::cout << "left state (r,u,p,re,gc): " << rl << " " << ul << " " << pl << " " << rel << " " << gcl << std::endl;
std::cout << "right state (r,u,p,re,gc): " << rr << " " << ur << " " << pr << " " << rer << " " << gcr << std::endl;
std::cout << "cavg, smallc: " << cavg << " " << csmall << std::endl;
amrex::Error("ERROR: non-convergence in the Riemann solver");
}
#endif
} else {
#ifndef AMREX_USE_GPU
amrex::Error("ERROR: unrecognized cg_blend option.");
#endif
}
}
// we converged! construct the single ustar for the region
// between the left and right waves, using the updated wave speeds
ustar_r = ur - (pr-pstar)*wr; // careful -- here wl, wr are 1/W
ustar_l = ul + (pl-pstar)*wl;
Real ustar = 0.5_rt * (ustar_l + ustar_r);
// for symmetry preservation, if ustar is really small, then we
// set it to zero
if (std::abs(ustar) < riemann_constants::smallu*0.5_rt*(std::abs(ul) + std::abs(ur))) {
ustar = 0.0_rt;
}
// sample the solution -- here we look first at the direction
// that the contact is moving. This tells us if we need to
// worry about the L/L* states or the R*/R states.
Real ro;
Real uo;
Real po;
Real tauo;
Real gamco;
Real gameo;
if (ustar > 0.0_rt) {
ro = rl;
uo = ul;
po = pl;
tauo = taul;
gamco = gcl;
gameo = gamel;
} else if (ustar < 0.0_rt) {
ro = rr;
uo = ur;
po = pr;
tauo = taur;
gamco = gcr;
gameo = gamer;
} else {
ro = 0.5_rt*(rl+rr);
uo = 0.5_rt*(ul+ur);
po = 0.5_rt*(pl+pr);
tauo = 0.5_rt*(taul+taur);
gamco = 0.5_rt*(gcl+gcr);
gameo = 0.5_rt*(gamel + gamer);
}
// use tau = 1/rho as the independent variable here
ro = amrex::max(lsmall_dens, 1.0_rt/tauo);
tauo = 1.0_rt/ro;
Real co = std::sqrt(std::abs(gamco*po*tauo));
co = amrex::max(csmall, co);
Real clsq = std::pow(co*ro, 2);
// now that we know which state (left or right) we need to worry
// about, get the value of gamstar and wosq across the wave we
// are dealing with.
Real wosq = 0.0;
wsqge(po, tauo, gameo, gdot, gamstar,
gmin, gmax, clsq, pstar, wosq);
Real sgnm = std::copysign(1.0_rt, ustar);
Real wo = std::sqrt(wosq);
Real dpjmp = pstar - po;
// is this max really necessary?
//rstar=max(ONE-ro*dpjmp/wosq, (gameo-ONE)/(gameo+ONE))
Real rstar = 1.0_rt - ro*dpjmp/wosq;
rstar = ro/rstar;
rstar = amrex::max(lsmall_dens, rstar);
Real cstar = std::sqrt(std::abs(gamco*pstar/rstar));
cstar = amrex::max(cstar, csmall);
Real spout = co - sgnm*uo;
Real spin = cstar - sgnm*ustar;
//ushock = 0.5_rt*(spin + spout)
Real ushock = wo*tauo - sgnm*uo;
if (pstar-po >= 0.0_rt) {
spin = ushock;
spout = ushock;
}
Real frac = 0.5_rt*(1.0_rt + (spin + spout)/amrex::max(amrex::max(spout-spin, spin+spout), lsmall*cavg));
// the transverse velocity states only depend on the
// direction that the contact moves
if (ustar > 0.0_rt) {
qint(i,j,k,iv1) = v1l;
qint(i,j,k,iv2) = v2l;
} else if (ustar < 0.0_rt) {
qint(i,j,k,iv1) = v1r;
qint(i,j,k,iv2) = v2r;
} else {
qint(i,j,k,iv1) = 0.5_rt*(v1l+v1r);
qint(i,j,k,iv2) = 0.5_rt*(v2l+v2r);
}
// linearly interpolate between the star and normal state -- this covers the
// case where we are inside the rarefaction fan.
qint(i,j,k,QRHO) = frac*rstar + (1.0_rt - frac)*ro;
qint(i,j,k,iu) = frac*ustar + (1.0_rt - frac)*uo;
qint(i,j,k,QPRES) = frac*pstar + (1.0_rt - frac)*po;
Real game_int = frac*gamstar + (1.0_rt-frac)*gameo;
// now handle the cases where instead we are fully in the
// star or fully in the original (l/r) state
if (spout < 0.0_rt) {
qint(i,j,k,QRHO) = ro;
qint(i,j,k,iu) = uo;
qint(i,j,k,QPRES) = po;
game_int = gameo;
}
if (spin >= 0.0_rt) {
qint(i,j,k,QRHO) = rstar;
qint(i,j,k,iu) = ustar;
qint(i,j,k,QPRES) = pstar;
game_int = gamstar;
}
qint(i,j,k,QPRES) = amrex::max(qint(i,j,k,QPRES), lsmall_pres);
qint(i,j,k,iu) = qint(i,j,k,iu) * bnd_fac;
// Compute fluxes, order as conserved state (not q)
// compute the total energy from the internal, p/(gamma - 1), and the kinetic
qint(i,j,k,QREINT) = qint(i,j,k,QPRES)/(game_int - 1.0_rt);
// advected quantities -- only the contact matters
for (int ipassive = 0; ipassive < npassive; ipassive++) {
int nqp = qpassmap(ipassive);
if (ustar > 0.0_rt) {
qint(i,j,k,nqp) = ql(i,j,k,nqp);
} else if (ustar < 0.0_rt) {
qint(i,j,k,nqp) = qr(i,j,k,nqp);
} else {
qint(i,j,k,nqp) = 0.5_rt * (ql(i,j,k,nqp) + qr(i,j,k,nqp));
}
}
});
}
void
Castro::riemannus(const Box& bx,
Array4<Real> const& ql,
Array4<Real> const& qr,
Array4<Real const> const& qaux_arr,
Array4<Real> const& qint,
#ifdef RADIATION
Array4<Real> const& lambda_int,
#endif
const int idir, const int compute_gammas) {
// Colella, Glaz, and Ferguson solver
//
// this is a 2-shock solver that uses a very simple approximation for the
// star state, and carries an auxiliary jump condition for (rho e) to
// deal with a real gas
// set integer pointers for the normal and transverse velocity and
// momentum
const auto domlo = geom.Domain().loVect3d();
const auto domhi = geom.Domain().hiVect3d();
int iu, iv1, iv2;
if (idir == 0) {
iu = QU;
iv1 = QV;
iv2 = QW;
} else if (idir == 1) {
iu = QV;
iv1 = QU;
iv2 = QW;
} else {
iu = QW;
iv1 = QU;
iv2 = QV;
}
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
// do we want to force the flux to zero at the boundary?
const bool special_bnd_lo = (lo_bc[idir] == Symmetry ||
lo_bc[idir] == SlipWall ||
lo_bc[idir] == NoSlipWall);
const bool special_bnd_hi = (hi_bc[idir] == Symmetry ||
hi_bc[idir] == SlipWall ||
hi_bc[idir] == NoSlipWall);
const int luse_eos_in_riemann = use_eos_in_riemann;
const Real lsmall = riemann_constants::small;
const Real lsmall_dens = small_dens;
const Real lsmall_pres = small_pres;
const Real lT_guess = T_guess;
amrex::ParallelFor(bx,
[=] AMREX_GPU_HOST_DEVICE (int i, int j, int k)
{
// deal with hard walls
Real bnd_fac = 1.0_rt;
if (idir == 0) {
if ((i == domlo[0] && special_bnd_lo) ||
(i == domhi[0]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else if (idir == 1) {
if ((j == domlo[1] && special_bnd_lo) ||
(j == domhi[1]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else {
if ((k == domlo[2] && special_bnd_lo) ||
(k == domhi[2]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
}
// set the left and right states for this interface
#ifdef RADIATION
Real laml[NGROUPS];
Real lamr[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
if (idir == 0) {
laml[g] = qaux_arr(i-1,j,k,QLAMS+g);
} else if (idir == 1) {
laml[g] = qaux_arr(i,j-1,k,QLAMS+g);
} else {
laml[g] = qaux_arr(i,j,k-1,QLAMS+g);
}
lamr[g] = qaux_arr(i,j,k,QLAMS+g);
}
#endif
Real rl = amrex::max(ql(i,j,k,QRHO), lsmall_dens);
// pick left velocities based on direction
Real ul = ql(i,j,k,iu);
Real v1l = ql(i,j,k,iv1);
Real v2l = ql(i,j,k,iv2);
#ifdef RADIATION
Real pl = ql(i,j,k,QPTOT);
Real rel = ql(i,j,k,QREITOT);
Real erl[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
erl[g] = ql(i,j,k,QRAD+g);
}
Real pl_g = ql(i,j,k,QPRES);
Real rel_g = ql(i,j,k,QREINT);
#else
Real pl = amrex::max(ql(i,j,k,QPRES), lsmall_pres);
Real rel = ql(i,j,k,QREINT);
#endif
Real rr = amrex::max(qr(i,j,k,QRHO), lsmall_dens);
// pick right velocities based on direction
Real ur = qr(i,j,k,iu);
Real v1r = qr(i,j,k,iv1);
Real v2r = qr(i,j,k,iv2);
#ifdef RADIATION
Real pr = qr(i,j,k,QPTOT);
Real rer = qr(i,j,k,QREITOT);
Real err[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
err[g] = qr(i,j,k,QRAD+g);
}
Real pr_g = qr(i,j,k,QPRES);
Real rer_g = qr(i,j,k,QREINT);
#else
Real pr = amrex::max(qr(i,j,k,QPRES), lsmall_pres);
Real rer = qr(i,j,k,QREINT);
#endif
// estimate the star state: pstar, ustar
Real csmall;
Real cavg;
Real gamcl;
Real gamcr;
#ifdef RADIATION
Real gamcgl;
Real gamcgr;
#endif
if (idir == 0) {
csmall = amrex::max(lsmall, lsmall * amrex::max(qaux_arr(i,j,k,QC), qaux_arr(i-1,j,k,QC)));
cavg = 0.5_rt*(qaux_arr(i,j,k,QC) + qaux_arr(i-1,j,k,QC));
gamcl = qaux_arr(i-1,j,k,QGAMC);
gamcr = qaux_arr(i,j,k,QGAMC);
#ifdef RADIATION
gamcgl = qaux_arr(i-1,j,k,QGAMCG);
gamcgr = qaux_arr(i,j,k,QGAMCG);
#endif
} else if (idir == 1) {
csmall = amrex::max(lsmall, lsmall * amrex::max(qaux_arr(i,j,k,QC), qaux_arr(i,j-1,k,QC)));
cavg = 0.5_rt*(qaux_arr(i,j,k,QC) + qaux_arr(i,j-1,k,QC));
gamcl = qaux_arr(i,j-1,k,QGAMC);
gamcr = qaux_arr(i,j,k,QGAMC);
#ifdef RADIATION
gamcgl = qaux_arr(i,j-1,k,QGAMCG);
gamcgr = qaux_arr(i,j,k,QGAMCG);
#endif
} else {
csmall = amrex::max(lsmall, lsmall * amrex::max(qaux_arr(i,j,k,QC), qaux_arr(i,j,k-1,QC)));
cavg = 0.5_rt*(qaux_arr(i,j,k,QC) + qaux_arr(i,j,k-1,QC));
gamcl = qaux_arr(i,j,k-1,QGAMC);
gamcr = qaux_arr(i,j,k,QGAMC);
#ifdef RADIATION
gamcgl = qaux_arr(i,j,k-1,QGAMCG);
gamcgr = qaux_arr(i,j,k,QGAMCG);
#endif
}
#ifndef RADIATION
if (compute_gammas == 1) {
// we come in with a good p, rho, and X on the interfaces
// -- use this to find the gamma used in the sound speed
eos_t eos_state;
eos_state.p = pl;
eos_state.rho = rl;
for (int n = 0; n < NumSpec; n++) {
eos_state.xn[n] = ql(i,j,k,QFS+n);
}
eos_state.T = lT_guess; // initial guess
#if NAUX_NET > 0
for (int n = 0; n < NumAux; n++) {
eos_state.aux[n] = ql(i,j,k,QFX+n);
}
#endif
eos(eos_input_rp, eos_state);
gamcl = eos_state.gam1;
eos_state.p = pr;
eos_state.rho = rr;
for (int n = 0; n < NumSpec; n++) {
eos_state.xn[n] = qr(i,j,k,QFS+n);
}
eos_state.T = lT_guess; // initial guess
#if NAUX_NET > 0
for (int n = 0; n < NumAux; n++) {
eos_state.aux[n] = qr(i,j,k,QFX+n);
}
#endif
eos(eos_input_rp, eos_state);
gamcr = eos_state.gam1;
#ifdef TRUE_SDC
} else if (use_reconstructed_gamma1 == 1) {
gamcl = ql(i,j,k,QGC);
gamcr = qr(i,j,k,QGC);
#endif
}
#endif
Real wsmall = lsmall_dens*csmall;
// this is Castro I: Eq. 33
Real wl = amrex::max(wsmall, std::sqrt(std::abs(gamcl*pl*rl)));
Real wr = amrex::max(wsmall, std::sqrt(std::abs(gamcr*pr*rr)));
Real wwinv = 1.0_rt/(wl + wr);
Real pstar = ((wr*pl + wl*pr) + wl*wr*(ul - ur))*wwinv;
Real ustar = ((wl*ul + wr*ur) + (pl - pr))*wwinv;
pstar = amrex::max(pstar, lsmall_pres);
// for symmetry preservation, if ustar is really small, then we
// set it to zero
if (std::abs(ustar) < riemann_constants::smallu*0.5_rt*(std::abs(ul) + std::abs(ur))) {
ustar = 0.0_rt;
}
// look at the contact to determine which region we are in
// this just determines which of the left or right states is still
// in play. We still need to look at the other wave to determine
// if the star state or this state is on the interface.
Real sgnm = std::copysign(1.0_rt, ustar);
if (ustar == 0.0_rt) {
sgnm = 0.0_rt;
}
Real fp = 0.5_rt*(1.0_rt + sgnm);
Real fm = 0.5_rt*(1.0_rt - sgnm);
Real ro = fp*rl + fm*rr;
Real uo = fp*ul + fm*ur;
Real po = fp*pl + fm*pr;
Real reo = fp*rel + fm*rer;
Real gamco = fp*gamcl + fm*gamcr;
#ifdef RADIATION
Real lambda[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
lambda[g] = fp*laml[g] + fm*lamr[g];
}
if (ustar == 0) {
// harmonic average
for (int g = 0; g < NGROUPS; g++) {
lambda[g] = 2.0_rt*(laml[g]*lamr[g])/(laml[g] + lamr[g] + 1.e-50_rt);
}
}
Real po_g = fp*pl_g + fm*pr_g;
Real reo_r[NGROUPS];
Real po_r[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
reo_r[g] = fp*erl[g] + fm*err[g];
po_r[g] = lambda[g]*reo_r[g];
}
Real reo_g = fp*rel_g + fm*rer_g;
Real gamco_g = fp*gamcgl + fm*gamcgr;
#endif
ro = amrex::max(lsmall_dens, ro);
Real roinv = 1.0_rt/ro;
Real co = std::sqrt(std::abs(gamco*po*roinv));
co = amrex::max(csmall, co);
Real co2inv = 1.0_rt/(co*co);
// we can already deal with the transverse velocities -- they
// only jump across the contact
qint(i,j,k,iv1) = fp*v1l + fm*v1r;
qint(i,j,k,iv2) = fp*v2l + fm*v2r;
// compute the rest of the star state
Real drho = (pstar - po)*co2inv;
Real rstar = ro + drho;
rstar = amrex::max(lsmall_dens, rstar);
#ifdef RADIATION
Real estar_g = reo_g + drho*(reo_g + po_g)*roinv;
Real co_g = std::sqrt(std::abs(gamco_g*po_g*roinv));
co_g = amrex::max(csmall, co_g);
Real pstar_g = po_g + drho*co_g*co_g;
pstar_g = amrex::max(pstar_g, lsmall_pres);
Real estar_r[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
estar_r[g] = reo_r[g] + drho*(reo_r[g] + po_r[g])*roinv;
}
#else
Real entho = (reo + po)*roinv*co2inv;
Real estar = reo + (pstar - po)*entho;
#endif
Real cstar = std::sqrt(std::abs(gamco*pstar/rstar));
cstar = amrex::max(cstar, csmall);
// finish sampling the solution
// look at the remaining wave to determine if the star state or the
// 'o' state above is on the interface
// the values of u +/- c on either side of the non-contact wave
Real spout = co - sgnm*uo;
Real spin = cstar - sgnm*ustar;
// a simple estimate of the shock speed
Real ushock = 0.5_rt*(spin + spout);
if (pstar-po > 0.0_rt) {
spin = ushock;
spout = ushock;
}
Real scr = spout - spin;
if (spout-spin == 0.0_rt) {
scr = lsmall*cavg;
}
// interpolate for the case that we are in a rarefaction
Real frac = (1.0_rt + (spout + spin)/scr)*0.5_rt;
frac = amrex::max(0.0_rt, amrex::min(1.0_rt, frac));
qint(i,j,k,QRHO) = frac*rstar + (1.0_rt - frac)*ro;
qint(i,j,k,iu ) = frac*ustar + (1.0_rt - frac)*uo;
#ifdef RADIATION
Real pgdnv_t = frac*pstar + (1.0_rt - frac)*po;
Real pgdnv_g = frac*pstar_g + (1.0_rt - frac)*po_g;
Real regdnv_g = frac*estar_g + (1.0_rt - frac)*reo_g;
Real regdnv_r[NGROUPS];
for (int g = 0; g < NGROUPS; g++) {
regdnv_r[g] = frac*estar_r[g] + (1.0_rt - frac)*reo_r[g];
}
#else
qint(i,j,k,QPRES) = frac*pstar + (1.0_rt - frac)*po;
Real regdnv = frac*estar + (1.0_rt - frac)*reo;
#endif
// as it stands now, we set things assuming that the rarefaction
// spans the interface. We overwrite that here depending on the
// wave speeds
// look at the speeds on either side of the remaining wave
// to determine which region we are in
if (spout < 0.0_rt) {
// the l or r state is on the interface
qint(i,j,k,QRHO) = ro;
qint(i,j,k,iu ) = uo;
#ifdef RADIATION
pgdnv_t = po;
pgdnv_g = po_g;
regdnv_g = reo_g;
for (int g = 0; g < NGROUPS; g++) {
regdnv_r[g] = reo_r[g];
}
#else
qint(i,j,k,QPRES) = po;
regdnv = reo;
#endif
}
if (spin >= 0.0_rt) {
// the star state is on the interface
qint(i,j,k,QRHO) = rstar;
qint(i,j,k,iu ) = ustar;
#ifdef RADIATION
pgdnv_t = pstar;
pgdnv_g = pstar_g;
regdnv_g = estar_g;
for (int g = 0; g < NGROUPS; g++) {
regdnv_r[g] = estar_r[g];
}
#else
qint(i,j,k,QPRES) = pstar;
regdnv = estar;
#endif
}
#ifdef RADIATION
for (int g = 0; g < NGROUPS; g++) {
qint(i,j,k,QRAD+g) = amrex::max(regdnv_r[g], 0.0_rt);
}
qint(i,j,k,QPRES) = pgdnv_g;
qint(i,j,k,QPTOT) = pgdnv_t;
qint(i,j,k,QREINT) = regdnv_g;
qint(i,j,k,QREITOT) = regdnv_g;
for (int g = 0; g < NGROUPS; g++) {
qint(i,j,k,QREITOT) += regdnv_r[g];
}
for (int g = 0; g < NGROUPS; g++) {
lambda_int(i,j,k,g) = lambda[g];
}
#else
qint(i,j,k,QPRES) = amrex::max(qint(i,j,k,QPRES), lsmall_pres);
qint(i,j,k,QREINT) = regdnv;
#endif
// we are potentially thermodynamically inconsistent, fix that
// here
if (luse_eos_in_riemann == 1) {
// we need to know the species -- they only jump across
// the contact
eos_t eos_state;
eos_state.rho = qint(i,j,k,QRHO);
eos_state.p = qint(i,j,k,QPRES);
for (int n = 0; n < NumSpec; n++) {
eos_state.xn[n] = fp*ql(i,j,k,QFS+n) + fm*qr(i,j,k,QFS+n);
}
eos_state.T = lT_guess;
#if NAUX_NET > 0
for (int n = 0; n < NumAux; n++) {
eos_state.aux[n] = fp*ql(i,j,k,QFX+n) + fm*qr(i,j,k,QFX+n);
}
#endif
eos(eos_input_rp, eos_state);
qint(i,j,k,QREINT) = eos_state.rho * eos_state.e;
}
// Enforce that fluxes through a symmetry plane or wall are hard zero.
qint(i,j,k,iu) = qint(i,j,k,iu) * bnd_fac;
// passively advected quantities
for (int ipassive = 0; ipassive < npassive; ipassive++) {
int nqp = qpassmap(ipassive);
qint(i,j,k,nqp) = fp*ql(i,j,k,nqp) + fm*qr(i,j,k,nqp);
}
});
}
void
Castro::HLLC(const Box& bx,
Array4<Real const> const& ql,
Array4<Real const> const& qr,
Array4<Real const> const& qaux_arr,
Array4<Real> const& uflx,
Array4<Real> const& qint,
const int idir) {
// this is an implementation of the HLLC solver described in Toro's
// book. it uses the simplest estimate of the wave speeds, since
// those should work for a general EOS. We also initially do the
// CGF Riemann construction to get pstar and ustar, since we'll
// need to know the pressure and velocity on the interface for the
// pdV term in the internal energy update.
const auto domlo = geom.Domain().loVect3d();
const auto domhi = geom.Domain().hiVect3d();
int iu;
int sx, sy, sz;
if (idir == 0) {
iu = QU;
sx = 1;
sy = 0;
sz = 0;
} else if (idir == 1) {
iu = QV;
sx = 0;
sy = 1;
sz = 0;
} else {
iu = QW;
sx = 0;
sy = 0;
sz = 1;
}
const int* lo_bc = phys_bc.lo();
const int* hi_bc = phys_bc.hi();
// do we want to force the flux to zero at the boundary?
const bool special_bnd_lo = (lo_bc[idir] == Symmetry ||
lo_bc[idir] == SlipWall ||
lo_bc[idir] == NoSlipWall);
const bool special_bnd_hi = (hi_bc[idir] == Symmetry ||
hi_bc[idir] == SlipWall ||
hi_bc[idir] == NoSlipWall);
const Real lsmall_dens = small_dens;
const Real lsmall_pres = small_pres;
const Real lsmall = riemann_constants::small;
int coord = geom.Coord();
amrex::ParallelFor(bx,
[=] AMREX_GPU_HOST_DEVICE (int i, int j, int k)
{
// deal with hard walls
Real bnd_fac = 1.0_rt;
if (idir == 0) {
if ((i == domlo[0] && special_bnd_lo) ||
(i == domhi[0]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else if (idir == 1) {
if ((j == domlo[1] && special_bnd_lo) ||
(j == domhi[1]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
} else {
if ((k == domlo[2] && special_bnd_lo) ||
(k == domhi[2]+1 && special_bnd_hi)) {
bnd_fac = 0.0_rt;
}
}
Real rl = amrex::max(ql(i,j,k,QRHO), lsmall_dens);
// pick left velocities based on direction
Real ul = ql(i,j,k,iu);
Real pl = amrex::max(ql(i,j,k,QPRES), lsmall_pres);
Real rr = amrex::max(qr(i,j,k,QRHO), lsmall_dens);
// pick right velocities based on direction
Real ur = qr(i,j,k,iu);
Real pr = amrex::max(qr(i,j,k,QPRES), lsmall_pres);
// now we essentially do the CGF solver to get p and u on the
// interface, but we won't use these in any flux construction.
Real csmall = amrex::max(lsmall, amrex::max(lsmall * qaux_arr(i,j,k,QC), lsmall * qaux_arr(i-sx,j-sy,k-sz,QC)));
Real cavg = 0.5_rt*(qaux_arr(i,j,k,QC) + qaux_arr(i-sx,j-sy,k-sz,QC));
Real gamcl = qaux_arr(i-sx,j-sy,k-sz,QGAMC);
Real gamcr = qaux_arr(i,j,k,QGAMC);
#ifdef TRUE_SDC
if (use_reconstructed_gamma1 == 1) {
gamcl = ql(i,j,k,QGC);
gamcr = qr(i,j,k,QGC);
}
#endif
Real wsmall = lsmall_dens*csmall;
Real wl = amrex::max(wsmall, std::sqrt(std::abs(gamcl*pl*rl)));
Real wr = amrex::max(wsmall, std::sqrt(std::abs(gamcr*pr*rr)));
Real wwinv = 1.0_rt/(wl + wr);
Real pstar = ((wr*pl + wl*pr) + wl*wr*(ul - ur))*wwinv;
Real ustar = ((wl*ul + wr*ur) + (pl - pr))*wwinv;
pstar = amrex::max(pstar, lsmall_pres);
// for symmetry preservation, if ustar is really small, then we
// set it to zero
if (std::abs(ustar) < riemann_constants::smallu*0.5_rt*(std::abs(ul) + std::abs(ur))){
ustar = 0.0_rt;
}
Real ro;
Real uo;
Real po;
Real gamco;
if (ustar > 0.0_rt) {
ro = rl;
uo = ul;
po = pl;
gamco = gamcl;
} else if (ustar < 0.0_rt) {
ro = rr;
uo = ur;
po = pr;
gamco = gamcr;
} else {
ro = 0.5_rt*(rl + rr);
uo = 0.5_rt*(ul + ur);
po = 0.5_rt*(pl + pr);
gamco = 0.5_rt*(gamcl + gamcr);
}
ro = amrex::max(lsmall_dens, ro);
Real roinv = 1.0_rt/ro;
Real co = std::sqrt(std::abs(gamco*po*roinv));
co = amrex::max(csmall, co);
Real co2inv = 1.0_rt/(co*co);
Real rstar = ro + (pstar - po)*co2inv;
rstar = amrex::max(lsmall_dens, rstar);
Real cstar = std::sqrt(std::abs(gamco*pstar/rstar));
cstar = max(cstar, csmall);
Real sgnm = std::copysign(1.0_rt, ustar);
Real spout = co - sgnm*uo;
Real spin = cstar - sgnm*ustar;
Real ushock = 0.5_rt*(spin + spout);
if (pstar-po > 0.0_rt) {
spin = ushock;
spout = ushock;
}
Real scr = spout-spin;
if (spout-spin == 0.0_rt) {
scr = lsmall*cavg;
}
Real frac = (1.0_rt + (spout + spin)/scr)*0.5_rt;
frac = amrex::max(0.0_rt, amrex::min(1.0_rt, frac));
qint(i,j,k,iu) = frac*ustar + (1.0_rt - frac)*uo;
qint(i,j,k,QPRES) = frac*pstar + (1.0_rt - frac)*po;
// now we do the HLLC construction
// use the simplest estimates of the wave speeds
Real S_l = amrex::min(ul - std::sqrt(gamcl*pl/rl), ur - std::sqrt(gamcr*pr/rr));
Real S_r = amrex::max(ul + std::sqrt(gamcl*pl/rl), ur + std::sqrt(gamcr*pr/rr));
// estimate of the contact speed -- this is Toro Eq. 10.8
Real S_c = (pr - pl + rl*ul*(S_l - ul) - rr*ur*(S_r - ur))/
(rl*(S_l - ul) - rr*(S_r - ur));
Real q_zone[NQ];
Real U_state[NUM_STATE];
Real U_hllc_state[NUM_STATE];
Real F_state[NUM_STATE];
if (S_r <= 0.0_rt) {
// R region
for (int n = 0; n < NQ; n++) {
q_zone[n] = qr(i,j,k,n);
}
cons_state(q_zone, U_state);
compute_flux(idir, bnd_fac, coord,
U_state, pr, F_state);
} else if (S_r > 0.0_rt && S_c <= 0.0_rt) {
// R* region
for (int n = 0; n < NQ; n++) {
q_zone[n] = qr(i,j,k,n);
}
cons_state(q_zone, U_state);
compute_flux(idir, bnd_fac, coord,
U_state, pr, F_state);
HLLC_state(idir, S_r, S_c, q_zone, U_hllc_state);
// correct the flux
for (int n = 0; n < NUM_STATE; n++) {
F_state[n] = F_state[n] + S_r*(U_hllc_state[n] - U_state[n]);
}
} else if (S_c > 0.0_rt && S_l < 0.0_rt) {
// L* region
for (int n = 0; n < NQ; n++) {
q_zone[n] = ql(i,j,k,n);
}
cons_state(q_zone, U_state);
compute_flux(idir, bnd_fac, coord,
U_state, pl, F_state);
HLLC_state(idir, S_l, S_c, q_zone, U_hllc_state);
// correct the flux
for (int n = 0; n < NUM_STATE; n++) {
F_state[n] = F_state[n] + S_l*(U_hllc_state[n] - U_state[n]);
}
} else {
// L region
for (int n = 0; n < NQ; n++) {
q_zone[n] = ql(i,j,k,n);
}
cons_state(q_zone, U_state);
compute_flux(idir, bnd_fac, coord,
U_state, pl, F_state);
}
for (int n = 0; n < NUM_STATE; n++) {
uflx(i,j,k,n) = F_state[n];
}
});
}
| 27.815326 | 132 | 0.550924 | nmford20 |
7087b9f7b595d991d7bd8dc0259da6e47acca312 | 8,047 | cpp | C++ | x3py/source/core/x3manager/plugins.cpp | xueyu200/CbersUI | 85bfe9f16e0ff17361875461818006efc51d8d28 | [
"Apache-2.0"
] | 11 | 2019-05-13T02:40:42.000Z | 2021-12-19T20:03:29.000Z | x3py/source/core/x3manager/plugins.cpp | xueyu200/CbersUI | 85bfe9f16e0ff17361875461818006efc51d8d28 | [
"Apache-2.0"
] | 1 | 2022-02-16T09:18:15.000Z | 2022-02-18T02:00:20.000Z | x3py/source/core/x3manager/plugins.cpp | xueyu200/CbersUI | 85bfe9f16e0ff17361875461818006efc51d8d28 | [
"Apache-2.0"
] | 7 | 2019-02-23T13:55:25.000Z | 2021-04-21T11:33:24.000Z | // x3py framework: https://github.com/rhcad/x3py
#include <module/plugininc.h>
#include <utilfunc/convstr.h>
#include "plugins.h"
BEGIN_NAMESPACE_X3
CPlugins::CPlugins()
{
}
CPlugins::~CPlugins()
{
}
int CPlugins::getPluginCount() const
{
LockRW locker(_plugins.locker);
return locker.canRead() ? (1 + GetSize(_plugins)) : 1;
}
void CPlugins::getPluginFiles(std::vector<std::string>& files) const
{
char filename[MAX_PATH] = { 0 };
files.clear();
GetModuleFileNameA(getModuleHandle(), filename, MAX_PATH);
files.push_back(filename);
LockRW locker(_plugins.locker);
if (locker.canRead())
{
for (std::vector<Plugin>::const_iterator it = _plugins.begin();
it != _plugins.end(); ++it)
{
GetModuleFileNameA(it->second, filename, MAX_PATH);
files.push_back(filename);
}
}
}
bool CPlugins::registerPlugin(Creator creator, HMODULE hmod, const char** clsids)
{
bool needInit = true;
LockRW locker(_plugins.locker, true);
if (locker.canWrite() && find_value(_plugins, Plugin(creator, hmod)) < 0)
{
_plugins.push_back(Plugin(creator, hmod));
LockRW lockcls(_clsmap.locker, true);
for (; *clsids && lockcls.canWrite(); clsids++)
{
_clsmap.insert(CreatorPair(*clsids, creator));
#ifdef USE_VECTOR_CLSID
_clsids.push_back(*clsids);
#endif
}
}
return needInit;
}
void CPlugins::unregisterPlugin(Creator creator)
{
LockRW locker(_plugins.locker, true);
if (locker.canWrite())
{
for (std::vector<Plugin>::iterator it = _plugins.begin();
it != _plugins.end(); ++it)
{
if (it->first == creator)
{
_plugins.erase(it);
break;
}
}
}
LockRW lockcls(_clsmap.locker, true);
if (lockcls.canWrite())
{
CreatorMap::iterator it = _clsmap.begin();
while (it != _clsmap.end())
{
if (it->second == creator)
{
#ifdef USE_VECTOR_CLSID
for (std::vector<std::string>::iterator pit = _clsids.begin(); pit != _clsids.end(); pit++)
{
if (compare(it->first, *pit, false) == 0){
_clsids.erase(pit);
break;
}
}
#endif
_clsmap.erase(it);
it = _clsmap.begin();
}
else
{
++it;
}
}
}
LockRW lockobserver(_observers.locker, true);
if (lockobserver.canRead())
{
for (MAP_IT it = _observers.begin(); it != _observers.end(); )
{
if (it->second.creator == creator)
{
if (lockobserver.canWrite())
{
_observers.erase(it);
it = _observers.begin();
}
else
{
it->second = ObserverItem();
++it;
}
}
else
{
++it;
}
}
}
}
void CPlugins::unregisterObserver(ObserverObject* obj)
{
LockRW locker(_observers.locker, true);
if (!locker.canRead())
{
return;
}
for (MAP_IT it = _observers.begin(); it != _observers.end(); )
{
if (it->second.obj == obj)
{
if (locker.canWrite())
{
_observers.erase(it);
it = _observers.begin();
}
else
{
it->second.obj = NULL;
++it;
}
}
else
{
++it;
}
}
}
Creator CPlugins::findPluginByClassID(const char* clsid) const
{
LockRW locker(_clsmap.locker);
Creator ret = NULL;
if (locker.canRead())
{
CreatorMap::const_iterator it = _clsmap.find(clsid);
ret = (it != _clsmap.end()) ? it->second : NULL;
}
return ret;
}
bool CPlugins::createFromOthers(const char* clsid, long iid, IObject** p)
{
Creator creator = findPluginByClassID(clsid);
if (creator && creator(clsid, iid, p))
{
return true;
}
return false;
}
bool CPlugins::registerObserver(const char* type, PROC handler, Creator creator)
{
LockRW locker(_observers.locker, true);
bool ret = type && handler && creator && locker.canWrite();
if (ret)
{
ObserverItem item;
item.creator = creator;
item.handler = handler;
item.obj = NULL;
item.objhandler = NULL;
_observers.insert(ObserverPair(type, item));
}
return ret;
}
bool CPlugins::registerObserver(const char* type, ObserverObject* obj,
ON_EVENT handler, Creator creator)
{
LockRW locker(_observers.locker, true);
bool ret = type && obj && handler && creator && locker.canWrite();
if (ret)
{
ObserverItem item;
item.creator = creator;
item.handler = NULL;
item.obj = obj;
item.objhandler = handler;
_observers.insert(ObserverPair(type, item));
}
return ret;
}
int CPlugins::fireEvent(const char* type, EventDispatcher dispatcher, void* data)
{
LockRW locker(_observers.locker);
std::vector<PROC> observers;
if (locker.canRead())
{
std::pair<MAP_IT, MAP_IT> range (_observers.equal_range(type));
for (MAP_IT it = range.first; it != range.second; ++it)
{
if (it->second.handler)
{
observers.push_back(it->second.handler);
}
}
}
locker.free();
int count = 0;
std::vector<PROC>::iterator it = observers.begin();
for (; it != observers.end(); ++it)
{
count++;
if (!dispatcher(*it, data))
break;
}
return count;
}
int CPlugins::fireEvent(const char* type, ObjectEventDispatcher dispatcher, void* data)
{
LockRW locker(_observers.locker);
typedef std::pair<ObserverObject*, ON_EVENT> Pair;
std::vector<Pair> observers;
if (locker.canRead())
{
std::pair<MAP_IT, MAP_IT> range (_observers.equal_range(type));
for (MAP_IT it = range.first; it != range.second; ++it)
{
if (it->second.obj && it->second.objhandler)
{
observers.push_back(Pair(it->second.obj, it->second.objhandler));
}
}
}
locker.free();
int count = 0;
std::vector<Pair>::iterator it = observers.begin();
for (; it != observers.end(); ++it)
{
count++;
if (!dispatcher(it->first, it->second, data))
break;
}
return count;
}
HMODULE CPlugins::findModuleByFileName(const char* filename)
{
char tmp[MAX_PATH];
LockRW locker(_plugins.locker);
if (!locker.canRead())
{
return NULL;
}
for (std::vector<Plugin>::const_iterator it = _plugins.begin();
it != _plugins.end(); ++it)
{
typedef bool (*F)(char*, int);
F f = (F)GetProcAddress(it->second, "_getdlname");
if (f && f(tmp, MAX_PATH) && _stricmp(tmp, filename) == 0)
{
return it->second;
}
}
return NULL;
}
int CPlugins::getCLSIDCount() const
{
LockRW locker(_clsmap.locker);
return locker.canRead() ? _clsmap.size() : 0;
}
const char* CPlugins::getCLSID(int index)
{
LockRW locker(_clsmap.locker);
const char* ret = NULL;
if (locker.canRead())
{
if( index>=0 && index<_clsmap.size() )
{
#ifdef USE_VECTOR_CLSID
return _clsids.at(index).c_str();
#else
hash_map<std::string, Creator>::iterator it = _clsmap.begin();
for( int i=0; i<index; i++ )
it++;
if( it != _clsmap.end() )
{
ret = it->first.c_str();
}
#endif
}
}
return ret;
}
END_NAMESPACE_X3
| 23.190202 | 107 | 0.524668 | xueyu200 |
70896f1016eea0ce36f018167de3b001c2ad1ae0 | 2,721 | cpp | C++ | src/arrow.cpp | mayankmusaddi/PlaneSimulation-OpenGL | cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6 | [
"MIT"
] | null | null | null | src/arrow.cpp | mayankmusaddi/PlaneSimulation-OpenGL | cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6 | [
"MIT"
] | null | null | null | src/arrow.cpp | mayankmusaddi/PlaneSimulation-OpenGL | cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6 | [
"MIT"
] | null | null | null | #include "arrow.h"
#include "main.h"
#include "primitives.h"
Arrow::Arrow(float x, float y,float z) {
this->position = glm::vec3(x, y, z);
this->direction = glm::mat4(1.0f);
this->rotation = 0;
float size = 0.05;
float thickness = size/2;
static const GLfloat head[] = {
-size, 0, 0,
0, float(sqrt(3))*size, 0,
+size, 0, 0,
-size, 0, -thickness,
0, float(sqrt(3))*size, -thickness,
+size, 0, -thickness,
-size, 0, 0,
0, float(sqrt(3))*size, 0,
-size, 0, -thickness,
0, float(sqrt(3))*size, 0,
-size, 0, -thickness,
0, float(sqrt(3))*size, -thickness,
0, float(sqrt(3))*size, 0,
+size, 0, 0,
0, float(sqrt(3))*size, -thickness,
+size, 0, 0,
0, float(sqrt(3))*size, -thickness,
+size, 0, -thickness,
-size, 0, 0,
+size, 0, 0,
-size, 0, -thickness,
+size, 0, 0,
-size, 0, -thickness,
+size, 0, -thickness,
};
GLfloat body[100000];
makeCuboid(0,-size,-thickness/2, 2*0.6*size, 2*size, thickness, body);
this->body = create3DObject(GL_TRIANGLES, 12*3, body, COLOR_RED, GL_FILL);
this->head = create3DObject(GL_TRIANGLES, 8*3, head, COLOR_RED, GL_FILL);
}
void Arrow::draw(glm::mat4 VP,glm::vec3 target) {
glm::vec3 up = glm::vec3(0,0,-1);
glm::vec3 y = glm::normalize(target - this->position);
glm::vec3 x = glm::normalize(glm::cross(y, up));
glm::vec3 z = glm::normalize(glm::cross(x,y));
this->set_orientation(x,y,z);
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1));
Matrices.model *= (translate * direction * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->head);
draw3DObject(this->body);
}
void Arrow::set_position(float x, float y, float z) {
this->position = glm::vec3(x, y, z);
}
void Arrow::set_orientation(glm::vec3 x,glm::vec3 y,glm::vec3 z){
this->direction[0][0] = x.x;
this->direction[0][1] = x.y;
this->direction[0][2] = x.z;
this->direction[0][3] = 0;
this->direction[1][0] = y.x;
this->direction[1][1] = y.y;
this->direction[1][2] = y.z;
this->direction[1][3] = 0;
this->direction[2][0] = z.x;
this->direction[2][1] = z.y;
this->direction[2][2] = z.z;
this->direction[2][3] = 0;
this->direction[3][0] = 0;
this->direction[3][1] = 0;
this->direction[3][2] = 0;
this->direction[3][3] = 1;
} | 28.34375 | 100 | 0.556413 | mayankmusaddi |
708d27424075645d50b80c8c7c48dd34d886cf4c | 289 | cpp | C++ | Unit 4/TicTacToe/TicTacToe/player.cpp | hhaslam11/C-Projects | c9e76edcd136a163d61fc38a80e419c55f84354d | [
"MIT"
] | null | null | null | Unit 4/TicTacToe/TicTacToe/player.cpp | hhaslam11/C-Projects | c9e76edcd136a163d61fc38a80e419c55f84354d | [
"MIT"
] | null | null | null | Unit 4/TicTacToe/TicTacToe/player.cpp | hhaslam11/C-Projects | c9e76edcd136a163d61fc38a80e419c55f84354d | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
//Prettiness
#include <iomanip>
using std::fixed;
using std::setprecision;
private char type;
void player(char type){
this.type = type;
}
char getType(){
return this.type;
}
| 12.565217 | 24 | 0.705882 | hhaslam11 |
708db4245424c6ba1f235be35eb1285a823cce5c | 803 | cpp | C++ | Kattis/dasort.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | 3 | 2021-02-19T17:01:11.000Z | 2021-03-11T16:50:19.000Z | Kattis/dasort.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | Kattis/dasort.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | //
// https://open.kattis.com/problems/dasort
#include <iostream>
//#include <deque>
#include <algorithm>
//#include <cmath>
#include <vector>
#include <stack>
using namespace std;
int n, a[1010];
stack<int> stk;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t, th;
cin >> t;
while (t--) {
while (!stk.empty()) stk.pop();
cin >> th >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
while (!stk.empty() && stk.top() > a[i]) stk.pop();
stk.push(a[i]);
}
sort(a, a + n);
while (!stk.empty() && stk.top() > a[stk.size() - 1]) stk.pop();
cout << th << ' ' << n - stk.size() << '\n';
}
return 0;
} | 19.585366 | 74 | 0.435866 | YourName0729 |
708fe94a1f3aec06f5746b9be7ba6bf3c0d6db44 | 4,308 | cpp | C++ | ares/n64/cpu/core/core.cpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/n64/cpu/core/core.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/n64/cpu/core/core.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | #include "registers.hpp"
#include "scc-tlb.cpp"
#include "scc-registers.cpp"
#include "fpu-registers.cpp"
#include "memory.cpp"
#include "decoder.cpp"
#include "cpu-instructions.cpp"
#include "scc-instructions.cpp"
#include "fpu-instructions.cpp"
#include "recompiler.cpp"
#include "disassembler.cpp"
#include "serialization.cpp"
auto CPU::raiseException(uint code, uint coprocessor) -> void {
if(debugger.tracer.exception->enabled()) {
if(code != 0) debugger.exception(hex(code, 2L));
}
if(!scc.status.exceptionLevel) {
scc.epc = PC;
scc.status.exceptionLevel = 1;
scc.cause.exceptionCode = code;
scc.cause.coprocessorError = coprocessor;
if(scc.cause.branchDelay = branch.inDelaySlot()) scc.epc -= 4;
} else {
scc.cause.exceptionCode = code;
scc.cause.coprocessorError = coprocessor;
}
u64 vectorBase = !scc.status.vectorLocation ? i32(0x8000'0000) : i32(0xbfc0'0200);
u32 vectorOffset = (code == 2 || code == 3) ? 0x0000 : 0x0180;
PC = vectorBase + vectorOffset;
branch.exception();
context.setMode();
}
auto CPU::instruction() -> void {
if(auto interrupts = scc.cause.interruptPending & scc.status.interruptMask) {
if(scc.status.interruptEnable && !scc.status.exceptionLevel && !scc.status.errorLevel) {
if(debugger.tracer.interrupt->enabled()) {
debugger.interrupt(hex(scc.cause.interruptPending, 2L));
}
scc.cause.interruptPending = interrupts;
step(2);
return raiseException(0);
}
}
//devirtualize the program counter
auto address = readAddress(PC)(0);
if constexpr(Accuracy::CPU::Interpreter == 0) {
auto block = recompiler.block(address);
block->execute();
step(block->step);
}
if constexpr(Accuracy::CPU::Interpreter == 1) {
pipeline.address = PC;
pipeline.instruction = bus.readWord(address);
debugger.instruction();
//instructionDebug();
decoderEXECUTE();
instructionEpilogue();
step(2);
}
}
auto CPU::instructionEpilogue() -> bool {
GPR[0].u64 = 0;
if(--scc.random.index < scc.wired.index) {
scc.random.index = 31;
}
switch(branch.state) {
case Branch::Step: PC += 4; return 0;
case Branch::Take: PC += 4; branch.delaySlot(); return 0;
case Branch::DelaySlot: PC = branch.pc; branch.reset(); return 1;
case Branch::Exception: branch.reset(); return 1;
case Branch::Discard: PC += 8; branch.reset(); return 1;
}
unreachable;
}
auto CPU::instructionDebug() -> void {
pipeline.address = PC;
pipeline.instruction = readWord(pipeline.address)(0);
static vector<bool> mask;
if(!mask) mask.resize(0x0800'0000);
if(mask[(PC & 0x1fff'ffff) >> 2]) return;
mask[(PC & 0x1fff'ffff) >> 2] = 1;
static uint counter = 0;
//if(++counter > 100) return;
print(
disassembler.hint(hex(pipeline.address, 8L)), " ",
//disassembler.hint(hex(pipeline.instruction, 8L)), " ",
disassembler.disassemble(pipeline.address, pipeline.instruction), "\n"
);
}
auto CPU::powerR4300(bool reset) -> void {
for(uint n : range(32)) GPR[n].u64 = 0;
scc = {};
scc.status.softReset = 1; //reset;
fpu = {};
LO.u64 = 0;
HI.u64 = 0;
GPR[Core::Register::SP].u64 = u32(0xa400'1ff0);
PC = u32(0xbfc0'0000);
branch.reset();
fesetround(FE_TONEAREST);
context.setMode();
if constexpr(Accuracy::CPU::Interpreter == 0) {
recompiler.allocator.resize(512_MiB, bump_allocator::executable | bump_allocator::zero_fill);
recompiler.reset();
}
}
auto CPU::Context::setMode() -> void {
mode = min(2, self.scc.status.privilegeMode);
if(self.scc.status.exceptionLevel) mode = Mode::Kernel;
if(self.scc.status.errorLevel) mode = Mode::Kernel;
segment[0] = Segment::Mapped;
segment[1] = Segment::Mapped;
segment[2] = Segment::Mapped;
segment[3] = Segment::Mapped;
if(mode == Mode::Kernel) {
segment[4] = Segment::Cached;
segment[5] = Segment::Uncached;
segment[6] = Segment::Mapped;
segment[7] = Segment::Mapped;
}
if(mode == Mode::Supervisor) {
segment[4] = Segment::Invalid;
segment[5] = Segment::Invalid;
segment[6] = Segment::Mapped;
segment[7] = Segment::Invalid;
}
if(mode == Mode::User) {
segment[4] = Segment::Invalid;
segment[5] = Segment::Invalid;
segment[6] = Segment::Invalid;
segment[7] = Segment::Invalid;
}
}
| 28.342105 | 97 | 0.659006 | moon-chilled |
7095174ff4e48d7b5e5fdbe12f0b98afe38df733 | 11,472 | cpp | C++ | roomedit/owl-6.34/source/appdict.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | roomedit/owl-6.34/source/appdict.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | roomedit/owl-6.34/source/appdict.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | null | null | null | //----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1991, 1996 by Borland International, All Rights Reserved
//
/// \file
/// Implementation of class TAppDictionary, a dictionary of associations
/// between pids (Process IDs) and TApplication pointers.
/// Used to support GetApplicationObject().
//----------------------------------------------------------------------------
#include <owl/pch.h>
#include <owl/appdict.h>
#include <owl/applicat.h>
#if defined(BI_APP_DLL)
# if !defined(__CYGWIN__) && !defined(WINELIB)
# include <dos.h>
# endif
# include <string.h>
#endif
#if defined(__BORLANDC__)
# pragma option -w-ccc // Disable "Condition is always true/false"
#endif
namespace owl {
OWL_DIAGINFO;
// Defining LOCALALLOC_TABLE instructs OWL to use LocalAlloc for the table
//
//#define LOCALALLOC_TABLE
/// Global dictionary used by OWL for EXE Application lookup
//
_OWLFUNC(TAppDictionary&)
OWLGetAppDictionary()
{
static TAppDictionary OwlAppDictionary;
return OwlAppDictionary;
};
//----------------------------------------------------------------------------
//
/// Dictionary implementation used to associate Pids (hTasks) with running Owl
/// apps when Owl is in a DLL or used by a DLL. 32bit only needs this when
/// running win32s (no per-instance data) since per-instance data makes it
/// unnecesasry
//
# if defined(BI_COMP_BORLANDC)
# pragma warn -inl
# endif
/// \addtogroup internal
/// @{
//
/// Abstract Base for dictionary implementation
//
class TAppDictImp {
public:
virtual ~TAppDictImp() {}
virtual void Add(unsigned pid, TApplication* app) = 0;
virtual void Remove(unsigned pid) = 0;
virtual TAppDictionary::TEntry* Lookup(unsigned pid) = 0;
virtual TAppDictionary::TEntry* Lookup(TApplication* app) = 0;
virtual void Iterate(TAppDictionary::TEntryIterator) = 0;
virtual int GetCount() const = 0;
};
//
/// Fast, small, per-instance data based Dictionary implementation (32bit only)
//
class TAppDictInstImp : public TAppDictImp {
public:
TAppDictInstImp() {Entry.App = 0;}
void Add(unsigned pid, TApplication* app) {Entry.App = app;}
void Remove(unsigned) {Entry.App = 0;}
TAppDictionary::TEntry* Lookup(unsigned) {return &Entry;}
TAppDictionary::TEntry* Lookup(TApplication* app) {return &Entry;}
void Iterate(TAppDictionary::TEntryIterator iter)
{(*iter)(Entry);}
int GetCount() const {return Entry.App ? 1 : 0;}
private:
TAppDictionary::TEntry Entry;
};
# if defined(BI_COMP_BORLANDC)
# pragma warn .inl
# endif
/// @}
//} // OWL namespace
//----------------------------------------------------------------------------
/// \class TAppDictionary
/// TAppDictionary implementation for DLLs only. EXE version is all inline.
/// Flat model must implement here, not inline, because same lib is used by DLLs
///
/// A TAppDictionary is a dictionary of associations between a process ID and an
/// application object. A process ID identifies a process: a program (including all
/// its affiliated code, data, and system resources) that is loaded into memory and
/// ready to execute. A TAppDictionary object supports global application lookups
/// using the global GetApplicationObject function or TAppDictionary's
/// GetApplication function. If you do not define an application dictionary,
/// ObjectWindows provides a default, global application dictionary that is
/// exported. In fact, for .EXEs, this global application dictionary is
/// automatically used.
///
/// TAppDictionary includes a TEntry struct, which stores a process ID and the
/// corresponding application object associated with the ID. The public member
/// functions add, find, and remove the entries in the application dictionary.
///
/// If you are statically linking ObjectWindows, you do not have to explicitly
/// create an application dictionary because the default global ObjectWindows
/// application dictionary is used. However, when writing a DLL component that is
/// using ObjectWindows in a DLL, you do need to create your own dictionary. To make
/// it easier to define an application dictionary, ObjectWindows includes a macro
/// DEFINE_APP_DICTIONARY, which automatically creates or references the correct
/// dictionary for your application.
///
/// Although this class is transparent to most users building EXEs, component DLLs
/// need to create an instance of a TApplication class for each task that they
/// service. This kind of application differs from an .EXE application in that it
/// never runs a message loop. (All the other application services are available,
/// however.)
///
/// Although a component may consist of several DLLs, each with its own TModule, the
/// component as a whole has only one TApplication for each task. A TAppDictionary,
/// which is used for all servers (including DLL servers) and components, lets users
/// produce a complete, self-contained application or component. By using a
/// TAppDictionary, these components can share application objects.
///
/// When 16-bit ObjectWindows is statically linked with an .EXE or under Win32, with
/// per- instance data, the TAppDictionary class is implemented as a wrapper to a
/// single application pointer. In this case, there is only one TApplication that
/// the component ever sees.
///
/// To build a component DLL using the ObjectWindows DLL, a new TAppDictionary
/// object must be constructed for that DLL. These are the steps an application must
/// follow in order to associate the component DLL with the TAppDictionary, the
/// application, and the window class hierarchy:
/// 1. Use the DEFINE_APP_DICTIONARY macro to construct an instance of
/// TAppDictionary. Typically, this will be a static global in one of the
/// application's modules (referred to as "AppDictionary"). The DEFINE_DICTIONARY
/// macro allows the same code to be used for EXEs and DLLs.
/// DEFINE_APP_DICTIONARY(AppDictionary);
/// 2. Construct a generic TModule and assign it to the global ::Module. This is
/// the default provided in the ObjectWindows' LibMain function.
/// LibMain(...)
/// ::Module = new TModule(0, hInstance);
/// 3. When each TApplication instance is constructed, pass a pointer to the
/// TAppDictionary as the last argument to ensure that the application will insert
/// itself into this dictionary. In addition, for 16 bit DLLs, the global module argument
/// needs to be supplied with a placeholder value because the Module construction
/// has already been completed at this point, as a result of the process performed
/// in step 2 above.
/// TApplication* app = new TMyApp(..., app, AppDictionary);
/// 4. If the Doc/View model is used, supply the application pointer when
/// constructing the TDocManager object.
/// SetDocManager(new TDocManager(mode, this));
/// 5. When a non-parented window (for example, the main window) is being
/// constructed, pass the application as the module.
/// SetMainWindow(new TFrameWindow(0, "", false, this));
//
/// Application dictionary constructor
//
TAppDictionary::TAppDictionary()
{
Imp = new TAppDictInstImp(); // Could also use this case if linked to exe
}
//
/// Destroys the TAppDictionary object and calls DeleteCondemned to clean up the
/// condemned applications.
//
TAppDictionary::~TAppDictionary()
{
DeleteCondemned();
delete Imp;
}
//
/// Looks up and returns the application associated with a given process ID. The
/// default ID is the ID of the current process. If no application is associated
/// with the process ID, GetApplication returns 0.
//
TApplication*
TAppDictionary::GetApplication(uint pid)
{
if (!pid)
pid = ::GetCurrentProcessId();
TAppDictionary::TEntry* entry = Imp->Lookup(pid);
return entry ? entry->App : 0;
}
//
/// Adds an application object (app) and corresponding process ID to this
/// dictionary. The default ID is the current process's ID.
//
void
TAppDictionary::Add(TApplication* app, uint pid)
{
if (!pid)
pid = ::GetCurrentProcessId();
Imp->Add(pid, app);
}
//
/// Searches for the dictionary entry using the specified application (app). Then
/// removes a given application and process ID entry from this dictionary, but does
/// not delete the application object.
//
void
TAppDictionary::Remove(TApplication* app)
{
TAppDictionary::TEntry* entry = Imp->Lookup(app);
if (entry) {
entry->App = 0;
entry->Pid = 0;
}
}
//
/// Searches for the dictionary entry using the specified process ID (pid). Then
/// removes a given application and its associated process ID entry from this
/// dictionary, but does not delete the application.
//
void
TAppDictionary::Remove(uint pid)
{
TAppDictionary::TEntry* entry = Imp->Lookup(pid);
if (entry) {
entry->App = 0;
entry->Pid = 0;
}
}
//
/// Marks an application in this dictionary as condemned by zeroing its process ID
/// so that the application can be deleted later when DeleteCondemned is called.
//
void
TAppDictionary::Condemn(TApplication* app)
{
TAppDictionary::TEntry* entry = Imp->Lookup(app);
if (entry)
entry->Pid = 0;
}
//
//
//
static void _DeleteCondemnedIter(TAppDictionary::TEntry& entry)
{
if (!entry.Pid) {
delete entry.App;
entry.App = 0;
}
}
//
/// Iterates through the entries in the application dictionary, calling the iter
/// callback function for each entry.
//
void
TAppDictionary::Iterate(TAppDictionary::TEntryIterator iter)
{
Imp->Iterate(iter);
}
//
/// Deletes all condemned applications from the dictionary. If no applications
/// remain in the dictionary, DeleteCondemned returns true.
//
bool
TAppDictionary::DeleteCondemned()
{
Imp->Iterate(_DeleteCondemnedIter);
return Imp->GetCount() == 0;
}
} // OWL namespace
//
/// Exported entry for Debugger use
//
extern "C" _OWLFUNC(owl::TApplication*)
GetTaskApplicationObject(unsigned pid)
{
return owl::OWLGetAppDictionary().GetApplication(pid);
}
namespace owl {
//----------------------------------------------------------------------------
//
/// Global function that calls GetApplication() on OWL's app-dictionary.
/// Used by EXEs, or DLLs statically linking OWL. Never returns 0, will make
/// an alias app if needed. Primarily for compatibility
//
_OWLFUNC(TApplication*) GetApplicationObject(unsigned pid)
{
TApplication* app = OWLGetAppDictionary().GetApplication(pid);
// CHECK(app);
WARN(app == 0, _T("OWLGetAppDictionary().GetApplication(pid) returned NULL"));
if (app)
return app;
// Make alias app (will add itself to dictionary) because OWL always needs an
// app around. If the app is non-OWL, no TApplication will have been
// constructed.
// Override default constructor argument to prevent overwrite of ::Module,
// and pass the default dictionary.
//
TModule* tempModule;
return new TApplication(_T("ALIAS"), tempModule, &(OWLGetAppDictionary()));
}
} // OWL namespace
| 35.082569 | 90 | 0.67181 | Darkman-M59 |
709889e2f30586226288ba14b024539f8ed0cdc1 | 2,799 | cpp | C++ | 2002/samples/mfcsamps/modal/arxmfctmpl.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 1 | 2021-06-25T02:58:47.000Z | 2021-06-25T02:58:47.000Z | 2004/samples/editor/mfcsamps/modal/arxmfctmpl.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | null | null | null | 2004/samples/editor/mfcsamps/modal/arxmfctmpl.cpp | kevinzhwl/ObjectARXMod | ef4c87db803a451c16213a7197470a3e9b40b1c6 | [
"MIT"
] | 3 | 2020-05-23T02:47:44.000Z | 2020-10-27T01:26:53.000Z | // (C) Copyright 1996-1998 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//////////////////////////////////////////////////////////////
//
// Includes
//
//////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <afxdllx.h>
#include "modal.h"
extern "C" HWND adsw_acadMainWnd();
/////////////////////////////////////////////////////////////////////////////
// Define the sole extension module object.
AC_IMPLEMENT_EXTENSION_MODULE(theArxDLL);
void modalDlgTest()
{
// When resource from this ARX app is needed, just
// instantiate a local CAcModuleResourceOverride
CAcModuleResourceOverride resOverride;
CTestDlg dlg(CWnd::FromHandle(adsw_acadMainWnd()));
dlg.DoModal();
}
//////////////////////////////////////////////////////////////
//
// MFC Initialization - DllMain will be called first once
// the application loaded.
//
//////////////////////////////////////////////////////////////
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
// Remove this if you use lpReserved
UNREFERENCED_PARAMETER(lpReserved);
if (dwReason == DLL_PROCESS_ATTACH)
theArxDLL.AttachInstance(hInstance);
else if (dwReason == DLL_PROCESS_DETACH)
theArxDLL.DetachInstance();
return 1; // ok
}
//
// Entry point - called after DllMain() is called
//
extern "C" __declspec(dllexport)
AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* p)
{
switch( msg )
{
case AcRx::kInitAppMsg:
acrxRegisterAppMDIAware(p);
acedRegCmds->addCommand( "RX_TEST", "MODAL", "MODAL",
ACRX_CMD_MODAL, &modalDlgTest);
acutPrintf( "\nEnter \"modal\" to bring up the dialog.\n" );
break;
case AcRx::kUnloadAppMsg:
acedRegCmds->removeGroup("RX_TEST" );
break;
default:
break;
}
return AcRx::kRetOK;
}
| 31.449438 | 78 | 0.620222 | kevinzhwl |
7098c8d6a3770b3bede1f1fa8988b67adedf9952 | 15,420 | cpp | C++ | cpp/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | null | null | null | cpp/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | null | null | null | cpp/depends/igl/headers/igl/copyleft/cgal/outer_hull_legacy.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | null | null | null | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "outer_hull_legacy.h"
#include "extract_cells.h"
#include "remesh_self_intersections.h"
#include "assign.h"
#include "../../remove_unreferenced.h"
#include <CGAL/AABB_tree.h>
#include <CGAL/AABB_traits.h>
#include <CGAL/AABB_triangle_primitive.h>
#include <CGAL/intersections.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include "points_inside_component.h"
#include "order_facets_around_edges.h"
#include "outer_facet.h"
#include "../../sortrows.h"
#include "../../facet_components.h"
#include "../../winding_number.h"
#include "../../triangle_triangle_adjacency.h"
#include "../../unique_edge_map.h"
#include "../../barycenter.h"
#include "../../per_face_normals.h"
#include "../../sort_angles.h"
#include <Eigen/Geometry>
#include <vector>
#include <map>
#include <queue>
#include <iostream>
#include <type_traits>
#include <CGAL/number_utils.h>
//#define IGL_OUTER_HULL_DEBUG
template <
typename DerivedV,
typename DerivedF,
typename DerivedG,
typename DerivedJ,
typename Derivedflip>
IGL_INLINE void igl::copyleft::cgal::outer_hull_legacy(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
Eigen::PlainObjectBase<DerivedG> & G,
Eigen::PlainObjectBase<DerivedJ> & J,
Eigen::PlainObjectBase<Derivedflip> & flip)
{
#ifdef IGL_OUTER_HULL_DEBUG
std::cerr << "Extracting outer hull" << std::endl;
#endif
using namespace Eigen;
using namespace std;
typedef typename DerivedF::Index Index;
Matrix<Index,DerivedF::RowsAtCompileTime,1> C;
typedef Matrix<typename DerivedV::Scalar,Dynamic,DerivedV::ColsAtCompileTime> MatrixXV;
//typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF;
typedef Matrix<typename DerivedG::Scalar,Dynamic,DerivedG::ColsAtCompileTime> MatrixXG;
typedef Matrix<typename DerivedJ::Scalar,Dynamic,DerivedJ::ColsAtCompileTime> MatrixXJ;
const Index m = F.rows();
// UNUSED:
//const auto & duplicate_simplex = [&F](const int f, const int g)->bool
//{
// return
// (F(f,0) == F(g,0) && F(f,1) == F(g,1) && F(f,2) == F(g,2)) ||
// (F(f,1) == F(g,0) && F(f,2) == F(g,1) && F(f,0) == F(g,2)) ||
// (F(f,2) == F(g,0) && F(f,0) == F(g,1) && F(f,1) == F(g,2)) ||
// (F(f,0) == F(g,2) && F(f,1) == F(g,1) && F(f,2) == F(g,0)) ||
// (F(f,1) == F(g,2) && F(f,2) == F(g,1) && F(f,0) == F(g,0)) ||
// (F(f,2) == F(g,2) && F(f,0) == F(g,1) && F(f,1) == F(g,0));
//};
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"outer hull..."<<endl;
#endif
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"edge map..."<<endl;
#endif
typedef Matrix<typename DerivedF::Scalar,Dynamic,2> MatrixX2I;
typedef Matrix<typename DerivedF::Index,Dynamic,1> VectorXI;
//typedef Matrix<typename DerivedV::Scalar, 3, 1> Vector3F;
MatrixX2I E,uE;
VectorXI EMAP;
vector<vector<typename DerivedF::Index> > uE2E;
unique_edge_map(F,E,uE,EMAP,uE2E);
#ifdef IGL_OUTER_HULL_DEBUG
for (size_t ui=0; ui<uE.rows(); ui++) {
std::cout << ui << ": " << uE2E[ui].size() << " -- (";
for (size_t i=0; i<uE2E[ui].size(); i++) {
std::cout << uE2E[ui][i] << ", ";
}
std::cout << ")" << std::endl;
}
#endif
std::vector<std::vector<typename DerivedF::Index> > uE2oE;
std::vector<std::vector<bool> > uE2C;
order_facets_around_edges(V, F, uE, uE2E, uE2oE, uE2C);
uE2E = uE2oE;
VectorXI diIM(3*m);
for (auto ue : uE2E) {
for (size_t i=0; i<ue.size(); i++) {
auto fe = ue[i];
diIM[fe] = i;
}
}
vector<vector<vector<Index > > > TT,_1;
triangle_triangle_adjacency(E,EMAP,uE2E,false,TT,_1);
VectorXI counts;
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"facet components..."<<endl;
#endif
facet_components(TT,C,counts);
assert(C.maxCoeff()+1 == counts.rows());
const size_t ncc = counts.rows();
G.resize(0,F.cols());
J.resize(0,1);
flip.setConstant(m,1,false);
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"reindex..."<<endl;
#endif
// H contains list of faces on outer hull;
vector<bool> FH(m,false);
vector<bool> EH(3*m,false);
vector<MatrixXG> vG(ncc);
vector<MatrixXJ> vJ(ncc);
vector<MatrixXJ> vIM(ncc);
//size_t face_count = 0;
for(size_t id = 0;id<ncc;id++)
{
vIM[id].resize(counts[id],1);
}
// current index into each IM
vector<size_t> g(ncc,0);
// place order of each face in its respective component
for(Index f = 0;f<m;f++)
{
vIM[C(f)](g[C(f)]++) = f;
}
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"barycenters..."<<endl;
#endif
// assumes that "resolve" has handled any coplanar cases correctly and nearly
// coplanar cases can be sorted based on barycenter.
MatrixXV BC;
barycenter(V,F,BC);
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"loop over CCs (="<<ncc<<")..."<<endl;
#endif
for(Index id = 0;id<(Index)ncc;id++)
{
auto & IM = vIM[id];
// starting face that's guaranteed to be on the outer hull and in this
// component
int f;
bool f_flip;
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"outer facet..."<<endl;
#endif
igl::copyleft::cgal::outer_facet(V,F,IM,f,f_flip);
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"outer facet: "<<f<<endl;
//cout << V.row(F(f, 0)) << std::endl;
//cout << V.row(F(f, 1)) << std::endl;
//cout << V.row(F(f, 2)) << std::endl;
#endif
int FHcount = 1;
FH[f] = true;
// Q contains list of face edges to continue traversing upong
queue<int> Q;
Q.push(f+0*m);
Q.push(f+1*m);
Q.push(f+2*m);
flip(f) = f_flip;
//std::cout << "face " << face_count++ << ": " << f << std::endl;
//std::cout << "f " << F.row(f).array()+1 << std::endl;
//cout<<"flip("<<f<<") = "<<(flip(f)?"true":"false")<<endl;
#ifdef IGL_OUTER_HULL_DEBUG
cout<<"BFS..."<<endl;
#endif
while(!Q.empty())
{
// face-edge
const int e = Q.front();
Q.pop();
// face
const int f = e%m;
// corner
const int c = e/m;
#ifdef IGL_OUTER_HULL_DEBUG
std::cout << "edge: " << e << ", ue: " << EMAP(e) << std::endl;
std::cout << "face: " << f << std::endl;
std::cout << "corner: " << c << std::endl;
std::cout << "consistent: " << uE2C[EMAP(e)][diIM[e]] << std::endl;
#endif
// Should never see edge again...
if(EH[e] == true)
{
continue;
}
EH[e] = true;
// source of edge according to f
const int fs = flip(f)?F(f,(c+2)%3):F(f,(c+1)%3);
// destination of edge according to f
const int fd = flip(f)?F(f,(c+1)%3):F(f,(c+2)%3);
// edge valence
const size_t val = uE2E[EMAP(e)].size();
#ifdef IGL_OUTER_HULL_DEBUG
//std::cout << "vd: " << V.row(fd) << std::endl;
//std::cout << "vs: " << V.row(fs) << std::endl;
//std::cout << "edge: " << V.row(fd) - V.row(fs) << std::endl;
for (size_t i=0; i<val; i++) {
if (i == diIM(e)) {
std::cout << "* ";
} else {
std::cout << " ";
}
std::cout << i << ": "
<< " (e: " << uE2E[EMAP(e)][i] << ", f: "
<< uE2E[EMAP(e)][i] % m * (uE2C[EMAP(e)][i] ? 1:-1) << ")" << std::endl;
}
#endif
// is edge consistent with edge of face used for sorting
const int e_cons = (uE2C[EMAP(e)][diIM(e)] ? 1: -1);
int nfei = -1;
// Loop once around trying to find suitable next face
for(size_t step = 1; step<val+2;step++)
{
const int nfei_new = (diIM(e) + 2*val + e_cons*step*(flip(f)?-1:1))%val;
const int nf = uE2E[EMAP(e)][nfei_new] % m;
{
#ifdef IGL_OUTER_HULL_DEBUG
//cout<<"Next facet: "<<(f+1)<<" --> "<<(nf+1)<<", |"<<
// di[EMAP(e)][diIM(e)]<<" - "<<di[EMAP(e)][nfei_new]<<"| = "<<
// abs(di[EMAP(e)][diIM(e)] - di[EMAP(e)][nfei_new])
// <<endl;
#endif
// Only use this face if not already seen
if(!FH[nf])
{
nfei = nfei_new;
//} else {
// std::cout << "skipping face " << nfei_new << " because it is seen before"
// << std::endl;
}
break;
//} else {
// std::cout << di[EMAP(e)][diIM(e)].transpose() << std::endl;
// std::cout << di[EMAP(e)][diIM(nfei_new)].transpose() << std::endl;
// std::cout << "skipping face " << nfei_new << " with identical dihedral angle"
// << std::endl;
}
//#ifdef IGL_OUTER_HULL_DEBUG
// cout<<"Skipping co-planar facet: "<<(f+1)<<" --> "<<(nf+1)<<endl;
//#endif
}
int max_ne = -1;
if(nfei >= 0)
{
max_ne = uE2E[EMAP(e)][nfei];
}
if(max_ne>=0)
{
// face of neighbor
const int nf = max_ne%m;
#ifdef IGL_OUTER_HULL_DEBUG
if(!FH[nf])
{
// first time seeing face
cout<<(f+1)<<" --> "<<(nf+1)<<endl;
}
#endif
FH[nf] = true;
//std::cout << "face " << face_count++ << ": " << nf << std::endl;
//std::cout << "f " << F.row(nf).array()+1 << std::endl;
FHcount++;
// corner of neighbor
const int nc = max_ne/m;
const int nd = F(nf,(nc+2)%3);
const bool cons = (flip(f)?fd:fs) == nd;
flip(nf) = (cons ? flip(f) : !flip(f));
//cout<<"flip("<<nf<<") = "<<(flip(nf)?"true":"false")<<endl;
const int ne1 = nf+((nc+1)%3)*m;
const int ne2 = nf+((nc+2)%3)*m;
if(!EH[ne1])
{
Q.push(ne1);
}
if(!EH[ne2])
{
Q.push(ne2);
}
}
}
{
vG[id].resize(FHcount,3);
vJ[id].resize(FHcount,1);
//nG += FHcount;
size_t h = 0;
assert(counts(id) == IM.rows());
for(int i = 0;i<counts(id);i++)
{
const size_t f = IM(i);
//if(f_flip)
//{
// flip(f) = !flip(f);
//}
if(FH[f])
{
vG[id].row(h) = (flip(f)?F.row(f).reverse().eval():F.row(f));
vJ[id](h,0) = f;
h++;
}
}
assert((int)h == FHcount);
}
}
// Is A inside B? Assuming A and B are consistently oriented but closed and
// non-intersecting.
const auto & has_overlapping_bbox = [](
const Eigen::PlainObjectBase<DerivedV> & V,
const MatrixXG & A,
const MatrixXG & B)->bool
{
const auto & bounding_box = [](
const Eigen::PlainObjectBase<DerivedV> & V,
const MatrixXG & F)->
DerivedV
{
DerivedV BB(2,3);
BB<<
1e26,1e26,1e26,
-1e26,-1e26,-1e26;
const size_t m = F.rows();
for(size_t f = 0;f<m;f++)
{
for(size_t c = 0;c<3;c++)
{
const auto & vfc = V.row(F(f,c)).eval();
BB(0,0) = std::min(BB(0,0), vfc(0,0));
BB(0,1) = std::min(BB(0,1), vfc(0,1));
BB(0,2) = std::min(BB(0,2), vfc(0,2));
BB(1,0) = std::max(BB(1,0), vfc(0,0));
BB(1,1) = std::max(BB(1,1), vfc(0,1));
BB(1,2) = std::max(BB(1,2), vfc(0,2));
}
}
return BB;
};
// A lot of the time we're dealing with unrelated, distant components: cull
// them.
DerivedV ABB = bounding_box(V,A);
DerivedV BBB = bounding_box(V,B);
if( (BBB.row(0)-ABB.row(1)).maxCoeff()>0 ||
(ABB.row(0)-BBB.row(1)).maxCoeff()>0 )
{
// bounding boxes do not overlap
return false;
} else {
return true;
}
};
// Reject components which are completely inside other components
vector<bool> keep(ncc,true);
size_t nG = 0;
// This is O( ncc * ncc * m)
for(size_t id = 0;id<ncc;id++)
{
if (!keep[id]) continue;
std::vector<size_t> unresolved;
for(size_t oid = 0;oid<ncc;oid++)
{
if(id == oid || !keep[oid])
{
continue;
}
if (has_overlapping_bbox(V, vG[id], vG[oid])) {
unresolved.push_back(oid);
}
}
const size_t num_unresolved_components = unresolved.size();
DerivedV query_points(num_unresolved_components, 3);
for (size_t i=0; i<num_unresolved_components; i++) {
const size_t oid = unresolved[i];
DerivedF f = vG[oid].row(0);
query_points(i,0) = (V(f(0,0), 0) + V(f(0,1), 0) + V(f(0,2), 0))/3.0;
query_points(i,1) = (V(f(0,0), 1) + V(f(0,1), 1) + V(f(0,2), 1))/3.0;
query_points(i,2) = (V(f(0,0), 2) + V(f(0,1), 2) + V(f(0,2), 2))/3.0;
}
Eigen::VectorXi inside;
igl::copyleft::cgal::points_inside_component(V, vG[id], query_points, inside);
assert((size_t)inside.size() == num_unresolved_components);
for (size_t i=0; i<num_unresolved_components; i++) {
if (inside(i, 0)) {
const size_t oid = unresolved[i];
keep[oid] = false;
}
}
}
for (size_t id = 0; id<ncc; id++) {
if (keep[id]) {
nG += vJ[id].rows();
}
}
// collect G and J across components
G.resize(nG,3);
J.resize(nG,1);
{
size_t off = 0;
for(Index id = 0;id<(Index)ncc;id++)
{
if(keep[id])
{
assert(vG[id].rows() == vJ[id].rows());
G.block(off,0,vG[id].rows(),vG[id].cols()) = vG[id];
J.block(off,0,vJ[id].rows(),vJ[id].cols()) = vJ[id];
off += vG[id].rows();
}
}
}
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template void igl::copyleft::cgal::outer_hull_legacy<Eigen::Matrix<CGAL::Epeck::FT, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Epeck::FT, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::copyleft::cgal::outer_hull_legacy< Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > &, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > &, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > &);
template void igl::copyleft::cgal::outer_hull_legacy<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
#ifdef WIN32
#endif
#endif
| 34.039735 | 602 | 0.550713 | GitZHCODE |
709a6bf3440894db1d5b5820e4103cf408740079 | 5,690 | cpp | C++ | src/materialsystem/stdshaders/portalstaticoverlay_dx60.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/materialsystem/stdshaders/portalstaticoverlay_dx60.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/materialsystem/stdshaders/portalstaticoverlay_dx60.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "BaseVSShader.h"
#include "convar.h"
#include "d3dx.h"
DEFINE_FALLBACK_SHADER( PortalStaticOverlay, PortalStaticOverlay_DX60 );
BEGIN_VS_SHADER( PortalStaticOverlay_DX60,
"Help for PortalStaticOverlay_DX60 shader" )
BEGIN_SHADER_PARAMS
SHADER_PARAM_OVERRIDE( COLOR, SHADER_PARAM_TYPE_COLOR, "{255 255 255}", "unused", SHADER_PARAM_NOT_EDITABLE )
SHADER_PARAM_OVERRIDE( ALPHA, SHADER_PARAM_TYPE_FLOAT, "1.0", "unused", SHADER_PARAM_NOT_EDITABLE )
SHADER_PARAM( STATICAMOUNT, SHADER_PARAM_TYPE_FLOAT, "0.0", "Amount of the static blend texture to blend into the base texture" )
SHADER_PARAM( STATICBLENDTEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "When adding static, this is the texture that gets blended in" )
SHADER_PARAM( STATICBLENDTEXTUREFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "" )
SHADER_PARAM( ALPHAMASKTEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "An alpha mask for odd shaped portals" )
SHADER_PARAM( ALPHAMASKTEXTUREFRAME, SHADER_PARAM_TYPE_INTEGER, "0", "" )
SHADER_PARAM( NOCOLORWRITE, SHADER_PARAM_TYPE_INTEGER, "0", "" )
END_SHADER_PARAMS
SHADER_INIT_PARAMS()
{
SET_FLAGS( MATERIAL_VAR_TRANSLUCENT );
}
SHADER_FALLBACK
{
return 0;
}
SHADER_INIT
{
if( params[STATICBLENDTEXTURE]->IsDefined() )
LoadTexture( STATICBLENDTEXTURE );
if( params[ALPHAMASKTEXTURE]->IsDefined() )
LoadTexture( ALPHAMASKTEXTURE );
if( !params[STATICAMOUNT]->IsDefined() )
params[STATICAMOUNT]->SetFloatValue( 0.0f );
if( !params[STATICBLENDTEXTURE]->IsDefined() )
params[STATICBLENDTEXTURE]->SetIntValue( 0 );
if( !params[STATICBLENDTEXTUREFRAME]->IsDefined() )
params[STATICBLENDTEXTUREFRAME]->SetIntValue( 0 );
if( !params[ALPHAMASKTEXTURE]->IsDefined() )
params[ALPHAMASKTEXTURE]->SetIntValue( 0 );
if( !params[ALPHAMASKTEXTUREFRAME]->IsDefined() )
params[ALPHAMASKTEXTUREFRAME]->SetIntValue( 0 );
if( !params[NOCOLORWRITE]->IsDefined() )
params[NOCOLORWRITE]->SetIntValue( 0 );
}
SHADER_DRAW
{
SHADOW_STATE
{
SetInitialShadowState();
FogToFogColor();
//pShaderShadow->EnablePolyOffset( SHADER_POLYOFFSET_DECAL ); //a portal is effectively a decal on top of a wall
pShaderShadow->DepthFunc( SHADER_DEPTHFUNC_NEAREROREQUAL );
pShaderShadow->EnableDepthWrites( true );
pShaderShadow->EnableAlphaTest( true );
pShaderShadow->EnableColorWrites( params[NOCOLORWRITE]->GetIntValue() == 0 );
}
DYNAMIC_STATE
{
pShaderAPI->SetDefaultState();
}
if( params[ALPHAMASKTEXTURE]->IsTexture() )
StaticPass_WithAlphaMask( pShaderShadow, pShaderAPI, params ); //portal static texture blending, with an alpha mask
else
StaticPass_NoAlphaMask( pShaderShadow, pShaderAPI, params ); //portal static texture blending
}
void StaticPass_NoAlphaMask( IShaderShadow *pShaderShadow, IShaderDynamicAPI *pShaderAPI, IMaterialVar **params )
{
SHADOW_STATE
{
pShaderShadow->DrawFlags( SHADER_DRAW_POSITION | SHADER_DRAW_TEXCOORD0 );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->EnableBlending( true );
pShaderShadow->BlendFunc( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
pShaderShadow->EnableCustomPixelPipe( true );
pShaderShadow->CustomTextureStages( 1 );
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0,
SHADER_TEXCHANNEL_COLOR,
SHADER_TEXOP_SELECTARG1,
SHADER_TEXARG_TEXTURE, SHADER_TEXARG_TEXTURE );
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0,
SHADER_TEXCHANNEL_ALPHA,
SHADER_TEXOP_BLEND_CONSTANTALPHA,
SHADER_TEXARG_ZERO, SHADER_TEXARG_ONE );
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, STATICBLENDTEXTURE, STATICBLENDTEXTUREFRAME );
pShaderAPI->Color4f( 0.0f, 0.0f, 0.0f, params[STATICAMOUNT]->GetFloatValue() );
}
Draw();
SHADOW_STATE
{
pShaderShadow->EnableCustomPixelPipe( false );
}
}
void StaticPass_WithAlphaMask( IShaderShadow *pShaderShadow, IShaderDynamicAPI *pShaderAPI, IMaterialVar **params )
{
SHADOW_STATE
{
pShaderShadow->DrawFlags( SHADER_DRAW_POSITION | SHADER_DRAW_TEXCOORD0 | SHADER_DRAW_TEXCOORD1 );
pShaderShadow->EnableTexture( SHADER_SAMPLER0, true );
pShaderShadow->EnableTexture( SHADER_SAMPLER1, true );
pShaderShadow->EnableBlending( true );
pShaderShadow->BlendFunc( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA );
pShaderShadow->EnableCustomPixelPipe( true );
pShaderShadow->CustomTextureStages( 2 );
//portal static
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0,
SHADER_TEXCHANNEL_COLOR,
SHADER_TEXOP_SELECTARG1,
SHADER_TEXARG_TEXTURE, SHADER_TEXARG_TEXTURE );
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE0,
SHADER_TEXCHANNEL_ALPHA,
SHADER_TEXOP_BLEND_CONSTANTALPHA,
SHADER_TEXARG_ZERO, SHADER_TEXARG_ONE );
//alpha mask
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE1,
SHADER_TEXCHANNEL_COLOR,
SHADER_TEXOP_SELECTARG1,
SHADER_TEXARG_PREVIOUSSTAGE, SHADER_TEXARG_PREVIOUSSTAGE );
pShaderShadow->CustomTextureOperation( SHADER_TEXTURE_STAGE1,
SHADER_TEXCHANNEL_ALPHA,
SHADER_TEXOP_MODULATE,
SHADER_TEXARG_TEXTUREALPHA, SHADER_TEXARG_PREVIOUSSTAGE );
}
DYNAMIC_STATE
{
BindTexture( SHADER_SAMPLER0, STATICBLENDTEXTURE, STATICBLENDTEXTUREFRAME );
BindTexture( SHADER_SAMPLER1, ALPHAMASKTEXTURE, ALPHAMASKTEXTUREFRAME );
pShaderAPI->Color4f( 0.0f, 0.0f, 0.0f, params[STATICAMOUNT]->GetFloatValue() );
}
Draw();
SHADOW_STATE
{
pShaderShadow->EnableCustomPixelPipe( false );
}
}
END_SHADER
| 31.263736 | 133 | 0.762214 | DeadZoneLuna |
709c54024f16a027c4f756a6d0e761667d8e0e50 | 1,357 | hpp | C++ | sd6/A3_UDP_Session/GameCode/TheApp.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | sd6/A3_UDP_Session/GameCode/TheApp.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | sd6/A3_UDP_Session/GameCode/TheApp.hpp | achen889/Warlockery_Engine | 160a14e85009057f4505ff5380a8c17258698f3e | [
"MIT"
] | null | null | null | //==============================================================================================================
//TheApp.hpp
//by Albert Chen Jan-13-2015.
//==============================================================================================================
#pragma once
#ifndef _included_TheApp__
#define _included_TheApp__
#include "Engine/Renderer/OpenGLRenderer.hpp"
#include "World.hpp"
#include "Engine/Core/Time.hpp"
#include "Engine/Input/InputSystem.hpp"
//#include "Engine/Sound/SoundSystem.hpp"
#include "Engine/Math/Vector3.hpp"
#include "Engine/ParticleSystem/ParticleSystem.hpp"
#include "Engine/Renderer/Text/TextSystem.hpp"
#include "Engine/Multithreading/JobManager.hpp"
#include "Engine/Core/Memory.hpp"
#include "Engine/Networking/NetworkSystem.hpp"
class TheApp{
public:
TheApp();
~TheApp();
void StartUp( void* windowHandle );
void ShutDown();
void Run();
void ProcessInput();
bool ProcessKeyDown(int keyData );
bool ProcessKeyUp(int keyData );
void Update();
void RenderWorld();
private:
World* m_world;
void* m_windowHandle;
OpenGLRenderer* m_renderer;
bool m_isRunning;
InputSystem* m_inputSystem;
//SoundSystem* m_soundSystem;
ParticleSystem* m_particleSystem;
JobManager* m_jobManager;
TextSystem* m_textSystem;
Camera3D* m_mainCamera;
NetworkSystem* m_networkSystem;
};//end of class
#endif | 26.607843 | 112 | 0.644068 | achen889 |
709d276c04cb807382c6ed8a52f0b4751aa33559 | 10,045 | cpp | C++ | src/mongo/s/write_ops/write_op.cpp | stevelyall/mongol-db | d8046147bfe806f7acc0ec4aa70c132507b761fb | [
"Apache-2.0"
] | 1 | 2018-03-16T09:49:05.000Z | 2018-03-16T09:49:05.000Z | src/mongo/s/write_ops/write_op.cpp | stevelyall/mongol-db | d8046147bfe806f7acc0ec4aa70c132507b761fb | [
"Apache-2.0"
] | null | null | null | src/mongo/s/write_ops/write_op.cpp | stevelyall/mongol-db | d8046147bfe806f7acc0ec4aa70c132507b761fb | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2013 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongol/platform/basic.h"
#include "mongol/s/write_ops/write_op.h"
#include "mongol/base/error_codes.h"
#include "mongol/base/owned_pointer_vector.h"
#include "mongol/util/assert_util.h"
namespace mongol {
using std::stringstream;
using std::vector;
static void clear(vector<ChildWriteOp*>* childOps) {
for (vector<ChildWriteOp*>::const_iterator it = childOps->begin(); it != childOps->end();
++it) {
delete *it;
}
childOps->clear();
}
WriteOp::~WriteOp() {
clear(&_childOps);
clear(&_history);
}
const BatchItemRef& WriteOp::getWriteItem() const {
return _itemRef;
}
WriteOpState WriteOp::getWriteState() const {
return _state;
}
const WriteErrorDetail& WriteOp::getOpError() const {
dassert(_state == WriteOpState_Error);
return *_error;
}
Status WriteOp::targetWrites(OperationContext* txn,
const NSTargeter& targeter,
std::vector<TargetedWrite*>* targetedWrites) {
bool isUpdate = _itemRef.getOpType() == BatchedCommandRequest::BatchType_Update;
bool isDelete = _itemRef.getOpType() == BatchedCommandRequest::BatchType_Delete;
bool isIndexInsert = _itemRef.getRequest()->isInsertIndexRequest();
Status targetStatus = Status::OK();
OwnedPointerVector<ShardEndpoint> endpointsOwned;
vector<ShardEndpoint*>& endpoints = endpointsOwned.mutableVector();
if (isUpdate) {
targetStatus = targeter.targetUpdate(txn, *_itemRef.getUpdate(), &endpoints);
} else if (isDelete) {
targetStatus = targeter.targetDelete(txn, *_itemRef.getDelete(), &endpoints);
} else {
dassert(_itemRef.getOpType() == BatchedCommandRequest::BatchType_Insert);
ShardEndpoint* endpoint = NULL;
// TODO: Remove the index targeting stuff once there is a command for it
if (!isIndexInsert) {
targetStatus = targeter.targetInsert(txn, _itemRef.getDocument(), &endpoint);
} else {
// TODO: Retry index writes with stale version?
targetStatus = targeter.targetCollection(&endpoints);
}
if (!targetStatus.isOK()) {
dassert(NULL == endpoint);
return targetStatus;
}
// Store single endpoint result if we targeted a single endpoint
if (endpoint)
endpoints.push_back(endpoint);
}
// If we're targeting more than one endpoint with an update/delete, we have to target
// everywhere since we cannot currently retry partial results.
// NOTE: Index inserts are currently specially targeted only at the current collection to
// avoid creating collections everywhere.
if (targetStatus.isOK() && endpoints.size() > 1u && !isIndexInsert) {
endpointsOwned.clear();
invariant(endpoints.empty());
targetStatus = targeter.targetAllShards(&endpoints);
}
// If we had an error, stop here
if (!targetStatus.isOK())
return targetStatus;
for (vector<ShardEndpoint*>::iterator it = endpoints.begin(); it != endpoints.end(); ++it) {
ShardEndpoint* endpoint = *it;
_childOps.push_back(new ChildWriteOp(this));
WriteOpRef ref(_itemRef.getItemIndex(), _childOps.size() - 1);
// For now, multiple endpoints imply no versioning - we can't retry half a multi-write
if (endpoints.size() == 1u) {
targetedWrites->push_back(new TargetedWrite(*endpoint, ref));
} else {
ShardEndpoint broadcastEndpoint(endpoint->shardName, ChunkVersion::IGNORED());
targetedWrites->push_back(new TargetedWrite(broadcastEndpoint, ref));
}
_childOps.back()->pendingWrite = targetedWrites->back();
_childOps.back()->state = WriteOpState_Pending;
}
_state = WriteOpState_Pending;
return Status::OK();
}
size_t WriteOp::getNumTargeted() {
return _childOps.size();
}
static bool isRetryErrCode(int errCode) {
return errCode == ErrorCodes::StaleShardVersion;
}
// Aggregate a bunch of errors for a single op together
static void combineOpErrors(const vector<ChildWriteOp*>& errOps, WriteErrorDetail* error) {
// Special case single response
if (errOps.size() == 1) {
errOps.front()->error->cloneTo(error);
return;
}
error->setErrCode(ErrorCodes::MultipleErrorsOccurred);
// Generate the multi-error message below
stringstream msg;
msg << "multiple errors for op : ";
BSONArrayBuilder errB;
for (vector<ChildWriteOp*>::const_iterator it = errOps.begin(); it != errOps.end(); ++it) {
const ChildWriteOp* errOp = *it;
if (it != errOps.begin())
msg << " :: and :: ";
msg << errOp->error->getErrMessage();
errB.append(errOp->error->toBSON());
}
error->setErrInfo(BSON("causedBy" << errB.arr()));
error->setIndex(errOps.front()->error->getIndex());
error->setErrMessage(msg.str());
}
/**
* This is the core function which aggregates all the results of a write operation on multiple
* shards and updates the write operation's state.
*/
void WriteOp::updateOpState() {
vector<ChildWriteOp*> childErrors;
bool isRetryError = true;
for (vector<ChildWriteOp*>::iterator it = _childOps.begin(); it != _childOps.end(); it++) {
ChildWriteOp* childOp = *it;
// Don't do anything till we have all the info
if (childOp->state != WriteOpState_Completed && childOp->state != WriteOpState_Error) {
return;
}
if (childOp->state == WriteOpState_Error) {
childErrors.push_back(childOp);
// Any non-retry error aborts all
if (!isRetryErrCode(childOp->error->getErrCode()))
isRetryError = false;
}
}
if (!childErrors.empty() && isRetryError) {
// Since we're using broadcast mode for multi-shard writes, which cannot SCE
dassert(childErrors.size() == 1u);
_state = WriteOpState_Ready;
} else if (!childErrors.empty()) {
_error.reset(new WriteErrorDetail);
combineOpErrors(childErrors, _error.get());
_state = WriteOpState_Error;
} else {
_state = WriteOpState_Completed;
}
// Now that we're done with the child ops, do something with them
// TODO: Don't store unlimited history?
dassert(_state != WriteOpState_Pending);
_history.insert(_history.end(), _childOps.begin(), _childOps.end());
_childOps.clear();
}
void WriteOp::cancelWrites(const WriteErrorDetail* why) {
dassert(_state == WriteOpState_Pending || _state == WriteOpState_Ready);
for (vector<ChildWriteOp*>::iterator it = _childOps.begin(); it != _childOps.end(); ++it) {
ChildWriteOp* childOp = *it;
if (childOp->state == WriteOpState_Pending) {
childOp->endpoint.reset(new ShardEndpoint(childOp->pendingWrite->endpoint));
if (why) {
childOp->error.reset(new WriteErrorDetail);
why->cloneTo(childOp->error.get());
}
childOp->state = WriteOpState_Cancelled;
}
}
_history.insert(_history.end(), _childOps.begin(), _childOps.end());
_childOps.clear();
_state = WriteOpState_Ready;
}
void WriteOp::noteWriteComplete(const TargetedWrite& targetedWrite) {
const WriteOpRef& ref = targetedWrite.writeOpRef;
dassert(static_cast<size_t>(ref.second) < _childOps.size());
ChildWriteOp& childOp = *_childOps.at(ref.second);
childOp.pendingWrite = NULL;
childOp.endpoint.reset(new ShardEndpoint(targetedWrite.endpoint));
childOp.state = WriteOpState_Completed;
updateOpState();
}
void WriteOp::noteWriteError(const TargetedWrite& targetedWrite, const WriteErrorDetail& error) {
const WriteOpRef& ref = targetedWrite.writeOpRef;
ChildWriteOp& childOp = *_childOps.at(ref.second);
childOp.pendingWrite = NULL;
childOp.endpoint.reset(new ShardEndpoint(targetedWrite.endpoint));
childOp.error.reset(new WriteErrorDetail);
error.cloneTo(childOp.error.get());
dassert(ref.first == _itemRef.getItemIndex());
childOp.error->setIndex(_itemRef.getItemIndex());
childOp.state = WriteOpState_Error;
updateOpState();
}
void WriteOp::setOpError(const WriteErrorDetail& error) {
dassert(_state == WriteOpState_Ready);
_error.reset(new WriteErrorDetail);
error.cloneTo(_error.get());
_error->setIndex(_itemRef.getItemIndex());
_state = WriteOpState_Error;
// No need to updateOpState, set directly
}
}
| 36.394928 | 97 | 0.670184 | stevelyall |
709d4b3ba6f0d31fb6624fc7bae7234cac2540a2 | 27,342 | hpp | C++ | src/omni/pool.hpp | Pilatuz/omni | c74a48e4637074dbc9f777c839b6575b4434ad05 | [
"MIT"
] | 1 | 2020-04-07T13:44:28.000Z | 2020-04-07T13:44:28.000Z | src/omni/pool.hpp | Pilatuz/omni | c74a48e4637074dbc9f777c839b6575b4434ad05 | [
"MIT"
] | null | null | null | src/omni/pool.hpp | Pilatuz/omni | c74a48e4637074dbc9f777c839b6575b4434ad05 | [
"MIT"
] | 2 | 2020-09-16T12:00:46.000Z | 2020-09-16T12:59:01.000Z | ///////////////////////////////////////////////////////////////////////////////
// This material is provided "as is", with absolutely no warranty
// expressed or implied. Any use is at your own risk.
//
// Permission to use or copy this software for any purpose is hereby
// granted without fee, provided the above notices are retained on all
// copies. Permission to modify the code and to distribute modified code
// is granted, provided the above notices are retained, and a notice that
// the code was modified is included with the above copyright notice.
//
// https://bitbucket.org/pilatuz/omni
///////////////////////////////////////////////////////////////////////////////
/** @file
@brief Fast memory management.
@author Sergey Polichnoy <pilatuz@gmail.com>
@see @ref omni_pool
*/
#ifndef __OMNI_POOL_HPP_
#define __OMNI_POOL_HPP_
#include <omni/defs.hpp>
#include <assert.h>
#include <memory>
#include <new>
#include <Windows.h>
namespace omni
{
/// @brief Fast memory manager.
/**
@see @ref omni_pool
*/
namespace pool
{
/// @brief Memory manager: implementation.
namespace details
{
///////////////////////////////////////////////////////////////////////////////
/// @brief Constants.
enum
{
/// @brief Default chunk size. @hideinitializer
DEF_CHUNK_SIZE = 64*1024 // 64KB
};
///////////////////////////////////////////////////////////////////////////////
/// @brief Round-up to the next integer power of 2.
/**
This function is compile-time equivalent of the utils::clp2() function.
@tparam X The input, should be in range [0..2^32).
*/
template<size_t X>
class CLP2
{
private: // see utils::clp2() function
enum
{
A1 = X - 1,
A2 = A1 | (A1>>1),
A3 = A2 | (A2>>2),
A4 = A3 | (A3>>4),
A5 = A4 | (A4>>8),
Y = A5 | (A5>>16)
};
public: // result
enum
{
/// @brief The result. @hideinitializer
RESULT = Y+1
};
};
// zero specialization
template<>
class CLP2<0>
{
public:
enum
{
RESULT = 1
};
};
} // details namespace
} // pool namespace
// ObjPool
namespace pool
{
///////////////////////////////////////////////////////////////////////////////
/// @brief The pool of fixed-size memory blocks.
/**
The class manages the fixed-size memory blocks. These memory blocks
are organized as a single-linked list (list of unused blocks or pool).
The get() method returns the first memory block from the pool.
The put() method puts the memory block back into the pool.
If there are no unused memory blocks (i.e. the pool is empty),
then you should call grow() method. The grow() method allocates
memory chunk (several adjacent memory blocks) and puts these
blocks into the list of unused blocks.
For chunk allocation/deallocation global
@b new / @b delete operators are used.
The template parameter @a A is an alignment of memory blocks. It should
be integer power of two: 1, 2, 4, 8, 16, ...
The class does not contain the memory block size. So you should provide
the correct block size each time the grow() method is called.
As an example of using ObjPool class see implementation of FastObjT class.
@see @ref omni_pool
*/
template<size_t A> // A - alignment (for example: 1, 4, 16)
class ObjPool:
private omni::NonCopyable
{
public:
typedef size_t size_type; ///< @brief Size type.
typedef void* pointer; ///< @brief Pointer type.
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief The constants.
enum Const
{
///< @brief The base alignemnt. @hideinitializer
BASE_ALIGNMENT = details::CLP2<A>::RESULT,
/// @brief Alignment of memory blocks. @hideinitializer
ALIGNMENT = BASE_ALIGNMENT < MEMORY_ALLOCATION_ALIGNMENT
? MEMORY_ALLOCATION_ALIGNMENT : BASE_ALIGNMENT
};
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief The default constructor.
/**
The constructor initializes an empty pool. The empty pool has no unused
memory blocks. So, before getting the memory block you should call
grow() method.
@see grow()
*/
ObjPool()
#if OMNI_DEBUG
: m_obj_size(0),
m_N_used(0)
#endif
{
::InitializeSListHead(&m_chunks);
::InitializeSListHead(&m_unused);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief The destructor.
/**
The destructor releases all (used and unused) memory blocks.
@warning Make sure that all memory blocks are returned to the pool.
In debug version there is a memory leak checking.
*/
~ObjPool()
{
#if OMNI_DEBUG
assert(0 == m_N_used
&& "memory leak");
#endif
while (pointer p = ::InterlockedPopEntrySList(&m_chunks))
release_chunk(p);
}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Grow the pool.
/**
One memory chunk is several adjacent memory blocks. This method
allocates one memory chunk and puts these blocks into the list
of unused blocks.
Allocated memory chunk contains at least one memory block.
The ObjPool class does not contain memory block size, so, you should
provide the correct memory block size each time grow() method is called. You should
specify the same memory block size @a obj_size each time grow() is called.
Otherwise your program will have undefined behavior.
@param[in] obj_size The memory block size in bytes.
@param[in] chunk_size Approximate memory chunk size in bytes.
*/
void grow(size_type obj_size, size_type chunk_size = details::DEF_CHUNK_SIZE)
{
const size_type ptr_size = sizeof(SLIST_ENTRY);
const size_type aux_size = ptr_size + ALIGNMENT-1;
obj_size = align(obj_size ? obj_size : 1);
#if OMNI_DEBUG
if (!m_obj_size)
m_obj_size = obj_size;
assert(m_obj_size == obj_size
&& "invalid block size");
#endif
// number of blocks
size_type No = (chunk_size - aux_size) / obj_size;
if (!No) No = 1; // (!) one block minimum
char *chunk = static_cast<char*>(alloc_chunk(aux_size + No*obj_size));
// single-linked list of chunks
::InterlockedPushEntrySList(&m_chunks,
reinterpret_cast<PSLIST_ENTRY>(chunk));
// update list of unused elements
chunk = static_cast<char*>(align(chunk + ptr_size)); // "useful" memory
for (size_type i = 0; i < No; ++i)
put(chunk + (No-1-i)*obj_size); // (!) locality
OMNI_DEBUG_CODE(::InterlockedExchangeAdd(&m_N_used, LONG(No))); // (!) put() makes (--m_N_used);
}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Get the memory block from the pool.
/**
This method returns the first unused memory block.
If the pool is empty the null pointer will be return.
In this case call the grow() method and then get() again.
@return Pointer to the memory block or null.
@see grow()
*/
pointer get()
{
// pop from the list
pointer pObj = ::InterlockedPopEntrySList(&m_unused);
#if OMNI_DEBUG
if (pObj)
{
::InterlockedIncrement(&m_N_used);
}
#endif
return pObj;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Put the memory block back into the pool.
/**
This method puts the memory block @a pObj back into the pool.
The memory block is inserted into the beginning of the unused blocks list.
So, next call of the get() method will return memory block @a pObj again.
@param[in] pObj Pointer to the memory block.
*/
void put(pointer pObj)
{
assert(pObj == align(pObj)
&& "invalid block alignemnt");
// push to the list
::InterlockedPushEntrySList(&m_unused,
reinterpret_cast<PSLIST_ENTRY>(pObj));
#if OMNI_DEBUG
::InterlockedDecrement(&m_N_used);
#endif
}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Align block size.
/**
This method aligns the memory block size @a obj_size.
@param[in] obj_size The memory block size.
@return The aligned memory block size.
*/
static size_type align(size_type obj_size)
{
return (obj_size + ALIGNMENT-1) & ~size_type(ALIGNMENT-1);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Align block pointer.
/**
This method aligns the memory block pointer @a ptr.
@param[in] ptr The memory block pointer.
@return The aligned memory block pointer.
*/
static pointer align(pointer ptr)
{
const size_type x = reinterpret_cast<size_type>(ptr);
return reinterpret_cast<pointer>(align(x));
}
private:
///////////////////////////////////////////////////////////////////////////////
/// @brief Allocate memory chunk.
/**
This method allocates @a chunk_size bytes memory chunk.
@param[in] chunk_size The chunk size in bytes.
@return Pointer to allocated chunk.
*/
static pointer alloc_chunk(size_type chunk_size)
{
return _aligned_malloc(chunk_size, ALIGNMENT);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Release memory chunk.
/**
This method releases memory chunk @a pChunk.
@param[in] pChunk Pointer to the chunk.
*/
static void release_chunk(pointer pChunk)
{
_aligned_free(pChunk);
}
private:
SLIST_HEADER m_unused; ///< @brief The list of unused memory blocks.
SLIST_HEADER m_chunks; ///< @brief The list of memory chunks.
#if OMNI_DEBUG
size_t m_obj_size; ///< @brief The object size.
LONG m_N_used; ///< @brief The total number of memory blocks used.
#endif // OMNI_DEBUG
};
} // ObjPool
// FastObjT
namespace pool
{
///////////////////////////////////////////////////////////////////////////////
/// @brief Fast object with individual pool.
/**
The FastObjT class contains individual pool object.
The @b new / @b delete operators of this class use this individual pool object.
To use fast memory management your class should be derived
from the FastObjT<> class. See the example below.
Since the pool object can manage only one memory block size,
the FastObjT class can't be used with polymorphic classes.
@tparam T Object type. This object type is used to determine memory
block size. The memory block size is equal to @b sizeof(T).
@tparam A Alignment of pointers. Should be integer power of two.
@tparam CS Approximate memory chunk size in bytes.
Example of using the FastObjT class:
@code
class Packet:
public omni::pool::FastObjT<Packet>
{
public:
char data[188]; // 188 bytes data payload
int a, b; // custom parameters
};
void f()
{
Packet *p1 = new Packet(); // ObjPool::get() used
// ...
delete p1; // ObjPool::put() used
// ...
Packet *p2 = new Packet(); // ObjPool::get() used
// ...
delete p2; // ObjPool::put() used
}
@endcode
Note: The Packet class is derived from FastObjT<Packet>.
@see @ref omni_pool
*/
template<typename T, size_t A = sizeof(void*),
size_t CS = details::DEFAULT_CHUNK_SIZE>
class FastObjT
{
public:
typedef ObjPool<A> pool_type; ///< @brief The pool type.
///////////////////////////////////////////////////////////////////////////////
/// @brief Constants.
enum
{
ALIGNMENT = pool_type::ALIGNMENT, ///< @brief The objects alignment. @hideinitializer
CHUNK_SIZE = CS ///< @brief Approximate chunk size. @hideinitializer
};
protected:
///////////////////////////////////////////////////////////////////////////////
/// @brief Trivial constructor.
FastObjT()
{}
///////////////////////////////////////////////////////////////////////////////
/// @brief Trivial destructor.
~FastObjT()
{}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory allocation.
/**
This operator allocates the @a buf_size bytes memory block.
Argument @a buf_size should be less than or equal to the @b sizeof(T)!
@throw std::bad_alloc If there's no available memory.
@param[in] buf_size The memory block size.
@return The memory block.
*/
static void* operator new(size_t buf_size) // throw(std::bad_alloc);
{
assert(buf_size <= sizeof(T)
&& "invalid object size");
buf_size; // argument not used
return alloc();
}
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory allocation.
/**
This operator allocates the @a buf_size bytes memory block.
Argument @a buf_size should be less than or equal to the @b sizeof(T)!
If there is no available memory, then this operator
will return null pointer.
@param[in] buf_size The memory block size.
@return The memory block or null.
*/
static void* operator new(size_t buf_size, std::nothrow_t const&) // throw();
{
assert(buf_size <= sizeof(T)
&& "invalid object size");
buf_size; // argument not used
try
{
return alloc();
}
catch (std::bad_alloc const&)
{}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Placement new operator.
/**
This operator is used only for correct overloading of
other @b new operators. It uses global placement @b new operator.
@param[in] buf_size The memory block size.
@param[in] p The memory block.
@return The memory block.
*/
static void* operator new(size_t buf_size, void *p) // throw();
{
return ::operator new(buf_size, p);
}
public:
///////////////////////////////////////////////////////////////////////////////
///@brief The memory deallocation.
/**
This operator deallocates the @a buf memory block.
@param[in] buf The memory block.
*/
static void operator delete(void *buf)
{
obj_pool().put(buf);
}
///////////////////////////////////////////////////////////////////////////////
///@brief The memory deallocation.
/**
This operator deallocates the @a buf memory block.
@param[in] buf The memory block.
*/
static void operator delete(void *buf, std::nothrow_t const&) // throw();
{
obj_pool().put(buf);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Placement delete operator?
/**
This operator is used only for correct overloading of
other @b delete operators. It uses global placement @b delete operator.
@param[in] buf The memory block?
@param[in] p The memory block?
*/
static void operator delete(void *buf, void *p) // throw();
{
::operator delete(buf, p);
}
private:
///////////////////////////////////////////////////////////////////////////////
/// @brief The individual pool object.
/**
This static method returns the ObjPool object.
This pool object is used for memory management operations.
@return The static ObjPool object.
*/
static pool_type& obj_pool()
{
static pool_type G;
return G;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Get memory block.
/**
This static method returns the memory block from the individual pool.
The size of allocated memory block is equal to @b sizeof(T).
@return The memory block.
*/
static void* alloc()
{
pool_type &x = obj_pool();
void *p = x.get();
while (!p) // unlikely
{
x.grow(sizeof(T),
CHUNK_SIZE);
p = x.get();
}
return p;
}
};
} // FastObjT
// Manager
namespace pool
{
///////////////////////////////////////////////////////////////////////////////
/// @brief The pool manager.
/**
The Manager class contains and manages several pool objects.
The number of managed pool objects is equal to POOL_SIZE.
The granularity argument is the difference between block sizes
of the two adjacent pool objects. For example, if granularity is 2,
then pools are 2, 4, 6, 8, ... bytes. If granularity is 4, then
pools are 4, 8, 12, 16, ... bytes. It is recommended to set granularity
to the alignment.
@param A Alignment of pointers. Should be integer power of two.
@param G Granularity of memory block sizes. Recommended as an alignment.
@param PS Total number of managed pool objects.
@param CS Approximate chunk size in bytes.
@see @ref omni_pool
*/
template<size_t A, size_t G, size_t PS = 1024, size_t CS = details::DEFAULT_CHUNK_SIZE> // A - alignment
class Manager:
private omni::NonCopyable
{
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Constants.
enum
{
MAX_SIZE = G*PS, ///< @brief Maximum available block size. @hideinitializer
GRANULARITY = G, ///< @brief Block size granularity. @hideinitializer
CHUNK_SIZE = CS, ///< @brief Approximate chunk size. @hideinitializer
POOL_SIZE = PS, ///< @brief Total number of pools. @hideinitializer
ALIGNMENT = ObjPool<A>::ALIGNMENT ///< @brief Alignment of pointers. @hideinitializer
};
public:
typedef ObjPool<A> pool_type; ///< @brief The pool type.
typedef typename pool_type::size_type size_type; ///< @brief Size type.
typedef typename pool_type::pointer pointer; ///< @brief Pointer type.
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief The default constructor.
/**
Initializes all managed pools.
*/
Manager()
{}
///////////////////////////////////////////////////////////////////////////////
/// @brief The destructor.
/**
Releases all managed pools.
*/
~Manager()
{}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Get the memory block.
/**
This method gets the memory block from
the corresponding managed pool object.
The memory block size @a obj_size
should be less than or equal to MAX_SIZE.
@param[in] obj_size The memory block size in bytes.
@return The memory block.
@see ObjPool::get()
*/
pointer get(size_type obj_size)
{
assert(obj_size <= MAX_SIZE
&& "object size too big");
pool_type &obj_pool = find(obj_size); // (!) obj_size changed due to granularity!
pointer pObj = obj_pool.get();
while (!pObj) // unlikely
{
obj_pool.grow(obj_size, CHUNK_SIZE);
pObj = obj_pool.get();
}
return pObj;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Put the memory block.
/**
This method puts the memory block @a obj back
into the corresponding managed pool object.
The memory block size @a obj_size
should be less than or equal to MAX_SIZE.
@param[in] obj The memory block.
@param[in] obj_size The memory block size in bytes.
@see ObjPool::put()
*/
void put(pointer obj, size_type obj_size)
{
assert(obj_size <= MAX_SIZE
&& "object size too big");
pool_type &obj_pool = find(obj_size);
obj_pool.put(obj);
}
private:
///////////////////////////////////////////////////////////////////////////////
/// @brief Find pool with specified block size.
/**
This method finds the managed pool object
by memory block size @a obj_size.
@param[in,out] obj_size The memory block size in bytes.
@return The pool object.
*/
pool_type& find(size_type &obj_size)
{
const size_type x = !obj_size ? 0
: (obj_size - 1) / GRANULARITY;
obj_size = (x+1)*GRANULARITY;
assert(x < POOL_SIZE
&& "object size too big");
return m_pools[x];
}
private:
pool_type m_pools[POOL_SIZE]; ///< @brief Managed pool objects.
};
} // Manager
// global pool manager
namespace pool
{
void* mem_get(size_t buf_size); ///< @brief Allocate the memory block.
void mem_put(void *buf, size_t buf_size); ///< @brief Release the memory block.
void* mem_get_sized(size_t buf_size); ///< @brief Allocate the memory block.
void mem_put_sized(void *buf); ///< @brief Release the memory block.
} // global pool manager
// FastObj
namespace pool
{
///////////////////////////////////////////////////////////////////////////////
/// @brief Fast object with global pool.
/**
The FastObj class uses global pool. So, the FastObj class may
be used with polymorphic classes in contrast to FastObjT class.
Any allocation/deallocation operations use mem_get_sized()
and mem_put_sized() functions.
To use fast memory management your class should be derived
from the FastObj class. See the example below.
@code
class MyClass:
public omni::pool::FastObj
{
// ...
};
class Test:
public MyClass
{
// ...
};
void f()
{
MyClass *p1 = new MyClass(); // mem_get_sized() used
// ...
delete p1; // mem_put_sized() used
Test *p2 = new Test(); // mem_get_sized() used
// ...
delete p2; // mem_put_sized() used
}
@endcode
@see @ref omni_pool
*/
class FastObj
{
protected:
FastObj();
virtual ~FastObj();
public:
static void* operator new(size_t buf_size); // throw(std::bad_alloc);
static void* operator new(size_t buf_size, std::nothrow_t const&); // throw();
static void* operator new(size_t buf_size, void *p); // throw();
static void operator delete(void *buf);
static void operator delete(void *buf, std::nothrow_t const&); // throw();
static void operator delete(void *buf, void *p); // throw();
};
} // FastObj
// Allocator
namespace pool
{
///////////////////////////////////////////////////////////////////////////////
/// @brief Fast allocator for STL containers.
/**
This class uses global pool and can be used with many STL containers.
Any allocation/deallocation methods use mem_get_sized()
and mem_put_sized() functions.
For example:
@code
std::vector<double, omni::pool::Allocator<double> > a;
std::list<int, omni::pool::Allocator<int> > b;
@endcode
*/
template<typename T>
class Allocator
{
public:
typedef T value_type; ///< @brief Value type.
typedef T const& const_reference; ///< @brief Constant reference type.
typedef T& reference; ///< @brief Reference type.
typedef T const* const_pointer; ///< @brief Constant pointer type.
typedef T* pointer; ///< @brief Pointer type.
typedef ptrdiff_t difference_type; ///< @brief Difference type.
typedef size_t size_type; ///< @brief Size type.
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Auxiliary structure.
/**
This structure is used to change current allocator's type.
*/
template<typename U>
struct rebind
{
typedef Allocator<U> other; ///< @brief New allocator's type.
};
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Get address by constant reference.
/**
@param[in] x The constant reference.
@return The constant pointer.
*/
const_pointer address(const_reference x) const
{
return &x;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Get address by reference.
/**
@param[in] x The reference.
@return The pointer.
*/
pointer address(reference x) const
{
return &x;
}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief Default constructor.
Allocator()
{}
///////////////////////////////////////////////////////////////////////////////
/// @brief Auxiliary copy-constructor.
template<typename U>
Allocator(Allocator<U> const&)
{}
///////////////////////////////////////////////////////////////////////////////
/// @brief Auxiliary assignment operator.
template<typename U>
Allocator<T>& operator=(Allocator<U> const&)
{
return (*this);
}
public:
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory allocation.
/**
This method allocates memory block for @a n objects.
@param[in] n The number of adjacent objects.
@return The memory block.
*/
pointer allocate(size_type n)
{
return static_cast<pointer>(mem_get_sized(n*sizeof(value_type)));
}
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory allocation.
/**
This method allocates memory block for @a n objects.
Second argument (allocation hint) is not used.
@param[in] n The number of adjacent objects.
@return The memory block.
*/
pointer allocate(size_type n, void const*)
{
return allocate(n);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory allocation.
/**
This method allocates memory block of @a n bytes.
It is used by STL containers in Visual C++ 6.0!
@param[in] n The memory block size in bytes.
@return The memory block.
*/
char* _Charalloc(size_type n)
{
return static_cast<char*>(mem_get_sized(n));
}
///////////////////////////////////////////////////////////////////////////////
/// @brief The memory deallocation.
/**
This method deallocates memory block @a p.
the second argument (memory block size) is not used.
@param[in] p The memory block.
*/
void deallocate(void *p, size_type)
{
mem_put_sized(p);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Object construction.
/**
This method constructs the object at address @a p
using placement @b new operator.
@param[in] p The address of object.
@param[in] x Construction prototype.
*/
void construct(pointer p, const_reference x)
{
new (static_cast<void*>(p)) value_type(x);
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Object destruction.
/**
This method destroys object @a p.
@param[in] p The address of object.
*/
void destroy(pointer p)
{
p->~T(); p;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Maximum number of objects.
/**
This method returns the maximum number of objects,
which can be allocated using this allocator.
@return The maximum number of objects.
*/
size_type max_size() const
{
return size_type(-1) / sizeof(value_type); // (?)
}
};
///////////////////////////////////////////////////////////////////////////////
/// @brief Are two allocators equal?
/**
The two allocators are always equal.
@return @b true.
*/
template<typename T, typename U> inline
bool operator==(Allocator<T> const&, Allocator<U> const&)
{
return true;
}
///////////////////////////////////////////////////////////////////////////////
/// @brief Are two allocators non-equal?
/**
The two allocators are always equal.
@return @b false.
*/
template<typename T, typename U> inline
bool operator!=(Allocator<T> const&, Allocator<U> const&)
{
return false;
}
} // Allocator
} // omni namespace
///////////////////////////////////////////////////////////////////////////////
/** @page omni_pool Fast memory management.
The pool is useful if your program contains many number of small objects.
These objects (for example, data packets) are created and destroyed dynamically.
In this case the standard memory manager is not effective enough,
because it is designed for various memory block sizes. The pool (also known
as "node allocator") in this case is more effective, because it doesn't use
real memory allocation/deallocation so often.
The omni::pool::ObjPool class is a pool for one memory block size.
The omni::pool::Manager class contains several pool objects, and
therefore can manage memory blocks of various sizes (within a specific range).
The omni::pool::FastObjT class overrides @b new / @b delete operators
and contains a pool object. So if your class is derived from
omni::pool::FastObjT, then fast memory management will be used.
There are one global pool. The omni::pool::mem_get() and
omni::pool::mem_put() functions use this global pool to allocate
and deallocate memory blocks. The omni::pool::FastObj class overrides
@b new / @b delete operators and uses the global pool.
The omni::pool::Allocator can be used with STL containers, so these
containers will use the global pool.
*/
#endif // __OMNI_POOL_HPP_
| 25.625117 | 104 | 0.5933 | Pilatuz |
709d783082ef94ea5c4a513c170e4df36aca953d | 112,211 | cpp | C++ | HotSpot1.7-JVM-Linux-x86/src/share/vm/runtime/sharedRuntime.cpp | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | HotSpot1.7/src/share/vm/runtime/sharedRuntime.cpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 1 | 2016-01-17T09:18:17.000Z | 2016-01-17T09:18:17.000Z | HotSpot1.7/src/share/vm/runtime/sharedRuntime.cpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | /*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/compiledIC.hpp"
#include "code/scopeDesc.hpp"
#include "code/vtableStubs.hpp"
#include "compiler/abstractCompiler.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/compilerOracle.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/interpreterRuntime.hpp"
#include "memory/gcLocker.inline.hpp"
#include "memory/universe.inline.hpp"
#include "oops/oop.inline.hpp"
#include "prims/forte.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiRedefineClassesTrace.hpp"
#include "prims/methodHandles.hpp"
#include "prims/nativeLookup.hpp"
#include "runtime/arguments.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vframeArray.hpp"
#include "utilities/copy.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/hashtable.inline.hpp"
#include "utilities/xmlstream.hpp"
#ifdef TARGET_ARCH_x86
# include "nativeInst_x86.hpp"
# include "vmreg_x86.inline.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "nativeInst_sparc.hpp"
# include "vmreg_sparc.inline.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "nativeInst_zero.hpp"
# include "vmreg_zero.inline.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "nativeInst_arm.hpp"
# include "vmreg_arm.inline.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "nativeInst_ppc.hpp"
# include "vmreg_ppc.inline.hpp"
#endif
#ifdef COMPILER1
#include "c1/c1_Runtime1.hpp"
#endif
// Shared stub locations
RuntimeStub* SharedRuntime::_wrong_method_blob;
RuntimeStub* SharedRuntime::_ic_miss_blob;
RuntimeStub* SharedRuntime::_resolve_opt_virtual_call_blob;
RuntimeStub* SharedRuntime::_resolve_virtual_call_blob;
RuntimeStub* SharedRuntime::_resolve_static_call_blob;
DeoptimizationBlob* SharedRuntime::_deopt_blob;
SafepointBlob* SharedRuntime::_polling_page_vectors_safepoint_handler_blob;
SafepointBlob* SharedRuntime::_polling_page_safepoint_handler_blob;
SafepointBlob* SharedRuntime::_polling_page_return_handler_blob;
#ifdef COMPILER2
UncommonTrapBlob* SharedRuntime::_uncommon_trap_blob;
#endif // COMPILER2
//----------------------------generate_stubs-----------------------------------
void SharedRuntime::generate_stubs() {
_wrong_method_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method), "wrong_method_stub");
_ic_miss_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss), "ic_miss_stub");
_resolve_opt_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C), "resolve_opt_virtual_call");
_resolve_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C), "resolve_virtual_call");
_resolve_static_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C), "resolve_static_call");
#ifdef COMPILER2
// Vectors are generated only by C2.
if (is_wide_vector(MaxVectorSize)) {
_polling_page_vectors_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_VECTOR_LOOP);
}
#endif // COMPILER2
_polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_LOOP);
_polling_page_return_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_RETURN);
generate_deopt_blob();
#ifdef COMPILER2
generate_uncommon_trap_blob();
#endif // COMPILER2
}
#include <math.h>
#ifndef USDT2
HS_DTRACE_PROBE_DECL4(hotspot, object__alloc, Thread*, char*, int, size_t);
HS_DTRACE_PROBE_DECL7(hotspot, method__entry, int,
char*, int, char*, int, char*, int);
HS_DTRACE_PROBE_DECL7(hotspot, method__return, int,
char*, int, char*, int, char*, int);
#endif /* !USDT2 */
// Implementation of SharedRuntime
#ifndef PRODUCT
// For statistics
int SharedRuntime::_ic_miss_ctr = 0;
int SharedRuntime::_wrong_method_ctr = 0;
int SharedRuntime::_resolve_static_ctr = 0;
int SharedRuntime::_resolve_virtual_ctr = 0;
int SharedRuntime::_resolve_opt_virtual_ctr = 0;
int SharedRuntime::_implicit_null_throws = 0;
int SharedRuntime::_implicit_div0_throws = 0;
int SharedRuntime::_throw_null_ctr = 0;
int SharedRuntime::_nof_normal_calls = 0;
int SharedRuntime::_nof_optimized_calls = 0;
int SharedRuntime::_nof_inlined_calls = 0;
int SharedRuntime::_nof_megamorphic_calls = 0;
int SharedRuntime::_nof_static_calls = 0;
int SharedRuntime::_nof_inlined_static_calls = 0;
int SharedRuntime::_nof_interface_calls = 0;
int SharedRuntime::_nof_optimized_interface_calls = 0;
int SharedRuntime::_nof_inlined_interface_calls = 0;
int SharedRuntime::_nof_megamorphic_interface_calls = 0;
int SharedRuntime::_nof_removable_exceptions = 0;
int SharedRuntime::_new_instance_ctr=0;
int SharedRuntime::_new_array_ctr=0;
int SharedRuntime::_multi1_ctr=0;
int SharedRuntime::_multi2_ctr=0;
int SharedRuntime::_multi3_ctr=0;
int SharedRuntime::_multi4_ctr=0;
int SharedRuntime::_multi5_ctr=0;
int SharedRuntime::_mon_enter_stub_ctr=0;
int SharedRuntime::_mon_exit_stub_ctr=0;
int SharedRuntime::_mon_enter_ctr=0;
int SharedRuntime::_mon_exit_ctr=0;
int SharedRuntime::_partial_subtype_ctr=0;
int SharedRuntime::_jbyte_array_copy_ctr=0;
int SharedRuntime::_jshort_array_copy_ctr=0;
int SharedRuntime::_jint_array_copy_ctr=0;
int SharedRuntime::_jlong_array_copy_ctr=0;
int SharedRuntime::_oop_array_copy_ctr=0;
int SharedRuntime::_checkcast_array_copy_ctr=0;
int SharedRuntime::_unsafe_array_copy_ctr=0;
int SharedRuntime::_generic_array_copy_ctr=0;
int SharedRuntime::_slow_array_copy_ctr=0;
int SharedRuntime::_find_handler_ctr=0;
int SharedRuntime::_rethrow_ctr=0;
int SharedRuntime::_ICmiss_index = 0;
int SharedRuntime::_ICmiss_count[SharedRuntime::maxICmiss_count];
address SharedRuntime::_ICmiss_at[SharedRuntime::maxICmiss_count];
void SharedRuntime::trace_ic_miss(address at) {
for (int i = 0; i < _ICmiss_index; i++) {
if (_ICmiss_at[i] == at) {
_ICmiss_count[i]++;
return;
}
}
int index = _ICmiss_index++;
if (_ICmiss_index >= maxICmiss_count) _ICmiss_index = maxICmiss_count - 1;
_ICmiss_at[index] = at;
_ICmiss_count[index] = 1;
}
void SharedRuntime::print_ic_miss_histogram() {
if (ICMissHistogram) {
tty->print_cr ("IC Miss Histogram:");
int tot_misses = 0;
for (int i = 0; i < _ICmiss_index; i++) {
tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", _ICmiss_at[i], _ICmiss_count[i]);
tot_misses += _ICmiss_count[i];
}
tty->print_cr ("Total IC misses: %7d", tot_misses);
}
}
#endif // PRODUCT
#ifndef SERIALGC
// G1 write-barrier pre: executed before a pointer store.
JRT_LEAF(void, SharedRuntime::g1_wb_pre(oopDesc* orig, JavaThread *thread))
if (orig == NULL) {
assert(false, "should be optimized out");
return;
}
assert(orig->is_oop(true /* ignore mark word */), "Error");
// store the original value that was in the field reference
thread->satb_mark_queue().enqueue(orig);
JRT_END
// G1 write-barrier post: executed after a pointer store.
JRT_LEAF(void, SharedRuntime::g1_wb_post(void* card_addr, JavaThread* thread))
thread->dirty_card_queue().enqueue(card_addr);
JRT_END
#endif // !SERIALGC
JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
return x * y;
JRT_END
JRT_LEAF(jlong, SharedRuntime::ldiv(jlong y, jlong x))
if (x == min_jlong && y == CONST64(-1)) {
return x;
} else {
return x / y;
}
JRT_END
JRT_LEAF(jlong, SharedRuntime::lrem(jlong y, jlong x))
if (x == min_jlong && y == CONST64(-1)) {
return 0;
} else {
return x % y;
}
JRT_END
const juint float_sign_mask = 0x7FFFFFFF;
const juint float_infinity = 0x7F800000;
const julong double_sign_mask = CONST64(0x7FFFFFFFFFFFFFFF);
const julong double_infinity = CONST64(0x7FF0000000000000);
JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y))
#ifdef _WIN64
// 64-bit Windows on amd64 returns the wrong values for
// infinity operands.
union { jfloat f; juint i; } xbits, ybits;
xbits.f = x;
ybits.f = y;
// x Mod Infinity == x unless x is infinity
if ( ((xbits.i & float_sign_mask) != float_infinity) &&
((ybits.i & float_sign_mask) == float_infinity) ) {
return x;
}
#endif
return ((jfloat)fmod((double)x,(double)y));
JRT_END
JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y))
#ifdef _WIN64
union { jdouble d; julong l; } xbits, ybits;
xbits.d = x;
ybits.d = y;
// x Mod Infinity == x unless x is infinity
if ( ((xbits.l & double_sign_mask) != double_infinity) &&
((ybits.l & double_sign_mask) == double_infinity) ) {
return x;
}
#endif
return ((jdouble)fmod((double)x,(double)y));
JRT_END
#ifdef __SOFTFP__
JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y))
return x + y;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y))
return x - y;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y))
return x * y;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y))
return x / y;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y))
return x + y;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y))
return x - y;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y))
return x * y;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y))
return x / y;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::i2f(jint x))
return (jfloat)x;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::i2d(jint x))
return (jdouble)x;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x))
return (jdouble)x;
JRT_END
JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y))
return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan*/
JRT_END
JRT_LEAF(int, SharedRuntime::fcmpg(float x, float y))
return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
JRT_END
JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y))
return x>y ? 1 : (x==y ? 0 : -1); /* x<y or is_nan */
JRT_END
JRT_LEAF(int, SharedRuntime::dcmpg(double x, double y))
return x<y ? -1 : (x==y ? 0 : 1); /* x>y or is_nan */
JRT_END
// Functions to return the opposite of the aeabi functions for nan.
JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y))
return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y))
return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y))
return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y))
return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y))
return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y))
return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y))
return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y))
return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0);
JRT_END
// Intrinsics make gcc generate code for these.
float SharedRuntime::fneg(float f) {
return -f;
}
double SharedRuntime::dneg(double f) {
return -f;
}
#endif // __SOFTFP__
#if defined(__SOFTFP__) || defined(E500V2)
// Intrinsics make gcc generate code for these.
double SharedRuntime::dabs(double f) {
return (f <= (double)0.0) ? (double)0.0 - f : f;
}
#endif
#if defined(__SOFTFP__) || defined(PPC)
double SharedRuntime::dsqrt(double f) {
return sqrt(f);
}
#endif
JRT_LEAF(jint, SharedRuntime::f2i(jfloat x))
if (g_isnan(x))
return 0;
if (x >= (jfloat) max_jint)
return max_jint;
if (x <= (jfloat) min_jint)
return min_jint;
return (jint) x;
JRT_END
JRT_LEAF(jlong, SharedRuntime::f2l(jfloat x))
if (g_isnan(x))
return 0;
if (x >= (jfloat) max_jlong)
return max_jlong;
if (x <= (jfloat) min_jlong)
return min_jlong;
return (jlong) x;
JRT_END
JRT_LEAF(jint, SharedRuntime::d2i(jdouble x))
if (g_isnan(x))
return 0;
if (x >= (jdouble) max_jint)
return max_jint;
if (x <= (jdouble) min_jint)
return min_jint;
return (jint) x;
JRT_END
JRT_LEAF(jlong, SharedRuntime::d2l(jdouble x))
if (g_isnan(x))
return 0;
if (x >= (jdouble) max_jlong)
return max_jlong;
if (x <= (jdouble) min_jlong)
return min_jlong;
return (jlong) x;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::d2f(jdouble x))
return (jfloat)x;
JRT_END
JRT_LEAF(jfloat, SharedRuntime::l2f(jlong x))
return (jfloat)x;
JRT_END
JRT_LEAF(jdouble, SharedRuntime::l2d(jlong x))
return (jdouble)x;
JRT_END
// Exception handling accross interpreter/compiler boundaries
//
// exception_handler_for_return_address(...) returns the continuation address.
// The continuation address is the entry point of the exception handler of the
// previous frame depending on the return address.
address SharedRuntime::raw_exception_handler_for_return_address(JavaThread* thread, address return_address) {
assert(frame::verify_return_pc(return_address), err_msg("must be a return address: " INTPTR_FORMAT, return_address));
// Reset method handle flag.
thread->set_is_method_handle_return(false);
// The fastest case first
CodeBlob* blob = CodeCache::find_blob(return_address);
nmethod* nm = (blob != NULL) ? blob->as_nmethod_or_null() : NULL;
if (nm != NULL) {
// Set flag if return address is a method handle call site.
thread->set_is_method_handle_return(nm->is_method_handle_return(return_address));
// native nmethods don't have exception handlers
assert(!nm->is_native_method(), "no exception handler");
assert(nm->header_begin() != nm->exception_begin(), "no exception handler");
if (nm->is_deopt_pc(return_address)) {
return SharedRuntime::deopt_blob()->unpack_with_exception();
} else {
return nm->exception_begin();
}
}
// Entry code
if (StubRoutines::returns_to_call_stub(return_address)) {
return StubRoutines::catch_exception_entry();
}
// Interpreted code
if (Interpreter::contains(return_address)) {
return Interpreter::rethrow_exception_entry();
}
guarantee(blob == NULL || !blob->is_runtime_stub(), "caller should have skipped stub");
guarantee(!VtableStubs::contains(return_address), "NULL exceptions in vtables should have been handled already!");
#ifndef PRODUCT
{ ResourceMark rm;
tty->print_cr("No exception handler found for exception at " INTPTR_FORMAT " - potential problems:", return_address);
tty->print_cr("a) exception happened in (new?) code stubs/buffers that is not handled here");
tty->print_cr("b) other problem");
}
#endif // PRODUCT
ShouldNotReachHere();
return NULL;
}
JRT_LEAF(address, SharedRuntime::exception_handler_for_return_address(JavaThread* thread, address return_address))
return raw_exception_handler_for_return_address(thread, return_address);
JRT_END
address SharedRuntime::get_poll_stub(address pc) {
address stub;
// Look up the code blob
CodeBlob *cb = CodeCache::find_blob(pc);
// Should be an nmethod
assert( cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod" );
// Look up the relocation information
assert( ((nmethod*)cb)->is_at_poll_or_poll_return(pc),
"safepoint polling: type must be poll" );
assert( ((NativeInstruction*)pc)->is_safepoint_poll(),
"Only polling locations are used for safepoint");
bool at_poll_return = ((nmethod*)cb)->is_at_poll_return(pc);
bool has_wide_vectors = ((nmethod*)cb)->has_wide_vectors();
if (at_poll_return) {
assert(SharedRuntime::polling_page_return_handler_blob() != NULL,
"polling page return stub not created yet");
stub = SharedRuntime::polling_page_return_handler_blob()->entry_point();
} else if (has_wide_vectors) {
assert(SharedRuntime::polling_page_vectors_safepoint_handler_blob() != NULL,
"polling page vectors safepoint stub not created yet");
stub = SharedRuntime::polling_page_vectors_safepoint_handler_blob()->entry_point();
} else {
assert(SharedRuntime::polling_page_safepoint_handler_blob() != NULL,
"polling page safepoint stub not created yet");
stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point();
}
#ifndef PRODUCT
if( TraceSafepoint ) {
char buf[256];
jio_snprintf(buf, sizeof(buf),
"... found polling page %s exception at pc = "
INTPTR_FORMAT ", stub =" INTPTR_FORMAT,
at_poll_return ? "return" : "loop",
(intptr_t)pc, (intptr_t)stub);
tty->print_raw_cr(buf);
}
#endif // PRODUCT
return stub;
}
oop SharedRuntime::retrieve_receiver( Symbol* sig, frame caller ) {
assert(caller.is_interpreted_frame(), "");
int args_size = ArgumentSizeComputer(sig).size() + 1;
assert(args_size <= caller.interpreter_frame_expression_stack_size(), "receiver must be on interpreter stack");
oop result = (oop) *caller.interpreter_frame_tos_at(args_size - 1);
assert(Universe::heap()->is_in(result) && result->is_oop(), "receiver must be an oop");
return result;
}
void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Handle h_exception) {
if (JvmtiExport::can_post_on_exceptions()) {
vframeStream vfst(thread, true);
methodHandle method = methodHandle(thread, vfst.method());
address bcp = method()->bcp_from(vfst.bci());
JvmtiExport::post_exception_throw(thread, method(), bcp, h_exception());
}
Exceptions::_throw(thread, __FILE__, __LINE__, h_exception);
}
void SharedRuntime::throw_and_post_jvmti_exception(JavaThread *thread, Symbol* name, const char *message) {
Handle h_exception = Exceptions::new_exception(thread, name, message);
throw_and_post_jvmti_exception(thread, h_exception);
}
// The interpreter code to call this tracing function is only
// called/generated when TraceRedefineClasses has the right bits
// set. Since obsolete methods are never compiled, we don't have
// to modify the compilers to generate calls to this function.
//
JRT_LEAF(int, SharedRuntime::rc_trace_method_entry(
JavaThread* thread, methodOopDesc* method))
assert(RC_TRACE_IN_RANGE(0x00001000, 0x00002000), "wrong call");
if (method->is_obsolete()) {
// We are calling an obsolete method, but this is not necessarily
// an error. Our method could have been redefined just after we
// fetched the methodOop from the constant pool.
// RC_TRACE macro has an embedded ResourceMark
RC_TRACE_WITH_THREAD(0x00001000, thread,
("calling obsolete method '%s'",
method->name_and_sig_as_C_string()));
if (RC_TRACE_ENABLED(0x00002000)) {
// this option is provided to debug calls to obsolete methods
guarantee(false, "faulting at call to an obsolete method.");
}
}
return 0;
JRT_END
// ret_pc points into caller; we are returning caller's exception handler
// for given exception
address SharedRuntime::compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
bool force_unwind, bool top_frame_only) {
assert(nm != NULL, "must exist");
ResourceMark rm;
ScopeDesc* sd = nm->scope_desc_at(ret_pc);
// determine handler bci, if any
EXCEPTION_MARK;
int handler_bci = -1;
int scope_depth = 0;
if (!force_unwind) {
int bci = sd->bci();
bool recursive_exception = false;
do {
bool skip_scope_increment = false;
// exception handler lookup
KlassHandle ek (THREAD, exception->klass());
handler_bci = methodOopDesc::fast_exception_handler_bci_for(sd->method(), ek, bci, THREAD);
if (HAS_PENDING_EXCEPTION) {
recursive_exception = true;
// We threw an exception while trying to find the exception handler.
// Transfer the new exception to the exception handle which will
// be set into thread local storage, and do another lookup for an
// exception handler for this exception, this time starting at the
// BCI of the exception handler which caused the exception to be
// thrown (bugs 4307310 and 4546590). Set "exception" reference
// argument to ensure that the correct exception is thrown (4870175).
exception = Handle(THREAD, PENDING_EXCEPTION);
CLEAR_PENDING_EXCEPTION;
if (handler_bci >= 0) {
bci = handler_bci;
handler_bci = -1;
skip_scope_increment = true;
}
}
else {
recursive_exception = false;
}
if (!top_frame_only && handler_bci < 0 && !skip_scope_increment) {
sd = sd->sender();
if (sd != NULL) {
bci = sd->bci();
}
++scope_depth;
}
} while (recursive_exception || (!top_frame_only && handler_bci < 0 && sd != NULL));
}
// found handling method => lookup exception handler
int catch_pco = ret_pc - nm->code_begin();
ExceptionHandlerTable table(nm);
HandlerTableEntry *t = table.entry_for(catch_pco, handler_bci, scope_depth);
if (t == NULL && (nm->is_compiled_by_c1() || handler_bci != -1)) {
// Allow abbreviated catch tables. The idea is to allow a method
// to materialize its exceptions without committing to the exact
// routing of exceptions. In particular this is needed for adding
// a synthethic handler to unlock monitors when inlining
// synchonized methods since the unlock path isn't represented in
// the bytecodes.
t = table.entry_for(catch_pco, -1, 0);
}
#ifdef COMPILER1
if (t == NULL && nm->is_compiled_by_c1()) {
assert(nm->unwind_handler_begin() != NULL, "");
return nm->unwind_handler_begin();
}
#endif
if (t == NULL) {
tty->print_cr("MISSING EXCEPTION HANDLER for pc " INTPTR_FORMAT " and handler bci %d", ret_pc, handler_bci);
tty->print_cr(" Exception:");
exception->print();
tty->cr();
tty->print_cr(" Compiled exception table :");
table.print();
nm->print_code();
guarantee(false, "missing exception handler");
return NULL;
}
return nm->code_begin() + t->pco();
}
JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* thread))
// These errors occur only at call sites
throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_AbstractMethodError());
JRT_END
JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
// These errors occur only at call sites
throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub");
JRT_END
JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* thread))
throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero");
JRT_END
JRT_ENTRY(void, SharedRuntime::throw_NullPointerException(JavaThread* thread))
throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
JRT_END
JRT_ENTRY(void, SharedRuntime::throw_NullPointerException_at_call(JavaThread* thread))
// This entry point is effectively only used for NullPointerExceptions which occur at inline
// cache sites (when the callee activation is not yet set up) so we are at a call site
throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
JRT_END
JRT_ENTRY(void, SharedRuntime::throw_StackOverflowError(JavaThread* thread))
// We avoid using the normal exception construction in this case because
// it performs an upcall to Java, and we're already out of stack space.
klassOop k = SystemDictionary::StackOverflowError_klass();
oop exception_oop = instanceKlass::cast(k)->allocate_instance(CHECK);
Handle exception (thread, exception_oop);
if (StackTraceInThrowable) {
java_lang_Throwable::fill_in_stack_trace(exception);
}
throw_and_post_jvmti_exception(thread, exception);
JRT_END
address SharedRuntime::continuation_for_implicit_exception(JavaThread* thread,
address pc,
SharedRuntime::ImplicitExceptionKind exception_kind)
{
address target_pc = NULL;
if (Interpreter::contains(pc)) {
#ifdef CC_INTERP
// C++ interpreter doesn't throw implicit exceptions
ShouldNotReachHere();
#else
switch (exception_kind) {
case IMPLICIT_NULL: return Interpreter::throw_NullPointerException_entry();
case IMPLICIT_DIVIDE_BY_ZERO: return Interpreter::throw_ArithmeticException_entry();
case STACK_OVERFLOW: return Interpreter::throw_StackOverflowError_entry();
default: ShouldNotReachHere();
}
#endif // !CC_INTERP
} else {
switch (exception_kind) {
case STACK_OVERFLOW: {
// Stack overflow only occurs upon frame setup; the callee is
// going to be unwound. Dispatch to a shared runtime stub
// which will cause the StackOverflowError to be fabricated
// and processed.
// For stack overflow in deoptimization blob, cleanup thread.
if (thread->deopt_mark() != NULL) {
Deoptimization::cleanup_deopt_info(thread, NULL);
}
Events::log_exception(thread, "StackOverflowError at " INTPTR_FORMAT, pc);
return StubRoutines::throw_StackOverflowError_entry();
}
case IMPLICIT_NULL: {
if (VtableStubs::contains(pc)) {
// We haven't yet entered the callee frame. Fabricate an
// exception and begin dispatching it in the caller. Since
// the caller was at a call site, it's safe to destroy all
// caller-saved registers, as these entry points do.
VtableStub* vt_stub = VtableStubs::stub_containing(pc);
// If vt_stub is NULL, then return NULL to signal handler to report the SEGV error.
if (vt_stub == NULL) return NULL;
if (vt_stub->is_abstract_method_error(pc)) {
assert(!vt_stub->is_vtable_stub(), "should never see AbstractMethodErrors from vtable-type VtableStubs");
Events::log_exception(thread, "AbstractMethodError at " INTPTR_FORMAT, pc);
return StubRoutines::throw_AbstractMethodError_entry();
} else {
Events::log_exception(thread, "NullPointerException at vtable entry " INTPTR_FORMAT, pc);
return StubRoutines::throw_NullPointerException_at_call_entry();
}
} else {
CodeBlob* cb = CodeCache::find_blob(pc);
// If code blob is NULL, then return NULL to signal handler to report the SEGV error.
if (cb == NULL) return NULL;
// Exception happened in CodeCache. Must be either:
// 1. Inline-cache check in C2I handler blob,
// 2. Inline-cache check in nmethod, or
// 3. Implict null exception in nmethod
if (!cb->is_nmethod()) {
guarantee(cb->is_adapter_blob() || cb->is_method_handles_adapter_blob(),
"exception happened outside interpreter, nmethods and vtable stubs (1)");
Events::log_exception(thread, "NullPointerException in code blob at " INTPTR_FORMAT, pc);
// There is no handler here, so we will simply unwind.
return StubRoutines::throw_NullPointerException_at_call_entry();
}
// Otherwise, it's an nmethod. Consult its exception handlers.
nmethod* nm = (nmethod*)cb;
if (nm->inlinecache_check_contains(pc)) {
// exception happened inside inline-cache check code
// => the nmethod is not yet active (i.e., the frame
// is not set up yet) => use return address pushed by
// caller => don't push another return address
Events::log_exception(thread, "NullPointerException in IC check " INTPTR_FORMAT, pc);
return StubRoutines::throw_NullPointerException_at_call_entry();
}
if (nm->method()->is_method_handle_intrinsic()) {
// exception happened inside MH dispatch code, similar to a vtable stub
Events::log_exception(thread, "NullPointerException in MH adapter " INTPTR_FORMAT, pc);
return StubRoutines::throw_NullPointerException_at_call_entry();
}
#ifndef PRODUCT
_implicit_null_throws++;
#endif
target_pc = nm->continuation_for_implicit_exception(pc);
// If there's an unexpected fault, target_pc might be NULL,
// in which case we want to fall through into the normal
// error handling code.
}
break; // fall through
}
case IMPLICIT_DIVIDE_BY_ZERO: {
nmethod* nm = CodeCache::find_nmethod(pc);
guarantee(nm != NULL, "must have containing nmethod for implicit division-by-zero exceptions");
#ifndef PRODUCT
_implicit_div0_throws++;
#endif
target_pc = nm->continuation_for_implicit_exception(pc);
// If there's an unexpected fault, target_pc might be NULL,
// in which case we want to fall through into the normal
// error handling code.
break; // fall through
}
default: ShouldNotReachHere();
}
assert(exception_kind == IMPLICIT_NULL || exception_kind == IMPLICIT_DIVIDE_BY_ZERO, "wrong implicit exception kind");
// for AbortVMOnException flag
NOT_PRODUCT(Exceptions::debug_check_abort("java.lang.NullPointerException"));
if (exception_kind == IMPLICIT_NULL) {
Events::log_exception(thread, "Implicit null exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, pc, target_pc);
} else {
Events::log_exception(thread, "Implicit division by zero exception at " INTPTR_FORMAT " to " INTPTR_FORMAT, pc, target_pc);
}
return target_pc;
}
ShouldNotReachHere();
return NULL;
}
/**
* Throws an java/lang/UnsatisfiedLinkError. The address of this method is
* installed in the native function entry of all native Java methods before
* they get linked to their actual native methods.
*
* \note
* This method actually never gets called! The reason is because
* the interpreter's native entries call NativeLookup::lookup() which
* throws the exception when the lookup fails. The exception is then
* caught and forwarded on the return from NativeLookup::lookup() call
* before the call to the native function. This might change in the future.
*/
JNI_ENTRY(void*, throw_unsatisfied_link_error(JNIEnv* env, ...))
{
// We return a bad value here to make sure that the exception is
// forwarded before we look at the return value.
THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badJNIHandle);
}
JNI_END
address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
}
#ifndef PRODUCT
JRT_ENTRY(intptr_t, SharedRuntime::trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2))
const frame f = thread->last_frame();
assert(f.is_interpreted_frame(), "must be an interpreted frame");
#ifndef PRODUCT
methodHandle mh(THREAD, f.interpreter_frame_method());
BytecodeTracer::trace(mh, f.interpreter_frame_bcp(), tos, tos2);
#endif // !PRODUCT
return preserve_this_value;
JRT_END
#endif // !PRODUCT
JRT_ENTRY(void, SharedRuntime::yield_all(JavaThread* thread, int attempts))
os::yield_all(attempts);
JRT_END
JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
assert(obj->is_oop(), "must be a valid oop");
assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise");
instanceKlass::register_finalizer(instanceOop(obj), CHECK);
JRT_END
jlong SharedRuntime::get_java_tid(Thread* thread) {
if (thread != NULL) {
if (thread->is_Java_thread()) {
oop obj = ((JavaThread*)thread)->threadObj();
return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj);
}
}
return 0;
}
/**
* This function ought to be a void function, but cannot be because
* it gets turned into a tail-call on sparc, which runs into dtrace bug
* 6254741. Once that is fixed we can remove the dummy return value.
*/
int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
return dtrace_object_alloc_base(Thread::current(), o);
}
int SharedRuntime::dtrace_object_alloc_base(Thread* thread, oopDesc* o) {
assert(DTraceAllocProbes, "wrong call");
Klass* klass = o->blueprint();
int size = o->size();
Symbol* name = klass->name();
#ifndef USDT2
HS_DTRACE_PROBE4(hotspot, object__alloc, get_java_tid(thread),
name->bytes(), name->utf8_length(), size * HeapWordSize);
#else /* USDT2 */
HOTSPOT_OBJECT_ALLOC(
get_java_tid(thread),
(char *) name->bytes(), name->utf8_length(), size * HeapWordSize);
#endif /* USDT2 */
return 0;
}
JRT_LEAF(int, SharedRuntime::dtrace_method_entry(
JavaThread* thread, methodOopDesc* method))
assert(DTraceMethodProbes, "wrong call");
Symbol* kname = method->klass_name();
Symbol* name = method->name();
Symbol* sig = method->signature();
#ifndef USDT2
HS_DTRACE_PROBE7(hotspot, method__entry, get_java_tid(thread),
kname->bytes(), kname->utf8_length(),
name->bytes(), name->utf8_length(),
sig->bytes(), sig->utf8_length());
#else /* USDT2 */
HOTSPOT_METHOD_ENTRY(
get_java_tid(thread),
(char *) kname->bytes(), kname->utf8_length(),
(char *) name->bytes(), name->utf8_length(),
(char *) sig->bytes(), sig->utf8_length());
#endif /* USDT2 */
return 0;
JRT_END
JRT_LEAF(int, SharedRuntime::dtrace_method_exit(
JavaThread* thread, methodOopDesc* method))
assert(DTraceMethodProbes, "wrong call");
Symbol* kname = method->klass_name();
Symbol* name = method->name();
Symbol* sig = method->signature();
#ifndef USDT2
HS_DTRACE_PROBE7(hotspot, method__return, get_java_tid(thread),
kname->bytes(), kname->utf8_length(),
name->bytes(), name->utf8_length(),
sig->bytes(), sig->utf8_length());
#else /* USDT2 */
HOTSPOT_METHOD_RETURN(
get_java_tid(thread),
(char *) kname->bytes(), kname->utf8_length(),
(char *) name->bytes(), name->utf8_length(),
(char *) sig->bytes(), sig->utf8_length());
#endif /* USDT2 */
return 0;
JRT_END
// Finds receiver, CallInfo (i.e. receiver method), and calling bytecode)
// for a call current in progress, i.e., arguments has been pushed on stack
// put callee has not been invoked yet. Used by: resolve virtual/static,
// vtable updates, etc. Caller frame must be compiled.
Handle SharedRuntime::find_callee_info(JavaThread* thread, Bytecodes::Code& bc, CallInfo& callinfo, TRAPS) {
ResourceMark rm(THREAD);
// last java frame on stack (which includes native call frames)
vframeStream vfst(thread, true); // Do not skip and javaCalls
return find_callee_info_helper(thread, vfst, bc, callinfo, CHECK_(Handle()));
}
// Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
// for a call current in progress, i.e., arguments has been pushed on stack
// but callee has not been invoked yet. Caller frame must be compiled.
Handle SharedRuntime::find_callee_info_helper(JavaThread* thread,
vframeStream& vfst,
Bytecodes::Code& bc,
CallInfo& callinfo, TRAPS) {
Handle receiver;
Handle nullHandle; //create a handy null handle for exception returns
assert(!vfst.at_end(), "Java frame must exist");
// Find caller and bci from vframe
methodHandle caller(THREAD, vfst.method());
int bci = vfst.bci();
// Find bytecode
Bytecode_invoke bytecode(caller, bci);
bc = bytecode.invoke_code();
int bytecode_index = bytecode.index();
// Find receiver for non-static call
if (bc != Bytecodes::_invokestatic &&
bc != Bytecodes::_invokedynamic) {
// This register map must be update since we need to find the receiver for
// compiled frames. The receiver might be in a register.
RegisterMap reg_map2(thread);
frame stubFrame = thread->last_frame();
// Caller-frame is a compiled frame
frame callerFrame = stubFrame.sender(®_map2);
methodHandle callee = bytecode.static_target(CHECK_(nullHandle));
if (callee.is_null()) {
THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
}
// Retrieve from a compiled argument list
receiver = Handle(THREAD, callerFrame.retrieve_receiver(®_map2));
if (receiver.is_null()) {
THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
}
}
// Resolve method. This is parameterized by bytecode.
constantPoolHandle constants(THREAD, caller->constants());
assert(receiver.is_null() || receiver->is_oop(), "wrong receiver");
LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_(nullHandle));
#ifdef ASSERT
// Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
if (bc != Bytecodes::_invokestatic && bc != Bytecodes::_invokedynamic) {
assert(receiver.not_null(), "should have thrown exception");
KlassHandle receiver_klass(THREAD, receiver->klass());
klassOop rk = constants->klass_ref_at(bytecode_index, CHECK_(nullHandle));
// klass is already loaded
KlassHandle static_receiver_klass(THREAD, rk);
// Method handle invokes might have been optimized to a direct call
// so don't check for the receiver class.
// FIXME this weakens the assert too much
methodHandle callee = callinfo.selected_method();
assert(receiver_klass->is_subtype_of(static_receiver_klass()) ||
callee->is_method_handle_intrinsic() ||
callee->is_compiled_lambda_form(),
"actual receiver must be subclass of static receiver klass");
if (receiver_klass->oop_is_instance()) {
if (instanceKlass::cast(receiver_klass())->is_not_initialized()) {
tty->print_cr("ERROR: Klass not yet initialized!!");
receiver_klass.print();
}
assert(!instanceKlass::cast(receiver_klass())->is_not_initialized(), "receiver_klass must be initialized");
}
}
#endif
return receiver;
}
methodHandle SharedRuntime::find_callee_method(JavaThread* thread, TRAPS) {
ResourceMark rm(THREAD);
// We need first to check if any Java activations (compiled, interpreted)
// exist on the stack since last JavaCall. If not, we need
// to get the target method from the JavaCall wrapper.
vframeStream vfst(thread, true); // Do not skip any javaCalls
methodHandle callee_method;
if (vfst.at_end()) {
// No Java frames were found on stack since we did the JavaCall.
// Hence the stack can only contain an entry_frame. We need to
// find the target method from the stub frame.
RegisterMap reg_map(thread, false);
frame fr = thread->last_frame();
assert(fr.is_runtime_frame(), "must be a runtimeStub");
fr = fr.sender(®_map);
assert(fr.is_entry_frame(), "must be");
// fr is now pointing to the entry frame.
callee_method = methodHandle(THREAD, fr.entry_frame_call_wrapper()->callee_method());
assert(fr.entry_frame_call_wrapper()->receiver() == NULL || !callee_method->is_static(), "non-null receiver for static call??");
} else {
Bytecodes::Code bc;
CallInfo callinfo;
find_callee_info_helper(thread, vfst, bc, callinfo, CHECK_(methodHandle()));
callee_method = callinfo.selected_method();
}
assert(callee_method()->is_method(), "must be");
return callee_method;
}
// Resolves a call.
methodHandle SharedRuntime::resolve_helper(JavaThread *thread,
bool is_virtual,
bool is_optimized, TRAPS) {
methodHandle callee_method;
callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD);
if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
int retry_count = 0;
while (!HAS_PENDING_EXCEPTION && callee_method->is_old() &&
callee_method->method_holder() != SystemDictionary::Object_klass()) {
// If has a pending exception then there is no need to re-try to
// resolve this method.
// If the method has been redefined, we need to try again.
// Hack: we have no way to update the vtables of arrays, so don't
// require that java.lang.Object has been updated.
// It is very unlikely that method is redefined more than 100 times
// in the middle of resolve. If it is looping here more than 100 times
// means then there could be a bug here.
guarantee((retry_count++ < 100),
"Could not resolve to latest version of redefined method");
// method is redefined in the middle of resolve so re-try.
callee_method = resolve_sub_helper(thread, is_virtual, is_optimized, THREAD);
}
}
return callee_method;
}
// Resolves a call. The compilers generate code for calls that go here
// and are patched with the real destination of the call.
methodHandle SharedRuntime::resolve_sub_helper(JavaThread *thread,
bool is_virtual,
bool is_optimized, TRAPS) {
ResourceMark rm(thread);
RegisterMap cbl_map(thread, false);
frame caller_frame = thread->last_frame().sender(&cbl_map);
CodeBlob* caller_cb = caller_frame.cb();
guarantee(caller_cb != NULL && caller_cb->is_nmethod(), "must be called from nmethod");
nmethod* caller_nm = caller_cb->as_nmethod_or_null();
// make sure caller is not getting deoptimized
// and removed before we are done with it.
// CLEANUP - with lazy deopt shouldn't need this lock
nmethodLocker caller_lock(caller_nm);
// determine call info & receiver
// note: a) receiver is NULL for static calls
// b) an exception is thrown if receiver is NULL for non-static calls
CallInfo call_info;
Bytecodes::Code invoke_code = Bytecodes::_illegal;
Handle receiver = find_callee_info(thread, invoke_code,
call_info, CHECK_(methodHandle()));
methodHandle callee_method = call_info.selected_method();
assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
(!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
(!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
#ifndef PRODUCT
// tracing/debugging/statistics
int *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
(is_virtual) ? (&_resolve_virtual_ctr) :
(&_resolve_static_ctr);
Atomic::inc(addr);
if (TraceCallFixup) {
ResourceMark rm(thread);
tty->print("resolving %s%s (%s) call to",
(is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
Bytecodes::name(invoke_code));
callee_method->print_short_name(tty);
tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT, caller_frame.pc(), callee_method->code());
}
#endif
// JSR 292 key invariant:
// If the resolved method is a MethodHandle invoke target the call
// site must be a MethodHandle call site, because the lambda form might tail-call
// leaving the stack in a state unknown to either caller or callee
// TODO detune for now but we might need it again
// assert(!callee_method->is_compiled_lambda_form() ||
// caller_nm->is_method_handle_return(caller_frame.pc()), "must be MH call site");
// Compute entry points. This might require generation of C2I converter
// frames, so we cannot be holding any locks here. Furthermore, the
// computation of the entry points is independent of patching the call. We
// always return the entry-point, but we only patch the stub if the call has
// not been deoptimized. Return values: For a virtual call this is an
// (cached_oop, destination address) pair. For a static call/optimized
// virtual this is just a destination address.
StaticCallInfo static_call_info;
CompiledICInfo virtual_call_info;
// Make sure the callee nmethod does not get deoptimized and removed before
// we are done patching the code.
nmethod* callee_nm = callee_method->code();
nmethodLocker nl_callee(callee_nm);
#ifdef ASSERT
address dest_entry_point = callee_nm == NULL ? 0 : callee_nm->entry_point(); // used below
#endif
if (is_virtual) {
assert(receiver.not_null(), "sanity check");
bool static_bound = call_info.resolved_method()->can_be_statically_bound();
KlassHandle h_klass(THREAD, receiver->klass());
CompiledIC::compute_monomorphic_entry(callee_method, h_klass,
is_optimized, static_bound, virtual_call_info,
CHECK_(methodHandle()));
} else {
// static call
CompiledStaticCall::compute_entry(callee_method, static_call_info);
}
// grab lock, check for deoptimization and potentially patch caller
{
MutexLocker ml_patch(CompiledIC_lock);
// Now that we are ready to patch if the methodOop was redefined then
// don't update call site and let the caller retry.
if (!callee_method->is_old()) {
#ifdef ASSERT
// We must not try to patch to jump to an already unloaded method.
if (dest_entry_point != 0) {
assert(CodeCache::find_blob(dest_entry_point) != NULL,
"should not unload nmethod while locked");
}
#endif
if (is_virtual) {
CompiledIC* inline_cache = CompiledIC_before(caller_frame.pc());
if (inline_cache->is_clean()) {
inline_cache->set_to_monomorphic(virtual_call_info);
}
} else {
CompiledStaticCall* ssc = compiledStaticCall_before(caller_frame.pc());
if (ssc->is_clean()) ssc->set(static_call_info);
}
}
} // unlock CompiledIC_lock
return callee_method;
}
// Inline caches exist only in compiled code
JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* thread))
#ifdef ASSERT
RegisterMap reg_map(thread, false);
frame stub_frame = thread->last_frame();
assert(stub_frame.is_runtime_frame(), "sanity check");
frame caller_frame = stub_frame.sender(®_map);
assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame(), "unexpected frame");
#endif /* ASSERT */
methodHandle callee_method;
JRT_BLOCK
callee_method = SharedRuntime::handle_ic_miss_helper(thread, CHECK_NULL);
// Return methodOop through TLS
thread->set_vm_result(callee_method());
JRT_BLOCK_END
// return compiled code entry point after potential safepoints
assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
return callee_method->verified_code_entry();
JRT_END
// Handle call site that has been made non-entrant
JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* thread))
// 6243940 We might end up in here if the callee is deoptimized
// as we race to call it. We don't want to take a safepoint if
// the caller was interpreted because the caller frame will look
// interpreted to the stack walkers and arguments are now
// "compiled" so it is much better to make this transition
// invisible to the stack walking code. The i2c path will
// place the callee method in the callee_target. It is stashed
// there because if we try and find the callee by normal means a
// safepoint is possible and have trouble gc'ing the compiled args.
RegisterMap reg_map(thread, false);
frame stub_frame = thread->last_frame();
assert(stub_frame.is_runtime_frame(), "sanity check");
frame caller_frame = stub_frame.sender(®_map);
// MethodHandle invokes don't have a CompiledIC and should always
// simply redispatch to the callee_target.
address sender_pc = caller_frame.pc();
CodeBlob* sender_cb = caller_frame.cb();
nmethod* sender_nm = sender_cb->as_nmethod_or_null();
if (caller_frame.is_interpreted_frame() ||
caller_frame.is_entry_frame()) {
methodOop callee = thread->callee_target();
guarantee(callee != NULL && callee->is_method(), "bad handshake");
thread->set_vm_result(callee);
thread->set_callee_target(NULL);
return callee->get_c2i_entry();
}
// Must be compiled to compiled path which is safe to stackwalk
methodHandle callee_method;
JRT_BLOCK
// Force resolving of caller (if we called from compiled frame)
callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_NULL);
thread->set_vm_result(callee_method());
JRT_BLOCK_END
// return compiled code entry point after potential safepoints
assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
return callee_method->verified_code_entry();
JRT_END
// resolve a static call and patch code
JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread *thread ))
methodHandle callee_method;
JRT_BLOCK
callee_method = SharedRuntime::resolve_helper(thread, false, false, CHECK_NULL);
thread->set_vm_result(callee_method());
JRT_BLOCK_END
// return compiled code entry point after potential safepoints
assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
return callee_method->verified_code_entry();
JRT_END
// resolve virtual call and update inline cache to monomorphic
JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread *thread ))
methodHandle callee_method;
JRT_BLOCK
callee_method = SharedRuntime::resolve_helper(thread, true, false, CHECK_NULL);
thread->set_vm_result(callee_method());
JRT_BLOCK_END
// return compiled code entry point after potential safepoints
assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
return callee_method->verified_code_entry();
JRT_END
// Resolve a virtual call that can be statically bound (e.g., always
// monomorphic, so it has no inline cache). Patch code to resolved target.
JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread *thread))
methodHandle callee_method;
JRT_BLOCK
callee_method = SharedRuntime::resolve_helper(thread, true, true, CHECK_NULL);
thread->set_vm_result(callee_method());
JRT_BLOCK_END
// return compiled code entry point after potential safepoints
assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
return callee_method->verified_code_entry();
JRT_END
methodHandle SharedRuntime::handle_ic_miss_helper(JavaThread *thread, TRAPS) {
ResourceMark rm(thread);
CallInfo call_info;
Bytecodes::Code bc;
// receiver is NULL for static calls. An exception is thrown for NULL
// receivers for non-static calls
Handle receiver = find_callee_info(thread, bc, call_info,
CHECK_(methodHandle()));
// Compiler1 can produce virtual call sites that can actually be statically bound
// If we fell thru to below we would think that the site was going megamorphic
// when in fact the site can never miss. Worse because we'd think it was megamorphic
// we'd try and do a vtable dispatch however methods that can be statically bound
// don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a
// reresolution of the call site (as if we did a handle_wrong_method and not an
// plain ic_miss) and the site will be converted to an optimized virtual call site
// never to miss again. I don't believe C2 will produce code like this but if it
// did this would still be the correct thing to do for it too, hence no ifdef.
//
if (call_info.resolved_method()->can_be_statically_bound()) {
methodHandle callee_method = SharedRuntime::reresolve_call_site(thread, CHECK_(methodHandle()));
if (TraceCallFixup) {
RegisterMap reg_map(thread, false);
frame caller_frame = thread->last_frame().sender(®_map);
ResourceMark rm(thread);
tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc));
callee_method->print_short_name(tty);
tty->print_cr(" from pc: " INTPTR_FORMAT, caller_frame.pc());
tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code());
}
return callee_method;
}
methodHandle callee_method = call_info.selected_method();
bool should_be_mono = false;
#ifndef PRODUCT
Atomic::inc(&_ic_miss_ctr);
// Statistics & Tracing
if (TraceCallFixup) {
ResourceMark rm(thread);
tty->print("IC miss (%s) call to", Bytecodes::name(bc));
callee_method->print_short_name(tty);
tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code());
}
if (ICMissHistogram) {
MutexLocker m(VMStatistic_lock);
RegisterMap reg_map(thread, false);
frame f = thread->last_frame().real_sender(®_map);// skip runtime stub
// produce statistics under the lock
trace_ic_miss(f.pc());
}
#endif
// install an event collector so that when a vtable stub is created the
// profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
// event can't be posted when the stub is created as locks are held
// - instead the event will be deferred until the event collector goes
// out of scope.
JvmtiDynamicCodeEventCollector event_collector;
// Update inline cache to megamorphic. Skip update if caller has been
// made non-entrant or we are called from interpreted.
{ MutexLocker ml_patch (CompiledIC_lock);
RegisterMap reg_map(thread, false);
frame caller_frame = thread->last_frame().sender(®_map);
CodeBlob* cb = caller_frame.cb();
if (cb->is_nmethod() && ((nmethod*)cb)->is_in_use()) {
// Not a non-entrant nmethod, so find inline_cache
CompiledIC* inline_cache = CompiledIC_before(caller_frame.pc());
bool should_be_mono = false;
if (inline_cache->is_optimized()) {
if (TraceCallFixup) {
ResourceMark rm(thread);
tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc));
callee_method->print_short_name(tty);
tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code());
}
should_be_mono = true;
} else {
compiledICHolderOop ic_oop = (compiledICHolderOop) inline_cache->cached_oop();
if ( ic_oop != NULL && ic_oop->is_compiledICHolder()) {
if (receiver()->klass() == ic_oop->holder_klass()) {
// This isn't a real miss. We must have seen that compiled code
// is now available and we want the call site converted to a
// monomorphic compiled call site.
// We can't assert for callee_method->code() != NULL because it
// could have been deoptimized in the meantime
if (TraceCallFixup) {
ResourceMark rm(thread);
tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc));
callee_method->print_short_name(tty);
tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code());
}
should_be_mono = true;
}
}
}
if (should_be_mono) {
// We have a path that was monomorphic but was going interpreted
// and now we have (or had) a compiled entry. We correct the IC
// by using a new icBuffer.
CompiledICInfo info;
KlassHandle receiver_klass(THREAD, receiver()->klass());
inline_cache->compute_monomorphic_entry(callee_method,
receiver_klass,
inline_cache->is_optimized(),
false,
info, CHECK_(methodHandle()));
inline_cache->set_to_monomorphic(info);
} else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) {
// Change to megamorphic
inline_cache->set_to_megamorphic(&call_info, bc, CHECK_(methodHandle()));
} else {
// Either clean or megamorphic
}
}
} // Release CompiledIC_lock
return callee_method;
}
//
// Resets a call-site in compiled code so it will get resolved again.
// This routines handles both virtual call sites, optimized virtual call
// sites, and static call sites. Typically used to change a call sites
// destination from compiled to interpreted.
//
methodHandle SharedRuntime::reresolve_call_site(JavaThread *thread, TRAPS) {
ResourceMark rm(thread);
RegisterMap reg_map(thread, false);
frame stub_frame = thread->last_frame();
assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
frame caller = stub_frame.sender(®_map);
// Do nothing if the frame isn't a live compiled frame.
// nmethod could be deoptimized by the time we get here
// so no update to the caller is needed.
if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) {
address pc = caller.pc();
// Default call_addr is the location of the "basic" call.
// Determine the address of the call we a reresolving. With
// Inline Caches we will always find a recognizable call.
// With Inline Caches disabled we may or may not find a
// recognizable call. We will always find a call for static
// calls and for optimized virtual calls. For vanilla virtual
// calls it depends on the state of the UseInlineCaches switch.
//
// With Inline Caches disabled we can get here for a virtual call
// for two reasons:
// 1 - calling an abstract method. The vtable for abstract methods
// will run us thru handle_wrong_method and we will eventually
// end up in the interpreter to throw the ame.
// 2 - a racing deoptimization. We could be doing a vanilla vtable
// call and between the time we fetch the entry address and
// we jump to it the target gets deoptimized. Similar to 1
// we will wind up in the interprter (thru a c2i with c2).
//
address call_addr = NULL;
{
// Get call instruction under lock because another thread may be
// busy patching it.
MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag);
// Location of call instruction
if (NativeCall::is_call_before(pc)) {
NativeCall *ncall = nativeCall_before(pc);
call_addr = ncall->instruction_address();
}
}
// Check for static or virtual call
bool is_static_call = false;
nmethod* caller_nm = CodeCache::find_nmethod(pc);
// Make sure nmethod doesn't get deoptimized and removed until
// this is done with it.
// CLEANUP - with lazy deopt shouldn't need this lock
nmethodLocker nmlock(caller_nm);
if (call_addr != NULL) {
RelocIterator iter(caller_nm, call_addr, call_addr+1);
int ret = iter.next(); // Get item
if (ret) {
assert(iter.addr() == call_addr, "must find call");
if (iter.type() == relocInfo::static_call_type) {
is_static_call = true;
} else {
assert(iter.type() == relocInfo::virtual_call_type ||
iter.type() == relocInfo::opt_virtual_call_type
, "unexpected relocInfo. type");
}
} else {
assert(!UseInlineCaches, "relocation info. must exist for this address");
}
// Cleaning the inline cache will force a new resolve. This is more robust
// than directly setting it to the new destination, since resolving of calls
// is always done through the same code path. (experience shows that it
// leads to very hard to track down bugs, if an inline cache gets updated
// to a wrong method). It should not be performance critical, since the
// resolve is only done once.
MutexLocker ml(CompiledIC_lock);
//
// We do not patch the call site if the nmethod has been made non-entrant
// as it is a waste of time
//
if (caller_nm->is_in_use()) {
if (is_static_call) {
CompiledStaticCall* ssc= compiledStaticCall_at(call_addr);
ssc->set_to_clean();
} else {
// compiled, dispatched call (which used to call an interpreted method)
CompiledIC* inline_cache = CompiledIC_at(call_addr);
inline_cache->set_to_clean();
}
}
}
}
methodHandle callee_method = find_callee_method(thread, CHECK_(methodHandle()));
#ifndef PRODUCT
Atomic::inc(&_wrong_method_ctr);
if (TraceCallFixup) {
ResourceMark rm(thread);
tty->print("handle_wrong_method reresolving call to");
callee_method->print_short_name(tty);
tty->print_cr(" code: " INTPTR_FORMAT, callee_method->code());
}
#endif
return callee_method;
}
#ifdef ASSERT
void SharedRuntime::check_member_name_argument_is_last_argument(methodHandle method,
const BasicType* sig_bt,
const VMRegPair* regs) {
ResourceMark rm;
const int total_args_passed = method->size_of_parameters();
const VMRegPair* regs_with_member_name = regs;
VMRegPair* regs_without_member_name = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed - 1);
const int member_arg_pos = total_args_passed - 1;
assert(member_arg_pos >= 0 && member_arg_pos < total_args_passed, "oob");
assert(sig_bt[member_arg_pos] == T_OBJECT, "dispatch argument must be an object");
const bool is_outgoing = method->is_method_handle_intrinsic();
int comp_args_on_stack = java_calling_convention(sig_bt, regs_without_member_name, total_args_passed - 1, is_outgoing);
for (int i = 0; i < member_arg_pos; i++) {
VMReg a = regs_with_member_name[i].first();
VMReg b = regs_without_member_name[i].first();
assert(a->value() == b->value(), err_msg_res("register allocation mismatch: a=%d, b=%d", a->value(), b->value()));
}
assert(regs_with_member_name[member_arg_pos].first()->is_valid(), "bad member arg");
}
#endif
// ---------------------------------------------------------------------------
// We are calling the interpreter via a c2i. Normally this would mean that
// we were called by a compiled method. However we could have lost a race
// where we went int -> i2c -> c2i and so the caller could in fact be
// interpreted. If the caller is compiled we attempt to patch the caller
// so he no longer calls into the interpreter.
IRT_LEAF(void, SharedRuntime::fixup_callers_callsite(methodOopDesc* method, address caller_pc))
methodOop moop(method);
address entry_point = moop->from_compiled_entry();
// It's possible that deoptimization can occur at a call site which hasn't
// been resolved yet, in which case this function will be called from
// an nmethod that has been patched for deopt and we can ignore the
// request for a fixup.
// Also it is possible that we lost a race in that from_compiled_entry
// is now back to the i2c in that case we don't need to patch and if
// we did we'd leap into space because the callsite needs to use
// "to interpreter" stub in order to load up the methodOop. Don't
// ask me how I know this...
CodeBlob* cb = CodeCache::find_blob(caller_pc);
if (!cb->is_nmethod() || entry_point == moop->get_c2i_entry()) {
return;
}
// The check above makes sure this is a nmethod.
nmethod* nm = cb->as_nmethod_or_null();
assert(nm, "must be");
// Get the return PC for the passed caller PC.
address return_pc = caller_pc + frame::pc_return_offset;
// There is a benign race here. We could be attempting to patch to a compiled
// entry point at the same time the callee is being deoptimized. If that is
// the case then entry_point may in fact point to a c2i and we'd patch the
// call site with the same old data. clear_code will set code() to NULL
// at the end of it. If we happen to see that NULL then we can skip trying
// to patch. If we hit the window where the callee has a c2i in the
// from_compiled_entry and the NULL isn't present yet then we lose the race
// and patch the code with the same old data. Asi es la vida.
if (moop->code() == NULL) return;
if (nm->is_in_use()) {
// Expect to find a native call there (unless it was no-inline cache vtable dispatch)
MutexLockerEx ml_patch(Patching_lock, Mutex::_no_safepoint_check_flag);
if (NativeCall::is_call_before(return_pc)) {
NativeCall *call = nativeCall_before(return_pc);
//
// bug 6281185. We might get here after resolving a call site to a vanilla
// virtual call. Because the resolvee uses the verified entry it may then
// see compiled code and attempt to patch the site by calling us. This would
// then incorrectly convert the call site to optimized and its downhill from
// there. If you're lucky you'll get the assert in the bugid, if not you've
// just made a call site that could be megamorphic into a monomorphic site
// for the rest of its life! Just another racing bug in the life of
// fixup_callers_callsite ...
//
RelocIterator iter(nm, call->instruction_address(), call->next_instruction_address());
iter.next();
assert(iter.has_current(), "must have a reloc at java call site");
relocInfo::relocType typ = iter.reloc()->type();
if ( typ != relocInfo::static_call_type &&
typ != relocInfo::opt_virtual_call_type &&
typ != relocInfo::static_stub_type) {
return;
}
address destination = call->destination();
if (destination != entry_point) {
CodeBlob* callee = CodeCache::find_blob(destination);
// callee == cb seems weird. It means calling interpreter thru stub.
if (callee == cb || callee->is_adapter_blob()) {
// static call or optimized virtual
if (TraceCallFixup) {
tty->print("fixup callsite at " INTPTR_FORMAT " to compiled code for", caller_pc);
moop->print_short_name(tty);
tty->print_cr(" to " INTPTR_FORMAT, entry_point);
}
call->set_destination_mt_safe(entry_point);
} else {
if (TraceCallFixup) {
tty->print("failed to fixup callsite at " INTPTR_FORMAT " to compiled code for", caller_pc);
moop->print_short_name(tty);
tty->print_cr(" to " INTPTR_FORMAT, entry_point);
}
// assert is too strong could also be resolve destinations.
// assert(InlineCacheBuffer::contains(destination) || VtableStubs::contains(destination), "must be");
}
} else {
if (TraceCallFixup) {
tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", caller_pc);
moop->print_short_name(tty);
tty->print_cr(" to " INTPTR_FORMAT, entry_point);
}
}
}
}
IRT_END
// same as JVM_Arraycopy, but called directly from compiled code
JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos,
oopDesc* dest, jint dest_pos,
jint length,
JavaThread* thread)) {
#ifndef PRODUCT
_slow_array_copy_ctr++;
#endif
// Check if we have null pointers
if (src == NULL || dest == NULL) {
THROW(vmSymbols::java_lang_NullPointerException());
}
// Do the copy. The casts to arrayOop are necessary to the copy_array API,
// even though the copy_array API also performs dynamic checks to ensure
// that src and dest are truly arrays (and are conformable).
// The copy_array mechanism is awkward and could be removed, but
// the compilers don't call this function except as a last resort,
// so it probably doesn't matter.
Klass::cast(src->klass())->copy_array((arrayOopDesc*)src, src_pos,
(arrayOopDesc*)dest, dest_pos,
length, thread);
}
JRT_END
char* SharedRuntime::generate_class_cast_message(
JavaThread* thread, const char* objName) {
// Get target class name from the checkcast instruction
vframeStream vfst(thread, true);
assert(!vfst.at_end(), "Java frame must exist");
Bytecode_checkcast cc(vfst.method(), vfst.method()->bcp_from(vfst.bci()));
Klass* targetKlass = Klass::cast(vfst.method()->constants()->klass_at(
cc.index(), thread));
return generate_class_cast_message(objName, targetKlass->external_name());
}
char* SharedRuntime::generate_class_cast_message(
const char* objName, const char* targetKlassName, const char* desc) {
size_t msglen = strlen(objName) + strlen(desc) + strlen(targetKlassName) + 1;
char* message = NEW_RESOURCE_ARRAY(char, msglen);
if (NULL == message) {
// Shouldn't happen, but don't cause even more problems if it does
message = const_cast<char*>(objName);
} else {
jio_snprintf(message, msglen, "%s%s%s", objName, desc, targetKlassName);
}
return message;
}
JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
(void) JavaThread::current()->reguard_stack();
JRT_END
// Handles the uncommon case in locking, i.e., contention or an inflated lock.
#ifndef PRODUCT
int SharedRuntime::_monitor_enter_ctr=0;
#endif
JRT_ENTRY_NO_ASYNC(void, SharedRuntime::complete_monitor_locking_C(oopDesc* _obj, BasicLock* lock, JavaThread* thread))
oop obj(_obj);
#ifndef PRODUCT
_monitor_enter_ctr++; // monitor enter slow
#endif
if (PrintBiasedLockingStatistics) {
Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
}
Handle h_obj(THREAD, obj);
if (UseBiasedLocking) {
// Retry fast entry if bias is revoked to avoid unnecessary inflation
ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
} else {
ObjectSynchronizer::slow_enter(h_obj, lock, CHECK);
}
assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");
JRT_END
#ifndef PRODUCT
int SharedRuntime::_monitor_exit_ctr=0;
#endif
// Handles the uncommon cases of monitor unlocking in compiled code
JRT_LEAF(void, SharedRuntime::complete_monitor_unlocking_C(oopDesc* _obj, BasicLock* lock))
oop obj(_obj);
#ifndef PRODUCT
_monitor_exit_ctr++; // monitor exit slow
#endif
Thread* THREAD = JavaThread::current();
// I'm not convinced we need the code contained by MIGHT_HAVE_PENDING anymore
// testing was unable to ever fire the assert that guarded it so I have removed it.
assert(!HAS_PENDING_EXCEPTION, "Do we need code below anymore?");
#undef MIGHT_HAVE_PENDING
#ifdef MIGHT_HAVE_PENDING
// Save and restore any pending_exception around the exception mark.
// While the slow_exit must not throw an exception, we could come into
// this routine with one set.
oop pending_excep = NULL;
const char* pending_file;
int pending_line;
if (HAS_PENDING_EXCEPTION) {
pending_excep = PENDING_EXCEPTION;
pending_file = THREAD->exception_file();
pending_line = THREAD->exception_line();
CLEAR_PENDING_EXCEPTION;
}
#endif /* MIGHT_HAVE_PENDING */
{
// Exit must be non-blocking, and therefore no exceptions can be thrown.
EXCEPTION_MARK;
ObjectSynchronizer::slow_exit(obj, lock, THREAD);
}
#ifdef MIGHT_HAVE_PENDING
if (pending_excep != NULL) {
THREAD->set_pending_exception(pending_excep, pending_file, pending_line);
}
#endif /* MIGHT_HAVE_PENDING */
JRT_END
#ifndef PRODUCT
void SharedRuntime::print_statistics() {
ttyLocker ttyl;
if (xtty != NULL) xtty->head("statistics type='SharedRuntime'");
if (_monitor_enter_ctr ) tty->print_cr("%5d monitor enter slow", _monitor_enter_ctr);
if (_monitor_exit_ctr ) tty->print_cr("%5d monitor exit slow", _monitor_exit_ctr);
if (_throw_null_ctr) tty->print_cr("%5d implicit null throw", _throw_null_ctr);
SharedRuntime::print_ic_miss_histogram();
if (CountRemovableExceptions) {
if (_nof_removable_exceptions > 0) {
Unimplemented(); // this counter is not yet incremented
tty->print_cr("Removable exceptions: %d", _nof_removable_exceptions);
}
}
// Dump the JRT_ENTRY counters
if( _new_instance_ctr ) tty->print_cr("%5d new instance requires GC", _new_instance_ctr);
if( _new_array_ctr ) tty->print_cr("%5d new array requires GC", _new_array_ctr);
if( _multi1_ctr ) tty->print_cr("%5d multianewarray 1 dim", _multi1_ctr);
if( _multi2_ctr ) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr);
if( _multi3_ctr ) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr);
if( _multi4_ctr ) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr);
if( _multi5_ctr ) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr);
tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr );
tty->print_cr("%5d wrong method", _wrong_method_ctr );
tty->print_cr("%5d unresolved static call site", _resolve_static_ctr );
tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr );
tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr );
if( _mon_enter_stub_ctr ) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr );
if( _mon_exit_stub_ctr ) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr );
if( _mon_enter_ctr ) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr );
if( _mon_exit_ctr ) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr );
if( _partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr );
if( _jbyte_array_copy_ctr ) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr );
if( _jshort_array_copy_ctr ) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr );
if( _jint_array_copy_ctr ) tty->print_cr("%5d int array copies", _jint_array_copy_ctr );
if( _jlong_array_copy_ctr ) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr );
if( _oop_array_copy_ctr ) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr );
if( _checkcast_array_copy_ctr ) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr );
if( _unsafe_array_copy_ctr ) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr );
if( _generic_array_copy_ctr ) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr );
if( _slow_array_copy_ctr ) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr );
if( _find_handler_ctr ) tty->print_cr("%5d find exception handler", _find_handler_ctr );
if( _rethrow_ctr ) tty->print_cr("%5d rethrow handler", _rethrow_ctr );
AdapterHandlerLibrary::print_statistics();
if (xtty != NULL) xtty->tail("statistics");
}
inline double percent(int x, int y) {
return 100.0 * x / MAX2(y, 1);
}
class MethodArityHistogram {
public:
enum { MAX_ARITY = 256 };
private:
static int _arity_histogram[MAX_ARITY]; // histogram of #args
static int _size_histogram[MAX_ARITY]; // histogram of arg size in words
static int _max_arity; // max. arity seen
static int _max_size; // max. arg size seen
static void add_method_to_histogram(nmethod* nm) {
methodOop m = nm->method();
ArgumentCount args(m->signature());
int arity = args.size() + (m->is_static() ? 0 : 1);
int argsize = m->size_of_parameters();
arity = MIN2(arity, MAX_ARITY-1);
argsize = MIN2(argsize, MAX_ARITY-1);
int count = nm->method()->compiled_invocation_count();
_arity_histogram[arity] += count;
_size_histogram[argsize] += count;
_max_arity = MAX2(_max_arity, arity);
_max_size = MAX2(_max_size, argsize);
}
void print_histogram_helper(int n, int* histo, const char* name) {
const int N = MIN2(5, n);
tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
double sum = 0;
double weighted_sum = 0;
int i;
for (i = 0; i <= n; i++) { sum += histo[i]; weighted_sum += i*histo[i]; }
double rest = sum;
double percent = sum / 100;
for (i = 0; i <= N; i++) {
rest -= histo[i];
tty->print_cr("%4d: %7d (%5.1f%%)", i, histo[i], histo[i] / percent);
}
tty->print_cr("rest: %7d (%5.1f%%))", (int)rest, rest / percent);
tty->print_cr("(avg. %s = %3.1f, max = %d)", name, weighted_sum / sum, n);
}
void print_histogram() {
tty->print_cr("\nHistogram of call arity (incl. rcvr, calls to compiled methods only):");
print_histogram_helper(_max_arity, _arity_histogram, "arity");
tty->print_cr("\nSame for parameter size (in words):");
print_histogram_helper(_max_size, _size_histogram, "size");
tty->cr();
}
public:
MethodArityHistogram() {
MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
_max_arity = _max_size = 0;
for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram [i] = 0;
CodeCache::nmethods_do(add_method_to_histogram);
print_histogram();
}
};
int MethodArityHistogram::_arity_histogram[MethodArityHistogram::MAX_ARITY];
int MethodArityHistogram::_size_histogram[MethodArityHistogram::MAX_ARITY];
int MethodArityHistogram::_max_arity;
int MethodArityHistogram::_max_size;
void SharedRuntime::print_call_statistics(int comp_total) {
tty->print_cr("Calls from compiled code:");
int total = _nof_normal_calls + _nof_interface_calls + _nof_static_calls;
int mono_c = _nof_normal_calls - _nof_optimized_calls - _nof_megamorphic_calls;
int mono_i = _nof_interface_calls - _nof_optimized_interface_calls - _nof_megamorphic_interface_calls;
tty->print_cr("\t%9d (%4.1f%%) total non-inlined ", total, percent(total, total));
tty->print_cr("\t%9d (%4.1f%%) virtual calls ", _nof_normal_calls, percent(_nof_normal_calls, total));
tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_calls, percent(_nof_inlined_calls, _nof_normal_calls));
tty->print_cr("\t %9d (%3.0f%%) optimized ", _nof_optimized_calls, percent(_nof_optimized_calls, _nof_normal_calls));
tty->print_cr("\t %9d (%3.0f%%) monomorphic ", mono_c, percent(mono_c, _nof_normal_calls));
tty->print_cr("\t %9d (%3.0f%%) megamorphic ", _nof_megamorphic_calls, percent(_nof_megamorphic_calls, _nof_normal_calls));
tty->print_cr("\t%9d (%4.1f%%) interface calls ", _nof_interface_calls, percent(_nof_interface_calls, total));
tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_interface_calls, percent(_nof_inlined_interface_calls, _nof_interface_calls));
tty->print_cr("\t %9d (%3.0f%%) optimized ", _nof_optimized_interface_calls, percent(_nof_optimized_interface_calls, _nof_interface_calls));
tty->print_cr("\t %9d (%3.0f%%) monomorphic ", mono_i, percent(mono_i, _nof_interface_calls));
tty->print_cr("\t %9d (%3.0f%%) megamorphic ", _nof_megamorphic_interface_calls, percent(_nof_megamorphic_interface_calls, _nof_interface_calls));
tty->print_cr("\t%9d (%4.1f%%) static/special calls", _nof_static_calls, percent(_nof_static_calls, total));
tty->print_cr("\t %9d (%3.0f%%) inlined ", _nof_inlined_static_calls, percent(_nof_inlined_static_calls, _nof_static_calls));
tty->cr();
tty->print_cr("Note 1: counter updates are not MT-safe.");
tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
tty->print_cr(" %% in nested categories are relative to their category");
tty->print_cr(" (and thus add up to more than 100%% with inlining)");
tty->cr();
MethodArityHistogram h;
}
#endif
// A simple wrapper class around the calling convention information
// that allows sharing of adapters for the same calling convention.
class AdapterFingerPrint : public CHeapObj<mtCode> {
private:
enum {
_basic_type_bits = 4,
_basic_type_mask = right_n_bits(_basic_type_bits),
_basic_types_per_int = BitsPerInt / _basic_type_bits,
_compact_int_count = 3
};
// TO DO: Consider integrating this with a more global scheme for compressing signatures.
// For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
union {
int _compact[_compact_int_count];
int* _fingerprint;
} _value;
int _length; // A negative length indicates the fingerprint is in the compact form,
// Otherwise _value._fingerprint is the array.
// Remap BasicTypes that are handled equivalently by the adapters.
// These are correct for the current system but someday it might be
// necessary to make this mapping platform dependent.
static int adapter_encoding(BasicType in) {
switch(in) {
case T_BOOLEAN:
case T_BYTE:
case T_SHORT:
case T_CHAR:
// There are all promoted to T_INT in the calling convention
return T_INT;
case T_OBJECT:
case T_ARRAY:
// In other words, we assume that any register good enough for
// an int or long is good enough for a managed pointer.
#ifdef _LP64
return T_LONG;
#else
return T_INT;
#endif
case T_INT:
case T_LONG:
case T_FLOAT:
case T_DOUBLE:
case T_VOID:
return in;
default:
ShouldNotReachHere();
return T_CONFLICT;
}
}
public:
AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) {
// The fingerprint is based on the BasicType signature encoded
// into an array of ints with eight entries per int.
int* ptr;
int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
if (len <= _compact_int_count) {
assert(_compact_int_count == 3, "else change next line");
_value._compact[0] = _value._compact[1] = _value._compact[2] = 0;
// Storing the signature encoded as signed chars hits about 98%
// of the time.
_length = -len;
ptr = _value._compact;
} else {
_length = len;
_value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode);
ptr = _value._fingerprint;
}
// Now pack the BasicTypes with 8 per int
int sig_index = 0;
for (int index = 0; index < len; index++) {
int value = 0;
for (int byte = 0; byte < _basic_types_per_int; byte++) {
int bt = ((sig_index < total_args_passed)
? adapter_encoding(sig_bt[sig_index++])
: 0);
assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
value = (value << _basic_type_bits) | bt;
}
ptr[index] = value;
}
}
~AdapterFingerPrint() {
if (_length > 0) {
FREE_C_HEAP_ARRAY(int, _value._fingerprint, mtCode);
}
}
int value(int index) {
if (_length < 0) {
return _value._compact[index];
}
return _value._fingerprint[index];
}
int length() {
if (_length < 0) return -_length;
return _length;
}
bool is_compact() {
return _length <= 0;
}
unsigned int compute_hash() {
int hash = 0;
for (int i = 0; i < length(); i++) {
int v = value(i);
hash = (hash << 8) ^ v ^ (hash >> 5);
}
return (unsigned int)hash;
}
const char* as_string() {
stringStream st;
st.print("0x");
for (int i = 0; i < length(); i++) {
st.print("%08x", value(i));
}
return st.as_string();
}
bool equals(AdapterFingerPrint* other) {
if (other->_length != _length) {
return false;
}
if (_length < 0) {
assert(_compact_int_count == 3, "else change next line");
return _value._compact[0] == other->_value._compact[0] &&
_value._compact[1] == other->_value._compact[1] &&
_value._compact[2] == other->_value._compact[2];
} else {
for (int i = 0; i < _length; i++) {
if (_value._fingerprint[i] != other->_value._fingerprint[i]) {
return false;
}
}
}
return true;
}
};
// A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
class AdapterHandlerTable : public BasicHashtable<mtCode> {
friend class AdapterHandlerTableIterator;
private:
#ifndef PRODUCT
static int _lookups; // number of calls to lookup
static int _buckets; // number of buckets checked
static int _equals; // number of buckets checked with matching hash
static int _hits; // number of successful lookups
static int _compact; // number of equals calls with compact signature
#endif
AdapterHandlerEntry* bucket(int i) {
return (AdapterHandlerEntry*)BasicHashtable<mtCode>::bucket(i);
}
public:
AdapterHandlerTable()
: BasicHashtable<mtCode>(293, sizeof(AdapterHandlerEntry)) { }
// Create a new entry suitable for insertion in the table
AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry, address c2i_unverified_entry) {
AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable<mtCode>::new_entry(fingerprint->compute_hash());
entry->init(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
return entry;
}
// Insert an entry into the table
void add(AdapterHandlerEntry* entry) {
int index = hash_to_index(entry->hash());
add_entry(index, entry);
}
void free_entry(AdapterHandlerEntry* entry) {
entry->deallocate();
BasicHashtable<mtCode>::free_entry(entry);
}
// Find a entry with the same fingerprint if it exists
AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) {
NOT_PRODUCT(_lookups++);
AdapterFingerPrint fp(total_args_passed, sig_bt);
unsigned int hash = fp.compute_hash();
int index = hash_to_index(hash);
for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
NOT_PRODUCT(_buckets++);
if (e->hash() == hash) {
NOT_PRODUCT(_equals++);
if (fp.equals(e->fingerprint())) {
#ifndef PRODUCT
if (fp.is_compact()) _compact++;
_hits++;
#endif
return e;
}
}
}
return NULL;
}
#ifndef PRODUCT
void print_statistics() {
ResourceMark rm;
int longest = 0;
int empty = 0;
int total = 0;
int nonempty = 0;
for (int index = 0; index < table_size(); index++) {
int count = 0;
for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
count++;
}
if (count != 0) nonempty++;
if (count == 0) empty++;
if (count > longest) longest = count;
total += count;
}
tty->print_cr("AdapterHandlerTable: empty %d longest %d total %d average %f",
empty, longest, total, total / (double)nonempty);
tty->print_cr("AdapterHandlerTable: lookups %d buckets %d equals %d hits %d compact %d",
_lookups, _buckets, _equals, _hits, _compact);
}
#endif
};
#ifndef PRODUCT
int AdapterHandlerTable::_lookups;
int AdapterHandlerTable::_buckets;
int AdapterHandlerTable::_equals;
int AdapterHandlerTable::_hits;
int AdapterHandlerTable::_compact;
#endif
class AdapterHandlerTableIterator : public StackObj {
private:
AdapterHandlerTable* _table;
int _index;
AdapterHandlerEntry* _current;
void scan() {
while (_index < _table->table_size()) {
AdapterHandlerEntry* a = _table->bucket(_index);
_index++;
if (a != NULL) {
_current = a;
return;
}
}
}
public:
AdapterHandlerTableIterator(AdapterHandlerTable* table): _table(table), _index(0), _current(NULL) {
scan();
}
bool has_next() {
return _current != NULL;
}
AdapterHandlerEntry* next() {
if (_current != NULL) {
AdapterHandlerEntry* result = _current;
_current = _current->next();
if (_current == NULL) scan();
return result;
} else {
return NULL;
}
}
};
// ---------------------------------------------------------------------------
// Implementation of AdapterHandlerLibrary
AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL;
AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL;
const int AdapterHandlerLibrary_size = 16*K;
BufferBlob* AdapterHandlerLibrary::_buffer = NULL;
BufferBlob* AdapterHandlerLibrary::buffer_blob() {
// Should be called only when AdapterHandlerLibrary_lock is active.
if (_buffer == NULL) // Initialize lazily
_buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
return _buffer;
}
void AdapterHandlerLibrary::initialize() {
if (_adapters != NULL) return;
_adapters = new AdapterHandlerTable();
// Create a special handler for abstract methods. Abstract methods
// are never compiled so an i2c entry is somewhat meaningless, but
// fill it in with something appropriate just in case. Pass handle
// wrong method for the c2i transitions.
address wrong_method = SharedRuntime::get_handle_wrong_method_stub();
_abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL),
StubRoutines::throw_AbstractMethodError_entry(),
wrong_method, wrong_method);
}
AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint,
address i2c_entry,
address c2i_entry,
address c2i_unverified_entry) {
return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
}
AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(methodHandle method) {
// Use customized signature handler. Need to lock around updates to
// the AdapterHandlerTable (it is not safe for concurrent readers
// and a single writer: this could be fixed if it becomes a
// problem).
// Get the address of the ic_miss handlers before we grab the
// AdapterHandlerLibrary_lock. This fixes bug 6236259 which
// was caused by the initialization of the stubs happening
// while we held the lock and then notifying jvmti while
// holding it. This just forces the initialization to be a little
// earlier.
address ic_miss = SharedRuntime::get_ic_miss_stub();
assert(ic_miss != NULL, "must have handler");
ResourceMark rm;
NOT_PRODUCT(int insts_size);
AdapterBlob* B = NULL;
AdapterHandlerEntry* entry = NULL;
AdapterFingerPrint* fingerprint = NULL;
{
MutexLocker mu(AdapterHandlerLibrary_lock);
// make sure data structure is initialized
initialize();
if (method->is_abstract()) {
return _abstract_method_handler;
}
// Fill in the signature array, for the calling-convention call.
int total_args_passed = method->size_of_parameters(); // All args on stack
BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
int i = 0;
if (!method->is_static()) // Pass in receiver first
sig_bt[i++] = T_OBJECT;
for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) {
sig_bt[i++] = ss.type(); // Collect remaining bits of signature
if (ss.type() == T_LONG || ss.type() == T_DOUBLE)
sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots
}
assert(i == total_args_passed, "");
// Lookup method signature's fingerprint
entry = _adapters->lookup(total_args_passed, sig_bt);
#ifdef ASSERT
AdapterHandlerEntry* shared_entry = NULL;
if (VerifyAdapterSharing && entry != NULL) {
shared_entry = entry;
entry = NULL;
}
#endif
if (entry != NULL) {
return entry;
}
// Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, false);
// Make a C heap allocated version of the fingerprint to store in the adapter
fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt);
// Create I2C & C2I handlers
BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
if (buf != NULL) {
CodeBuffer buffer(buf);
short buffer_locs[20];
buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
sizeof(buffer_locs)/sizeof(relocInfo));
MacroAssembler _masm(&buffer);
entry = SharedRuntime::generate_i2c2i_adapters(&_masm,
total_args_passed,
comp_args_on_stack,
sig_bt,
regs,
fingerprint);
#ifdef ASSERT
if (VerifyAdapterSharing) {
if (shared_entry != NULL) {
assert(shared_entry->compare_code(buf->code_begin(), buffer.insts_size(), total_args_passed, sig_bt),
"code must match");
// Release the one just created and return the original
_adapters->free_entry(entry);
return shared_entry;
} else {
entry->save_code(buf->code_begin(), buffer.insts_size(), total_args_passed, sig_bt);
}
}
#endif
B = AdapterBlob::create(&buffer);
NOT_PRODUCT(insts_size = buffer.insts_size());
}
if (B == NULL) {
// CodeCache is full, disable compilation
// Ought to log this but compile log is only per compile thread
// and we're some non descript Java thread.
MutexUnlocker mu(AdapterHandlerLibrary_lock);
CompileBroker::handle_full_code_cache();
return NULL; // Out of CodeCache space
}
entry->relocate(B->content_begin());
#ifndef PRODUCT
// debugging suppport
if (PrintAdapterHandlers || PrintStubCode) {
ttyLocker ttyl;
entry->print_adapter_on(tty);
tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)",
_adapters->number_of_entries(), (method->is_static() ? "static" : "receiver"),
method->signature()->as_C_string(), insts_size);
tty->print_cr("c2i argument handler starts at %p",entry->get_c2i_entry());
if (Verbose || PrintStubCode) {
address first_pc = entry->base_address();
if (first_pc != NULL) {
Disassembler::decode(first_pc, first_pc + insts_size);
tty->cr();
}
}
}
#endif
_adapters->add(entry);
}
// Outside of the lock
if (B != NULL) {
char blob_id[256];
jio_snprintf(blob_id,
sizeof(blob_id),
"%s(%s)@" PTR_FORMAT,
B->name(),
fingerprint->as_string(),
B->content_begin());
Forte::register_stub(blob_id, B->content_begin(), B->content_end());
if (JvmtiExport::should_post_dynamic_code_generated()) {
JvmtiExport::post_dynamic_code_generated(blob_id, B->content_begin(), B->content_end());
}
}
return entry;
}
address AdapterHandlerEntry::base_address() {
address base = _i2c_entry;
if (base == NULL) base = _c2i_entry;
assert(base <= _c2i_entry || _c2i_entry == NULL, "");
assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == NULL, "");
return base;
}
void AdapterHandlerEntry::relocate(address new_base) {
address old_base = base_address();
assert(old_base != NULL, "");
ptrdiff_t delta = new_base - old_base;
if (_i2c_entry != NULL)
_i2c_entry += delta;
if (_c2i_entry != NULL)
_c2i_entry += delta;
if (_c2i_unverified_entry != NULL)
_c2i_unverified_entry += delta;
assert(base_address() == new_base, "");
}
void AdapterHandlerEntry::deallocate() {
delete _fingerprint;
#ifdef ASSERT
if (_saved_code) FREE_C_HEAP_ARRAY(unsigned char, _saved_code, mtCode);
if (_saved_sig) FREE_C_HEAP_ARRAY(Basictype, _saved_sig, mtCode);
#endif
}
#ifdef ASSERT
// Capture the code before relocation so that it can be compared
// against other versions. If the code is captured after relocation
// then relative instructions won't be equivalent.
void AdapterHandlerEntry::save_code(unsigned char* buffer, int length, int total_args_passed, BasicType* sig_bt) {
_saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
_code_length = length;
memcpy(_saved_code, buffer, length);
_total_args_passed = total_args_passed;
_saved_sig = NEW_C_HEAP_ARRAY(BasicType, _total_args_passed, mtCode);
memcpy(_saved_sig, sig_bt, _total_args_passed * sizeof(BasicType));
}
bool AdapterHandlerEntry::compare_code(unsigned char* buffer, int length, int total_args_passed, BasicType* sig_bt) {
if (length != _code_length) {
return false;
}
for (int i = 0; i < length; i++) {
if (buffer[i] != _saved_code[i]) {
return false;
}
}
return true;
}
#endif
// Create a native wrapper for this native method. The wrapper converts the
// java compiled calling convention to the native convention, handlizes
// arguments, and transitions to native. On return from the native we transition
// back to java blocking if a safepoint is in progress.
nmethod *AdapterHandlerLibrary::create_native_wrapper(methodHandle method, int compile_id) {
ResourceMark rm;
nmethod* nm = NULL;
assert(method->is_native(), "must be native");
assert(method->is_method_handle_intrinsic() ||
method->has_native_function(), "must have something valid to call!");
{
// perform the work while holding the lock, but perform any printing outside the lock
MutexLocker mu(AdapterHandlerLibrary_lock);
// See if somebody beat us to it
nm = method->code();
if (nm) {
return nm;
}
ResourceMark rm;
BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
if (buf != NULL) {
CodeBuffer buffer(buf);
double locs_buf[20];
buffer.insts()->initialize_shared_locs((relocInfo*)locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
MacroAssembler _masm(&buffer);
// Fill in the signature array, for the calling-convention call.
const int total_args_passed = method->size_of_parameters();
BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
int i=0;
if( !method->is_static() ) // Pass in receiver first
sig_bt[i++] = T_OBJECT;
SignatureStream ss(method->signature());
for( ; !ss.at_return_type(); ss.next()) {
sig_bt[i++] = ss.type(); // Collect remaining bits of signature
if( ss.type() == T_LONG || ss.type() == T_DOUBLE )
sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots
}
assert(i == total_args_passed, "");
BasicType ret_type = ss.type();
// Now get the compiled-Java layout as input (or output) arguments.
// NOTE: Stubs for compiled entry points of method handle intrinsics
// are just trampolines so the argument registers must be outgoing ones.
const bool is_outgoing = method->is_method_handle_intrinsic();
int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed, is_outgoing);
// Generate the compiled-to-native wrapper code
nm = SharedRuntime::generate_native_wrapper(&_masm,
method,
compile_id,
sig_bt,
regs,
ret_type);
}
}
// Must unlock before calling set_code
// Install the generated code.
if (nm != NULL) {
if (PrintCompilation) {
ttyLocker ttyl;
CompileTask::print_compilation(tty, nm, method->is_static() ? "(static)" : "");
}
method->set_code(method, nm);
nm->post_compiled_method_load_event();
} else {
// CodeCache is full, disable compilation
CompileBroker::handle_full_code_cache();
}
return nm;
}
JRT_ENTRY_NO_ASYNC(void, SharedRuntime::block_for_jni_critical(JavaThread* thread))
assert(thread == JavaThread::current(), "must be");
// The code is about to enter a JNI lazy critical native method and
// _needs_gc is true, so if this thread is already in a critical
// section then just return, otherwise this thread should block
// until needs_gc has been cleared.
if (thread->in_critical()) {
return;
}
// Lock and unlock a critical section to give the system a chance to block
GC_locker::lock_critical(thread);
GC_locker::unlock_critical(thread);
JRT_END
#ifdef HAVE_DTRACE_H
// Create a dtrace nmethod for this method. The wrapper converts the
// java compiled calling convention to the native convention, makes a dummy call
// (actually nops for the size of the call instruction, which become a trap if
// probe is enabled). The returns to the caller. Since this all looks like a
// leaf no thread transition is needed.
nmethod *AdapterHandlerLibrary::create_dtrace_nmethod(methodHandle method) {
ResourceMark rm;
nmethod* nm = NULL;
if (PrintCompilation) {
ttyLocker ttyl;
tty->print("--- n%s ");
method->print_short_name(tty);
if (method->is_static()) {
tty->print(" (static)");
}
tty->cr();
}
{
// perform the work while holding the lock, but perform any printing
// outside the lock
MutexLocker mu(AdapterHandlerLibrary_lock);
// See if somebody beat us to it
nm = method->code();
if (nm) {
return nm;
}
ResourceMark rm;
BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
if (buf != NULL) {
CodeBuffer buffer(buf);
// Need a few relocation entries
double locs_buf[20];
buffer.insts()->initialize_shared_locs(
(relocInfo*)locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
MacroAssembler _masm(&buffer);
// Generate the compiled-to-native wrapper code
nm = SharedRuntime::generate_dtrace_nmethod(&_masm, method);
}
}
return nm;
}
// the dtrace method needs to convert java lang string to utf8 string.
void SharedRuntime::get_utf(oopDesc* src, address dst) {
typeArrayOop jlsValue = java_lang_String::value(src);
int jlsOffset = java_lang_String::offset(src);
int jlsLen = java_lang_String::length(src);
jchar* jlsPos = (jlsLen == 0) ? NULL :
jlsValue->char_at_addr(jlsOffset);
assert(typeArrayKlass::cast(jlsValue->klass())->element_type() == T_CHAR, "compressed string");
(void) UNICODE::as_utf8(jlsPos, jlsLen, (char *)dst, max_dtrace_string_size);
}
#endif // ndef HAVE_DTRACE_H
// -------------------------------------------------------------------------
// Java-Java calling convention
// (what you use when Java calls Java)
//------------------------------name_for_receiver----------------------------------
// For a given signature, return the VMReg for parameter 0.
VMReg SharedRuntime::name_for_receiver() {
VMRegPair regs;
BasicType sig_bt = T_OBJECT;
(void) java_calling_convention(&sig_bt, ®s, 1, true);
// Return argument 0 register. In the LP64 build pointers
// take 2 registers, but the VM wants only the 'main' name.
return regs.first();
}
VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, int* arg_size) {
// This method is returning a data structure allocating as a
// ResourceObject, so do not put any ResourceMarks in here.
char *s = sig->as_C_string();
int len = (int)strlen(s);
*s++; len--; // Skip opening paren
char *t = s+len;
while( *(--t) != ')' ) ; // Find close paren
BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, 256 );
VMRegPair *regs = NEW_RESOURCE_ARRAY( VMRegPair, 256 );
int cnt = 0;
if (has_receiver) {
sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature
}
while( s < t ) {
switch( *s++ ) { // Switch on signature character
case 'B': sig_bt[cnt++] = T_BYTE; break;
case 'C': sig_bt[cnt++] = T_CHAR; break;
case 'D': sig_bt[cnt++] = T_DOUBLE; sig_bt[cnt++] = T_VOID; break;
case 'F': sig_bt[cnt++] = T_FLOAT; break;
case 'I': sig_bt[cnt++] = T_INT; break;
case 'J': sig_bt[cnt++] = T_LONG; sig_bt[cnt++] = T_VOID; break;
case 'S': sig_bt[cnt++] = T_SHORT; break;
case 'Z': sig_bt[cnt++] = T_BOOLEAN; break;
case 'V': sig_bt[cnt++] = T_VOID; break;
case 'L': // Oop
while( *s++ != ';' ) ; // Skip signature
sig_bt[cnt++] = T_OBJECT;
break;
case '[': { // Array
do { // Skip optional size
while( *s >= '0' && *s <= '9' ) s++;
} while( *s++ == '[' ); // Nested arrays?
// Skip element type
if( s[-1] == 'L' )
while( *s++ != ';' ) ; // Skip signature
sig_bt[cnt++] = T_ARRAY;
break;
}
default : ShouldNotReachHere();
}
}
assert( cnt < 256, "grow table size" );
int comp_args_on_stack;
comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt, true);
// the calling convention doesn't count out_preserve_stack_slots so
// we must add that in to get "true" stack offsets.
if (comp_args_on_stack) {
for (int i = 0; i < cnt; i++) {
VMReg reg1 = regs[i].first();
if( reg1->is_stack()) {
// Yuck
reg1 = reg1->bias(out_preserve_stack_slots());
}
VMReg reg2 = regs[i].second();
if( reg2->is_stack()) {
// Yuck
reg2 = reg2->bias(out_preserve_stack_slots());
}
regs[i].set_pair(reg2, reg1);
}
}
// results
*arg_size = cnt;
return regs;
}
// OSR Migration Code
//
// This code is used convert interpreter frames into compiled frames. It is
// called from very start of a compiled OSR nmethod. A temp array is
// allocated to hold the interesting bits of the interpreter frame. All
// active locks are inflated to allow them to move. The displaced headers and
// active interpeter locals are copied into the temp buffer. Then we return
// back to the compiled code. The compiled code then pops the current
// interpreter frame off the stack and pushes a new compiled frame. Then it
// copies the interpreter locals and displaced headers where it wants.
// Finally it calls back to free the temp buffer.
//
// All of this is done NOT at any Safepoint, nor is any safepoint or GC allowed.
JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) )
#ifdef IA64
ShouldNotReachHere(); // NYI
#endif /* IA64 */
//
// This code is dependent on the memory layout of the interpreter local
// array and the monitors. On all of our platforms the layout is identical
// so this code is shared. If some platform lays the their arrays out
// differently then this code could move to platform specific code or
// the code here could be modified to copy items one at a time using
// frame accessor methods and be platform independent.
frame fr = thread->last_frame();
assert( fr.is_interpreted_frame(), "" );
assert( fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks" );
// Figure out how many monitors are active.
int active_monitor_count = 0;
for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
kptr < fr.interpreter_frame_monitor_begin();
kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
if( kptr->obj() != NULL ) active_monitor_count++;
}
// QQQ we could place number of active monitors in the array so that compiled code
// could double check it.
methodOop moop = fr.interpreter_frame_method();
int max_locals = moop->max_locals();
// Allocate temp buffer, 1 word per local & 2 per active monitor
int buf_size_words = max_locals + active_monitor_count*2;
intptr_t *buf = NEW_C_HEAP_ARRAY(intptr_t,buf_size_words, mtCode);
// Copy the locals. Order is preserved so that loading of longs works.
// Since there's no GC I can copy the oops blindly.
assert( sizeof(HeapWord)==sizeof(intptr_t), "fix this code");
Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1),
(HeapWord*)&buf[0],
max_locals);
// Inflate locks. Copy the displaced headers. Be careful, there can be holes.
int i = max_locals;
for( BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end();
kptr2 < fr.interpreter_frame_monitor_begin();
kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) {
if( kptr2->obj() != NULL) { // Avoid 'holes' in the monitor array
BasicLock *lock = kptr2->lock();
// Inflate so the displaced header becomes position-independent
if (lock->displaced_header()->is_unlocked())
ObjectSynchronizer::inflate_helper(kptr2->obj());
// Now the displaced header is free to move
buf[i++] = (intptr_t)lock->displaced_header();
buf[i++] = (intptr_t)kptr2->obj();
}
}
assert( i - max_locals == active_monitor_count*2, "found the expected number of monitors" );
return buf;
JRT_END
JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) )
FREE_C_HEAP_ARRAY(intptr_t,buf, mtCode);
JRT_END
bool AdapterHandlerLibrary::contains(CodeBlob* b) {
AdapterHandlerTableIterator iter(_adapters);
while (iter.has_next()) {
AdapterHandlerEntry* a = iter.next();
if ( b == CodeCache::find_blob(a->get_i2c_entry()) ) return true;
}
return false;
}
void AdapterHandlerLibrary::print_handler_on(outputStream* st, CodeBlob* b) {
AdapterHandlerTableIterator iter(_adapters);
while (iter.has_next()) {
AdapterHandlerEntry* a = iter.next();
if (b == CodeCache::find_blob(a->get_i2c_entry())) {
st->print("Adapter for signature: ");
a->print_adapter_on(tty);
return;
}
}
assert(false, "Should have found handler");
}
void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
st->print_cr("AHE@" INTPTR_FORMAT ": %s i2c: " INTPTR_FORMAT " c2i: " INTPTR_FORMAT " c2iUV: " INTPTR_FORMAT,
(intptr_t) this, fingerprint()->as_string(),
get_i2c_entry(), get_c2i_entry(), get_c2i_unverified_entry());
}
#ifndef PRODUCT
void AdapterHandlerLibrary::print_statistics() {
_adapters->print_statistics();
}
#endif /* PRODUCT */
| 38.44159 | 174 | 0.681386 | codefollower |
709ddee84ea005adf095e8279af54bf701ff399b | 22,533 | hpp | C++ | viennacl/linalg/cuda/bisect_util.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | viennacl/linalg/cuda/bisect_util.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | viennacl/linalg/cuda/bisect_util.hpp | denis14/ViennaCL-1.5.2 | fec808905cca30196e10126681611bdf8da5297a | [
"MIT"
] | null | null | null | #ifndef VIENNACL_LINALG_CUDA_BISECT_BISECT_UTIL_HPP_
#define VIENNACL_LINALG_CUDA_BISECT_BISECT_UTIL_HPP_
/* =========================================================================
Copyright (c) 2010-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/cuda/bisect_kernel_small.hpp
@brief Utility / shared functionality for bisection kernels
Implementation based on the sample provided with the CUDA 6.0 SDK, for which
the creation of derivative works is allowed by including the following statement:
"This software contains source code provided by NVIDIA Corporation."
*/
// includes, project
#include "viennacl/linalg/detail/bisect/config.hpp"
#include "viennacl/linalg/detail/bisect/util.hpp"
namespace viennacl
{
namespace linalg
{
namespace cuda
{
////////////////////////////////////////////////////////////////////////////////
//! Compute the next lower power of two of n
//! @param n number for which next higher power of two is seeked
////////////////////////////////////////////////////////////////////////////////
__device__
inline int
floorPow2(int n)
{
// early out if already power of two
if (0 == (n & (n-1)))
{
return n;
}
int exp;
frexp((float)n, &exp);
return (1 << (exp - 1));
}
////////////////////////////////////////////////////////////////////////////////
//! Compute the next higher power of two of n
//! @param n number for which next higher power of two is seeked
////////////////////////////////////////////////////////////////////////////////
__device__
inline int
ceilPow2(int n)
{
// early out if already power of two
if (0 == (n & (n-1)))
{
return n;
}
int exp;
frexp((float)n, &exp);
return (1 << exp);
}
////////////////////////////////////////////////////////////////////////////////
//! Compute midpoint of interval [\a left, \a right] avoiding overflow if
//! possible
//! @param left left / lower limit of interval
//! @param right right / upper limit of interval
////////////////////////////////////////////////////////////////////////////////
template<typename NumericT>
__device__
inline NumericT
computeMidpoint(const NumericT left, const NumericT right)
{
NumericT mid;
if (viennacl::linalg::detail::sign_f(left) == viennacl::linalg::detail::sign_f(right))
{
mid = left + (right - left) * 0.5f;
}
else
{
mid = (left + right) * 0.5f;
}
return mid;
}
////////////////////////////////////////////////////////////////////////////////
//! Check if interval converged and store appropriately
//! @param addr address where to store the information of the interval
//! @param s_left shared memory storage for left interval limits
//! @param s_right shared memory storage for right interval limits
//! @param s_left_count shared memory storage for number of eigenvalues less
//! than left interval limits
//! @param s_right_count shared memory storage for number of eigenvalues less
//! than right interval limits
//! @param left lower limit of interval
//! @param right upper limit of interval
//! @param left_count eigenvalues less than \a left
//! @param right_count eigenvalues less than \a right
//! @param precision desired precision for eigenvalues
////////////////////////////////////////////////////////////////////////////////
template<class S, class T, class NumericT>
__device__
void
storeInterval(unsigned int addr,
NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
NumericT left, NumericT right,
S left_count, S right_count,
NumericT precision)
{
s_left_count[addr] = left_count;
s_right_count[addr] = right_count;
// check if interval converged
NumericT t0 = abs(right - left);
NumericT t1 = max(abs(left), abs(right)) * precision;
if (t0 <= max(static_cast<NumericT>(MIN_ABS_INTERVAL), t1))
{
// compute mid point
NumericT lambda = computeMidpoint(left, right);
// mark as converged
s_left[addr] = lambda;
s_right[addr] = lambda;
}
else
{
// store current limits
s_left[addr] = left;
s_right[addr] = right;
}
}
////////////////////////////////////////////////////////////////////////////////
//! Compute number of eigenvalues that are smaller than x given a symmetric,
//! real, and tridiagonal matrix
//! @param g_d diagonal elements stored in global memory
//! @param g_s superdiagonal elements stored in global memory
//! @param n size of matrix
//! @param x value for which the number of eigenvalues that are smaller is
//! seeked
//! @param tid thread identified (e.g. threadIdx.x or gtid)
//! @param num_intervals_active number of active intervals / threads that
//! currently process an interval
//! @param s_d scratch space to store diagonal entries of the tridiagonal
//! matrix in shared memory
//! @param s_s scratch space to store superdiagonal entries of the tridiagonal
//! matrix in shared memory
//! @param converged flag if the current thread is already converged (that
//! is count does not have to be computed)
////////////////////////////////////////////////////////////////////////////////
template<typename NumericT>
__device__
inline unsigned int
computeNumSmallerEigenvals(const NumericT *g_d, const NumericT *g_s, const unsigned int n,
const NumericT x,
const unsigned int tid,
const unsigned int num_intervals_active,
NumericT *s_d, NumericT *s_s,
unsigned int converged
)
{
NumericT delta = 1.0f;
unsigned int count = 0;
__syncthreads();
// read data into shared memory
if (threadIdx.x < n)
{
s_d[threadIdx.x] = *(g_d + threadIdx.x);
s_s[threadIdx.x] = *(g_s + threadIdx.x - 1);
}
__syncthreads();
// perform loop only for active threads
if ((tid < num_intervals_active) && (0 == converged))
{
// perform (optimized) Gaussian elimination to determine the number
// of eigenvalues that are smaller than n
for (unsigned int k = 0; k < n; ++k)
{
delta = s_d[k] - x - (s_s[k] * s_s[k]) / delta;
count += (delta < 0) ? 1 : 0;
}
} // end if thread currently processing an interval
return count;
}
////////////////////////////////////////////////////////////////////////////////
//! Compute number of eigenvalues that are smaller than x given a symmetric,
//! real, and tridiagonal matrix
//! @param g_d diagonal elements stored in global memory
//! @param g_s superdiagonal elements stored in global memory
//! @param n size of matrix
//! @param x value for which the number of eigenvalues that are smaller is
//! seeked
//! @param tid thread identified (e.g. threadIdx.x or gtid)
//! @param num_intervals_active number of active intervals / threads that
//! currently process an interval
//! @param s_d scratch space to store diagonal entries of the tridiagonal
//! matrix in shared memory
//! @param s_s scratch space to store superdiagonal entries of the tridiagonal
//! matrix in shared memory
//! @param converged flag if the current thread is already converged (that
//! is count does not have to be computed)
////////////////////////////////////////////////////////////////////////////////
template<typename NumericT>
__device__
inline unsigned int
computeNumSmallerEigenvalsLarge(const NumericT *g_d, const NumericT *g_s, const unsigned int n,
const NumericT x,
const unsigned int tid,
const unsigned int num_intervals_active,
NumericT *s_d, NumericT *s_s,
unsigned int converged
)
{
NumericT delta = 1.0f;
unsigned int count = 0;
unsigned int rem = n;
// do until whole diagonal and superdiagonal has been loaded and processed
for (unsigned int i = 0; i < n; i += blockDim.x)
{
__syncthreads();
// read new chunk of data into shared memory
if ((i + threadIdx.x) < n)
{
s_d[threadIdx.x] = *(g_d + i + threadIdx.x);
s_s[threadIdx.x] = *(g_s + i + threadIdx.x - 1);
}
__syncthreads();
if (tid < num_intervals_active)
{
// perform (optimized) Gaussian elimination to determine the number
// of eigenvalues that are smaller than n
for (unsigned int k = 0; k < min(rem,blockDim.x); ++k)
{
delta = s_d[k] - x - (s_s[k] * s_s[k]) / delta;
// delta = (abs( delta) < (1.0e-10)) ? -(1.0e-10) : delta;
count += (delta < 0) ? 1 : 0;
}
} // end if thread currently processing an interval
rem -= blockDim.x;
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
//! Store all non-empty intervals resulting from the subdivision of the interval
//! currently processed by the thread
//! @param addr base address for storing intervals
//! @param num_threads_active number of threads / intervals in current sweep
//! @param s_left shared memory storage for left interval limits
//! @param s_right shared memory storage for right interval limits
//! @param s_left_count shared memory storage for number of eigenvalues less
//! than left interval limits
//! @param s_right_count shared memory storage for number of eigenvalues less
//! than right interval limits
//! @param left lower limit of interval
//! @param mid midpoint of interval
//! @param right upper limit of interval
//! @param left_count eigenvalues less than \a left
//! @param mid_count eigenvalues less than \a mid
//! @param right_count eigenvalues less than \a right
//! @param precision desired precision for eigenvalues
//! @param compact_second_chunk shared mem flag if second chunk is used and
//! ergo requires compaction
//! @param s_compaction_list_exc helper array for stream compaction,
//! s_compaction_list_exc[tid] = 1 when the
//! thread generated two child intervals
//! @is_active_interval mark is thread has a second non-empty child interval
////////////////////////////////////////////////////////////////////////////////
template<class S, class T, class NumericT>
__device__
void
storeNonEmptyIntervals(unsigned int addr,
const unsigned int num_threads_active,
NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
NumericT left, NumericT mid, NumericT right,
const S left_count,
const S mid_count,
const S right_count,
NumericT precision,
unsigned int &compact_second_chunk,
T *s_compaction_list_exc,
unsigned int &is_active_second)
{
// check if both child intervals are valid
if ((left_count != mid_count) && (mid_count != right_count))
{
// store the left interval
storeInterval(addr, s_left, s_right, s_left_count, s_right_count,
left, mid, left_count, mid_count, precision);
// mark that a second interval has been generated, only stored after
// stream compaction of second chunk
is_active_second = 1;
s_compaction_list_exc[threadIdx.x] = 1;
compact_second_chunk = 1;
}
else
{
// only one non-empty child interval
// mark that no second child
is_active_second = 0;
s_compaction_list_exc[threadIdx.x] = 0;
// store the one valid child interval
if (left_count != mid_count)
{
storeInterval(addr, s_left, s_right, s_left_count, s_right_count,
left, mid, left_count, mid_count, precision);
}
else
{
storeInterval(addr, s_left, s_right, s_left_count, s_right_count,
mid, right, mid_count, right_count, precision);
}
}
}
////////////////////////////////////////////////////////////////////////////////
//! Create indices for compaction, that is process \a s_compaction_list_exc
//! which is 1 for intervals that generated a second child and 0 otherwise
//! and create for each of the non-zero elements the index where the new
//! interval belongs to in a compact representation of all generated second
//! childs
//! @param s_compaction_list_exc list containing the flags which threads
//! generated two childs
//! @param num_threads_compaction number of threads to employ for compaction
////////////////////////////////////////////////////////////////////////////////
template<class T>
__device__
void
createIndicesCompaction(T *s_compaction_list_exc,
unsigned int num_threads_compaction)
{
unsigned int offset = 1;
const unsigned int tid = threadIdx.x;
// if(tid == 0)
// printf("num_threads_compaction = %u\n", num_threads_compaction);
// higher levels of scan tree
for (int d = (num_threads_compaction >> 1); d > 0; d >>= 1)
{
__syncthreads();
if (tid < d)
{
unsigned int ai = offset*(2*tid+1)-1;
unsigned int bi = offset*(2*tid+2)-1;
s_compaction_list_exc[bi] = s_compaction_list_exc[bi]
+ s_compaction_list_exc[ai];
}
offset <<= 1;
}
// traverse down tree: first down to level 2 across
for (int d = 2; d < num_threads_compaction; d <<= 1)
{
offset >>= 1;
__syncthreads();
if (tid < (d-1))
{
unsigned int ai = offset*(tid+1) - 1;
unsigned int bi = ai + (offset >> 1);
s_compaction_list_exc[bi] = s_compaction_list_exc[bi]
+ s_compaction_list_exc[ai];
}
}
__syncthreads();
}
///////////////////////////////////////////////////////////////////////////////
//! Perform stream compaction for second child intervals
//! @param s_left shared
//! @param s_left shared memory storage for left interval limits
//! @param s_right shared memory storage for right interval limits
//! @param s_left_count shared memory storage for number of eigenvalues less
//! than left interval limits
//! @param s_right_count shared memory storage for number of eigenvalues less
//! than right interval limits
//! @param mid midpoint of current interval (left of new interval)
//! @param right upper limit of interval
//! @param mid_count eigenvalues less than \a mid
//! @param s_compaction_list list containing the indices where the data has
//! to be stored
//! @param num_threads_active number of active threads / intervals
//! @is_active_interval mark is thread has a second non-empty child interval
///////////////////////////////////////////////////////////////////////////////
template<class T, class NumericT>
__device__
void
compactIntervals(NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
NumericT mid, NumericT right,
unsigned int mid_count, unsigned int right_count,
T *s_compaction_list,
unsigned int num_threads_active,
unsigned int is_active_second)
{
const unsigned int tid = threadIdx.x;
// perform compaction / copy data for all threads where the second
// child is not dead
if ((tid < num_threads_active) && (1 == is_active_second))
{
unsigned int addr_w = num_threads_active + s_compaction_list[tid];
s_left[addr_w] = mid;
s_right[addr_w] = right;
s_left_count[addr_w] = mid_count;
s_right_count[addr_w] = right_count;
}
}
template<class T, class S, class NumericT>
__device__
void
storeIntervalConverged(NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
NumericT &left, NumericT &mid, NumericT &right,
S &left_count, S &mid_count, S &right_count,
T *s_compaction_list_exc,
unsigned int &compact_second_chunk,
const unsigned int num_threads_active,
unsigned int &is_active_second)
{
const unsigned int tid = threadIdx.x;
const unsigned int multiplicity = right_count - left_count;
// check multiplicity of eigenvalue
if (1 == multiplicity)
{
// just re-store intervals, simple eigenvalue
s_left[tid] = left;
s_right[tid] = right;
s_left_count[tid] = left_count;
s_right_count[tid] = right_count;
// mark that no second child / clear
is_active_second = 0;
s_compaction_list_exc[tid] = 0;
}
else
{
// number of eigenvalues after the split less than mid
mid_count = left_count + (multiplicity >> 1);
// store left interval
s_left[tid] = left;
s_right[tid] = right;
s_left_count[tid] = left_count;
s_right_count[tid] = mid_count;
mid = left;
// mark that second child interval exists
is_active_second = 1;
s_compaction_list_exc[tid] = 1;
compact_second_chunk = 1;
}
}
///////////////////////////////////////////////////////////////////////////////
//! Subdivide interval if active and not already converged
//! @param tid id of thread
//! @param s_left shared memory storage for left interval limits
//! @param s_right shared memory storage for right interval limits
//! @param s_left_count shared memory storage for number of eigenvalues less
//! than left interval limits
//! @param s_right_count shared memory storage for number of eigenvalues less
//! than right interval limits
//! @param num_threads_active number of active threads in warp
//! @param left lower limit of interval
//! @param right upper limit of interval
//! @param left_count eigenvalues less than \a left
//! @param right_count eigenvalues less than \a right
//! @param all_threads_converged shared memory flag if all threads are
//! converged
///////////////////////////////////////////////////////////////////////////////
template<class T, class NumericT>
__device__
void
subdivideActiveInterval(const unsigned int tid,
NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
const unsigned int num_threads_active,
NumericT &left, NumericT &right,
unsigned int &left_count, unsigned int &right_count,
NumericT &mid, unsigned int &all_threads_converged)
{
// for all active threads
if (tid < num_threads_active)
{
left = s_left[tid];
right = s_right[tid];
left_count = s_left_count[tid];
right_count = s_right_count[tid];
// check if thread already converged
if (left != right)
{
mid = computeMidpoint(left, right);
all_threads_converged = 0;
}
} // end for all active threads
}
template<class T, class NumericT>
__device__
void
subdivideActiveIntervalMulti(const unsigned int tid,
NumericT *s_left, NumericT *s_right,
T *s_left_count, T *s_right_count,
const unsigned int num_threads_active,
NumericT &left, NumericT &right,
unsigned int &left_count, unsigned int &right_count,
NumericT &mid, unsigned int &all_threads_converged)
{
// for all active threads
if (tid < num_threads_active)
{
left = s_left[tid];
right = s_right[tid];
left_count = s_left_count[tid];
right_count = s_right_count[tid];
// check if thread already converged
if (left != right)
{
mid = computeMidpoint(left, right);
all_threads_converged = 0;
}
else if ((right_count - left_count) > 1)
{
// mark as not converged if multiple eigenvalues enclosed
// duplicate interval in storeIntervalsConverged()
all_threads_converged = 0;
}
} // end for all active threads
}
}
}
}
#endif // #ifndef VIENNACL_LINALG_DETAIL_BISECT_UTIL_HPP_
| 36.758564 | 96 | 0.54347 | denis14 |
709e36fd8c2f302746c7f410484d8fedee7c6057 | 10,563 | cpp | C++ | Fractal_CPU_Multithreading/Fractal_CPU_Multithreading.cpp | Emmanuel-DUPUIS/multithreadedfractals | 430816e79346d9074a0a43698ef70879247af436 | [
"MIT"
] | null | null | null | Fractal_CPU_Multithreading/Fractal_CPU_Multithreading.cpp | Emmanuel-DUPUIS/multithreadedfractals | 430816e79346d9074a0a43698ef70879247af436 | [
"MIT"
] | null | null | null | Fractal_CPU_Multithreading/Fractal_CPU_Multithreading.cpp | Emmanuel-DUPUIS/multithreadedfractals | 430816e79346d9074a0a43698ef70879247af436 | [
"MIT"
] | null | null | null | //==============================================================================
// (c) Emmanuel DUPUIS 2016, emmanuel.dupuis@undecentum.com, MIT Licence
//==============================================================================
#include <cstdint>
#include <cmath>
#include <iostream>
#include <sstream>
#include <thread>
#include <chrono>
#include <Windows.h>
void saveAsBmp(const char* iFileName, uint32_t iWidth, uint32_t iHeight, void* iRawData);
#include "../../ExS/ExsMtS/includes/ExSMtS_TaskDispatcher.h"
static uint32_t gIter = 0;
#define FLOATING_TYPE double
void convergency(uint32_t* image, uint32_t iImageWidth, uint32_t iImageHeight, uint32_t iWPixel, uint32_t iHPixel, FLOATING_TYPE iCx, FLOATING_TYPE iCy, uint32_t iNbIterations)
{
FLOATING_TYPE x = iCx;
FLOATING_TYPE y = iCy;
FLOATING_TYPE x2 = x*x;
FLOATING_TYPE y2 = y*y;
for (uint_fast16_t n = 1; n < iNbIterations; n++)
{
y = (FLOATING_TYPE)2.0*x*y + iCy;
x = x2-y2 + iCx;
x2 = x*x;
y2 = y*y;
FLOATING_TYPE radius2 = x2 + y2;
if (radius2 > 4.0)
{
gIter++;
FLOATING_TYPE dist = (FLOATING_TYPE)1.4426954 * log(log(radius2) / (FLOATING_TYPE)1.38629436111);
FLOATING_TYPE f = abs((n + 1) % 12 - dist) / (FLOATING_TYPE)12.0;
uint32_t color = (uint32_t)(10.0 * f);
color |= (uint32_t)(20.0 * f) << 8;
color |= (uint32_t)(255.0 * f) << 16;
color |= 255 << 24;
image[iHPixel*iImageWidth + iWPixel] = color;
return;
}
}
image[iHPixel*iImageWidth + iWPixel] = 0xFF643264; // (100,50,100,255)
}
void ComputeThread(std::chrono::time_point<std::chrono::high_resolution_clock> tStartG, uint32_t affinity, uint32_t* image, uint32_t width, uint32_t height, uint32_t start, uint32_t end, double pixelSize, double cx, double cy, uint32_t nbIterations)
{
using namespace std::chrono_literals;
PROCESSOR_NUMBER pn;
GetCurrentProcessorNumberEx(&pn);
while (affinity != -1 && pn.Number != affinity)
{
std::this_thread::sleep_for(10us);
GetCurrentProcessorNumberEx(&pn);
}
uint32_t w = start % width;
uint32_t h = start / width;
uint32_t nb = end - start;
double hw = 0.5*width;
double hh = 0.5*height;
for (uint_fast32_t i = 0; i < nb; i++)
{
convergency(image, width, height, w, h, (FLOATING_TYPE)(cx+(w-hw)*pixelSize), (FLOATING_TYPE)(cy+ (hh-h)*pixelSize), nbIterations);
w++;
if (w == width)
{
w = 0;
h++;
}
}
}
struct SubImage
{
uint32_t wIndex;
uint32_t hIndex;
uint32_t width;
uint32_t height;
};
void requestToDispatcher(ExS::MtS::TaskDispatcher<SubImage>& dispatcher, uint32_t threadIndex, uint32_t width, uint32_t height, uint32_t sidePixelDim)
{
uint32_t nbW =(uint32_t)((width+sidePixelDim-1) / sidePixelDim);
uint32_t nbH = (uint32_t)((height + sidePixelDim - 1) / sidePixelDim);
uint32_t wLastDim = width - sidePixelDim*(nbW-1);
uint32_t hLastDim = height - sidePixelDim*(nbH-1);
for (uint32_t w=0; w < nbW; w++)
for (uint32_t h = 0; h < nbH; h++)
{
uint32_t wDim = sidePixelDim;
uint32_t hDim = sidePixelDim;
if (w == nbW-1)
wDim = wLastDim;
if (h == nbH-1)
hDim = hLastDim;
if (wDim && hDim)
{
SubImage image = { (uint32_t)(w*sidePixelDim), (uint32_t)(h*sidePixelDim), wDim, hDim };
dispatcher.send(image);
}
}
}
void respondToDispatcher(SubImage& subImage, uint32_t threadIndex, std::chrono::time_point<std::chrono::high_resolution_clock> tStartG,uint32_t* image, uint32_t width, uint32_t height, double pixelSize, double cx, double cy, uint32_t nbIterations)
{
double hw = 0.5*width;
double hh = 0.5*height;
for (uint_fast16_t i = 0; i < subImage.width; i++)
for (uint_fast16_t j = 0; j < subImage.height; j++)
{
convergency(image, width, height, subImage.wIndex + i, subImage.hIndex + j, (FLOATING_TYPE)(cx + (subImage.wIndex + i - hw)*pixelSize), (FLOATING_TYPE)(cy + (hh - subImage.hIndex - j)*pixelSize), nbIterations);
}
}
void ComputeOnCpu(std::string& mode, uint32_t* image, uint32_t width, uint32_t height, double pixelSize, double cx, double cy, uint32_t nbIterations, uint32_t sidePixelDim)
{
if (mode == "sequential")
{
double hw = 0.5*width;
double hh = 0.5*height;
for (uint_fast16_t w = 0; w < width; w++)
for (uint_fast16_t h = 0; h < height; h++)
convergency(image, width, height, w, h, (float)(cx + (w - hw)*pixelSize), (float)(cy + (hh - h)*pixelSize), nbIterations);
}
else if (mode == "multiFix")
{
uint32_t nbCores = std::thread::hardware_concurrency();
std::thread** threads = new std::thread*[nbCores];
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
uint32_t totalSize = width*height;
uint32_t packetSize = (uint32_t)(totalSize / nbCores);
for (uint32_t t = 0; t < nbCores; t++)
{
// No affinity, leaves the OS assigning
if (t != std::thread::hardware_concurrency() - 1)
threads[t] = new std::thread(ComputeThread, start, -1/*t*/, image, width, height, t*packetSize, (t + 1)*packetSize, pixelSize, cx, cy, nbIterations);
else
threads[t] = new std::thread(ComputeThread, start, -1/*t*/, image, width, height, t*packetSize, totalSize, pixelSize, cx, cy, nbIterations);
auto handle = threads[t]->native_handle();
//SetThreadAffinityMask(handle, (DWORD_PTR)1 << t);
}
for (uint32_t t = 0; t < nbCores; t++)
threads[t]->join();
}
else if (mode == "multiDispatcher1")
{
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
ExS::MtS::TaskDispatcher<SubImage> dispatcher(4096);
dispatcher.setCustomers(1, std::bind(requestToDispatcher, std::placeholders::_1, std::placeholders::_2, width, height, sidePixelDim));
// No affinity, leaves the OS assigning
//std::vector<int16_t> cores = { 0 };
dispatcher.setSuppliers(8, std::bind(respondToDispatcher, std::placeholders::_1, std::placeholders::_2, start, image, width, height, pixelSize, cx, cy, nbIterations)/*, &cores*/);
dispatcher.launch(true, true);
}
else if (mode == "multiDispatcher2")
{
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
ExS::MtS::TaskDispatcher<SubImage> dispatcher(4096);
dispatcher.setCustomers(1, std::bind(requestToDispatcher, std::placeholders::_1, std::placeholders::_2, width, height, sidePixelDim));
dispatcher.setSuppliers(4, std::bind(respondToDispatcher, std::placeholders::_1, std::placeholders::_2, start, image, width, height, pixelSize, cx, cy, nbIterations));
dispatcher.launch(true, true);
}
}
int main()
{
uint32_t w = 800; // 790;
uint32_t h = 600; // 590;
double pixelSize = 0.00405063294; // 1.0 / 800;
double cx = -0.5;// -1.5;
double cy = .0;
uint32_t* image = new uint32_t[w*h];
/*for (uint32_t sidePixelDim : {200}) //, 100, 50, 40, 25, 20, 10, 8, 5, 4, 2, 1})
{
using namespace std::chrono_literals;
auto tStart = std::chrono::high_resolution_clock::now();
constexpr uint32_t nbIters = 250;
for (uint32_t iter = 0; iter < nbIters; iter++)
{
ComputeOnCpu(std::string("sequential"), image, w, h, pixelSize, cx, cy, 200, sidePixelDim);
}
auto tEnd = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = tEnd - tStart;
std::stringstream msg;
msg << sidePixelDim << "=" << (1000 * diff.count() / nbIters) << "ms\n";
std::cout << msg.str();
}*/
for (int y = 0; y < 5; y++)
{
for (auto mode : { "sequential", "multiFix", "multiDispatcher1" })
{
using namespace std::chrono_literals;
auto tStart = std::chrono::high_resolution_clock::now();
constexpr uint32_t nbIters = 250;
for (uint32_t iter = 0; iter < nbIters; iter++)
{
ComputeOnCpu(std::string(mode), image, w, h, pixelSize, cx, cy, 200, 20);
}
auto tEnd = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = tEnd - tStart;
std::stringstream msg;
msg << mode << "=" << (1000 * diff.count() / nbIters) << "ms\n";
std::cout << msg.str();
}
}
saveAsBmp(std::string("mandelbrot_cpu.bmp").c_str(), w, h, image);
}
void saveAsBmp(const char* iFileName, uint32_t iWidth, uint32_t iHeight, void* iRawData)
{
FILE* fpW = nullptr;
if (!fopen_s(&fpW, iFileName, "wb"))
{
uint32_t zero = 0, size1 = 14 + 124 + 4 * iWidth*iHeight, offset = 14 + 124, size2 = 124;
// BMP header
fwrite((void*)"BM", 1, 2, fpW);
fwrite((unsigned char*)&size1, 4, 1, fpW);
fwrite((void*)&zero, 4, 1, fpW);
fwrite((void*)&offset, sizeof(offset), 1, fpW);
fwrite((void*)&size2, sizeof(size2), 1, fpW);
fwrite((void*)&iWidth, sizeof(iWidth), 1, fpW);
fwrite((void*)&iHeight, sizeof(iHeight), 1, fpW);
// Color plane
uint16_t t16 = 1;
fwrite((void*)&t16, sizeof(t16), 1, fpW);
// Number of bits per pixel
t16 = 32;
fwrite((void*)&t16, sizeof(t16), 1, fpW);
// Compression mode BI_BITFIELDS
uint32_t t32 = 3;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
// Size of raw data
t32 = 4 * iWidth*iHeight;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
// Print resolution
t32 = 2835;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
fwrite((void*)&t32, sizeof(t32), 1, fpW);
// Palette
fwrite((void*)&zero, 4, 1, fpW);
fwrite((void*)&zero, 4, 1, fpW);
// Masks
t32 = 0x000000FF;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
t32 = 0x0000FF00;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
t32 = 0x00FF0000;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
t32 = 0xFF000000;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
t32 = 0x73524742;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
for (uint16_t n = 0; n<48 / 4; n++)
fwrite((void*)&zero, 4, 1, fpW);
t32 = 0X02;
fwrite((void*)&t32, sizeof(t32), 1, fpW);
for (uint16_t n = 0; n<12 / 4; n++)
fwrite((void*)&zero, 4, 1, fpW);
fwrite((void*)iRawData, sizeof(uint32_t), iWidth*iHeight, fpW);
fclose(fpW);
}
} | 35.446309 | 250 | 0.605983 | Emmanuel-DUPUIS |
70a2160f19917bb2514fd5bc0c90d2636da71f13 | 5,736 | cpp | C++ | src/prod/src/data/txnreplicator/logrecordlib/EndTransactionLogRecord.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 1 | 2020-06-15T04:33:36.000Z | 2020-06-15T04:33:36.000Z | src/prod/src/data/txnreplicator/logrecordlib/EndTransactionLogRecord.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | null | null | null | src/prod/src/data/txnreplicator/logrecordlib/EndTransactionLogRecord.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace ktl;
using namespace Data::LogRecordLib;
using namespace TxnReplicator;
using namespace Data::Utilities;
const ULONG EndTransactionLogRecord::DiskSpaceUsed = sizeof(bool) + sizeof(LONG32);
const ULONG EndTransactionLogRecord::SizeOnWireIncrement = sizeof(LONG32) + sizeof(bool);
EndTransactionLogRecord::EndTransactionLogRecord(
__in LogRecordType::Enum recordType,
__in ULONG64 recordPosition,
__in LONG64 lsn,
__in PhysicalLogRecord & invalidPhysicalLogRecord,
__in TransactionLogRecord & invalidTransactionLog)
: TransactionLogRecord(recordType, recordPosition, lsn, invalidPhysicalLogRecord, invalidTransactionLog)
, isCommitted_(false)
, isThisReplicaTransaction_(false)
{
ASSERT_IFNOT(recordType == LogRecordType::Enum::EndTransaction, "Expected end xact record type, actual: {0}", recordType);
}
EndTransactionLogRecord::EndTransactionLogRecord(
__in TransactionBase & transaction,
__in bool isCommitted,
__in bool isThisReplicaTransaction,
__in PhysicalLogRecord & invalidPhysicalLogRecord,
__in TransactionLogRecord & invalidTransactionLog)
: TransactionLogRecord(LogRecordType::EndTransaction, transaction, invalidPhysicalLogRecord, invalidTransactionLog, &invalidTransactionLog)
, isCommitted_(isCommitted)
, isThisReplicaTransaction_(isThisReplicaTransaction)
{
UpdateApproximateDiskSize();
}
EndTransactionLogRecord::~EndTransactionLogRecord()
{
}
EndTransactionLogRecord::SPtr EndTransactionLogRecord::Create(
__in LogRecordType::Enum recordType,
__in ULONG64 recordPosition,
__in LONG64 lsn,
__in PhysicalLogRecord & invalidPhysicalLogRecord,
__in TransactionLogRecord & invalidTransactionLog,
__in KAllocator & allocator)
{
EndTransactionLogRecord* pointer = _new(ENDTXLOGRECORD_TAG, allocator) EndTransactionLogRecord(
recordType,
recordPosition,
lsn,
invalidPhysicalLogRecord,
invalidTransactionLog);
THROW_ON_ALLOCATION_FAILURE(pointer);
return EndTransactionLogRecord::SPtr(pointer);
}
EndTransactionLogRecord::SPtr EndTransactionLogRecord::Create(
__in TransactionBase & transaction,
__in bool isCommitted,
__in bool isThisReplicaTransaction,
__in PhysicalLogRecord & invalidPhysicalLogRecord,
__in TransactionLogRecord & invalidTransactionLog,
__in KAllocator & allocator)
{
EndTransactionLogRecord* pointer = _new(ENDTXLOGRECORD_TAG, allocator) EndTransactionLogRecord(
transaction,
isCommitted,
isThisReplicaTransaction,
invalidPhysicalLogRecord,
invalidTransactionLog);
THROW_ON_ALLOCATION_FAILURE(pointer);
return EndTransactionLogRecord::SPtr(pointer);;
}
void EndTransactionLogRecord::UpdateApproximateDiskSize()
{
ApproximateSizeOnDisk = ApproximateSizeOnDisk + DiskSpaceUsed;
}
void EndTransactionLogRecord::Read(
__in BinaryReader & binaryReader,
__in bool isPhysicalRead)
{
__super::Read(binaryReader, isPhysicalRead);
ReadPrivate(binaryReader, isPhysicalRead);
}
void EndTransactionLogRecord::ReadLogical(
__in OperationData const & operationData,
__inout INT & index)
{
__super::ReadLogical(operationData, index);
KBuffer::CSPtr buffer = OperationData::IncrementIndexAndGetBuffer(operationData, index);
BinaryReader reader(*buffer, GetThisAllocator());
ReadPrivate(reader, false);
}
void EndTransactionLogRecord::ReadPrivate(
__in BinaryReader & binaryReader,
__in bool isPhysicalRead)
{
UNREFERENCED_PARAMETER(isPhysicalRead);
// Read Metadata size
ULONG32 startingPosition = binaryReader.Position;
ULONG32 sizeOfSection = 0;
binaryReader.Read(sizeOfSection);
ULONG32 endPosition = startingPosition + sizeOfSection;
binaryReader.Read(isCommitted_);
ASSERT_IFNOT(
endPosition >= binaryReader.Position,
"Invalid end xact op log record, end position: {0} reader position:{1}",
endPosition, binaryReader.Position);
binaryReader.Position = endPosition;
UpdateApproximateDiskSize();
}
void EndTransactionLogRecord::Write(
__in BinaryWriter & binaryWriter,
__inout OperationData & operationData,
__in bool isPhysicalWrite,
__in bool forceRecomputeOffsets)
{
__super::Write(binaryWriter, operationData, isPhysicalWrite, forceRecomputeOffsets);
if (replicatedData_ == nullptr)
{
ULONG32 startingPosition = binaryWriter.Position;
binaryWriter.Position += sizeof(ULONG32);
binaryWriter.Write(isCommitted_);
ULONG32 endPosition = binaryWriter.Position;
ULONG32 sizeOfSection = endPosition - startingPosition;
binaryWriter.Position = startingPosition;
binaryWriter.Write(sizeOfSection);
binaryWriter.Position = endPosition;
replicatedData_ = binaryWriter.GetBuffer(startingPosition);
}
operationData.Append(*replicatedData_);
}
ULONG EndTransactionLogRecord::GetSizeOnWire() const
{
return __super::GetSizeOnWire() + SizeOnWireIncrement;
}
bool EndTransactionLogRecord::Test_Equals(__in LogRecord const & other) const
{
EndTransactionLogRecord const & otherEndTxLogRecord = dynamic_cast<EndTransactionLogRecord const &>(other);
if (__super::Test_Equals(other))
{
return
isCommitted_ == otherEndTxLogRecord.isCommitted_;
}
return false;
}
| 32.40678 | 143 | 0.737796 | vishnuk007 |
70ac01228431afed0fe0a790bd32c1793cebcd77 | 2,136 | cpp | C++ | Tarefa 03/Ex. 4 - Iron Maiden.cpp | leandrophiga/TADS-PDFA1 | 51240d4cbee34e042e35069f5030f4dc31104935 | [
"MIT"
] | null | null | null | Tarefa 03/Ex. 4 - Iron Maiden.cpp | leandrophiga/TADS-PDFA1 | 51240d4cbee34e042e35069f5030f4dc31104935 | [
"MIT"
] | null | null | null | Tarefa 03/Ex. 4 - Iron Maiden.cpp | leandrophiga/TADS-PDFA1 | 51240d4cbee34e042e35069f5030f4dc31104935 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h> // utilizar strcmp()
#include <termios.h>
#include <unistd.h>
int main(void)
{
int getch(void);
char SenhaDigitada[100], caractere, senha[] = "iron maiden";
int i, r = 1, n_tentativa = 1;
while (r != 0 && n_tentativa <= 3) // r = 0 dirá se a senha digitada está correta.
{
printf("Digite a senha: ");
i = 0;
caractere = getch(); // a tecla digitada não aparecerá e será alocada em 'caractere'.
SenhaDigitada[i] = caractere; // o caractere digitado estará na posição 0 de 'SenhaDigitada'.
++i; // 'i' passa a ser de 0 para 1
while (i < 99 && caractere != 10)
/*
Enquanto não acabar os espaços da string 'SenhaDigitada'
e o caractere não for ENTER poderá continuar digitando a senha
*/
{
printf("*"); // o último 'caractere' digitado aparecerá como '*'.
caractere = getch(); // captura a próxima tecla e aloca em 'caractere'.
SenhaDigitada[i] = caractere; // o caractere digitado vai para a posição 'i' de 'SenhaDigitada'.
++i; // 'i' passa para a próxima posição.
}
SenhaDigitada[i - 1] = '\0'; // coloca valor vazio para o resto das posições de 'SenhaDigitada'.
printf("\n\n");
r = strcmp(SenhaDigitada, senha); // se a 'SenhaDigitada' for igual a 'senha', r = 0.
if (r != 0) // caso for diferente, aparecerá...
{
printf("Senha inválida.");
getch();
++n_tentativa;
printf("\n\n");
} // como a senha foi inválida voltará para a digitação da senha após inserir qualquer tecla.
}
if (r != 0)
{
printf("BARRADO NA ENTRADA\n");
}
else
{
printf("Acesso Vip!\n");
}
return 0;
}
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
| 31.411765 | 108 | 0.571161 | leandrophiga |
70b050bfb41e8700ade293b43fd42725046e8212 | 315 | hpp | C++ | include/mgcpp/expressions/inspect_graph.hpp | MGfoundation/mgcpp | 66c072191e58871637bcb3b76701a79a4ae89779 | [
"BSL-1.0"
] | 48 | 2018-01-02T03:47:18.000Z | 2021-09-09T05:55:45.000Z | include/mgcpp/expressions/inspect_graph.hpp | MGfoundation/mgcpp | 66c072191e58871637bcb3b76701a79a4ae89779 | [
"BSL-1.0"
] | 24 | 2017-12-27T18:03:13.000Z | 2018-07-02T09:00:30.000Z | include/mgcpp/expressions/inspect_graph.hpp | MGfoundation/mgcpp | 66c072191e58871637bcb3b76701a79a4ae89779 | [
"BSL-1.0"
] | 6 | 2018-01-14T14:06:10.000Z | 2018-10-16T08:43:01.000Z | #ifndef INSPECT_GRAPH_HPP
#define INSPECT_GRAPH_HPP
#include <ostream>
#include <mgcpp/expressions/expression.hpp>
namespace mgcpp {
template <typename Expr>
std::ostream& operator<<(std::ostream& os, expression<Expr> const& expr);
}
#include <mgcpp/expressions/inspect_graph.tpp>
#endif // INSPECT_GRAPH_HPP
| 19.6875 | 73 | 0.774603 | MGfoundation |
70b2ae7b36b4998bf3854c0eca9bbcc0be7cc3b2 | 13,863 | cpp | C++ | Modules/Rendering/DirectX/vaTextureHelpersDX11.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 110 | 2018-09-04T20:33:59.000Z | 2021-12-17T08:46:11.000Z | Modules/Rendering/DirectX/vaTextureHelpersDX11.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 5 | 2018-09-05T20:57:08.000Z | 2021-02-24T09:02:31.000Z | Modules/Rendering/DirectX/vaTextureHelpersDX11.cpp | magcius/CMAA2 | 8ceb0daa2afa6b12804da62631494d2ed4b31b53 | [
"Apache-2.0"
] | 20 | 2018-09-05T00:41:13.000Z | 2021-08-04T01:31:50.000Z | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016, Intel Corporation
// 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.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Author(s): Filip Strugar (filip.strugar@intel.com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Core/vaCoreIncludes.h"
#include "Rendering/DirectX/vaDirectXIncludes.h"
#include "Rendering/DirectX/vaDirectXTools.h"
#include "Rendering/vaRenderingIncludes.h"
#include "Rendering/vaTextureHelpers.h"
#include "vaTextureDX11.h"
#include "Rendering/DirectX/vaRenderDeviceContextDX11.h"
#include "Core/Misc/vaProfiler.h"
namespace VertexAsylum
{
// OBSOLETE - scheduled for delete; use vaTexture::TryMap stuff instead
class vaTextureCPU2GPUDX11 : public vaTextureCPU2GPU
{
VA_RENDERING_MODULE_MAKE_FRIENDS( );
private:
protected:
friend class vaTexture;
vaTextureCPU2GPUDX11( const vaRenderingModuleParams & params );
virtual ~vaTextureCPU2GPUDX11( ) ;
public:
// vaTextureCPU2GPU
virtual void TickGPU( vaRenderDeviceContext & context );
};
// OBSOLETE - scheduled for delete; use vaTexture::TryMap stuff instead
class vaTextureGPU2CPUDX11 : public vaTextureGPU2CPU
{
VA_RENDERING_MODULE_MAKE_FRIENDS( );
private:
protected:
friend class vaTexture;
vaTextureGPU2CPUDX11( const vaRenderingModuleParams & params );
virtual ~vaTextureGPU2CPUDX11( ) ;
public:
// vaTextureCPU2GPU
virtual void TickGPU( vaRenderDeviceContext & context );
};
}
using namespace VertexAsylum;
vaTextureCPU2GPUDX11::vaTextureCPU2GPUDX11( const vaRenderingModuleParams & params ) : vaTextureCPU2GPU( params )
{
params; // unreferenced
assert( false ); // OBSOLETE - scheduled for delete; use vaTexture::TryMap stuff instead
}
vaTextureCPU2GPUDX11::~vaTextureCPU2GPUDX11( )
{
}
void vaTextureCPU2GPUDX11::TickGPU( vaRenderDeviceContext & context )
{
if( m_GPUTexture == nullptr )
{
assert( false );
return;
}
// VA_SCOPE_CPUGPU_TIMER( vaTextureCPU2GPUDX11_TickGPU, context );
if( !m_uploadRequested )
return;
ID3D11DeviceContext * dx11Context = vaSaferStaticCast< vaRenderDeviceContextDX11 * >( &context )->GetDXContext( );
if( m_GPUTexture->GetType( ) == vaTextureType::Texture2D )
{
//ID3D11Texture2D * texture2D = m_GPUTexture->SafeCast<vaTextureDX11*>()->GetTexture2D();
ID3D11Resource * resource = m_GPUTexture->SafeCast<vaTextureDX11*>()->GetResource();
assert( m_CPUData.size() == m_GPUTexture->GetMipLevels() );
for( int i = 0; i < m_GPUTexture->GetMipLevels(); i++ )
{
auto cpuSubresource = GetSubresource( i );
assert( cpuSubresource != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
assert( cpuSubresource->Buffer != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
if( (cpuSubresource != nullptr) && (cpuSubresource->Buffer != nullptr) )
{
D3D11_BOX destBox;
destBox.left = 0;
destBox.top = 0;
destBox.front = 0;
destBox.back = 1;
destBox.right = cpuSubresource->SizeX;
destBox.bottom = cpuSubresource->SizeY;
// VA_SCOPE_CPUGPU_TIMER( UpdateSubresource, context );
dx11Context->UpdateSubresource( resource, i, /*&destBox*/NULL, cpuSubresource->Buffer, cpuSubresource->RowPitch, cpuSubresource->RowPitch * cpuSubresource->SizeY );
/*
D3D11_MAPPED_SUBRESOURCE mappedSubresource;
HRESULT hr = dx11Context->Map( resource, i, D3D11_MAP_WRITE_DISCARD, 0, &mappedSubresource );
if( SUCCEEDED( hr ) )
{
if( mappedSubresource.RowPitch != cpuSubresource->RowPitch )
{
for( int y = 0; y < m_GPUTexture->GetSizeY(); y++ )
{
byte * srcData = cpuSubresource->Buffer + cpuSubresource->RowPitch * y;
byte * dstData = (byte *)(mappedSubresource.pData) + mappedSubresource.RowPitch * y;
memcpy( dstData, srcData, cpuSubresource->RowPitch );
}
}
else
{
assert( false ); // not tested
memcpy( mappedSubresource.pData, cpuSubresource->Buffer, cpuSubresource->SizeInBytes );
}
dx11Context->Unmap( resource, i );
cpuSubresource->Modified = false;
}
else
{
// directx error, check HR
assert( false );
}
*/
}
}
m_uploadRequested = false;
}
//dx11Context->CopyResource( m_GPUTexture->SafeCast<vaTextureDX11*>()->GetResource(), m_CPUTexture->SafeCast<vaTextureDX11*>()->GetResource() );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
vaTextureGPU2CPUDX11::vaTextureGPU2CPUDX11( const vaRenderingModuleParams & params ) : vaTextureGPU2CPU( params )
{
params; // unreferenced
assert( false ); // OBSOLETE - scheduled for delete; use vaTexture::TryMap stuff instead
}
vaTextureGPU2CPUDX11::~vaTextureGPU2CPUDX11( )
{
}
void vaTextureGPU2CPUDX11::TickGPU( vaRenderDeviceContext & context )
{
if( (m_GPUTexture == nullptr) || (m_CPUTexture == nullptr) )
{
assert( false );
return;
}
VA_SCOPE_CPUGPU_TIMER( vaTextureGPU2CPUDX11_TickGPU, context );
m_ticksFromLastDownloadRequest++;
ID3D11DeviceContext * dx11Context = vaSaferStaticCast< vaRenderDeviceContextDX11 * >( &context )->GetDXContext( );
if( m_directMappedMarkForUnmap )
{
assert( m_directMapped );
assert( m_directMapMode );
if( ( m_GPUTexture->GetType( ) == vaTextureType::Texture2D ) )
{
ID3D11Resource * cpuDX11Resource = m_CPUTexture->SafeCast<vaTextureDX11*>()->GetResource();
for( int i = 0; i < m_GPUTexture->GetMipLevels(); i++ )
{
auto cpuSubresource = GetSubresource( i );
assert( cpuSubresource != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
assert( cpuSubresource->Buffer != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
if( !((cpuSubresource != nullptr) && (cpuSubresource->Buffer != nullptr)) )
continue;
assert( m_CPUDataDownloaded[i] );
{
// VA_SCOPE_CPU_TIMER( unmap );
dx11Context->Unmap( cpuDX11Resource, i );
}
cpuSubresource->Buffer = nullptr;
cpuSubresource->RowPitch = 0;
cpuSubresource->DepthPitch = 0; //mappedSubresource.DepthPitch;
cpuSubresource->SizeInBytes = 0;
m_CPUDataDownloaded[i] = false;
}
}
m_directMappedMarkForUnmap = false;
m_directMapped = false;
m_downloadFinished = false;
assert( !m_downloadRequested );
return;
}
if( m_downloadRequested && !m_downloadFinished )
{
bool stillWorkToDo = false;
// first frame since requested?
if( m_ticksFromLastDownloadRequest == 1 )
{
if( m_CPUTexture != m_GPUTexture )
dx11Context->CopyResource( m_CPUTexture->SafeCast<vaTextureDX11*>()->GetResource(), m_GPUTexture->SafeCast<vaTextureDX11*>()->GetResource() );
}
bool skipThis = m_ticksFromLastDownloadRequest <= m_copyToMapDelayTicks;
stillWorkToDo = skipThis;
if( !skipThis && ( m_GPUTexture->GetType( ) == vaTextureType::Texture2D ) )
{
ID3D11Resource * cpuDX11Resource = m_CPUTexture->SafeCast<vaTextureDX11*>()->GetResource();
assert( m_CPUData.size() == m_GPUTexture->GetMipLevels() );
for( int i = 0; i < m_GPUTexture->GetMipLevels(); i++ )
{
auto cpuSubresource = GetSubresource( i );
assert( cpuSubresource != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
if( cpuSubresource == nullptr )
continue;
if( m_CPUDataDownloaded[i] )
continue;
// VA_SCOPE_CPUGPU_TIMER( MapCopyUnmap, context );
D3D11_MAPPED_SUBRESOURCE mappedSubresource; memset( &mappedSubresource, 0, sizeof(mappedSubresource) );
HRESULT hr;
{
VA_SCOPE_CPU_TIMER( map );
hr = dx11Context->Map( cpuDX11Resource, i, D3D11_MAP_READ, D3D11_MAP_FLAG_DO_NOT_WAIT, &mappedSubresource );
}
if( SUCCEEDED( hr ) )
{
if( m_directMapMode )
{
cpuSubresource->Buffer = (byte*)mappedSubresource.pData;
cpuSubresource->RowPitch = mappedSubresource.RowPitch;
cpuSubresource->DepthPitch = 0; //mappedSubresource.DepthPitch;
cpuSubresource->SizeInBytes = cpuSubresource->SizeY * cpuSubresource->RowPitch;
//assert( cpuSubresource->DepthPitch == 0 );
assert( mappedSubresource.DepthPitch == cpuSubresource->SizeInBytes );
}
else
{
assert( cpuSubresource->Buffer != nullptr ); // not fatal, checked below but still unexpected, indicating a bug
VA_SCOPE_CPU_TIMER( copy );
if( mappedSubresource.RowPitch != (UINT)cpuSubresource->RowPitch )
{
for( int y = 0; y < cpuSubresource->SizeY; y++ )
{
byte * dstData = cpuSubresource->Buffer + cpuSubresource->RowPitch * y;
byte * srcData = (byte *)(mappedSubresource.pData) + mappedSubresource.RowPitch * y;
memcpy( dstData, srcData, cpuSubresource->RowPitch );
}
}
else
{
memcpy( cpuSubresource->Buffer, mappedSubresource.pData, cpuSubresource->SizeInBytes );
}
dx11Context->Unmap( cpuDX11Resource, i );
}
m_CPUDataDownloaded[i] = true;
continue;
}
else
{
int dbg = 0;
dbg++;
}
stillWorkToDo = true;
}
}
if( !stillWorkToDo )
{
for( int i = 0; i < m_GPUTexture->GetMipLevels( ); i++ )
{
assert( m_CPUDataDownloaded[i] );
}
m_downloadFinished = true;
m_downloadRequested = false;
if( m_directMapMode )
{
m_directMapped = true;
assert( !m_directMappedMarkForUnmap );
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void RegisterTextureToolsDX11( )
{
VA_RENDERING_MODULE_REGISTER( vaRenderDeviceDX11, vaTextureCPU2GPU, vaTextureCPU2GPUDX11 );
VA_RENDERING_MODULE_REGISTER( vaRenderDeviceDX11, vaTextureGPU2CPU, vaTextureGPU2CPUDX11 );
} | 40.893805 | 180 | 0.530044 | magcius |
70b34ae106b2549ef4cca4328e2c50f6dcdbde11 | 6,120 | tcc | C++ | libfqfft/polynomial_arithmetic/basic_operations.tcc | clearmatics/libfqfft | 620cef1c2d88901c497e2c27a6e64308329660b7 | [
"MIT"
] | null | null | null | libfqfft/polynomial_arithmetic/basic_operations.tcc | clearmatics/libfqfft | 620cef1c2d88901c497e2c27a6e64308329660b7 | [
"MIT"
] | 1 | 2021-10-04T09:33:40.000Z | 2021-10-04T09:33:40.000Z | libfqfft/polynomial_arithmetic/basic_operations.tcc | clearmatics/libfqfft | 620cef1c2d88901c497e2c27a6e64308329660b7 | [
"MIT"
] | null | null | null | /** @file
*****************************************************************************
Implementation of interfaces for basic polynomial operation routines.
See basic_operations.hpp .
*****************************************************************************
* @author This file is part of libfqfft, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef BASIC_OPERATIONS_TCC_
#define BASIC_OPERATIONS_TCC_
#include <algorithm>
#include <functional>
#include <libfqfft/evaluation_domain/domains/basic_radix2_domain_aux.hpp>
#include <libfqfft/kronecker_substitution/kronecker_substitution.hpp>
#include <libfqfft/tools/exceptions.hpp>
#ifdef MULTICORE
#include <omp.h>
#endif
namespace libfqfft {
template<typename FieldT>
bool _is_zero(const std::vector<FieldT> &a)
{
return std::all_of(a.begin(), a.end(), [](FieldT i) { return i == FieldT::zero(); });
}
template<typename FieldT>
void _condense(std::vector<FieldT> &a)
{
while (a.begin() != a.end() && a.back() == FieldT::zero())
a.pop_back();
}
template<typename FieldT>
void _reverse(std::vector<FieldT> &a, const size_t n)
{
std::reverse(a.begin(), a.end());
a.resize(n);
}
template<typename FieldT>
void _polynomial_addition(std::vector<FieldT> &c, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
if (_is_zero(a))
{
c = b;
}
else if (_is_zero(b))
{
c = a;
}
else
{
size_t a_size = a.size();
size_t b_size = b.size();
if (a_size > b_size)
{
c.resize(a_size);
std::transform(b.begin(), b.end(), a.begin(), c.begin(), std::plus<FieldT>());
std::copy(a.begin() + b_size, a.end(), c.begin() + b_size);
}
else
{
c.resize(b_size);
std::transform(a.begin(), a.end(), b.begin(), c.begin(), std::plus<FieldT>());
std::copy(b.begin() + a_size, b.end(), c.begin() + a_size);
}
}
_condense(c);
}
template<typename FieldT>
void _polynomial_subtraction(std::vector<FieldT> &c, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
if (_is_zero(b))
{
c = a;
}
else if (_is_zero(a))
{
c.resize(b.size());
std::transform(b.begin(), b.end(), c.begin(), std::negate<FieldT>());
}
else
{
size_t a_size = a.size();
size_t b_size = b.size();
if (a_size > b_size)
{
c.resize(a_size);
std::transform(a.begin(), a.begin() + b_size, b.begin(), c.begin(), std::minus<FieldT>());
std::copy(a.begin() + b_size, a.end(), c.begin() + b_size);
}
else
{
c.resize(b_size);
std::transform(a.begin(), a.end(), b.begin(), c.begin(), std::minus<FieldT>());
std::transform(b.begin() + a_size, b.end(), c.begin() + a_size, std::negate<FieldT>());
}
}
_condense(c);
}
template<typename FieldT>
void _polynomial_multiplication(std::vector<FieldT> &c, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
_polynomial_multiplication_on_fft(c, a, b);
}
template<typename FieldT>
void _polynomial_multiplication_on_fft(std::vector<FieldT> &c, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
const size_t n = libff::get_power_of_two(a.size() + b.size() - 1);
FieldT omega = libff::get_root_of_unity<FieldT>(n);
std::vector<FieldT> u(a);
std::vector<FieldT> v(b);
u.resize(n, FieldT::zero());
v.resize(n, FieldT::zero());
c.resize(n, FieldT::zero());
#ifdef MULTICORE
_basic_parallel_radix2_FFT(u, omega);
_basic_parallel_radix2_FFT(v, omega);
#else
_basic_serial_radix2_FFT(u, omega);
_basic_serial_radix2_FFT(v, omega);
#endif
std::transform(u.begin(), u.end(), v.begin(), c.begin(), std::multiplies<FieldT>());
#ifdef MULTICORE
_basic_parallel_radix2_FFT(c, omega.inverse());
#else
_basic_serial_radix2_FFT(c, omega.inverse());
#endif
const FieldT sconst = FieldT(n).inverse();
std::transform(
c.begin(),
c.end(),
c.begin(),
std::bind(std::multiplies<FieldT>(), sconst, std::placeholders::_1));
_condense(c);
}
template<typename FieldT>
void _polynomial_multiplication_on_kronecker(std::vector<FieldT> &c, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
kronecker_substitution(c, a, b);
}
template<typename FieldT>
std::vector<FieldT> _polynomial_multiplication_transpose(const size_t &n, const std::vector<FieldT> &a, const std::vector<FieldT> &c)
{
const size_t m = a.size();
if (c.size() - 1 > m + n) throw InvalidSizeException("expected c.size() - 1 <= m + n");
std::vector<FieldT> r(a);
_reverse(r, m);
_polynomial_multiplication(r, r, c);
/* Determine Middle Product */
std::vector<FieldT> result;
for (size_t i = m - 1; i < n + m; i++)
{
result.emplace_back(r[i]);
}
return result;
}
template<typename FieldT>
void _polynomial_division(std::vector<FieldT> &q, std::vector<FieldT> &r, const std::vector<FieldT> &a, const std::vector<FieldT> &b)
{
size_t d = b.size() - 1; /* Degree of B */
FieldT c = b.back().inverse(); /* Inverse of Leading Coefficient of B */
r = std::vector<FieldT>(a);
q = std::vector<FieldT>(r.size(), FieldT::zero());
size_t r_deg = r.size() - 1;
size_t shift;
while (r_deg >= d && !_is_zero(r))
{
if (r_deg >= d) shift = r_deg - d;
else shift = 0;
FieldT lead_coeff = r.back() * c;
q[shift] += lead_coeff;
if (b.size() + shift + 1 > r.size()) r.resize(b.size() + shift + 1);
auto glambda = [=](FieldT x, FieldT y) { return y - (x * lead_coeff); };
std::transform(b.begin(), b.end(), r.begin() + shift, r.begin() + shift, glambda);
_condense(r);
r_deg = r.size() - 1;
}
_condense(q);
}
} // libfqfft
#endif // BASIC_OPERATIONS_TCC_
| 27.945205 | 133 | 0.576634 | clearmatics |
70b78dee07b94530f44ae6919c274ff0a90c4629 | 1,173 | hpp | C++ | library/ATF/_DCB.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/_DCB.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/_DCB.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 _DCB
{
unsigned int DCBlength;
unsigned int BaudRate;
unsigned __int32 fBinary : 1;
unsigned __int32 fParity : 1;
unsigned __int32 fOutxCtsFlow : 1;
unsigned __int32 fOutxDsrFlow : 1;
unsigned __int32 fDtrControl : 2;
unsigned __int32 fDsrSensitivity : 1;
unsigned __int32 fTXContinueOnXoff : 1;
unsigned __int32 fOutX : 1;
unsigned __int32 fInX : 1;
unsigned __int32 fErrorChar : 1;
unsigned __int32 fNull : 1;
unsigned __int32 fRtsControl : 2;
unsigned __int32 fAbortOnError : 1;
unsigned __int32 fDummy2 : 17;
unsigned __int16 wReserved;
unsigned __int16 XonLim;
unsigned __int16 XoffLim;
char ByteSize;
char Parity;
char StopBits;
char XonChar;
char XoffChar;
char ErrorChar;
char EofChar;
char EvtChar;
unsigned __int16 wReserved1;
};
END_ATF_NAMESPACE
| 29.325 | 108 | 0.635124 | lemkova |
70b7ce0dc3701c5945dd7e3cc8f7d1b1eb7cc5b6 | 222 | cpp | C++ | Pointers/simplearray.cpp | dealbisac/cprograms | 89af58a30295099b45406cf192f4c4eb4a06f9fe | [
"Unlicense"
] | 4 | 2019-01-27T01:00:44.000Z | 2019-01-29T02:09:55.000Z | Pointers/simplearray.cpp | dealbisac/cprograms | 89af58a30295099b45406cf192f4c4eb4a06f9fe | [
"Unlicense"
] | null | null | null | Pointers/simplearray.cpp | dealbisac/cprograms | 89af58a30295099b45406cf192f4c4eb4a06f9fe | [
"Unlicense"
] | 1 | 2019-02-04T11:34:40.000Z | 2019-02-04T11:34:40.000Z | //Simple Array Pointers Example
#include <stdio.h>
int main()
{
int x[4];
int i;
for(i = 0; i < 4; ++i)
{
printf("&x[%d] = %u\n", i, &x[i]);
}
printf("Address of array x: %u", x);
return 0;
}
| 13.058824 | 40 | 0.477477 | dealbisac |
70b814f959a944f1978a91fe88d1eb529eaabd26 | 211 | cpp | C++ | src/network/message.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 3 | 2015-02-22T20:34:28.000Z | 2020-03-04T08:55:25.000Z | src/network/message.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 22 | 2015-12-13T16:29:40.000Z | 2017-03-04T15:45:44.000Z | src/network/message.cpp | Reaping2/Reaping2 | 0d4c988c99413e50cc474f6206cf64176eeec95d | [
"MIT"
] | 14 | 2015-11-23T21:25:09.000Z | 2020-07-17T17:03:23.000Z | #include "network/message.h"
namespace network {
Message::Message()
: mSenderId( -1 )
{
}
Message::~Message()
{
}
} // namespace network
BOOST_CLASS_EXPORT_GUID( network::DefaultMessage, "default" )
| 10.55 | 61 | 0.677725 | MrPepperoni |
70b8c9b996274447f48c4121979ecd90a15b74d5 | 2,054 | cpp | C++ | Root Folder/Game/Render Engine/basics/DisplayManager.cpp | zhangjianagry/2018-Game | aebc4c3f6c98bb7e909f2ff4d71e32b63ba7fc14 | [
"MIT"
] | 1 | 2018-12-25T03:18:42.000Z | 2018-12-25T03:18:42.000Z | Root Folder/Game/Render Engine/basics/DisplayManager.cpp | zhangjianagry/2018-Game | aebc4c3f6c98bb7e909f2ff4d71e32b63ba7fc14 | [
"MIT"
] | null | null | null | Root Folder/Game/Render Engine/basics/DisplayManager.cpp | zhangjianagry/2018-Game | aebc4c3f6c98bb7e909f2ff4d71e32b63ba7fc14 | [
"MIT"
] | null | null | null | #include "DisplayManager.h"
#include <iostream>
int DisplayManager::SCREEN_WIDTH = 1280;
int DisplayManager::SCREEN_HEIGHT = 720;
const char * DisplayManager::SCREEN_TITLE = "Game";
float DisplayManager::ASPECTRATIO;
int DisplayManager::FPS_CAP = 100;
float DisplayManager::MAX_DELTA = 0.2f;
float DisplayManager::STABLE_DELTA_TIME = 2.0f;
long DisplayManager::LASTFRAMETIME;
float DisplayManager::DELTA;
float DisplayManager::TIME = 0;
Window * DisplayManager::window;
void DisplayManager::cretaDisplay() {
window = new Window(SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
ASPECTRATIO = (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT;
LASTFRAMETIME = getCurrentTime();
DELTA = 1.0f / FPS_CAP;
}
bool DisplayManager::closedDisplay() {
return window->closed();
}
void DisplayManager::updateDisplay() {
updateDelta();
// printf("Time: %f, Delta: %f\n", TIME, DELTA);
window->update();
}
void DisplayManager::clearDisplay() {
window->clear();
}
int DisplayManager::getScreenHeigh() {
SCREEN_HEIGHT = window->getHeight();
return SCREEN_HEIGHT;
}
int DisplayManager::getScreenWidth() {
SCREEN_WIDTH = window->getWidth();
return SCREEN_WIDTH;
}
bool DisplayManager::isKeyPressed(unsigned int keycode) {
return window->isKeyPressed(keycode);
}
bool DisplayManager::isMouseButtonPressed(unsigned int button) {
return window->isMouseButtonPressed(button);
}
void DisplayManager::getMousePosition(double &x, double &y) {
window->getMousePosition(x, y);
}
long DisplayManager::getCurrentTime() {
return GetTickCount();
}
void DisplayManager::updateDelta() {
long currentFramTime = getCurrentTime();
float nowDelta = (currentFramTime - LASTFRAMETIME) / 1000.0f;
DELTA = MAX_DELTA < nowDelta ? MAX_DELTA : nowDelta;
LASTFRAMETIME = currentFramTime;
TIME += DELTA;
if (TIME < STABLE_DELTA_TIME) {
DELTA = 1.0f / FPS_CAP;
}
}
float DisplayManager::getDelta() {
return DELTA;
}
float DisplayManager::getTime() {
return TIME;
}
float DisplayManager::getAspectRatio() {
return ASPECTRATIO;
}
| 22.822222 | 64 | 0.746349 | zhangjianagry |
70c1a1675562c5ab2d5609136b1ae34adcd636c8 | 3,595 | cpp | C++ | src/game/shared/movevars_shared.cpp | vxsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 4 | 2019-08-31T10:48:22.000Z | 2019-11-03T19:36:45.000Z | src/game/shared/movevars_shared.cpp | undbsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 2 | 2020-07-18T10:39:32.000Z | 2020-09-14T04:37:18.000Z | src/game/shared/movevars_shared.cpp | undbsd/refraction | bb6def1feb6c2e5c94b2604ad55607ed380a2d7e | [
"MIT"
] | 1 | 2019-12-20T20:40:12.000Z | 2019-12-20T20:40:12.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "movevars_shared.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
float GetCurrentGravity(void)
{
return sv_gravity.GetFloat();
}
ConVar sv_gravity("sv_gravity", "600", FCVAR_NOTIFY | FCVAR_REPLICATED, "World gravity.");
ConVar sv_stopspeed("sv_stopspeed", "100", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Minimum stopping speed when on ground.");
ConVar sv_noclipaccelerate("sv_noclipaccelerate", "5", FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_REPLICATED);
ConVar sv_noclipspeed("sv_noclipspeed", "5", FCVAR_ARCHIVE | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar sv_specaccelerate("sv_specaccelerate", "5", FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_REPLICATED);
ConVar sv_specspeed("sv_specspeed", "3", FCVAR_ARCHIVE | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar sv_specnoclip("sv_specnoclip", "1", FCVAR_ARCHIVE | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar sv_accelerate("sv_accelerate", "10", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY);
ConVar sv_airaccelerate("sv_airaccelerate", "10", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY);
ConVar sv_wateraccelerate("sv_wateraccelerate", "10", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY);
ConVar sv_friction("sv_friction", "4", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "World friction.");
ConVar sv_waterfriction("sv_waterfriction", "1", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY);
ConVar sv_bounce("sv_bounce", "0", FCVAR_NOTIFY | FCVAR_REPLICATED, "Bounce multiplier for when physically simulated objects collide with other objects.");
ConVar sv_maxspeed("sv_maxspeed", "320", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY);
ConVar sv_maxvelocity("sv_maxvelocity", "3500", FCVAR_REPLICATED | FCVAR_CHEAT, "Maximum speed any ballistically moving object is allowed to attain per axis.");
ConVar sv_backspeed("sv_backspeed", "0.6", FCVAR_ARCHIVE | FCVAR_REPLICATED, "How much to slow down backwards motion");
ConVar sv_footsteps("sv_footsteps", "1", FCVAR_NOTIFY | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Play footstep sound for players");
ConVar sv_stepsize("sv_stepsize", "18", FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar sv_rollspeed("sv_rollspeed", "300.0", FCVAR_REPLICATED);
ConVar sv_rollangle("sv_rollangle", "3.0", FCVAR_REPLICATED, "Max view roll angle");
ConVar sv_waterdist("sv_waterdist", "12", FCVAR_REPLICATED, "Vertical view fixup when eyes are near water plane.");
ConVar sv_skyname("sv_skyname", "sky_urb01", FCVAR_ARCHIVE | FCVAR_REPLICATED, "Current name of the skybox texture");
// Vehicle convars
ConVar r_VehicleViewDampen("r_VehicleViewDampen", "1", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
// Jeep convars
ConVar r_JeepViewDampenFreq("r_JeepViewDampenFreq", "7.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar r_JeepViewDampenDamp("r_JeepViewDampenDamp", "1.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar r_JeepViewZHeight("r_JeepViewZHeight", "10.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
// Airboat convars
ConVar r_AirboatViewDampenFreq("r_AirboatViewDampenFreq", "7.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar r_AirboatViewDampenDamp("r_AirboatViewDampenDamp", "1.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
ConVar r_AirboatViewZHeight("r_AirboatViewZHeight", "0.0", FCVAR_CHEAT | FCVAR_NOTIFY | FCVAR_REPLICATED);
| 57.063492 | 160 | 0.76662 | vxsd |
70d39e4d147f1db11596ff7be458c90ef3cbbd7a | 1,073 | cpp | C++ | src/imu-frontend/ImuFrontEndParams.cpp | tonioteran/Kimera-VIO | fe3ab9554a30fdff760da53d5ad22ee45f91c498 | [
"BSD-2-Clause"
] | 2 | 2019-12-18T12:38:24.000Z | 2019-12-25T08:18:02.000Z | src/imu-frontend/ImuFrontEndParams.cpp | tonioteran/Kimera-VIO | fe3ab9554a30fdff760da53d5ad22ee45f91c498 | [
"BSD-2-Clause"
] | null | null | null | src/imu-frontend/ImuFrontEndParams.cpp | tonioteran/Kimera-VIO | fe3ab9554a30fdff760da53d5ad22ee45f91c498 | [
"BSD-2-Clause"
] | 1 | 2020-01-18T09:52:52.000Z | 2020-01-18T09:52:52.000Z | /* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file ImuFrontEndParams.cpp
* @brief Params for ImuFrontEnd.
* @author Antoni Rosinol
*/
#include "imu-frontend/ImuFrontEndParams.h"
#include <glog/logging.h>
namespace VIO {
void ImuParams::print() const {
LOG(INFO) << "------------ ImuParams::print -------------\n"
<< "gyroscope_noise_density: " << gyro_noise_ << '\n'
<< "gyroscope_random_walk: " << gyro_walk_ << '\n'
<< "accelerometer_noise_density: " << acc_noise_ << '\n'
<< "accelerometer_random_walk: " << acc_walk_ << '\n'
<< "n_gravity: " << n_gravity_ << '\n'
<< "imu_integration_sigma: " << imu_integration_sigma_;
}
} // namespace VIO
| 33.53125 | 80 | 0.521901 | tonioteran |
70d5536548f830dcd1cc7831e247b4efa560e504 | 328 | hpp | C++ | src/Graphics/glHeaders.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | 1 | 2020-05-31T02:25:39.000Z | 2020-05-31T02:25:39.000Z | src/Graphics/glHeaders.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | null | null | null | src/Graphics/glHeaders.hpp | ryu-raptor/amf | 33a42cf1025ea512f23c4769a5be27d6a0c335bc | [
"MIT"
] | null | null | null | #ifndef glHeaders_hpp_included
#define glHeaders_hpp_included
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define GLM_MESSAGES
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/transform.hpp>
#include <glm/gtx/string_cast.hpp>
#endif /* end of include guard */
| 21.866667 | 39 | 0.780488 | ryu-raptor |
70d64b81fcdbbc58739b812150d232add48eb461 | 475 | cpp | C++ | source/consolelogger.cpp | JRKalyan/affign | ef5816ecc683d4720595414a4e8355057dbbff78 | [
"MIT"
] | 21 | 2018-01-21T19:29:05.000Z | 2022-02-23T19:18:58.000Z | source/consolelogger.cpp | JRKalyan/affign | ef5816ecc683d4720595414a4e8355057dbbff78 | [
"MIT"
] | null | null | null | source/consolelogger.cpp | JRKalyan/affign | ef5816ecc683d4720595414a4e8355057dbbff78 | [
"MIT"
] | null | null | null | #include "consolelogger.h"
#include <iostream>
void ConsoleLogger::Log(const std::string& msg, MessageType type) {
std::string prefix;
switch (type)
{
case MessageType::error:
prefix = "[ERROR]";
break;
case MessageType::standard:
prefix = "[STATUS]";
break;
case MessageType::success:
prefix = "[SUCCESS]";
break;
case MessageType::warning:
prefix = "[WARNING]";
break;
}
std::cout << prefix << " " << msg << std::endl;
}
| 19.791667 | 67 | 0.614737 | JRKalyan |
70d862fc96d9a59cc1f162b35b34b9ad1d237757 | 343 | cpp | C++ | WinRT/HelloWinRT/Main.cpp | weliwita/CPPWindowsTutorial | 0bba092c20e1afad3434b521a21ae09573579cde | [
"Apache-2.0"
] | null | null | null | WinRT/HelloWinRT/Main.cpp | weliwita/CPPWindowsTutorial | 0bba092c20e1afad3434b521a21ae09573579cde | [
"Apache-2.0"
] | null | null | null | WinRT/HelloWinRT/Main.cpp | weliwita/CPPWindowsTutorial | 0bba092c20e1afad3434b521a21ae09573579cde | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Networking;
using namespace Windows::Networking::Connectivity;
int main()
{
init_apartment();
for (HostName const & name : NetworkInformation::GetHostNames())
{
printf("%ls\n", name.ToString().c_str());
}
}
| 17.15 | 68 | 0.676385 | weliwita |
70d922514e131d20838131448b18e3a57aac0a35 | 2,672 | cpp | C++ | src/Values.cpp | errata-c/ez-kvstore | 9e68d4cb18e17cb6ba4a7c2a6aaf6cddd9d829cf | [
"MIT"
] | null | null | null | src/Values.cpp | errata-c/ez-kvstore | 9e68d4cb18e17cb6ba4a7c2a6aaf6cddd9d829cf | [
"MIT"
] | null | null | null | src/Values.cpp | errata-c/ez-kvstore | 9e68d4cb18e17cb6ba4a7c2a6aaf6cddd9d829cf | [
"MIT"
] | null | null | null | #include "KVPrivate.hpp"
#include <cassert>
#include <iostream>
#include <fmt/core.h>
namespace ez {
std::size_t KVPrivate::numValues() const {
if (!db) {
return 0;
}
SQLite::Statement stmt(
db.value(),
fmt::format(
"SELECT COUNT(*) FROM \"{}\";",
tableID
)
);
bool res = stmt.executeStep();
assert(res == true);
int64_t val = stmt.getColumn(0).getInt64();
assert(val >= 0);
return static_cast<std::size_t>(val);
}
bool KVPrivate::contains(std::string_view name) const {
if (!db) {
return false;
}
if (!containsStmt) {
containsStmt.emplace(
db.value(),
fmt::format(
"SELECT 1 WHERE EXISTS (SELECT * FROM \"{}\" WHERE \"hash\" = ?);",
tableID
)
);
}
else {
containsStmt.value().reset();
}
SQLite::Statement& stmt = containsStmt.value();
stmt.bind(1, kvhash(name));
return stmt.executeStep();
}
bool KVPrivate::getRaw(std::string_view name, const void*& data, std::size_t& len) const {
if (db) {
if (!getStmt) {
getStmt.emplace(
db.value(),
fmt::format(
"SELECT \"value\" FROM \"{}\" WHERE \"hash\" = ?",
tableID
)
);
}
else {
getStmt.value().reset();
}
SQLite::Statement& stmt = getStmt.value();
stmt.bind(1, kvhash(name));
if (stmt.executeStep()) {
SQLite::Column col = stmt.getColumn(0);
data = col.getBlob();
len = static_cast<std::size_t>(col.getBytes());
return true;
}
else {
return false;
}
}
else {
return false;
}
}
bool KVPrivate::setRaw(std::string_view key, const void* data, std::size_t len) {
if (!db) {
return false;
}
if (!setStmt) {
setStmt.emplace(
db.value(),
fmt::format(
"INSERT INTO \"{}\" (\"hash\", \"key\", \"value\") "
"VALUES (?, ?, ?) ON CONFLICT(\"hash\") "
"DO UPDATE SET \"value\"=excluded.\"value\";",
tableID
)
);
}
else {
setStmt.value().reset();
}
SQLite::Statement& stmt = setStmt.value();
stmt.bind(1, kvhash(key));
stmt.bind(2, key.data(), key.length());
stmt.bind(3, data, len);
bool res = stmt.executeStep();
assert(res == false);
return true;
}
bool KVPrivate::erase(std::string_view name) {
if (db) {
if (!eraseStmt) {
eraseStmt.emplace(
db.value(),
fmt::format(
"DELETE FROM \"{}\" WHERE \"hash\" = ?; SELECT changes();",
tableID
)
);
}
else {
eraseStmt.value().reset();
}
SQLite::Statement& stmt = eraseStmt.value();
stmt.bind(1, kvhash(name));
bool res = stmt.executeStep();
assert(res);
return stmt.getColumn(0).getInt() == 1;
}
else {
return false;
}
}
} | 18.30137 | 91 | 0.561377 | errata-c |
70dc33b8488c49143d5ff4c482003d3272fe8362 | 687 | cpp | C++ | src/xyz.cpp | andreaskoepf/torch-pcl | 54244b69f9483d84e4f7d1da637c09d1de73acf1 | [
"BSD-3-Clause"
] | 36 | 2016-02-11T06:57:33.000Z | 2020-05-30T05:08:18.000Z | src/xyz.cpp | andreaskoepf/torch-pcl | 54244b69f9483d84e4f7d1da637c09d1de73acf1 | [
"BSD-3-Clause"
] | 13 | 2015-10-23T13:00:34.000Z | 2017-01-05T16:35:32.000Z | src/xyz.cpp | andreaskoepf/torch-pcl | 54244b69f9483d84e4f7d1da637c09d1de73acf1 | [
"BSD-3-Clause"
] | 8 | 2016-02-21T01:47:46.000Z | 2019-11-01T12:48:57.000Z | #define _PointT pcl::PointXYZ
#define _PointNormalT pcl::PointNormal
#define TYPE_KEY _XYZ_
#include "utils.h"
#include <pcl/keypoints/sift_keypoint.h>
// SIFTKeypointFieldSelector specialization to calculate SIFTKeypoint based
// on the z component of point clouds without color or intensity information.
namespace pcl
{
template<>
struct SIFTKeypointFieldSelector<PointXYZ>
{
inline float
operator () (const PointXYZ& p) const
{
return p.z;
}
};
}
#include "generic.cpp"
#include "generic/cloudviewer.cpp"
#include "mesh_sampling.cpp"
#include "generic/openni2.cpp"
#include "generic/normal_estimation.cpp"
#include "generic/integral_image_normal.cpp"
| 23.689655 | 77 | 0.756914 | andreaskoepf |
70dffa1383cc22b22a12f4dcd872ed6e226644a0 | 24,866 | cpp | C++ | src/Simd/SimdAvx1Convolution.cpp | frankyhit/Simd | 05c5d3bfa83e55f33dd669dfef4995332fd5ef61 | [
"MIT"
] | 1 | 2018-12-14T06:19:36.000Z | 2018-12-14T06:19:36.000Z | src/Simd/SimdAvx1Convolution.cpp | frankyhit/Simd | 05c5d3bfa83e55f33dd669dfef4995332fd5ef61 | [
"MIT"
] | null | null | null | src/Simd/SimdAvx1Convolution.cpp | frankyhit/Simd | 05c5d3bfa83e55f33dd669dfef4995332fd5ef61 | [
"MIT"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2018 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/SimdConvolution.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdAvx1.h"
namespace Simd
{
#ifdef SIMD_AVX_ENABLE
namespace Avx
{
void ConvolutionBiasAndActivation(const float * bias, size_t count, size_t size, ::SimdConvolutionActivationType activation, const float * params, float * dst)
{
size_t aligned = AlignLo(size, F);
if (activation == ::SimdConvolutionActivationIdentity)
{
if (bias)
SynetAddBias(bias, count, size, dst, SimdFalse);
}
else if (activation == ::SimdConvolutionActivationRelu)
{
if (bias)
{
__m256 _0 = _mm256_set1_ps(0.0f);
for (size_t i = 0; i < count; ++i)
{
float shift = bias[i];
__m256 _shift = _mm256_set1_ps(shift);
size_t j = 0;
for (; j < aligned; j += F)
{
__m256 _dst = _mm256_loadu_ps(dst + j);
_mm256_storeu_ps(dst + j, _mm256_max_ps(_0, _mm256_add_ps(_dst, _shift)));
}
for (; j < size; ++j)
dst[j] = Simd::Max(0.0f, dst[j] + shift);
dst += size;
}
}
else
{
float slope = 0;
NeuralRelu(dst, size*count, &slope, dst);
}
}
else if (activation == ::SimdConvolutionActivationLeakyRelu)
{
float slope = params[0];
if (bias)
{
__m256 _slope = _mm256_set1_ps(slope);
__m256 _0 = _mm256_set1_ps(0.0f);
for (size_t i = 0; i < count; ++i)
{
float shift = bias[i];
__m256 _shift = _mm256_set1_ps(shift);
size_t j = 0;
for (; j < aligned; j += F)
{
__m256 value = _mm256_add_ps(_mm256_loadu_ps(dst + j), _shift);
_mm256_storeu_ps(dst + j, _mm256_add_ps(_mm256_max_ps(_0, value), _mm256_mul_ps(_slope, _mm256_min_ps(_0, value))));
}
for (; j < size; ++j)
{
float value = dst[j] + shift;
dst[i] = Simd::Max(0.0f, value) + slope * Simd::Min(value, 0.0f);
}
dst += size;
}
}
else
NeuralRelu(dst, size*count, &slope, dst);
}
else if (activation == ::SimdConvolutionActivationRestrictRange)
{
float lower = params[0];
float upper = params[1];
if (bias)
{
__m256 _lower = _mm256_set1_ps(lower);
__m256 _upper = _mm256_set1_ps(upper);
for (size_t i = 0; i < count; ++i)
{
float shift = bias[i];
__m256 _shift = _mm256_set1_ps(shift);
size_t j = 0;
for (; j < aligned; j += F)
{
__m256 value = _mm256_add_ps(_mm256_loadu_ps(dst + j), _shift);
_mm256_storeu_ps(dst + j, _mm256_min_ps(_mm256_max_ps(_lower, value), _upper));
}
for (; j < size; ++j)
dst[j] = Simd::RestrictRange(dst[j] + shift, lower, upper);
dst += size;
}
}
else
SynetRestrictRange(dst, size*count, &lower, &upper, dst);
}
else if (activation == ::SimdConvolutionActivationPrelu)
{
if (bias)
{
__m256 _0 = _mm256_set1_ps(0.0f);
for (size_t i = 0; i < count; ++i)
{
float shift = bias[i];
float slope = params[i];
__m256 _shift = _mm256_set1_ps(shift);
__m256 _slope = _mm256_set1_ps(slope);
size_t j = 0;
for (; j < aligned; j += F)
{
__m256 value = _mm256_add_ps(_mm256_loadu_ps(dst + j), _shift);
_mm256_storeu_ps(dst + j, _mm256_add_ps(_mm256_max_ps(_0, value), _mm256_mul_ps(_slope, _mm256_min_ps(_0, value))));
}
for (; j < size; ++j)
{
float value = dst[j] + shift;
dst[j] = Simd::Max(0.0f, value) + slope*Simd::Min(value, 0.0f);
}
dst += size;
}
}
else
{
for (size_t i = 0; i < count; ++i)
NeuralRelu(dst + i*size, size, params + i, dst + i*size);
}
}
}
//---------------------------------------------------------------------
ConvolutionImgToCol::ConvolutionImgToCol(const ConvParam & p)
: Sse::ConvolutionImgToCol(p)
{
}
void ConvolutionImgToCol::GemmAndBias(const float * src, float * dst)
{
const ConvParam & p = _param;
for (size_t g = 0; g < p.group; ++g)
Avx::Gemm32fNN(_M, _N, _K, &_1, _weight + _weightStep * g, _K, src + _srcStep * g, _N, &_0, dst + _dstStep * g, _N);
Avx::ConvolutionBiasAndActivation(_bias, p.dstC, p.dstH*p.dstW, p.activation, _params, dst);
}
//---------------------------------------------------------------------
ConvolutionImgToRow::ConvolutionImgToRow(const ConvParam & p)
: Sse3::ConvolutionImgToRow(p)
{
}
void ConvolutionImgToRow::GemmAndBias(const float * src, float * dst)
{
const ConvParam & p = _param;
for (size_t g = 0; g < p.group; ++g)
Avx::Gemm32fNT(_M, _N, _K, &_1, _weight + _weightStep * g, _K, src + _srcStep * g, _K, &_0, dst + _dstStep * g, _N);
Avx::ConvolutionBiasAndActivation(_bias, p.dstC, p.dstH*p.dstW, p.activation, _params, dst);
}
//---------------------------------------------------------------------
ConvolutionWinograd2x3p::ConvolutionWinograd2x3p(const ConvParam & p)
: Sse::ConvolutionWinograd2x3p(p)
{
}
void ConvolutionWinograd2x3p::Forward(const float * src, float * buf, float * dst)
{
const ConvParam & p = _param;
float * bufS = Buffer(buf);
float * bufD = bufS + _strideS * _count;
Avx::Winograd2x3pSetInput(src, p.srcC, p.srcH, p.srcW, buf, _pad);
for (size_t i = 0; i < _count; ++i)
Avx::Gemm32fNN(_M, _N, _K, &_1, _weight.data + i * _strideW, _K, bufS + i * _strideS, _N, &_0, bufD + i * _strideD, _N);
Avx::Winograd2x3pSetOutput(bufD, dst, p.dstC, p.dstH, p.dstW);
Avx::ConvolutionBiasAndActivation(_bias, p.dstC, p.dstH*p.dstW, p.activation, _params, dst);
}
//---------------------------------------------------------------------
ConvolutionDirect::ConvolutionDirect(const ConvParam & p)
: Sse::ConvolutionDirect(p)
{
_convolutionBiasActivation = SetConvolutionBiasActivation();
}
template <size_t size> SIMD_INLINE void LoadWeight(const float * src, __m256 * dst)
{
for (size_t i = 0; i < size; ++i)
dst[i] = _mm256_set1_ps(src[i]);
}
template<int kernel, int stride> struct Kernel
{
static __m256 Convolution(const float * src, size_t step, const __m256 * weight);
};
template<> struct Kernel<1, 1>
{
static SIMD_INLINE __m256 Convolution(const float * src, size_t step, const __m256 * weight)
{
return _mm256_mul_ps(_mm256_loadu_ps(src), weight[0]);
}
};
template<> struct Kernel<2, 1>
{
static SIMD_INLINE __m256 RowConv(const float * src, const __m256 * weight)
{
return _mm256_add_ps(_mm256_mul_ps(_mm256_loadu_ps(src + 0), weight[0]), _mm256_mul_ps(_mm256_loadu_ps(src + 1), weight[1]));
}
static SIMD_INLINE __m256 Convolution(const float * src, size_t step, const __m256 * weight)
{
return _mm256_add_ps(RowConv(src, weight), RowConv(src + step, weight + 2));
}
};
template<> struct Kernel<3, 1>
{
static SIMD_INLINE __m256 RowConv(const float * src, const __m256 * weight)
{
return _mm256_add_ps(_mm256_mul_ps(_mm256_loadu_ps(src), weight[0]),
_mm256_add_ps(_mm256_mul_ps(_mm256_loadu_ps(src + 1), weight[1]),
_mm256_mul_ps(_mm256_loadu_ps(src + 2), weight[2])));
}
static SIMD_INLINE __m256 Convolution(const float * src, size_t step, const __m256 * weight)
{
return _mm256_add_ps(RowConv(src, weight),
_mm256_add_ps(RowConv(src + step, weight + 3),
RowConv(src + 2 * step, weight + 6)));
}
};
template<::SimdConvolutionActivationType type> SIMD_INLINE __m256 Activate(__m256 value, const __m256 * params);
template<> SIMD_INLINE __m256 Activate<::SimdConvolutionActivationIdentity>(__m256 value, const __m256 * params)
{
return value;
}
template<> SIMD_INLINE __m256 Activate<::SimdConvolutionActivationRelu>(__m256 value, const __m256 * params)
{
return _mm256_max_ps(_mm256_setzero_ps(), value);
}
template<> SIMD_INLINE __m256 Activate<::SimdConvolutionActivationLeakyRelu>(__m256 value, const __m256 * params)
{
return _mm256_add_ps(_mm256_max_ps(_mm256_setzero_ps(), value), _mm256_mul_ps(params[0], _mm256_min_ps(_mm256_setzero_ps(), value)));
}
template<> SIMD_INLINE __m256 Activate<::SimdConvolutionActivationRestrictRange>(__m256 value, const __m256 * params)
{
return _mm256_min_ps(_mm256_max_ps(params[0], value), params[1]);
}
template<> SIMD_INLINE __m256 Activate<::SimdConvolutionActivationPrelu>(__m256 value, const __m256 * params)
{
return _mm256_add_ps(_mm256_max_ps(_mm256_setzero_ps(), value), _mm256_mul_ps(params[0], _mm256_min_ps(_mm256_setzero_ps(), value)));
}
template<int kernel, int stride, ::SimdConvolutionActivationType type>
void ConvolutionBiasActivation(const float * src, size_t srcC, size_t srcH, size_t srcW, const float * weight,
const float * bias, const float * params, float * dst, size_t dstC, size_t dstH, size_t dstW)
{
__m256 _weight[kernel*kernel];
__m256 _params[2];
_params[0] = _mm256_set1_ps(params[0]);
if (type == ::SimdConvolutionActivationRestrictRange)
_params[1] = _mm256_set1_ps(params[1]);
size_t dstWF = Simd::AlignLo(dstW, F);
__m256 tail = RightNotZero(dstW - dstWF);
for (size_t dc = 0; dc < dstC; ++dc)
{
if (type == ::SimdConvolutionActivationPrelu)
_params[0] = _mm256_set1_ps(params[dc]);
if (srcC == 1)
{
const float * ps = src;
float * pd = dst;
LoadWeight<kernel*kernel>(weight, _weight);
__m256 _bias = bias ? _mm256_set1_ps(bias[dc]) : _mm256_setzero_ps();
for (size_t y = 0; y < dstH; ++y)
{
for (size_t x = 0; x < dstWF; x += F)
{
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, Activate<type>(_mm256_add_ps(_bias, conv), _params));
}
if (dstWF < dstW)
{
size_t x = dstW - F;
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_blendv_ps(_dst, Activate<type>(_mm256_add_ps(_bias, conv), _params), tail));
}
ps += srcW * stride;
pd += dstW;
}
weight += kernel * kernel;
}
else
{
size_t sc = 0;
for (; sc < 1; ++sc)
{
const float * ps = src;
float * pd = dst;
LoadWeight<kernel*kernel>(weight, _weight);
__m256 _bias = bias ? _mm256_set1_ps(bias[dc]) : _mm256_setzero_ps();
for (size_t y = 0; y < dstH; ++y)
{
for (size_t x = 0; x < dstWF; x += F)
{
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_add_ps(_bias, conv));
}
if (dstWF < dstW)
{
size_t x = dstW - F;
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_blendv_ps(_dst, _mm256_add_ps(_bias, conv), tail));
}
ps += srcW * stride;
pd += dstW;
}
weight += kernel * kernel;
}
for (; sc < srcC - 1; ++sc)
{
const float * ps = src + sc * srcW * srcH;
float * pd = dst;
LoadWeight<kernel*kernel>(weight, _weight);
for (size_t y = 0; y < dstH; ++y)
{
for (size_t x = 0; x < dstWF; x += F)
{
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_add_ps(_dst, conv));
}
if (dstWF < dstW)
{
size_t x = dstW - F;
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_add_ps(_dst, _mm256_and_ps(conv, tail)));
}
ps += srcW * stride;
pd += dstW;
}
weight += kernel * kernel;
}
for (; sc < srcC; ++sc)
{
const float * ps = src + sc * srcW * srcH;
float * pd = dst;
LoadWeight<kernel*kernel>(weight, _weight);
for (size_t y = 0; y < dstH; ++y)
{
for (size_t x = 0; x < dstWF; x += F)
{
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, Activate<type>(_mm256_add_ps(_dst, conv), _params));
}
if (dstWF < dstW)
{
size_t x = dstW - F;
__m256 _dst = _mm256_loadu_ps(pd + x);
__m256 conv = Kernel<kernel, stride>::Convolution(ps + x * stride, srcW, _weight);
_mm256_storeu_ps(pd + x, _mm256_blendv_ps(_dst, Activate<type>(_mm256_add_ps(_dst, conv), _params), tail));
}
ps += srcW * stride;
pd += dstW;
}
weight += kernel * kernel;
}
}
dst += dstH * dstW;
}
}
template <int kernel, int stride> ConvolutionDirect::ConvolutionBiasActivationPtr SetConvolutionBiasActivation(::SimdConvolutionActivationType type)
{
switch (type)
{
case ::SimdConvolutionActivationIdentity: return ConvolutionBiasActivation<kernel, stride, ::SimdConvolutionActivationIdentity>;
case ::SimdConvolutionActivationRelu: return ConvolutionBiasActivation<kernel, stride, ::SimdConvolutionActivationRelu>;
case ::SimdConvolutionActivationLeakyRelu: return ConvolutionBiasActivation<kernel, stride, ::SimdConvolutionActivationLeakyRelu>;
case ::SimdConvolutionActivationRestrictRange: return ConvolutionBiasActivation<kernel, stride, ::SimdConvolutionActivationRestrictRange>;
case ::SimdConvolutionActivationPrelu: return ConvolutionBiasActivation<kernel, stride, ::SimdConvolutionActivationPrelu>;
default:
assert(0);
return NULL;
}
}
ConvolutionDirect::ConvolutionBiasActivationPtr ConvolutionDirect::SetConvolutionBiasActivation()
{
const ConvParam & p = _param;
if (p.dstW < F)
return Sse::ConvolutionDirect::SetConvolutionBiasActivation();
switch (p.strideX)
{
case 1:
if (p.kernelX == 1)
return Avx::SetConvolutionBiasActivation<1, 1>(p.activation);
if (p.kernelX == 2)
return Avx::SetConvolutionBiasActivation<2, 1>(p.activation);
if (p.kernelX == 3)
return Avx::SetConvolutionBiasActivation<3, 1>(p.activation);
break;
}
return Sse::ConvolutionDirect::SetConvolutionBiasActivation();
}
//---------------------------------------------------------------------
ConvolutionDepthwiseDotProduct::ConvolutionDepthwiseDotProduct(const ConvParam & p)
: Sse::ConvolutionDepthwiseDotProduct(p)
{
}
SIMD_INLINE void DotProduct(const float * a, const float * b, size_t offset, __m256 & sum)
{
__m256 _a = _mm256_loadu_ps(a + offset);
__m256 _b = _mm256_loadu_ps(b + offset);
sum = _mm256_add_ps(_mm256_mul_ps(_a, _b), sum);
}
SIMD_INLINE float DotProduct(const float * a, const float * b, size_t size)
{
float sum = 0;
size_t partialAlignedSize = AlignLo(size, F);
size_t fullAlignedSize = AlignLo(size, QF);
size_t i = 0;
if (partialAlignedSize)
{
__m256 sums[4] = { _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps() };
if (fullAlignedSize)
{
for (; i < fullAlignedSize; i += QF)
{
DotProduct(a, b, i + F * 0, sums[0]);
DotProduct(a, b, i + F * 1, sums[1]);
DotProduct(a, b, i + F * 2, sums[2]);
DotProduct(a, b, i + F * 3, sums[3]);
}
sums[0] = _mm256_add_ps(_mm256_add_ps(sums[0], sums[1]), _mm256_add_ps(sums[2], sums[3]));
}
for (; i < partialAlignedSize; i += F)
DotProduct(a, b, i, sums[0]);
sum += ExtractSum(sums[0]);
}
for (; i < size; ++i)
sum += a[i] * b[i];
return sum;
}
void ConvolutionDepthwiseDotProduct::Forward(const float * src, float * buf, float * dst)
{
if (_bias)
{
for (size_t i = 0; i < _count; ++i)
dst[i] = DotProduct(src + i * _size, _weight + i * _size, _size) + _bias[i];
}
else
{
for (size_t i = 0; i < _count; ++i)
dst[i] = DotProduct(src + i * _size, _weight + i * _size, _size);
}
if (_param.activation)
ConvolutionBiasAndActivation(NULL, _count, 1, _param.activation, _params, dst);
}
//---------------------------------------------------------------------
void * ConvolutionInit(size_t srcC, size_t srcH, size_t srcW, SimdBool srcT, size_t dstC, SimdBool dstT,
size_t kernelY, size_t kernelX, size_t dilationY, size_t dilationX, size_t strideY, size_t strideX,
size_t padY, size_t padX, size_t padH, size_t padW, size_t group, SimdConvolutionActivationType activation)
{
ConvParam param(srcC, srcH, srcW, srcT, dstC, dstT, kernelY, kernelX, dilationY, dilationX, strideY, strideX, padY, padX, padH, padW, group, activation);
if (!param.Valid())
return NULL;
else if (ConvolutionDepthwiseDotProduct::Preferable(param))
return new ConvolutionDepthwiseDotProduct(param);
else if (ConvolutionWinograd2x3p::Preferable(param))
return new ConvolutionWinograd2x3p(param);
else if (ConvolutionImgToRow::Preferable(param))
return new ConvolutionImgToRow(param);
else if (ConvolutionDirect::Preferable(param))
return new Avx::ConvolutionDirect(param);
else
return new ConvolutionImgToCol(param);
}
}
#endif//SIMD_AVX_ENABLE
}
| 47.273764 | 168 | 0.466179 | frankyhit |
70e09544681d966b75f30c3a0b66d0ff81552c5b | 207 | hpp | C++ | src/scenario/scenario_search.hpp | reyreaud-l/CppTrie | 8e939aa5ff11aecbb7ea79fa38cb5f53bdb0ca17 | [
"MIT"
] | 5 | 2018-07-30T08:50:39.000Z | 2018-08-10T15:41:42.000Z | src/scenario/scenario_search.hpp | reyreaud-l/CppTrie | 8e939aa5ff11aecbb7ea79fa38cb5f53bdb0ca17 | [
"MIT"
] | null | null | null | src/scenario/scenario_search.hpp | reyreaud-l/CppTrie | 8e939aa5ff11aecbb7ea79fa38cb5f53bdb0ca17 | [
"MIT"
] | null | null | null | #include "scenario.hpp"
class ScenarioSearch : public Scenario
{
public:
virtual ~ScenarioSearch();
ScenarioSearch(const std::vector<std::string>& word_list,
std::size_t nqueries);
};
| 18.818182 | 59 | 0.681159 | reyreaud-l |
70e0aacda54edf0132ab4c71556094413a587948 | 3,956 | cpp | C++ | tools/headergen/HeaderGen.cpp | lifting-bits/rellic | 96fc148723be33e1dcdca256d3f28d75dc4339c2 | [
"Apache-2.0"
] | 187 | 2019-10-31T19:31:00.000Z | 2022-03-31T15:37:05.000Z | tools/headergen/HeaderGen.cpp | lifting-bits/rellic | 96fc148723be33e1dcdca256d3f28d75dc4339c2 | [
"Apache-2.0"
] | 116 | 2019-10-25T12:12:58.000Z | 2022-03-30T20:58:04.000Z | tools/headergen/HeaderGen.cpp | lifting-bits/rellic | 96fc148723be33e1dcdca256d3f28d75dc4339c2 | [
"Apache-2.0"
] | 19 | 2019-11-11T02:27:12.000Z | 2021-11-03T17:12:28.000Z | /*
* Copyright (c) 2021-present, Trail of Bits, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <clang/Tooling/Tooling.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <llvm/Support/Host.h>
#include <fstream>
#include <iostream>
#include <streambuf>
#include "rellic/AST/CXXToCDecl.h"
#include "rellic/Version/Version.h"
#ifndef LLVM_VERSION_STRING
#define LLVM_VERSION_STRING LLVM_VERSION_MAJOR << "." << LLVM_VERSION_MINOR
#endif
DEFINE_string(input, "", "Input header file.");
DEFINE_string(output, "", "Output file.");
DECLARE_bool(version);
namespace {
static std::string ReadFile(std::string path) {
auto err_or_buf = llvm::MemoryBuffer::getFile(path);
if (!err_or_buf) {
auto msg = err_or_buf.getError().message();
LOG(FATAL) << "Failed to read input file: " << msg;
}
return err_or_buf.get()->getBuffer().str();
}
} // namespace
static void SetVersion(void) {
std::stringstream version;
auto vs = rellic::Version::GetVersionString();
if (0 == vs.size()) {
vs = "unknown";
}
version << vs << "\n";
if (!rellic::Version::HasVersionData()) {
version << "No extended version information found!\n";
} else {
version << "Commit Hash: " << rellic::Version::GetCommitHash() << "\n";
version << "Commit Date: " << rellic::Version::GetCommitDate() << "\n";
version << "Last commit by: " << rellic::Version::GetAuthorName() << " ["
<< rellic::Version::GetAuthorEmail() << "]\n";
version << "Commit Subject: [" << rellic::Version::GetCommitSubject()
<< "]\n";
version << "\n";
if (rellic::Version::HasUncommittedChanges()) {
version << "Uncommitted changes were present during build.\n";
} else {
version << "All changes were committed prior to building.\n";
}
}
version << "Using LLVM " << LLVM_VERSION_STRING << std::endl;
google::SetVersionString(version.str());
}
int main(int argc, char* argv[]) {
std::stringstream usage;
usage << std::endl
<< std::endl
<< " " << argv[0] << " \\" << std::endl
<< " --input INPUT_HEADER_FILE \\" << std::endl
<< " --output OUTPUT_FILE \\" << std::endl
<< std::endl
// Print the version and exit.
<< " [--version]" << std::endl
<< std::endl;
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
google::SetUsageMessage(usage.str());
SetVersion();
google::ParseCommandLineFlags(&argc, &argv, true);
LOG_IF(ERROR, FLAGS_input.empty())
<< "Must specify the path to an input header file.";
LOG_IF(ERROR, FLAGS_output.empty())
<< "Must specify the path to an output file.";
if (FLAGS_input.empty() || FLAGS_output.empty()) {
std::cerr << google::ProgramUsage();
return EXIT_FAILURE;
}
std::error_code ec;
llvm::raw_fd_ostream output(FLAGS_output, ec, llvm::sys::fs::F_Text);
CHECK(!ec) << "Failed to create output file: " << ec.message();
// Read a CXX AST from our input file
auto cxx_ast_unit =
clang::tooling::buildASTFromCode(ReadFile(FLAGS_input), FLAGS_input);
// Exit if AST generation has failed
if (cxx_ast_unit->getDiagnostics().hasErrorOccurred()) {
return EXIT_FAILURE;
}
// Run our visitor on the CXX AST
std::vector<std::string> args{"-target", llvm::sys::getDefaultTargetTriple()};
auto ast_unit{clang::tooling::buildASTFromCodeWithArgs("", args, "out.c")};
auto& c_ast_ctx = ast_unit->getASTContext();
rellic::CXXToCDeclVisitor visitor(*ast_unit);
// cxx_ast_unit->getASTContext().getTranslationUnitDecl()->dump();
visitor.TraverseDecl(c_ast_ctx.getTranslationUnitDecl());
// Print output
c_ast_ctx.getTranslationUnitDecl()->print(output);
google::ShutDownCommandLineFlags();
google::ShutdownGoogleLogging();
return EXIT_SUCCESS;
}
| 31.149606 | 80 | 0.654954 | lifting-bits |
70e0ef13c81f3597048d79c438d890bace388f38 | 16,473 | cc | C++ | src/kudu/util/file_cache-test.cc | acelyc111/kudu | 55cab441c2d66c92f0c769e98d6a2f079e5563b2 | [
"Apache-2.0"
] | null | null | null | src/kudu/util/file_cache-test.cc | acelyc111/kudu | 55cab441c2d66c92f0c769e98d6a2f079e5563b2 | [
"Apache-2.0"
] | null | null | null | src/kudu/util/file_cache-test.cc | acelyc111/kudu | 55cab441c2d66c92f0c769e98d6a2f079e5563b2 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/util/file_cache.h"
#include <unistd.h>
#include <cstdint>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <gflags/gflags_declare.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "kudu/gutil/basictypes.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/cache.h"
#include "kudu/util/debug-util.h"
#include "kudu/util/env.h"
#include "kudu/util/metrics.h" // IWYU pragma: keep
#include "kudu/util/random.h"
#include "kudu/util/scoped_cleanup.h"
#include "kudu/util/slice.h"
#include "kudu/util/status.h"
#include "kudu/util/test_macros.h"
#include "kudu/util/test_util.h"
DECLARE_bool(cache_force_single_shard);
DECLARE_int32(file_cache_expiry_period_ms);
DECLARE_bool(encrypt_data_at_rest);
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;
namespace {
void SetEncryptionFlags(bool encryption_enabled) {
FLAGS_encrypt_data_at_rest = encryption_enabled;
}
} // namespace
namespace kudu {
template <class FileType>
class FileCacheTest : public KuduTest {
public:
FileCacheTest()
: rand_(SeedRandom()) {
// Simplify testing of the actual cache capacity.
FLAGS_cache_force_single_shard = true;
// Speed up tests that check the number of descriptors.
FLAGS_file_cache_expiry_period_ms = 1;
// libunwind internally uses two file descriptors as a pipe.
// Make sure it gets initialized early so that our fd count
// doesn't get affected by it.
ignore_result(GetStackTraceHex());
initial_open_fds_ = CountOpenFds();
}
int CountOpenFds() const {
// Only count files in the test working directory so that we don't
// accidentally count other fds that might be opened or closed in
// the background by other threads.
return kudu::CountOpenFds(env_, GetTestPath("*"));
}
void SetUp() override {
KuduTest::SetUp();
ASSERT_OK(ReinitCache(1));
}
protected:
Status ReinitCache(int max_open_files) {
cache_.reset(new FileCache("test",
env_,
max_open_files,
/*entity=*/ nullptr));
return cache_->Init();
}
Status WriteTestFile(const string& name, const string& data) {
unique_ptr<RWFile> f;
RWFileOptions opts;
opts.is_sensitive = true;
RETURN_NOT_OK(env_->NewRWFile(opts, name, &f));
RETURN_NOT_OK(f->Write(0, data));
return Status::OK();
}
void AssertFdsAndDescriptors(int num_expected_fds,
int num_expected_descriptors) {
ASSERT_EQ(initial_open_fds_ + num_expected_fds, CountOpenFds());
// The expiry thread may take some time to run.
ASSERT_EVENTUALLY([&]() {
ASSERT_EQ(num_expected_descriptors, cache_->NumDescriptorsForTests());
});
}
Random rand_;
int initial_open_fds_;
unique_ptr<FileCache> cache_;
};
typedef ::testing::Types<RWFile, RandomAccessFile> FileTypes;
TYPED_TEST_SUITE(FileCacheTest, FileTypes);
TYPED_TEST(FileCacheTest, TestBasicOperations) {
// Open a non-existent file.
{
shared_ptr<TypeParam> f;
ASSERT_TRUE(this->cache_->template OpenFile<Env::MUST_EXIST>(
"/does/not/exist", &f).IsNotFound());
NO_FATALS(this->AssertFdsAndDescriptors(0, 0));
}
const string kFile1 = this->GetTestPath("foo");
const string kFile2 = this->GetTestPath("bar");
const string kData1 = "test data 1";
const string kData2 = "test data 2";
// Create some test files.
ASSERT_OK(this->WriteTestFile(kFile1, kData1));
ASSERT_OK(this->WriteTestFile(kFile2, kData2));
NO_FATALS(this->AssertFdsAndDescriptors(0, 0));
{
// Open a test file. It should open an fd and create a descriptor.
shared_ptr<TypeParam> f1;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile1, &f1));
NO_FATALS(this->AssertFdsAndDescriptors(1, 1));
// Spot check the test data by comparing sizes.
for (int i = 0; i < 3; i++) {
uint64_t size;
ASSERT_OK(f1->Size(&size));
ASSERT_EQ(kData1.size(), size);
NO_FATALS(this->AssertFdsAndDescriptors(1, 1));
}
// Open the same file a second time. It should reuse the existing
// descriptor and not open a second fd.
shared_ptr<TypeParam> f2;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile1, &f2));
NO_FATALS(this->AssertFdsAndDescriptors(1, 1));
{
auto uh(this->cache_->cache_->Lookup(kFile1, Cache::EXPECT_IN_CACHE));
ASSERT_TRUE(uh);
}
// Open a second file. This will create a new descriptor, but evict the fd
// opened for the first file, so the fd count should remain constant.
shared_ptr<TypeParam> f3;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile2, &f3));
NO_FATALS(this->AssertFdsAndDescriptors(1, 2));
{
auto uh(this->cache_->cache_->Lookup(kFile1, Cache::EXPECT_IN_CACHE));
ASSERT_FALSE(uh);
}
{
auto uh(this->cache_->cache_->Lookup(kFile2, Cache::EXPECT_IN_CACHE));
ASSERT_TRUE(uh);
}
}
// The descriptors are all out of scope, and so are the cached fds.
NO_FATALS(this->AssertFdsAndDescriptors(0, 0));
// With the cache gone, nothing changes.
this->cache_.reset();
ASSERT_EQ(this->initial_open_fds_, this->CountOpenFds());
}
TYPED_TEST(FileCacheTest, TestDeletion) {
// Deleting a file that doesn't exist does nothing.
ASSERT_TRUE(this->cache_->DeleteFile("/does/not/exist").IsNotFound());
// Create a test file, then delete it. It will be deleted immediately.
const string kFile1 = this->GetTestPath("foo");
const string kData1 = "test data 1";
ASSERT_OK(this->WriteTestFile(kFile1, kData1));
ASSERT_TRUE(this->env_->FileExists(kFile1));
ASSERT_OK(this->cache_->DeleteFile(kFile1));
ASSERT_FALSE(this->env_->FileExists(kFile1));
// Trying to delete it again fails.
ASSERT_TRUE(this->cache_->DeleteFile(kFile1).IsNotFound());
// Create another test file, open it, then delete it. The delete is not
// effected until the last open descriptor is closed. In between, the
// cache won't allow the file to be opened again.
const string kFile2 = this->GetTestPath("bar");
const string kData2 = "test data 2";
ASSERT_OK(this->WriteTestFile(kFile2, kData2));
ASSERT_TRUE(this->env_->FileExists(kFile2));
{
shared_ptr<TypeParam> f1;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile2, &f1));
ASSERT_EQ(this->initial_open_fds_ + 1, this->CountOpenFds());
ASSERT_OK(this->cache_->DeleteFile(kFile2));
{
shared_ptr<TypeParam> f2;
ASSERT_TRUE(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile2, &f2).IsNotFound());
}
ASSERT_TRUE(this->cache_->DeleteFile(kFile2).IsNotFound());
ASSERT_TRUE(this->env_->FileExists(kFile2));
ASSERT_EQ(this->initial_open_fds_ + 1, this->CountOpenFds());
}
ASSERT_FALSE(this->env_->FileExists(kFile2));
ASSERT_EQ(this->initial_open_fds_, this->CountOpenFds());
// Create a test file, open it, and let it go out of scope before
// deleting it. The fd is already evicted and closed; this is effectively a
// non-cached deletion.
const string kFile3 = this->GetTestPath("baz");
const string kData3 = "test data 3";
ASSERT_OK(this->WriteTestFile(kFile3, kData3));
{
shared_ptr<TypeParam> f3;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile3, &f3));
}
ASSERT_TRUE(this->env_->FileExists(kFile3));
ASSERT_EQ(this->initial_open_fds_, this->CountOpenFds());
ASSERT_OK(this->cache_->DeleteFile(kFile3));
ASSERT_FALSE(this->env_->FileExists(kFile3));
ASSERT_EQ(this->initial_open_fds_, this->CountOpenFds());
}
TYPED_TEST(FileCacheTest, TestInvalidation) {
const string kFile1 = this->GetTestPath("foo");
const string kData1 = "test data 1";
ASSERT_OK(this->WriteTestFile(kFile1, kData1));
// Open the file.
shared_ptr<TypeParam> f;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile1, &f));
// Write a new file and rename it in place on top of file1.
const string kFile2 = this->GetTestPath("foo2");
const string kData2 = "test data 2 (longer than original)";
ASSERT_OK(this->WriteTestFile(kFile2, kData2));
ASSERT_OK(this->env_->RenameFile(kFile2, kFile1));
// We should still be able to access the file, since it has a cached fd.
uint64_t size;
ASSERT_OK(f->Size(&size));
ASSERT_EQ(kData1.size(), size);
// If we invalidate it from the cache and try again, it should crash because
// the existing descriptor was invalidated.
this->cache_->Invalidate(kFile1);
ASSERT_DEATH({ f->Size(&size); }, "invalidated");
// But if we re-open the path again, the new descriptor should read the
// new data.
shared_ptr<TypeParam> f2;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile1, &f2));
ASSERT_OK(f2->Size(&size));
ASSERT_EQ(kData2.size(), size);
}
TYPED_TEST(FileCacheTest, TestHeavyReads) {
const int kNumFiles = 20;
const int kNumIterations = 100;
const int kCacheCapacity = 5;
ASSERT_OK(this->ReinitCache(kCacheCapacity));
// Randomly generate some data.
string data;
for (int i = 0; i < 1000; i++) {
data += Substitute("$0", this->rand_.Next());
}
// Write that data to a bunch of files and open them through the cache.
vector<shared_ptr<TypeParam>> opened_files;
for (int i = 0; i < kNumFiles; i++) {
string filename = this->GetTestPath(Substitute("$0", i));
ASSERT_OK(this->WriteTestFile(filename, data));
shared_ptr<TypeParam> f;
ASSERT_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(filename, &f));
opened_files.push_back(f);
}
// Read back the data at random through the cache.
unique_ptr<uint8_t[]> buf(new uint8_t[data.length()]);
for (int i = 0; i < kNumIterations; i++) {
int idx = this->rand_.Uniform(opened_files.size());
const auto& f = opened_files[idx];
uint64_t size;
ASSERT_OK(f->Size(&size));
Slice s(buf.get(), size);
ASSERT_OK(f->Read(0, s));
ASSERT_EQ(data, s);
ASSERT_LE(this->CountOpenFds(),
this->initial_open_fds_ + kCacheCapacity);
}
}
TYPED_TEST(FileCacheTest, TestNoRecursiveDeadlock) {
// This test triggered a deadlock in a previous implementation, when expired
// weak_ptrs were removed from the descriptor map in the descriptor's
// destructor.
alarm(60);
auto cleanup = MakeScopedCleanup([]() {
alarm(0);
});
const string kFile = this->GetTestPath("foo");
ASSERT_OK(this->WriteTestFile(kFile, "test data"));
vector<std::thread> threads;
threads.reserve(2);
for (int i = 0; i < 2; i++) {
threads.emplace_back([&]() {
for (int i = 0; i < 10000; i++) {
shared_ptr<TypeParam> f;
CHECK_OK(this->cache_->template OpenFile<Env::MUST_EXIST>(kFile, &f));
}
});
}
for (auto& t : threads) {
t.join();
}
}
class RandomAccessFileCacheTest :
public FileCacheTest<RandomAccessFile>,
public ::testing::WithParamInterface<bool> {
};
INSTANTIATE_TEST_SUITE_P(, RandomAccessFileCacheTest, ::testing::Values(false, true));
TEST_P(RandomAccessFileCacheTest, TestMemoryFootprintDoesNotCrash) {
SetEncryptionFlags(GetParam());
const string kFile = this->GetTestPath("foo");
ASSERT_OK(this->WriteTestFile(kFile, "test data"));
shared_ptr<RandomAccessFile> f;
ASSERT_OK(cache_->OpenFile<Env::MUST_EXIST>(kFile, &f));
// This used to crash due to a kudu_malloc_usable_size() call on a memory
// address that wasn't the start of an actual heap allocation.
LOG(INFO) << f->memory_footprint();
}
class RWFileCacheTest :
public FileCacheTest<RWFile>,
public ::testing::WithParamInterface<bool> {
};
INSTANTIATE_TEST_SUITE_P(, RWFileCacheTest, ::testing::Values(false, true));
TEST_P(RWFileCacheTest, TestOpenMustCreate) {
SetEncryptionFlags(GetParam());
const string kFile1 = this->GetTestPath("foo");
const string kFile2 = this->GetTestPath("bar");
{
shared_ptr<RWFile> rwf1;
ASSERT_OK(cache_->OpenFile<Env::MUST_CREATE>(kFile1, &rwf1));
NO_FATALS(AssertFdsAndDescriptors(1, 1));
// If there's already a descriptor, a second open will fail in the file cache.
shared_ptr<RWFile> rwf2;
ASSERT_TRUE(cache_->OpenFile<Env::MUST_CREATE>(kFile1, &rwf2).IsAlreadyPresent());
// Now let's evict kFile1.
shared_ptr<RWFile> rwf3;
ASSERT_OK(cache_->OpenFile<Env::MUST_CREATE>(kFile2, &rwf3));
NO_FATALS(AssertFdsAndDescriptors(1, 2));
// The reopen of kFile1 shouldn't be with MUST_CREATE; otherwise this would fail.
ASSERT_OK(rwf1->Sync());
}
{
// Without any existing descriptors, open will fail in the filesystem.
NO_FATALS(AssertFdsAndDescriptors(0, 0));
shared_ptr<RWFile> rwf;
ASSERT_TRUE(cache_->OpenFile<Env::MUST_CREATE>(kFile1, &rwf).IsAlreadyPresent());
}
}
TEST_P(RWFileCacheTest, TestOpenCreateOrOpen) {
SetEncryptionFlags(GetParam());
const string kFile1 = this->GetTestPath("foo");
const string kFile2 = this->GetTestPath("bar");
shared_ptr<RWFile> rwf1;
ASSERT_OK(cache_->OpenFile<Env::CREATE_OR_OPEN>(kFile1, &rwf1));
// If there's already a descriptor, a second open will also succeed.
shared_ptr<RWFile> rwf2;
ASSERT_OK(cache_->OpenFile<Env::CREATE_OR_OPEN>(kFile1, &rwf2));
// Now let's evict kFile1.
shared_ptr<RWFile> rwf3;
ASSERT_OK(cache_->OpenFile<Env::CREATE_OR_OPEN>(kFile2, &rwf3));
NO_FATALS(AssertFdsAndDescriptors(1, 2));
// The reopen of kFile1 should use MUST_EXIST. If we delete the file out
// from under the cache, we can see this in action as the reopen fails.
ASSERT_OK(env_->DeleteFile(kFile1));
ASSERT_TRUE(rwf1->Sync().IsNotFound());
}
class MixedFileCacheTest :
public KuduTest,
public ::testing::WithParamInterface<bool> {
};
INSTANTIATE_TEST_SUITE_P(, MixedFileCacheTest, ::testing::Values(false, true));
TEST_P(MixedFileCacheTest, TestBothFileTypes) {
SetEncryptionFlags(GetParam());
const string kFile1 = GetTestPath("foo");
const string kData1 = "test data 1";
const string kFile2 = GetTestPath("foo2");
const string kData2 = "test data 2";
// Create the two test files.
{
unique_ptr<RWFile> f;
RWFileOptions opts;
opts.is_sensitive = true;
ASSERT_OK(env_->NewRWFile(opts, kFile1, &f));
ASSERT_OK(f->Write(0, kData1));
ASSERT_OK(env_->NewRWFile(opts, kFile2, &f));
ASSERT_OK(f->Write(0, kData2));
}
FileCache cache("test", env_, 1, /*entity=*/ nullptr);
ASSERT_OK(cache.Init());
// Open the test files, each as a different file type.
shared_ptr<RWFile> rwf;
ASSERT_OK(cache.OpenFile<Env::MUST_EXIST>(kFile1, &rwf));
shared_ptr<RandomAccessFile> raf;
ASSERT_OK(cache.OpenFile<Env::MUST_EXIST>(kFile2, &raf));
// Verify the correct file contents for each test file.
uint64_t size;
ASSERT_OK(rwf->Size(&size));
uint8_t buf[16];
Slice s1(buf, size);
ASSERT_OK(rwf->Read(0, s1));
ASSERT_EQ(kData1, s1);
ASSERT_OK(raf->Size(&size));
Slice s2(buf, size);
ASSERT_OK(raf->Read(0, s2));
ASSERT_EQ(kData2, s2);
// It's okay to reopen the test file using the same file type, but not with a
// different file type.
//
// These checks are expensive so they're only done in DEBUG mode.
shared_ptr<RWFile> rwf2;
ASSERT_OK(cache.OpenFile<Env::MUST_EXIST>(kFile1, &rwf2));
shared_ptr<RandomAccessFile> raf2;
ASSERT_OK(cache.OpenFile<Env::MUST_EXIST>(kFile2, &raf2));
#ifndef NDEBUG
ASSERT_DEATH({ cache.OpenFile<Env::MUST_EXIST>(kFile1, &raf); },
"!FindDescriptorUnlocked");
ASSERT_DEATH({ cache.OpenFile<Env::MUST_EXIST>(kFile2, &rwf); },
"!FindDescriptorUnlocked");
#endif
}
} // namespace kudu
| 33.413793 | 94 | 0.698841 | acelyc111 |
70e1051c3595d3701e7ed5abeb542251d0a322c8 | 379 | hpp | C++ | src/feedback_client.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | 2 | 2017-01-02T02:02:23.000Z | 2021-04-15T09:21:27.000Z | src/feedback_client.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | null | null | null | src/feedback_client.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | null | null | null | #pragma once
#include "client.hpp"
#include <wangle/channel/Pipeline.h>
#include <chrono>
typedef wangle::DefaultPipeline FeedbackClientPipeline;
typedef Client<FeedbackClientPipeline> FeedbackClient;
std::shared_ptr<wangle::PipelineFactory<FeedbackClientPipeline>>
FeedbackClientPipelineFactory(Client<FeedbackClientPipeline>* client, std::chrono::seconds reconnectTimeout);
| 31.583333 | 109 | 0.83905 | sgalkin |
70e46ee73ac188f7bc00891d0b95574a46b84414 | 2,457 | hpp | C++ | include/atd/stats/ExponentialSmoothing.hpp | galeone/openatd | b60c5fb774d8310e867363503dd4eb40bb2c8481 | [
"Apache-2.0"
] | 15 | 2017-11-06T17:20:29.000Z | 2021-12-09T19:31:18.000Z | include/atd/stats/ExponentialSmoothing.hpp | galeone/openatd | b60c5fb774d8310e867363503dd4eb40bb2c8481 | [
"Apache-2.0"
] | null | null | null | include/atd/stats/ExponentialSmoothing.hpp | galeone/openatd | b60c5fb774d8310e867363503dd4eb40bb2c8481 | [
"Apache-2.0"
] | 2 | 2018-07-21T20:37:34.000Z | 2021-02-01T19:55:01.000Z | /* Copyright 2017 Paolo Galeone <nessuno@nerdz.eu>. 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.*/
#ifndef ATD_STATS_H_
#define ATD_STATS_H_
#include <algorithm>
#include <cmath>
#include <numeric>
#include <tuple>
#include <vector>
namespace atd::stats {
/* First order exponential smoothing on vector ts, using the specified alpha
* factor*/
template <typename T>
class ExponentialSmoothing {
private:
// smoothing factor
T _alpha1, _alpha2;
std::vector<T> _ts, _first, _second;
public:
ExponentialSmoothing(std::vector<T> const &ts) { _ts = ts; }
/* Compute first order exponential smoothing. The result is stored
* internally and a copy of the smoothed time series is returned. */
const std::vector<T> first_order(T alpha1);
/* Second order exponential smoothing on vector ts, using the specified
* alpha factor. Brown's linear exponential smoothing (LES) aka Brown's
* double exp smoothing. Returns the second order smoothed series.*/
const inline std::pair<std::vector<T>, std::vector<T>> second_order(
T alpha2);
/* Given the resulting series of second_exp_smoothing, returns the series of
* the estimate values from 0 to the given time step. If the input time
* series have a size of N, then the result with t <= N will be the second
* order exponential smoothing value at t. If t > N it will be the second
* order forecast. In both cases the formula is: a_t = 2s'_t - s''t; =
* estimated level at time t b_t = \frac{alpha}{1-alpha}(s't - s''t); =
* estimated trend at time t F_{t+m} = a_t + m b_t, where m is != 0 only if
* t > N (m = N - t) The return value is the pari a_t, b_t
* TODO: sistemare questa funzione per farla andare. Muovere classe in
* header+cc separati
*/
const inline std::pair<T, T> second_order_forecast(size_t t);
};
} // namespace atd::stats
#endif // ATD_STATS_H_
| 37.8 | 80 | 0.700041 | galeone |
70e5328911d010f88f69a176d26d993df81ff387 | 727 | hpp | C++ | src/light/pointLight.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:29.000Z | 2021-09-13T20:22:29.000Z | src/light/pointLight.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | null | null | null | src/light/pointLight.hpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:31.000Z | 2021-09-13T20:22:31.000Z | #pragma once
#include "light.hpp"
#include <glm/glm.hpp>
class PointLight : public Light {
public:
PointLight(
glm::vec3 position,
glm::vec3 color,
float intensity,
float ambientCoefficient,
float attenuation
);
PointLight(PointLight&& other) = default;
PointLight& operator=(PointLight&& other) = default;
PointLight(const PointLight& other) = default;
PointLight& operator=(const PointLight& other) = default;
~PointLight() {};
void setPosition(glm::vec3 p) {
position = p;
}
LightInfo getLightInfo() const override;
private:
glm::vec3 position;
};
| 22.030303 | 65 | 0.570839 | mfirmin |
70e5f00096b4da76b6cb02fbece33d9223fd8d42 | 2,238 | cpp | C++ | src/ngraph/frontend/onnx_import/op/eye_like.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/op/eye_like.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/ngraph/frontend/onnx_import/op/eye_like.cpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 <memory>
#include "exceptions.hpp"
#include "eye_like.hpp"
#include "utils/common.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace op
{
namespace set_1
{
OutputVector eye_like(const Node& node)
{
const auto input = node.get_ng_inputs().at(0);
const auto& input_shape = input.get_shape();
std::int64_t dtype;
element::Type target_type;
std::int64_t shift = node.get_attribute_value<std::int64_t>("k", 0);
if (node.has_attribute("dtype"))
{
dtype = node.get_attribute_value<std::int64_t>("dtype");
target_type = common::get_ngraph_element_type(dtype);
}
else
{
target_type = input.get_element_type();
}
ASSERT_VALID_ARGUMENT(node, input_shape.size() == 2)
<< "The provided shape rank: " << input_shape.size()
<< " is unsupported, only 2D shapes are supported";
std::shared_ptr<ngraph::Node> eye_like_matrix =
common::shifted_square_identity(input_shape, target_type, shift);
return {eye_like_matrix};
}
}
}
}
}
| 35.52381 | 89 | 0.511618 | pqLee |
70ecdb64cd34cc1d408f806680b8114fe30c674d | 7,737 | cpp | C++ | gauss_tools/src/flight_plan_kml_to_json.cpp | hecperleo/gauss | 20ece37af00455ee760dcef1d583300eaa347a1d | [
"MIT"
] | 2 | 2021-06-22T16:53:08.000Z | 2021-11-27T05:06:49.000Z | gauss_tools/src/flight_plan_kml_to_json.cpp | hecperleo/gauss | 20ece37af00455ee760dcef1d583300eaa347a1d | [
"MIT"
] | 1 | 2021-09-10T10:24:20.000Z | 2021-09-10T10:24:20.000Z | gauss_tools/src/flight_plan_kml_to_json.cpp | hecperleo/gauss | 20ece37af00455ee760dcef1d583300eaa347a1d | [
"MIT"
] | 4 | 2021-03-25T12:50:23.000Z | 2022-03-11T11:14:21.000Z | #include <stdio.h>
#include <ros/ros.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <jsoncpp/json/json.h>
#include <pugixml.hpp>
#include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/LocalCartesian.hpp>
#define NOMINAL_SPEED 5.0 // meters per second
inline double distanceBetweenWaypoints(double &x1, double &y1, double &z1, double &x2, double &y2, double &z2);
inline double distanceBetweenWaypoints(double &x1, double &y1, double &z1, double &x2, double &y2, double &z2)
{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2)+pow(z1-z2,2));
}
int main(int argc, char** argv)
{
if(argc != 3)
{
std::cout << "Usage: flight_plan_kml_to_json KML_filename KML_INPUT_FILE JSON_OUTPUT_FILE\n";
return 1;
}
double lat0,lon0;
lat0 = 37.094784;
lon0 = -6.735478;
GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(), GeographicLib::Constants::WGS84_f());
GeographicLib::LocalCartesian proj(lat0,lon0,0,earth);
std::string kml_filename(argv[1]);
std::string json_filename(argv[2]);
Json::Value root;
/*
root["flight_plan"]["waypoints"] = Json::arrayValue;
Json::Value waypoint;
waypoint["x"] = 0;
waypoint["y"] = 0;
waypoint["z"] = 0;
waypoint["stamp"] = 0;
waypoint["mandatory"] = 0;
*/
root["icao"] = 11259137;
root["flight_plan_id"] = "MISSION01";
root["new_flight_plan"] = Json::arrayValue;
Json::Value flight_plan_array = Json::arrayValue;
/*
std::stringstream flight_plan_ss;
flight_plan_ss << std::fixed;
flight_plan_ss << std::setprecision(6);
flight_plan_ss << "[";
*/
// Read kml file
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(kml_filename.c_str());
//std::cout << "Result description: " << result.description() << "\n";
ros::Time::init();
double initial_timestamp = ros::Time::now().toSec();
double current_timestamp;
double previous_timestamp;
std::cout << "Doc:\n";
//std::cout << doc.value() << "\n";
pugi::xml_node kml_node = doc.document_element();
//std::cout << kml_node.attribute("xmlns").value() << "\n";
pugi::xml_node document_node = kml_node.child("Document");
pugi::xml_node placemark_node = document_node.child("Placemark");
if(placemark_node.empty())
std::cout << "Placemark node empty\n";
std::cout << "Placemark id: " << placemark_node.attribute("id").value() << "\n";
bool kml_end_found = false;
bool first_waypoint = true;
double previous_x, previous_y,previous_z;
while(!kml_end_found)
{
pugi::xml_node name_node = placemark_node.child("name");
if(name_node.empty())
std::cout << "name node empty\n";
std::string name_string(name_node.text().as_string());
std::cout << "Name string: " << name_string << "\n";
if(name_string[0] == 'W' && name_string[1] == 'P')
{
Json::Value waypoint_array = Json::arrayValue;
pugi::xml_node point_node = placemark_node.child("Point");
pugi::xml_node coordinates_node = point_node.child("coordinates");
std::string coordinates(coordinates_node.text().as_string());
std::cout << "Coordinates: " << coordinates << "\n";
std::vector<std::string> comma_separated_strings;
comma_separated_strings.push_back("");
int comma_counter = 0;
for(int i=0; i<coordinates.size(); i++)
{
if(coordinates[i] == ',')
{
comma_separated_strings.push_back("");
comma_counter++;
} else {
comma_separated_strings.at(comma_counter) += coordinates[i];
}
}
// Extract flight plan waypoints
double latitude,longitude,altitude;
longitude = atof(comma_separated_strings[0].c_str());
latitude = atof(comma_separated_strings[1].c_str());
pugi::xml_node look_at_node = placemark_node.child("LookAt");
//pugi::xml_node longitude_node = look_at_node.child("longitude");
//pugi::xml_node latitude_node = look_at_node.child("latitude");
pugi::xml_node altitude_node = look_at_node.child("altitude");
//latitude = latitude_node.text().as_double();
//longitude = longitude_node.text().as_double();
altitude = altitude_node.text().as_double();
// Convert geographic coordinates to local coordinates
double x,y,z;
proj.Forward(latitude,longitude,altitude,x,y,z);
/*
waypoint["x"] = x;
waypoint["y"] = y;
waypoint["z"] = z;
waypoint["stamp"] = timestamp;
*/
/*
if(first_waypoint)
{
current_timestamp = initial_timestamp;
previous_timestamp = current_timestamp;
previous_x = x;
previous_y = y;
previous_z = z;
first_waypoint = false;
//flight_plan_ss << "(" << x << "," << y << "," << z << "," << current_timestamp << ")";
flight_plan_ss << "[" << std::setw(10) << lon << std::setw(1) <<"," << std::setw(10) << lat << std::setw(1) << "," << z << std::setw(1) << "," << std::setw(10) << current_timestamp << std::setw(1)<< "]";
}
else
{
double delta_time = distanceBetweenWaypoints(x,y,z,previous_x,previous_y,previous_z)/NOMINAL_SPEED;
current_timestamp = previous_timestamp + delta_time;
previous_timestamp = current_timestamp;
previous_x = x;
previous_y = y;
previous_z = z;
//flight_plan_ss << ",(" << std::setw(10) << x << std::setw(1) <<"," << std::setw(10) << y << std::setw(1) << "," << z << std::setw(1) << "," << std::setw(10) << current_timestamp << std::setw(1)<< ")";
flight_plan_ss << ",[" << std::setw(10) << lon << std::setw(1) <<"," << std::setw(10) << lat << std::setw(1) << "," << z << std::setw(1) << "," << std::setw(10) << current_timestamp << std::setw(1)<< "]";
}
*/
if(first_waypoint)
{
current_timestamp = initial_timestamp;
previous_timestamp = current_timestamp;
first_waypoint = false;
}
else
{
double delta_time = distanceBetweenWaypoints(x,y,z,previous_x,previous_y,previous_z)/NOMINAL_SPEED;
current_timestamp = previous_timestamp + delta_time;
previous_timestamp = current_timestamp;
}
waypoint_array.append(longitude);
waypoint_array.append(latitude);
waypoint_array.append(altitude);
waypoint_array.append(current_timestamp);
flight_plan_array.append(waypoint_array);
//root["flight_plan"]["waypoints"].append(waypoint);
}
else
{
kml_end_found = true;
}
placemark_node = placemark_node.next_sibling();
if(placemark_node.empty())
kml_end_found = true;
}
/*
flight_plan_ss << "]";
root["new_flight_plan"] = flight_plan_ss.str();
*/
root["new_flight_plan"] = flight_plan_array;
// Write flight plan JSON to file
std::ofstream json_filestream(json_filename.c_str());
if(json_filestream.is_open())
{
json_filestream << root;
}
return 0;
} | 36.323944 | 220 | 0.565465 | hecperleo |
70f0b1da76a4055e015d7f1839f07c68fd56af60 | 2,116 | cpp | C++ | src/pola/utils/SharedBuffer.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | src/pola/utils/SharedBuffer.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | src/pola/utils/SharedBuffer.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null |
#include <stdlib.h>
#include <string.h>
#include "pola/utils/SharedBuffer.h"
// ---------------------------------------------------------------------------
namespace pola {
namespace utils {
SharedBuffer* SharedBuffer::alloc(size_t size)
{
SharedBuffer* sb = static_cast<SharedBuffer *>(malloc(sizeof(SharedBuffer) + size));
if (sb) {
sb->mRefs = 1;
sb->mSize = size;
}
return sb;
}
ssize_t SharedBuffer::dealloc(const SharedBuffer* released)
{
if (released->mRefs != 0) return -1; // XXX: invalid operation
free(const_cast<SharedBuffer*>(released));
return 0;
}
SharedBuffer* SharedBuffer::edit() const
{
if (onlyOwner()) {
return const_cast<SharedBuffer*>(this);
}
SharedBuffer* sb = alloc(mSize);
if (sb) {
memcpy(sb->data(), data(), size());
release();
}
return sb;
}
SharedBuffer* SharedBuffer::editResize(size_t newSize) const
{
if (onlyOwner()) {
SharedBuffer* buf = const_cast<SharedBuffer*>(this);
if (buf->mSize == newSize) return buf;
buf = (SharedBuffer*)realloc(buf, sizeof(SharedBuffer) + newSize);
if (buf != NULL) {
buf->mSize = newSize;
return buf;
}
}
SharedBuffer* sb = alloc(newSize);
if (sb) {
const size_t mySize = mSize;
memcpy(sb->data(), data(), newSize < mySize ? newSize : mySize);
release();
}
return sb;
}
SharedBuffer* SharedBuffer::attemptEdit() const
{
if (onlyOwner()) {
return const_cast<SharedBuffer*>(this);
}
return 0;
}
SharedBuffer* SharedBuffer::reset(size_t new_size) const
{
// cheap-o-reset.
SharedBuffer* sb = alloc(new_size);
if (sb) {
release();
}
return sb;
}
void SharedBuffer::acquire() const {
++ mRefs;
}
int32_t SharedBuffer::release(uint32_t flags) const
{
int32_t prev = 1;
if (onlyOwner() || ((prev = (-- mRefs)) == 1)) {
mRefs = 0;
if ((flags & eKeepStorage) == 0) {
free(const_cast<SharedBuffer*>(this));
}
}
return prev;
}
}
};
| 21.373737 | 88 | 0.560019 | lij0511 |
70f22934eafa1cb0c6af3cad35cea723308a3d9c | 3,320 | cpp | C++ | 3rdparty/detours/samples/slept/slept.cpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | 3rdparty/detours/samples/slept/slept.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | 3rdparty/detours/samples/slept/slept.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 43 | 2015-01-21T02:15:46.000Z | 2022-01-12T20:44:59.000Z | //////////////////////////////////////////////////////////////////////////////
//
// Detour Test Program (slept.cpp of slept.dll)
//
// Microsoft Research Detours Package, Version 3.0.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#include <stdio.h>
#include <windows.h>
#include "detours.h"
#include "slept.h"
#include "verify.cpp"
static BOOL fBroke = FALSE;
static LONG dwSlept = 0;
static DWORD (WINAPI * TrueSleepEx)(DWORD dwMilliseconds, BOOL bAlertable) = SleepEx;
DWORD WINAPI UntimedSleepEx(DWORD dwMilliseconds, BOOL bAlertable)
{
return TrueSleepEx(dwMilliseconds, bAlertable);
}
DWORD WINAPI TimedSleepEx(DWORD dwMilliseconds, BOOL bAlertable)
{
DWORD dwBeg = GetTickCount();
DWORD ret = TrueSleepEx(dwMilliseconds, bAlertable);
DWORD dwEnd = GetTickCount();
if (!fBroke) {
fBroke = TRUE;
// DebugBreak();
}
InterlockedExchangeAdd(&dwSlept, dwEnd - dwBeg);
return ret;
}
DWORD WINAPI GetSleptTicks(VOID)
{
return dwSlept;
}
DWORD WINAPI TestTicks(VOID)
{
return TestTicksEx(0);
}
DWORD WINAPI TestTicksEx(DWORD Add)
{
PDWORD pdw = new DWORD [Add + 1];
if (pdw != NULL) {
pdw[0] = dwSlept;
for (DWORD n = 1; n < Add + 1; n++) {
pdw[n] = pdw[n-1] + 1;
}
for (DWORD n = 1; n < Add + 1; n++) {
pdw[n-1] = pdw[n-1] - 1;
}
for (DWORD n = 1; n < Add + 1; n++) {
pdw[n] = pdw[n-1] + 1;
}
Add = pdw[Add] - Add;
delete pdw;
}
else {
Add = dwSlept + Add;
}
return Add;
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
LONG error;
(void)hinst;
(void)reserved;
if (DetourIsHelperProcess()) {
return TRUE;
}
if (dwReason == DLL_PROCESS_ATTACH) {
DetourRestoreAfterWith();
printf("slept" DETOURS_STRINGIFY(DETOURS_BITS) ".dll: "
" Starting.\n");
PVOID pbExeEntry = DetourGetEntryPoint(NULL);
PVOID pbDllEntry = DetourGetEntryPoint(hinst);
printf("slept" DETOURS_STRINGIFY(DETOURS_BITS) ".dll: "
" ExeEntry=%p, DllEntry=%p\n", pbExeEntry, pbDllEntry);
Verify("SleepEx", (PVOID)SleepEx);
printf("\n");
fflush(stdout);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)TrueSleepEx, TimedSleepEx);
error = DetourTransactionCommit();
if (error == NO_ERROR) {
printf("slept" DETOURS_STRINGIFY(DETOURS_BITS) ".dll: "
" Detoured SleepEx().\n");
}
else {
printf("slept" DETOURS_STRINGIFY(DETOURS_BITS) ".dll: "
" Error detouring SleepEx(): %d\n", error);
}
}
else if (dwReason == DLL_PROCESS_DETACH) {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)TrueSleepEx, TimedSleepEx);
error = DetourTransactionCommit();
printf("slept" DETOURS_STRINGIFY(DETOURS_BITS) ".dll: "
" Removed SleepEx() detour (%d), slept %d ticks.\n", error, dwSlept);
fflush(stdout);
}
return TRUE;
}
//
///////////////////////////////////////////////////////////////// End of File.
| 25.343511 | 85 | 0.564157 | wohaaitinciu |
70f698ca353208a9e2182bd5e89c1ddb9688de45 | 972 | hpp | C++ | Music/OnMei/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Music/OnMei/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Music/OnMei/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Music/OnMei/a_Body.hpp
#pragma once
#include "a.hpp"
#include "KanOn/a_Body.hpp"
#include "HenKaKiGou/a_Body.hpp"
#include "../../Mathematics/Arithmetic/Mod/a_Body.hpp"
inline OnMei::OnMei( const KanOn& N ) noexcept : OnMei( N , HenKaKiGou( 0 ) ){}
inline OnMei::OnMei( const KanOn& N , const HenKaKiGou& S ) noexcept : m_N( N ) , m_S( S ), m_pc( KanOnToPitchClass( N ) + S.GetNum() ) {}
inline string OnMei::Display() const noexcept { return m_N.Display() + m_S.Display(); }
inline const KanOn& OnMei::GetKanOn() const noexcept { return m_N; }
inline const HenKaKiGou& OnMei::GetHenKaKiGou() const noexcept { return m_S; }
inline const PitchClass& OnMei::GetPitchClass() const noexcept { return m_pc; }
inline bool operator==( const OnMei& N1 , const OnMei& N2 ) noexcept { return N1.Display() == N2.Display(); }
inline bool operator!=( const OnMei& N1 , const OnMei& N2 ) noexcept { return !( N1 == N2 ); }
| 48.6 | 139 | 0.687243 | p-adic |
70f835fb933473add54201ba766868762a9f453f | 21,669 | cc | C++ | src/components/security_manager/src/security_manager_impl.cc | shoamano83/sdl_core | ea5960280585d11ee02542b0ab183d4400ed691d | [
"BSD-3-Clause"
] | null | null | null | src/components/security_manager/src/security_manager_impl.cc | shoamano83/sdl_core | ea5960280585d11ee02542b0ab183d4400ed691d | [
"BSD-3-Clause"
] | null | null | null | src/components/security_manager/src/security_manager_impl.cc | shoamano83/sdl_core | ea5960280585d11ee02542b0ab183d4400ed691d | [
"BSD-3-Clause"
] | 1 | 2020-04-22T07:17:49.000Z | 2020-04-22T07:17:49.000Z | /*
* Copyright (c) 2018, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "security_manager/security_manager_impl.h"
#include <functional>
#include "security_manager/crypto_manager_impl.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/logger.h"
#include "utils/byte_order.h"
#include "json/json.h"
#include "utils/helpers.h"
namespace security_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "SecurityManager")
static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl(
std::unique_ptr<utils::SystemTimeHandler>&& system_time_handler)
: security_messages_("SecurityManager", this)
, session_observer_(NULL)
, crypto_manager_(NULL)
, protocol_handler_(NULL)
, system_time_handler_(std::move(system_time_handler))
, waiting_for_certificate_(false)
, waiting_for_time_(false) {
DCHECK(system_time_handler_);
system_time_handler_->SubscribeOnSystemTime(this);
}
SecurityManagerImpl::~SecurityManagerImpl() {
system_time_handler_->UnsubscribeFromSystemTime(this);
}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
if (message->service_type() != protocol_handler::kControl) {
return;
}
SecurityMessage securityMessagePtr(std::make_shared<SecurityQuery>());
const bool result =
securityMessagePtr->SerializeQuery(message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(
message->connection_key(), ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
// Post message to message query for next processing in thread
security_messages_.PostMessage(securityMessagePtr);
}
void SecurityManagerImpl::OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr) {}
void SecurityManagerImpl::set_session_observer(
protocol_handler::SessionObserver* observer) {
if (!observer) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SessionObserver.");
return;
}
session_observer_ = observer;
}
void SecurityManagerImpl::set_protocol_handler(
protocol_handler::ProtocolHandler* handler) {
if (!handler) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to ProtocolHandler.");
return;
}
protocol_handler_ = handler;
}
void SecurityManagerImpl::set_crypto_manager(CryptoManager* crypto_manager) {
if (!crypto_manager) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to CryptoManager.");
return;
}
crypto_manager_ = crypto_manager;
}
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
LOG4CXX_INFO(logger_, "Received Security message from Mobile side");
if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(
message->get_connection_key(), ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
case SecurityQuery::SEND_HANDSHAKE_DATA:
if (!ProccessHandshakeData(message)) {
LOG4CXX_ERROR(logger_, "Proccess HandshakeData failed");
}
break;
case SecurityQuery::SEND_INTERNAL_ERROR:
if (!ProccessInternalError(message)) {
LOG4CXX_ERROR(logger_, "Processing income InternalError failed");
}
break;
default: {
// SecurityQuery::InvalidQuery
const std::string error_text("Unknown query identifier.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
ERROR_INVALID_QUERY_ID,
error_text,
message->get_header().seq_number);
} break;
}
}
security_manager::SSLContext* SecurityManagerImpl::CreateSSLContext(
const uint32_t& connection_key, ContextCreationStrategy cc_strategy) {
LOG4CXX_INFO(logger_, "ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
if (kUseExisting == cc_strategy) {
security_manager::SSLContext* ssl_context =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
// If SSLContext for current connection/session exists - return it
if (ssl_context) {
return ssl_context;
}
}
security_manager::SSLContext* ssl_context =
crypto_manager_->CreateSSLContext();
if (!ssl_context) {
const std::string error_text("CryptoManager could not create SSL context.");
LOG4CXX_ERROR(logger_, error_text);
// Generate response query and post to security_messages_
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
return NULL;
}
const int result =
session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
SendInternalError(connection_key, result, "");
return NULL;
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
LOG4CXX_DEBUG(logger_,
"Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::PostponeHandshake(const uint32_t connection_key) {
LOG4CXX_TRACE(logger_, "Handshake postponed");
sync_primitives::AutoLock lock(connections_lock_);
if (waiting_for_certificate_) {
awaiting_certificate_connections_.insert(connection_key);
}
if (waiting_for_time_) {
awaiting_time_connections_.insert(connection_key);
}
}
void SecurityManagerImpl::ResumeHandshake(uint32_t connection_key) {
LOG4CXX_TRACE(logger_, "Handshake resumed");
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kForceRecreation);
if (!ssl_context) {
LOG4CXX_WARN(logger_,
"Unable to resume handshake. No SSL context for key "
<< connection_key);
return;
}
ssl_context->ResetConnection();
if (!waiting_for_certificate_ && !ssl_context->HasCertificate()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
ProceedHandshake(ssl_context, connection_key);
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
LOG4CXX_INFO(logger_, "StartHandshake: connection_key " << connection_key);
security_manager::SSLContext* ssl_context = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!ssl_context) {
const std::string error_text(
"StartHandshake failed, "
"connection is not protected");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
if (!ssl_context->HasCertificate()) {
LOG4CXX_ERROR(logger_, "Security certificate is absent");
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
NotifyOnCertificateUpdateRequired();
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = true;
}
PostponeHandshake(connection_key);
system_time_handler_->QuerySystemTime();
}
bool SecurityManagerImpl::IsSystemTimeProviderReady() const {
return system_time_handler_->system_time_can_be_received();
}
void SecurityManagerImpl::ProceedHandshake(
security_manager::SSLContext* ssl_context, uint32_t connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
if (!ssl_context) {
LOG4CXX_WARN(logger_,
"Unable to process handshake. No SSL context for key "
<< connection_key);
return;
}
if (ssl_context->IsInitCompleted()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
return;
}
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
LOG4CXX_ERROR(logger_, "Failed to get certificate due date!");
return;
}
if (crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date)) {
LOG4CXX_DEBUG(logger_, "Host certificate update required");
if (helpers::in_range(awaiting_certificate_connections_, connection_key)) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_CertExpired);
return;
}
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = true;
}
PostponeHandshake(connection_key);
NotifyOnCertificateUpdateRequired();
return;
}
SSLContext::HandshakeContext handshake_context =
session_observer_->GetHandshakeContext(connection_key);
handshake_context.system_time = system_time_handler_->GetUTCTime();
ssl_context->SetHandshakeContext(handshake_context);
size_t data_size = 0;
const uint8_t* data = NULL;
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
if (data != NULL && data_size != 0) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
bool SecurityManagerImpl::IsCertificateUpdateRequired(
const uint32_t connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
security_manager::SSLContext* ssl_context =
CreateSSLContext(connection_key, kUseExisting);
DCHECK_OR_RETURN(ssl_context, true);
LOG4CXX_DEBUG(logger_,
"Set SSL context to connection_key " << connection_key);
time_t cert_due_date;
if (!ssl_context->GetCertificateDueDate(cert_due_date)) {
LOG4CXX_ERROR(logger_, "Failed to get certificate due date!");
return true;
}
return crypto_manager_->IsCertificateUpdateRequired(
system_time_handler_->GetUTCTime(), cert_due_date);
}
void SecurityManagerImpl::AddListener(SecurityManagerListener* const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_,
"Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
void SecurityManagerImpl::RemoveListener(
SecurityManagerListener* const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_,
"Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
bool SecurityManagerImpl::OnCertificateUpdated(const std::string& data) {
LOG4CXX_AUTO_TRACE(logger_);
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_certificate_ = false;
}
crypto_manager_->OnCertificateUpdated(data);
std::for_each(
awaiting_certificate_connections_.begin(),
awaiting_certificate_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_certificate_connections_.clear();
return true;
}
void SecurityManagerImpl::OnSystemTimeArrived(const time_t utc_time) {
LOG4CXX_AUTO_TRACE(logger_);
{
sync_primitives::AutoLock lock(waiters_lock_);
waiting_for_time_ = false;
}
std::for_each(
awaiting_time_connections_.begin(),
awaiting_time_connections_.end(),
std::bind1st(std::mem_fun(&SecurityManagerImpl::ResumeHandshake), this));
awaiting_time_connections_.clear();
}
void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
const uint32_t& connection_key, SSLContext::HandshakeResult error) {
LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeDone(connection_key, error)) {
LOG4CXX_DEBUG(logger_, "Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
void SecurityManagerImpl::NotifyOnCertificateUpdateRequired() {
LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
(*it)->OnCertificateUpdateRequired();
++it;
}
}
void SecurityManagerImpl::NotifyListenersOnHandshakeFailed() {
LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeFailed()) {
LOG4CXX_DEBUG(logger_, "Destroying listener: " << *it);
delete (*it);
it = listeners_.erase(it);
} else {
++it;
}
}
}
bool SecurityManagerImpl::IsPolicyCertificateDataEmpty() {
LOG4CXX_AUTO_TRACE(logger_);
std::string certificate_data;
for (auto it = listeners_.begin(); it != listeners_.end(); ++it) {
if ((*it)->GetPolicyCertificateData(certificate_data)) {
LOG4CXX_DEBUG(logger_, "Certificate data received from listener");
return certificate_data.empty();
}
}
return false;
}
bool SecurityManagerImpl::ProccessHandshakeData(
const SecurityMessage& inMessage) {
LOG4CXX_INFO(logger_, "SendHandshakeData processing");
DCHECK(inMessage);
DCHECK(inMessage->get_header().query_id ==
SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
LOG4CXX_DEBUG(logger_,
"Received " << inMessage->get_data_size()
<< " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(
connection_key, ERROR_INVALID_QUERY_SIZE, error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
SSLContext* sslContext = session_observer_->GetSSLContext(
connection_key, protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(
connection_key, ERROR_SERVICE_NOT_PROTECTED, error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
const uint8_t* out_data;
const SSLContext::HandshakeResult handshake_result =
sslContext->DoHandshakeStep(inMessage->get_data(),
inMessage->get_data_size(),
&out_data,
&out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string erorr_text(sslContext->LastError());
LOG4CXX_ERROR(logger_,
"SendHandshakeData: Handshake failed: " << erorr_text);
SendInternalError(
connection_key, ERROR_SSL_INVALID_DATA, erorr_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
LOG4CXX_DEBUG(logger_, "SSL initialization finished success.");
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
} else if (handshake_result != SSLContext::Handshake_Result_Success) {
// On handshake fail
LOG4CXX_WARN(logger_, "SSL initialization finished with fail.");
NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
SendHandshakeBinData(connection_key, out_data, out_data_size, seqNumber);
}
return true;
}
bool SecurityManagerImpl::ProccessInternalError(
const SecurityMessage& inMessage) {
LOG4CXX_INFO(logger_,
"Received InternalError with Json message"
<< inMessage->get_json_message());
Json::Value root;
Json::Reader reader;
const bool parsingSuccessful =
reader.parse(inMessage->get_json_message(), root);
if (!parsingSuccessful)
return false;
LOG4CXX_DEBUG(logger_,
"Received InternalError id "
<< root[kErrId].asString()
<< ", text: " << root[kErrText].asString());
return true;
}
void SecurityManagerImpl::SendHandshakeBinData(const uint32_t connection_key,
const uint8_t* const data,
const size_t data_size,
const uint32_t seq_number) {
const SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_HANDSHAKE_DATA,
seq_number);
DCHECK(data_size < 1024 * 1024 * 1024);
const SecurityQuery query =
SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
const uint8_t& error_id,
const std::string& erorr_text,
const uint32_t seq_number) {
Json::Value value;
value[kErrId] = error_id;
value[kErrText] = erorr_text;
const std::string error_str = value.toStyledString();
SecurityQuery::QueryHeader header(
SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_INTERNAL_ERROR,
// header save json size only (exclude last byte)
seq_number,
error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
data_sending[data_sending.size() - 1] = error_id;
const SecurityQuery query(
header, connection_key, &data_sending[0], data_sending.size());
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_,
"Sent Internal error id " << static_cast<int>(error_id)
<< " : \"" << erorr_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
session_observer_->PairFromKey(
connection_key, &connection_handle, &sessionID);
if (session_observer_->ProtocolVersionUsed(
connection_handle, sessionID, protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
new protocol_handler::RawMessage(connection_key,
protocol_version,
&data_sending[0],
data_sending.size(),
protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false);
}
}
const char* SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
} // namespace security_manager
| 36.296482 | 80 | 0.698417 | shoamano83 |
70f86df5648300ef8db133d343a28ab064e59d2e | 319 | cc | C++ | lib/AST/InputPort.cc | rawatamit/scheme | 2c5e121fa873a2fb7762b69027480e28686bbb87 | [
"MIT"
] | null | null | null | lib/AST/InputPort.cc | rawatamit/scheme | 2c5e121fa873a2fb7762b69027480e28686bbb87 | [
"MIT"
] | null | null | null | lib/AST/InputPort.cc | rawatamit/scheme | 2c5e121fa873a2fb7762b69027480e28686bbb87 | [
"MIT"
] | null | null | null | #include "AST/InputPort.h"
Scheme::InputPort::InputPort(FILE* in) :
Scheme::SchemeObject(Scheme::SchemeObject::INPUT_PORT_TY), in_(in)
{}
Scheme::InputPort::~InputPort()
{}
FILE* Scheme::InputPort::getInputStream() const {
return in_;
}
int Scheme::InputPort::closeInputStream() {
return fclose(in_);
}
| 18.764706 | 70 | 0.702194 | rawatamit |
70f90d0fba9d5b84f55cf5f7eb9e017789c2cffc | 434 | cpp | C++ | main.cpp | tomasruizr/cpp-devcontainer | 027db80ca670a72cb8d46a54446fadbb14b80897 | [
"MIT"
] | null | null | null | main.cpp | tomasruizr/cpp-devcontainer | 027db80ca670a72cb8d46a54446fadbb14b80897 | [
"MIT"
] | null | null | null | main.cpp | tomasruizr/cpp-devcontainer | 027db80ca670a72cb8d46a54446fadbb14b80897 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "threadpool/threadpool.h"
using namespace std;
int multiply(int x, int y) {
return x * y;
}
int main() {
thread_pool pool(4);
std::vector<std::future<int>> futures;
for (const int &x : { 2, 4, 7, 13 }) {
futures.push_back(pool.execute(multiply, x, 2));
}
for (auto &fut : futures) {
std::cout << fut.get() << std::endl;
}
return 0;
} | 18.083333 | 56 | 0.573733 | tomasruizr |
70fb1484d7429403d5cbd72605db295d1e6b239e | 1,874 | hpp | C++ | src/Onsang/App.hpp | komiga/Onsang | 63169d822c23b61fa2537b8f66bb224d974072e7 | [
"MIT"
] | null | null | null | src/Onsang/App.hpp | komiga/Onsang | 63169d822c23b61fa2537b8f66bb224d974072e7 | [
"MIT"
] | null | null | null | src/Onsang/App.hpp | komiga/Onsang | 63169d822c23b61fa2537b8f66bb224d974072e7 | [
"MIT"
] | null | null | null | /**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief App class.
*/
#pragma once
#include <Onsang/config.hpp>
#include <Onsang/aux.hpp>
#include <Onsang/String.hpp>
#include <Onsang/ConfigNode.hpp>
#include <Onsang/System/Session.hpp>
#include <Onsang/System/SessionManager.hpp>
#include <Onsang/UI/Defs.hpp>
#include <Onsang/UI/CommandStatusLine.hpp>
#include <Beard/ui/Defs.hpp>
#include <Beard/ui/Widget/Defs.hpp>
#include <Beard/ui/Context.hpp>
#include <Beard/ui/Container.hpp>
#include <Hord/IO/Datastore.hpp>
#include <Hord/System/Driver.hpp>
#include <duct/StateStore.hpp>
namespace Onsang {
class App final {
public:
static App instance;
enum class Flags : unsigned {
no_auto_open = bit(0u),
no_stdout = bit(1u),
};
duct::StateStore<Flags> m_flags{};
Hord::System::Driver m_driver{true};
System::SessionManager m_session_manager;
bool m_running{false};
struct {
UI::Context ctx{{false}};
UI::Container::SPtr viewc{};
UI::CommandStatusLine::SPtr csline{};
} m_ui;
System::Session* m_session{nullptr};
ConfigNode m_config;
ConfigNode m_args;
void
toggle_stdout(
bool const enable
);
private:
App(App const&) = delete;
App& operator=(App const&) = delete;
App& operator=(App&&) = delete;
public:
// constructors, destructor, and operators
~App() = default;
App(App&&) = default;
App();
// operations
bool
add_session(
String const& type,
String const& name,
String const& path,
bool const auto_open,
bool const auto_create
);
public:
bool
init(
signed const argc,
char* argv[]
);
void
set_session(
System::Session* const session
);
private:
void
init_session(
System::Session&
);
void
close_session(
System::Session&
);
void
start_ui();
void
ui_event_filter(
UI::Event const&
);
public:
void
start();
};
} // namespace Onsang
| 15.616667 | 72 | 0.700107 | komiga |
cb03a98ef643c1ccc5782bbd14ce6831312fb2b0 | 513 | hpp | C++ | include/zisa/mpi/parallelization/mpi_all_variables_gatherer.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | include/zisa/mpi/parallelization/mpi_all_variables_gatherer.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | include/zisa/mpi/parallelization/mpi_all_variables_gatherer.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | 1 | 2021-08-24T11:52:51.000Z | 2021-08-24T11:52:51.000Z | // SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#ifndef ZISA_MPI_ALL_VARIABLES_GATHERER_HPP
#define ZISA_MPI_ALL_VARIABLES_GATHERER_HPP
#include <zisa/memory/array.hpp>
#include <zisa/mpi/mpi.hpp>
#include <zisa/parallelization/all_variables_gatherer.hpp>
namespace zisa {
std::unique_ptr<AllVariablesGatherer> make_mpi_all_variables_gatherer(
int base_tag, const MPI_Comm &comm, const array<int_t, 1> &boundaries);
}
#endif // ZISA_MPI_ALL_VARIABLES_GATHERER_HPP
| 27 | 75 | 0.807018 | 1uc |
cb06df6c590e750b77ab5f6b0f0bf92a1cb31998 | 2,366 | cpp | C++ | Samples/Client/DirectxWin32/src/data_channel_handler.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | Samples/Client/DirectxWin32/src/data_channel_handler.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | Samples/Client/DirectxWin32/src/data_channel_handler.cpp | rozele/3dtoolkit | a15fca73be15f96a165dd18e62180de693a5ab86 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "data_channel_handler.h"
#include "webrtc/base/json.h"
// Data channel message types.
const char kStereoRenderingType[] = "stereo-rendering";
const char kCameraTransformLookAtMsgType[] = "camera-transform-lookat";
const char kCameraTransformMsgType[] = "camera-transform";
const char kKeyboardEventMsgType[] = "keyboard-event";
const char kMouseEventMsgType[] = "mouse-event";
DataChannelHandler::DataChannelHandler(DataChannelCallback* data_channel_callback) :
data_channel_callback_(data_channel_callback)
{
}
DataChannelHandler::~DataChannelHandler()
{
}
bool DataChannelHandler::SendCameraInput(
Vector3 camera_position,
Vector3 camera_target,
Vector3 camera_up_vector)
{
char buffer[1024];
sprintf(buffer, "%f, %f, %f, %f, %f, %f, %f, %f, %f",
camera_position.x, camera_position.y, camera_position.z,
camera_target.x, camera_target.y, camera_target.z,
camera_up_vector.x, camera_up_vector.y, camera_up_vector.z);
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["type"] = kCameraTransformLookAtMsgType;
jmessage["body"] = buffer;
return data_channel_callback_->SendInputData(writer.write(jmessage));
}
bool DataChannelHandler::SendCameraInput(
float x, float y, float z, float yaw, float pitch, float roll)
{
char buffer[1024];
sprintf(buffer, "%f, %f, %f, %f, %f, %f",
x, y, z, yaw, pitch, roll);
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["type"] = kCameraTransformMsgType;
jmessage["body"] = buffer;
return data_channel_callback_->SendInputData(writer.write(jmessage));
}
bool DataChannelHandler::SendKeyboardInput(const std::string& msg)
{
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["type"] = kKeyboardEventMsgType;
jmessage["body"] = msg;
return data_channel_callback_->SendInputData(writer.write(jmessage));
}
bool DataChannelHandler::SendMouseInput(const std::string& msg)
{
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["type"] = kMouseEventMsgType;
jmessage["body"] = msg;
return data_channel_callback_->SendInputData(writer.write(jmessage));
}
bool DataChannelHandler::RequestStereoStream(bool stereo)
{
Json::StyledWriter writer;
Json::Value jmessage;
jmessage["type"] = kStereoRenderingType;
jmessage["body"] = stereo ? "1" : "0";
return data_channel_callback_->SendInputData(writer.write(jmessage));
} | 28.506024 | 84 | 0.756551 | rozele |
cb0b687b7a0d9262b2fd1fd594d4e3dd67849df3 | 4,604 | cpp | C++ | src/OpenGL/GDI_GLES2.cpp | GrimshawA/RenderX | 6edbd3be2fcf5ad1b684d87bae0aca898af1a90e | [
"MIT"
] | 1 | 2021-09-14T00:09:43.000Z | 2021-09-14T00:09:43.000Z | src/OpenGL/GDI_GLES2.cpp | GrimshawA/RenderX | 6edbd3be2fcf5ad1b684d87bae0aca898af1a90e | [
"MIT"
] | null | null | null | src/OpenGL/GDI_GLES2.cpp | GrimshawA/RenderX | 6edbd3be2fcf5ad1b684d87bae0aca898af1a90e | [
"MIT"
] | 1 | 2021-09-14T00:09:44.000Z | 2021-09-14T00:09:44.000Z | //#include <Nephilim/GDI/GL/GDI_GLES2.h>
//#include <Nephilim/GDI/GL/GLHelpers.h>
//#include <Nephilim/Foundation/Matrix.h>
//#include <Nephilim/Foundation/Logging.h>
//#include <Nephilim/Graphics/Window.h>
//#include <iostream>
//using namespace std;
//NEPHILIM_NS_BEGIN
//static const char gVertexSource[] =
// "attribute vec4 vertex;\n"
// "attribute vec4 color;\n"
// "attribute vec2 texCoord;\n"
// "varying vec4 fragColor;\n"
// "varying vec2 texUV;\n"
// "uniform mat4 projection;\n"
// "uniform mat4 model;\n"
// "uniform mat4 view;\n"
// "void main() {\n"
// " gl_Position = projection * view * model * vertex;\n"
// " fragColor = color;\n"
// " texUV = texCoord;\n"
// "}\n";
//static const char gFragmentSource[] =
// "precision mediump float;\n"
// "varying vec4 fragColor;\n"
// "varying vec2 texUV;\n"
// "uniform int textured;\n"
// "uniform sampler2D texture;\n"
// "void main() {\n"
// " gl_FragColor = texture2D(texture, texUV) * fragColor * fragColor.a;\n"
// "}\n";
//RendererGLES2::RendererGLES2()
//: GDI_OpenGLBase()
//{
// m_type = OpenGLES2;
// m_name = "OpenGL ES 2.0";
// reloadDefaultShader();
//}
///// This will cancel all shader-related settings and activate the default shader/fixed pipeline
//void RendererGLES2::setDefaultShader()
//{
// m_defaultShader.bind();
// m_activeShader = &m_defaultShader;
//}
//void RendererGLES2::reloadDefaultShader()
//{
// m_defaultShader.release();
// m_defaultShader.loadShader(GLShader::VertexUnit, gVertexSource);
// m_defaultShader.loadShader(GLShader::FragmentUnit, gFragmentSource);
// m_defaultShader.addAttributeLocation(0, "vertex");
// m_defaultShader.addAttributeLocation(1, "color");
// m_defaultShader.addAttributeLocation(2, "texCoord");
// m_defaultShader.create();
// m_defaultShader.bind();
// m_defaultShader.setUniformMatrix("projection", m_projection.get());
// m_defaultShader.setUniformMatrix("view", m_view.get());
// m_defaultShader.setUniformMatrix("model", m_model[m_model.size() - 1].get());
//}
///// Draw a vertex array
//void RendererGLES2::draw(const VertexArray2D& varray)
//{
// if(!m_activeShader)
// {
// return;
// }
// const char* data = reinterpret_cast<const char*>(&varray.m_vertices[0]);
// static_cast<GLShader*>(m_activeShader)->setUniformi("texture", 0);
// enableVertexAttribArray(0);
// enableVertexAttribArray(1);
// enableVertexAttribArray(2);
// setVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(VertexArray2D::Vertex), data + 0);
// setVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(VertexArray2D::Vertex), data + 8);
// setVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(VertexArray2D::Vertex), data + 12);
// drawArrays(varray.geometryType, 0, varray.m_vertices.size());
// disableVertexAttribArray(0);
// disableVertexAttribArray(1);
// disableVertexAttribArray(2);
//}
///// Set the current projection matrix
//void RendererGLES2::setProjectionMatrix(const mat4& projection)
//{
// GraphicsDevice::setProjectionMatrix(projection);
// if(m_activeShader)
// ((GLShader*)m_activeShader)->setUniformMatrix("projection", projection.get());
//}
///// Set the current view matrix
//void RendererGLES2::setViewMatrix(const mat4& view)
//{
// GraphicsDevice::setViewMatrix(view);
// if(m_activeShader)
// ((GLShader*)m_activeShader)->setUniformMatrix("view", view.get());
//}
///// Set the current model matrix
//void RendererGLES2::setModelMatrix(const mat4& model)
//{
// GraphicsDevice::setModelMatrix(model);
// if(m_activeShader)
// ((GLShader*)m_activeShader)->setUniformMatrix("model", model.get());
//}
//void RendererGLES2::applyView(const View &view)
//{
///* if(!m_renderTarget) return;
// IntRect viewport = m_surface->getViewport(view);
// int top = m_surface->getHeight() - (viewport.top + viewport.height);
// glViewport(viewport.left, top, viewport.width, viewport.height);
// m_shader->setUniformMatrix("projection", view.getTransform().getMatrix());*/
//}
///*
//void RendererGLES2::drawDebugCircle(Vector2 center, float radius, Vector2 axis, Color color)
//{
// VertexArray varray(Render::Primitive::TriangleFan, 0);
// const float k_segments = 32.0f;
// const float k_increment = 2.0f * 3.14159 / k_segments;
// float theta = 0.0f;
// glEnable(GL_BLEND);
// glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// for (int i = 0; i < k_segments; ++i)
// {
// Vector2 v = center + Vector2(cosf(theta), sinf(theta)) * radius;
// theta += k_increment;
// varray.append(Vertex(v, color, Vector2()));
// }
// glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// glDisable(GL_BLEND);
// draw(varray);
//}
//*/
//NEPHILIM_NS_END
| 29.139241 | 97 | 0.705474 | GrimshawA |
cb0c607ddf07e2062edcc2aef48aa6e36b4ddbac | 16,447 | cc | C++ | c++/examples/lms/lms_config/src/main.cc | AtlasBuggy/sicktoolbox-fork | 576f02ade4ec52c12887d6489e5219b90e33e833 | [
"BSD-3-Clause"
] | null | null | null | c++/examples/lms/lms_config/src/main.cc | AtlasBuggy/sicktoolbox-fork | 576f02ade4ec52c12887d6489e5219b90e33e833 | [
"BSD-3-Clause"
] | null | null | null | c++/examples/lms/lms_config/src/main.cc | AtlasBuggy/sicktoolbox-fork | 576f02ade4ec52c12887d6489e5219b90e33e833 | [
"BSD-3-Clause"
] | null | null | null | /*!
* \file main.cc
* \brief A simple config utility for Sick LMS 2xx LIDARs.
*
* Code by Jason C. Derenick and Thomas H. Miller.
* Contact derenick(at)lehigh(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2008, Jason C. Derenick and Thomas H. Miller
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
/* Implementation dependencies */
#include <stdlib.h>
#include <string>
#include <sstream>
#include <iostream>
#include <signal.h>
#include <sicklms-1.0/SickLMS.hh>
#define INVALID_OPTION_STRING " Invalid option!!! :o("
#define PROMPT_STRING "lms?> "
using namespace std;
using namespace SickToolbox;
/**
* \fn sigintHandler
* \brief Callback for SIGINT interrupt. Used for uninitialization.
* \param signal Signal ID
*/
void sigintHandler(int signal);
/**
* \fn strToInt
* \brief Utility function for converting string to int
* \param input_str Input string to convert
*/
int strToInt(string input_str);
/**
* \fn getUserOption
* \brief Utility function for grabbing user input
* \param is_null_input Output parameter indicating whether
* user entered NULL input
*/
int getUserOption(bool &is_null_input);
/**
* \fn writeToEEPROM
* \brief Confirms the user actually wants to perform write
*/
bool writeToEEPROM();
/**
* \fn setMeasuringUnits
* \brief Prompts the user and sets the desired measuring
* units via the driver interface.
*/
void setMeasuringUnits();
/**
* \fn setMeasuringMode
* \brief Prompts the user and sets the desired measuring
* mode via the driver interface.
*/
void setMeasuringMode();
/**
* \fn setAvailabilityLevel
* \brief Prompts the user and sets the desired availability
* level via the driver interface.
*/
void setAvailabilityLevel();
/**
* \fn setSensitivityLevel
* \brief Prompts the user and sets the desired sensitivity
* level via the driver interface.
*/
void setSensitivityLevel();
/* A pointer to the Sick obj */
SickLMS *sick_lms = NULL;
int main(int argc, char * argv[]) {
string device_str; // Device path of the Sick LMS 2xx
SickLMS::sick_lms_baud_t desired_baud = SickLMS::SICK_BAUD_38400;
/* Check for a device path. If it's not present, print a usage statement. */
if ((argc != 2 && argc != 3) || (argc == 2 && strcasecmp(argv[1],"--help") == 0)) {
cout << "Usage: lms_config PATH [BAUD RATE]" << endl
<< "Ex: lms_config /dev/ttyUSB0 9600" << endl;
return -1;
}
/* Only device path is given */
if (argc == 2) {
device_str = argv[1];
}
/* Device path and baud are given */
if (argc == 3) {
device_str = argv[1];
if ((desired_baud = SickLMS::StringToSickBaud(argv[2])) == SickLMS::SICK_BAUD_UNKNOWN) {
cerr << "Invalid baud value! Valid values are: 9600, 19200, 38400, and 500000" << endl;
return -1;
}
}
/* Instantiate the SickLMS class with the device path string. */
sick_lms = new SickLMS(device_str);
cout << endl;
cout << "The Sick LIDAR C++/Matlab Toolbox " << endl;
cout << "Sick LMS 2xx Config Utility " << endl;
/* Initialize the device */
try {
sick_lms->Initialize(desired_baud);
}
catch(...) {
cerr << "Initialize failed! Are you using the correct device path?" << endl;
return -1;
}
/* Register the signal handler */
signal(SIGINT,sigintHandler);
cout << "NOTE - Configuring the Sick LMS - REQUIRES - writing to the device's EEPROM." << endl;
cout << " The number of times this can be done is finite (a few thousand)." << endl;
cout << " Thus, you should configure sparingly." << endl;
cout << endl;
do {
cout << "Enter your choice: (Ctrl-c to exit)" << endl;
cout << " [1] Set measuring units"<< endl;
cout << " [2] Set measuring mode"<< endl;
cout << " [3] Set availability level" << endl;
cout << " [4] Set sensitivity level" << endl;
cout << " [5] Show detailed configuration" << endl;
cout << PROMPT_STRING;
bool is_null_input;
switch(getUserOption(is_null_input)) {
case 1:
setMeasuringUnits();
break;
case 2:
setMeasuringMode();
break;
case 3:
setAvailabilityLevel();
break;
case 4:
setSensitivityLevel();
break;
case 5:
sick_lms->PrintSickConfig();
break;
default:
if (!is_null_input) {
cerr << INVALID_OPTION_STRING << endl;
}
}
cout << endl;
} while(true);
/* Success! */
return 0;
}
/**
* Handle the SIGINT signal
*/
void sigintHandler( int signal ) {
cout << endl;
cout << "Quitting..." << endl;
/* Unitialize the device */
try {
sick_lms->Uninitialize();
delete sick_lms;
}
catch(...) {
cerr << "Uninitialize failed!" << endl;
exit(-1);
}
cout << endl;
cout << "Thanks for using the Sick LIDAR Matlab/C++ Toolbox!" << endl;
cout << "Bye Bye :o)" << endl;
exit(0);
}
/**
* Converts ascii string to an integer
*/
int strToInt( string input_str ) {
int int_val;
istringstream input_stream(input_str);
input_stream >> int_val;
return int_val;
}
/**
* Reads in user input string and returns numeric
* representation
*/
int getUserOption( bool &is_null_input ) {
string user_input_str;
getline(cin,user_input_str);
// Check whether its null input
is_null_input = true;
if (user_input_str.length() > 0) {
is_null_input = false;
}
return strToInt(user_input_str);
}
/**
* Prompts the user to confirm requested operation
*/
bool writeToEEPROM( ) {
string user_input_str;
do {
cout << "This will attempt to write to EEPROM. Continue [y/n]? ";
getline(cin,user_input_str);
// Check whether its null input
if (user_input_str == "Y" || user_input_str == "y") {
return true;
}
else if (user_input_str == "N" || user_input_str == "n") {
return false;
}
else {
cerr << "Please answer [y/n]!" << endl;
}
} while (true);
}
/**
* Sets the measuring units of the device
*/
void setMeasuringUnits() {
bool keep_running = true;
do {
cout << endl;
cout << "Select the desired units:" << endl;
cout << " [1] Centimeters (cm)"<< endl;
cout << " [2] Millimeters (mm)"<< endl;
cout << " [3] Back to main"<< endl;
cout << PROMPT_STRING;
try {
bool is_null_input;
switch(getUserOption(is_null_input)) {
case 1:
if (writeToEEPROM()) {
cout << " Setting Sick LMS units to (cm)" << endl;
sick_lms->SetSickMeasuringUnits(SickLMS::SICK_MEASURING_UNITS_CM);
cout << " Done!" << endl;
}
break;
case 2:
if (writeToEEPROM()) {
cout << " Setting Sick LMS units to (mm)" << endl;
sick_lms->SetSickMeasuringUnits(SickLMS::SICK_MEASURING_UNITS_MM);
cout << " Done!" << endl;
}
break;
case 3:
keep_running = !keep_running;
break;
default:
if (!is_null_input) {
cerr << INVALID_OPTION_STRING << endl;
}
}
}
catch( SickException &sick_exception ) {
cerr << "A Sick exception occurred!" << endl;
exit(-1);
}
catch(...) {
cerr << "An unknown exception occurred!" << endl;
exit(-1);
}
} while (keep_running);
}
/**
* Sets the measuring mode of the device
*/
void setMeasuringMode() {
bool keep_running = true;
do {
cout << endl;
cout << "Select the desired measuring mode (see telegram listing for descriptions):" << endl;
cout << " [1] Measurement range 8m/80m; field A, field B, and dazzle" << endl;
cout << " [2] Measurement range 8m/80m; reflector bits in 8 levels" << endl;
cout << " [3] Measurement range 8m/80m; field A, field B and field C" << endl;
cout << " [4] Measurement range 16m/theoretically 160m; reflector bits in 4 levels" << endl;
cout << " [5] Measurement range 16m/theoretically 160m; field A and field B" << endl;
cout << " [6] Measurement range 32m/theoretically 320m; reflector bits in 2 levels" << endl;
cout << " [7] Measurement range 32m/theoretically 320m; field A" << endl;
cout << " [8] Measurement range 32m/theoretically 320m; Immediate" << endl;
cout << " [9] Reflectivity/Intensity values" << endl;
cout << " [10] Back to main" << endl;
cout << PROMPT_STRING;
try {
bool is_null_input;
switch(getUserOption(is_null_input)) {
case 1:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 8m/80m; field A, field B, and dazzle" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_8_OR_80_FA_FB_DAZZLE);
cout << " Done!" << endl;
}
break;
case 2:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 8m/80m; reflector bits in 8 levels" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_8_OR_80_REFLECTOR);
cout << " Done!" << endl;
}
break;
case 3:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 8m/80m; field A, field B and field C" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_8_OR_80_FA_FB_FC);
cout << " Done!" << endl;
}
break;
case 4:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 16m/theoretically 160m; reflector bits in 4 levels" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_16_REFLECTOR);
cout << " Done!" << endl;
}
break;
case 5:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 16m/theoretically 160m; field A and field B" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_16_FA_FB);
cout << " Done!" << endl;
}
break;
case 6:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 32m/theoretically 320m; reflector bit in 2 levels" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_32_REFLECTOR);
cout << " Done!" << endl;
}
break;
case 7:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 32m/theoretically 320m; field A" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_32_FA);
cout << " Done!" << endl;
}
break;
case 8:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Measurement range 32m/theoretically 320m; Immediate" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_32_IMMEDIATE);
cout << " Done!" << endl;
}
break;
case 9:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Meas. Mode to: Reflectivity/Intensity" << endl;
sick_lms->SetSickMeasuringMode(SickLMS::SICK_MS_MODE_REFLECTIVITY);
cout << " Done!" << endl;
}
break;
case 10:
keep_running = !keep_running;
break;
default:
if (!is_null_input) {
cerr << INVALID_OPTION_STRING << endl;
}
}
}
catch( SickException &sick_exception ) {
cerr << "A Sick exception occurred!" << endl;
exit(-1);
}
catch(...) {
cerr << "An unknown exception occurred!" << endl;
exit(-1);
}
} while (keep_running);
}
/**
* Sets the measuring mode of the device
*/
void setAvailabilityLevel() {
bool keep_running = true;
do {
cout << endl;
cout << "Select the desired availability (see telegram listing for descriptions):" << endl;
cout << " [1] Restore to factory default" << endl;
cout << " [2] High" << endl;
cout << " [3] High w/ Real-time indices" << endl;
cout << " [4] High w/ No effect dazzle" << endl;
cout << " [5] High w/ Real-time indices and No effect dazzle" << endl;
cout << " [6] Real-time indices" << endl;
cout << " [7] Real-time indices w/ No effect dazzle" << endl;
cout << " [8] No effect dazzle" << endl;
cout << " [9] Back to main" << endl;
cout << PROMPT_STRING;
try {
bool is_null_input;
switch(getUserOption(is_null_input)) {
case 1:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: Factory settings" << endl;
sick_lms->SetSickAvailability();
cout << " Done!" << endl;
}
break;
case 2:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: High" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_HIGH);
cout << " Done!" << endl;
}
break;
case 3:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: High w/ Real-time indices" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_HIGH | SickLMS::SICK_FLAG_AVAILABILITY_REAL_TIME_INDICES);
cout << " Done!" << endl;
}
break;
case 4:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: High w/ No effect dazzle" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_HIGH | SickLMS::SICK_FLAG_AVAILABILITY_DAZZLE_NO_EFFECT);
cout << " Done!" << endl;
}
break;
case 5:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: High w/ Real-time indices and No effect dazzle" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_HIGH | SickLMS::SICK_FLAG_AVAILABILITY_REAL_TIME_INDICES | SickLMS::SICK_FLAG_AVAILABILITY_DAZZLE_NO_EFFECT);
cout << " Done!" << endl;
}
break;
case 6:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: Real-time indices" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_REAL_TIME_INDICES);
cout << " Done!" << endl;
}
break;
case 7:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: Real-time indices w/ No effect dazzle" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_REAL_TIME_INDICES | SickLMS::SICK_FLAG_AVAILABILITY_DAZZLE_NO_EFFECT);
cout << " Done!" << endl;
}
break;
case 8:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Availability to: No effect dazzle" << endl;
sick_lms->SetSickAvailability(SickLMS::SICK_FLAG_AVAILABILITY_DAZZLE_NO_EFFECT);
cout << " Done!" << endl;
}
break;
case 9:
keep_running = !keep_running;
break;
default:
if (!is_null_input) {
cerr << INVALID_OPTION_STRING << endl;
}
}
}
catch( SickException &sick_exception ) {
cerr << "A Sick exception occurred!" << endl;
exit(-1);
}
catch(...) {
cerr << "An unknown exception occurred!" << endl;
exit(-1);
}
} while (keep_running);
}
/**
* Sets the Sick LMS sensitivity level
*/
void setSensitivityLevel() {
bool keep_running = true;
do {
cout << endl;
cout << "Select the desired sensitivity level:" << endl;
cout << " [1] High (42m @ 10% reflectivity)"<< endl;
cout << " [2] Standard (30m @ 10% reflectivity, factory setting)"<< endl;
cout << " [3] Medium (25m @ 10% reflectivity)"<< endl;
cout << " [4] Low (20m @ 10% reflectivity)"<< endl;
cout << " [5] Back to main"<< endl;
cout << PROMPT_STRING;
try {
bool is_null_input;
switch(getUserOption(is_null_input)) {
case 1:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Sensitivity to: High" << endl;
sick_lms->SetSickSensitivity(SickLMS::SICK_SENSITIVITY_HIGH);
cout << " Done!" << endl;
}
break;
case 2:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Sensitivity to: Standard (Factory setting)" << endl;
sick_lms->SetSickSensitivity();
cout << " Done!" << endl;
}
break;
case 3:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Sensitivity to: Medium" << endl;
sick_lms->SetSickSensitivity(SickLMS::SICK_SENSITIVITY_MEDIUM);
cout << " Done!" << endl;
}
break;
case 4:
if (writeToEEPROM()) {
cout << " Setting Sick LMS Sensitivity to: Low" << endl;
sick_lms->SetSickSensitivity(SickLMS::SICK_SENSITIVITY_LOW);
cout << " Done!" << endl;
}
break;
case 5:
keep_running = !keep_running;
break;
default:
if (!is_null_input) {
cerr << INVALID_OPTION_STRING << endl;
}
}
}
catch( SickException &sick_exception ) {
cerr << "A Sick exception occurred!" << endl;
exit(-1);
}
catch(...) {
cerr << "An unknown exception occurred!" << endl;
exit(-1);
}
} while (keep_running);
}
| 26.23126 | 174 | 0.625768 | AtlasBuggy |
cb0d9a2160fd304759a040c8fbe794f64547b121 | 5,753 | cpp | C++ | src/multigrid/mgbval_zerograd.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 174 | 2016-11-30T01:20:14.000Z | 2022-02-22T16:23:55.000Z | src/multigrid/mgbval_zerograd.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 74 | 2017-01-30T22:37:33.000Z | 2021-05-10T17:20:33.000Z | src/multigrid/mgbval_zerograd.cpp | kahoooo/athena-public | 583aee106677cba7fa5ea4e3689e2cfb81796e25 | [
"BSD-3-Clause"
] | 126 | 2016-12-08T14:03:22.000Z | 2022-03-31T06:01:59.000Z | //========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file mgbval_zerograd.cpp
// \brief 6x zero gradient (outflow) boundary functions for Multigrid
// C headers
// C++ headers
// Athena++ headers
#include "../athena.hpp"
#include "../athena_arrays.hpp"
#include "../defs.hpp"
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientInnerX1(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the inner-X1 direction
void MGZeroGradientInnerX1(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=0; i<ngh; i++)
dst(n,k,j,is-i-1) = dst(n,k,j,is);
}
}
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientOuterX1(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the outer-X1 direction
void MGZeroGradientOuterX1(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=ks; k<=ke; k++) {
for (int j=js; j<=je; j++) {
for (int i=0; i<ngh; i++)
dst(n,k,j,ie+i+1) = dst(n,k,j,ie);
}
}
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientInnerX2(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the inner-X2 direction
void MGZeroGradientInnerX2(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=ks; k<=ke; k++) {
for (int j=0; j<ngh; j++) {
for (int i=is; i<=ie; i++)
dst(n,k,js-j-1,i) = dst(n,k,js,i);
}
}
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientOuterX2(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the outer-X2 direction
void MGZeroGradientOuterX2(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=ks; k<=ke; k++) {
for (int j=0; j<ngh; j++) {
for (int i=is; i<=ie; i++)
dst(n,k,je+j+1,i) = dst(n,k,je,i);
}
}
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientInnerX3(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the inner-X3 direction
void MGZeroGradientInnerX3(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=0; k<ngh; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++)
dst(n,ks-k-1,j,i) = dst(n,ks,j,i);
}
}
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn MGZeroGradientOuterX3(AthenaArray<Real> &dst, Real time, int nvar,
// int is, int ie, int js, int je, int ks, int ke, int ngh,
// Real x0, Real y0, Real z0, Real dx, Real dy, Real dz)
// \brief Zero gradient boundary condition in the outer-X3 direction
void MGZeroGradientOuterX3(AthenaArray<Real> &dst, Real time, int nvar,
int is, int ie, int js, int je, int ks, int ke, int ngh,
Real x0, Real y0, Real z0, Real dx, Real dy, Real dz) {
for (int n=0; n<nvar; n++) {
for (int k=0; k<ngh; k++) {
for (int j=js; j<=je; j++) {
for (int i=is; i<=ie; i++)
dst(n,ke+k+1,j,i) = dst(n,ke,j,i);
}
}
}
return;
}
| 39.951389 | 90 | 0.460629 | kahoooo |
cb10682ef97760c8ecc859f8d796327d03b628e3 | 16,097 | cpp | C++ | tests/src/runtimeApi/memory/hipMallocManaged_MultiScenario.cpp | parmance/HIP | 96ee9d1397f02ac4b4badd9243994728f6a89fe5 | [
"MIT"
] | 1,935 | 2017-05-28T04:52:18.000Z | 2022-03-30T23:50:43.000Z | tests/src/runtimeApi/memory/hipMallocManaged_MultiScenario.cpp | parmance/HIP | 96ee9d1397f02ac4b4badd9243994728f6a89fe5 | [
"MIT"
] | 1,310 | 2017-05-30T22:16:09.000Z | 2022-03-31T08:25:58.000Z | tests/src/runtimeApi/memory/hipMallocManaged_MultiScenario.cpp | parmance/HIP | 96ee9d1397f02ac4b4badd9243994728f6a89fe5 | [
"MIT"
] | 495 | 2017-06-01T01:26:27.000Z | 2022-03-28T16:36:51.000Z | /*
Copyright (c) 2020 - 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Test 6 is disabled */
/* HIT_START
* BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11
* TEST_NAMED: %t hipMallocManaged1 --tests 1
* TEST_NAMED: %t hipMallocManaged2 --tests 2
* TEST_NAMED: %t hipMallocManagedNegativeTests --tests 3
* TEST_NAMED: %t hipMallocManagedMultiChunkSingleDevice --tests 4
* TEST_NAMED: %t hipMallocManagedMultiChunkMultiDevice --tests 5
* TEST_NAMED: %t hipMallocManagedOversubscription --tests 6 EXCLUDE_HIP_PLATFORM nvidia EXCLUDE_HIP_RUNTIME rocclr
* HIT_END
*/
#include <atomic>
#include "test_common.h"
#define N 1048576 // equals to (1024*1024)
#define INIT_VAL 123
/*
* Kernel function to perform addition operation.
*/
template <typename T>
__global__ void
vector_sum(T *Ad1, T *Ad2, size_t NUM_ELMTS) {
size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
size_t stride = blockDim.x * gridDim.x;
for (size_t i = offset; i < NUM_ELMTS; i += stride) {
Ad2[i] = Ad1[i] + Ad1[i];
}
}
// The following Test case tests the following scenario:
// A large chunk of hipMallocManaged() memory(Hmm) is created
// Equal parts of Hmm is accessed on available gpus and
// kernel is launched on acessed chunk of hmm memory
// and checks if there are any inconsistencies or access issues
bool MultiChunkMultiDevice(int NumDevices) {
std::atomic<int> DataMismatch{0};
bool IfTestPassed = true;
int Counter = 0;
unsigned int NUM_ELMS = (1024 * 1024);
float *Ad[NumDevices], *Hmm = NULL, *Ah = new float[NUM_ELMS];
hipStream_t stream[NumDevices];
for (int Oloop = 0; Oloop < NumDevices; ++Oloop) {
HIPCHECK(hipSetDevice(Oloop));
HIPCHECK(hipMalloc(&Ad[Oloop], NUM_ELMS * sizeof(float)));
HIPCHECK(hipMemset(Ad[Oloop], 0, NUM_ELMS * sizeof(float)));
HIPCHECK(hipStreamCreate(&stream[Oloop]));
}
HIPCHECK(hipMallocManaged(&Hmm, (NumDevices * NUM_ELMS * sizeof(float))));
for (int i = 0; i < NumDevices; ++i) {
for (; Counter < ((i + 1) * NUM_ELMS); ++Counter) {
Hmm[Counter] = INIT_VAL + i;
}
}
const unsigned threadsPerBlock = 256;
const unsigned blocks = (NUM_ELMS + 255)/256;
for (int Klaunch = 0; Klaunch < NumDevices; ++Klaunch) {
// If without setting device, Hmm value will be read as 0 in kernel on
// GPU where Hmm isn't allocated by hipMallocManaged(). This looks like
// a bug of cuda. The following line is to fix the bug on cuda only.
HIPCHECK(hipSetDevice(Klaunch));
vector_sum<float> <<<blocks, threadsPerBlock, 0, stream[Klaunch]>>>
(&Hmm[Klaunch * NUM_ELMS], Ad[Klaunch], NUM_ELMS);
}
for (int m = 0; m < NumDevices; ++m) {
HIPCHECK(hipStreamSynchronize(stream[m]));
HIPCHECK(hipMemcpy(Ah, Ad[m], NUM_ELMS * sizeof(float),
hipMemcpyDeviceToHost));
for (int n = 0; n < NUM_ELMS; ++n) {
if (Ah[n] != ((INIT_VAL + m) * 2)) {
DataMismatch++;
}
}
memset(reinterpret_cast<void*>(Ah), 0, NUM_ELMS * sizeof(float));
}
if (DataMismatch.load() != 0) {
printf("MultiChunkMultiDevice: Mismatch observed!\n");
IfTestPassed = false;
}
for (int i = 0; i < NumDevices; ++i) {
HIPCHECK(hipFree(Ad[i]));
HIPCHECK(hipStreamDestroy(stream[i]));
}
HIPCHECK(hipFree(Hmm));
free(Ah);
return IfTestPassed;
}
// The following Test case tests the following scenario:
// A large chunk of hipMallocManaged() memory(Hmm) is created
// Equal parts of Hmm is accessed and
// kernel is launched on acessed chunk of hmm memory
// and checks if there are any inconsistencies or access issues
bool MultiChunkSingleDevice(int NumDevices) {
std::atomic<int> DataMismatch{0};
int Chunks = 4, Counter = 0;
bool IfTestPassed = true;
unsigned int NUM_ELMS = (1024 * 1024);
float *Ad[Chunks], *Hmm = NULL, *Ah = new float[NUM_ELMS];
hipStream_t stream[Chunks];
for (int i = 0; i < Chunks; ++i) {
HIPCHECK(hipMalloc(&Ad[i], NUM_ELMS * sizeof(float)));
HIPCHECK(hipMemset(Ad[i], 0, NUM_ELMS * sizeof(float)));
HIPCHECK(hipStreamCreate(&stream[i]));
}
HIPCHECK(hipMallocManaged(&Hmm, (Chunks * NUM_ELMS * sizeof(float))));
for (int i = 0; i < Chunks; ++i) {
for (; Counter < ((i + 1) * NUM_ELMS); ++Counter) {
Hmm[Counter] = (INIT_VAL + i);
}
}
const unsigned threadsPerBlock = 256;
const unsigned blocks = (NUM_ELMS + 255)/256;
for (int k = 0; k < Chunks; ++k) {
vector_sum<float> <<<blocks, threadsPerBlock, 0, stream[k]>>>
(&Hmm[k * NUM_ELMS], Ad[k], NUM_ELMS);
}
HIPCHECK(hipDeviceSynchronize());
for (int m = 0; m < Chunks; ++m) {
HIPCHECK(hipMemcpy(Ah, Ad[m], NUM_ELMS * sizeof(float),
hipMemcpyDeviceToHost));
for (int n = 0; n < NUM_ELMS; ++n) {
if (Ah[n] != ((INIT_VAL + m) * 2)) {
DataMismatch++;
}
}
}
if (DataMismatch.load() != 0) {
printf("MultiChunkSingleDevice: Mismatch observed!\n");
IfTestPassed = false;
}
for (int i = 0; i < Chunks; ++i) {
HIPCHECK(hipFree(Ad[i]));
HIPCHECK(hipStreamDestroy(stream[i]));
}
HIPCHECK(hipFree(Hmm));
free(Ah);
return IfTestPassed;
}
// The following tests oversubscription hipMallocManaged() api
// Currently disabled.
bool TestOversubscriptionMallocManaged(int NumDevices) {
bool IfTestPassed = true;
hipError_t err;
void *A = NULL;
size_t total = 0, free = 0;
HIPCHECK(hipMemGetInfo(&free, &total));
// ToDo: In case of HMM, memory over-subscription is allowed. Hence, relook
// into how out of memory can be tested.
// Demanding more mem size than available
err = hipMallocManaged(&A, (free +1), hipMemAttachGlobal);
if (hipErrorOutOfMemory != err) {
printf("hipMallocManaged: Returned %s for size value > device memory\n",
hipGetErrorString(err));
IfTestPassed = false;
}
return IfTestPassed;
}
// The following test does negative testing of hipMallocManaged() api
// by passing invalid values and check if the behavior is as expected
bool NegativeTestsMallocManaged(int NumDevices) {
bool IfTestPassed = true;
hipError_t err;
void *A;
size_t total = 0, free = 0;
HIPCHECK(hipMemGetInfo(&free, &total));
err = hipMallocManaged(NULL, 1024, hipMemAttachGlobal);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s when devPtr is null\n",
hipGetErrorString(err));
IfTestPassed = false;
}
// cuda api doc says : If size is 0, cudaMallocManaged returns
// cudaErrorInvalidValue. However, it is observed that cuda 11.2 api returns
// success and contradicts with api doc.
// With size(0), api expected to return error code (or)
// reset ptr while returning success (to accommodate cuda 11.2 api behavior).
err = hipMallocManaged(&A, 0, hipMemAttachGlobal);
if ((hipErrorInvalidValue == err) ||
((hipSuccess == err) && (nullptr == A))) {
IfTestPassed &= true;
} else {
IfTestPassed = false;
}
err = hipMallocManaged(NULL, 0, hipMemAttachGlobal);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s when devPtr & size is null & 0\n",
hipGetErrorString(err));
IfTestPassed = false;
}
err = hipMallocManaged(NULL, 1024, hipMemAttachHost);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s for 'hipMemAttachHost' flag\n",
hipGetErrorString(err));
IfTestPassed = false;
}
// cuda api doc says : If size is 0, cudaMallocManaged returns
// cudaErrorInvalidValue. However, it is observed that cuda 11.2 api returns
// success and contradicts with api doc.
// With size(0), api expected to return error code (or)
// reset ptr while returning success (to accommodate cuda 11.2 api behavior).
err = hipMallocManaged(&A, 0, hipMemAttachHost);
if ((hipErrorInvalidValue == err) ||
((hipSuccess == err) && (nullptr == A))) {
IfTestPassed &= true;
} else {
IfTestPassed = false;
}
err = hipMallocManaged(NULL, 0, hipMemAttachHost);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s when devPtr & size is null & 0\n",
hipGetErrorString(err));
IfTestPassed = false;
}
err = hipMallocManaged(NULL, 0, 0);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s when params are null, 0, 0\n",
hipGetErrorString(err));
IfTestPassed = false;
}
err = hipMallocManaged(&A, 1024, 145);
if (hipErrorInvalidValue != err) {
printf("hipMallocManaged: Returned %s when flag param is numerical 145\n",
hipGetErrorString(err));
IfTestPassed = false;
}
err = hipMallocManaged(&A, -10, hipMemAttachGlobal);
if (hipErrorOutOfMemory != err) {
printf("hipMallocManaged: Returned %s for negative size value.\n",
hipGetErrorString(err));
IfTestPassed = false;
}
return IfTestPassed;
}
// Allocate two pointers using hipMallocManaged(), initialize,
// then launch kernel using these pointers directly and
// later validate the content without using any Memcpy.
template <typename T>
bool TestMallocManaged2(int NumDevices) {
bool IfTestPassed = true;
T *Hmm1 = NULL, *Hmm2 = NULL;
for (int i = 0; i < NumDevices; ++i) {
HIPCHECK(hipSetDevice(i));
std::atomic<int> DataMismatch{0};
HIPCHECK(hipMallocManaged(&Hmm1, N * sizeof(T)));
HIPCHECK(hipMallocManaged(&Hmm2, N * sizeof(T)));
for (int m = 0; m < N; ++m) {
Hmm1[m] = m;
Hmm2[m] = 0;
}
const unsigned threadsPerBlock = 256;
const unsigned blocks = (N + 255)/256;
// Kernel launch
vector_sum <<<blocks, threadsPerBlock>>> (Hmm1, Hmm2, N);
HIPCHECK(hipDeviceSynchronize());
for (int v = 0; v < N; ++v) {
if (Hmm2[v] != (v + v)) {
DataMismatch++;
}
}
if (DataMismatch.load() != 0) {
IfTestPassed = false;
}
HIPCHECK(hipFree(Hmm1));
HIPCHECK(hipFree(Hmm2));
}
return IfTestPassed;
}
// In the following test, a memory is created using hipMallocManaged() by
// setting a device and verified if it is accessible when the context is set
// to all other devices. This include verification and Device two Device
// transfers and kernel launch o discover if there any access issues.
template <typename T>
bool TestMallocManaged1(int NumDevices) {
std::atomic<unsigned int> DataMismatch;
bool TestPassed = true;
T *Ah1 = new T[N], *Ah2 = new T[N], *Ad = NULL, *Hmm = NULL;
for (int i =0; i < N; ++i) {
Ah1[i] = INIT_VAL;
Ah2[i] = 0;
}
for (int Oloop = 0; Oloop < NumDevices; ++Oloop) {
DataMismatch = 0;
HIPCHECK(hipSetDevice(Oloop));
HIPCHECK(hipMallocManaged(&Hmm, N * sizeof(T)));
for (int Iloop = 0; Iloop < NumDevices; ++Iloop) {
HIPCHECK(hipSetDevice(Iloop));
HIPCHECK(hipMalloc(&Ad, N * sizeof(T)));
// Copy data from host to hipMallocMananged memory and verify
HIPCHECK(hipMemcpy(Hmm, Ah1, N * sizeof(T), hipMemcpyHostToDevice));
for (int v = 0; v < N; ++v) {
if (Hmm[v] != INIT_VAL) {
DataMismatch++;
}
}
if (DataMismatch.load() != 0) {
printf("Mismatch is observed with host data at device %d", Iloop);
printf(" while hipMallocManaged memory set to the device %d\n", Oloop);
TestPassed = false;
DataMismatch = 0;
}
// Executing D2D transfer with hipMallocManaged memory and verify
HIPCHECK(hipMemcpy(Ad, Hmm, N * sizeof(T), hipMemcpyDeviceToDevice));
HIPCHECK(hipMemcpy(Ah2, Ad, N * sizeof(T), hipMemcpyDeviceToHost));
for (int k = 0; k < N; ++k) {
if (Ah2[k] != INIT_VAL) {
DataMismatch++;
}
}
if (DataMismatch.load() != 0) {
printf("Mismatch is observed with D2D transfer at device %d\n", Iloop);
printf(" while hipMallocManaged memory set to the device %d\n", Oloop);
TestPassed = false;
DataMismatch = 0;
}
HIPCHECK(hipMemset(Ad, 0, N * sizeof(T)));
const unsigned threadsPerBlock = 256;
const unsigned blocks = (N + 255)/256;
// Launching the kernel to check if there is any access issue with
// hipMallocManaged memory and local device's memory
vector_sum <<<blocks, threadsPerBlock>>> (Hmm, Ad, N);
hipDeviceSynchronize();
HIPCHECK(hipMemcpy(Ah2, Ad, N * sizeof(T), hipMemcpyDeviceToHost));
for (int m = 0; m < N; ++m) {
if (Ah2[m] != 246) {
DataMismatch++;
}
}
if (DataMismatch.load() != 0) {
printf("Data Mismatch observed after kernel lch device %d\n", Iloop);
TestPassed = false;
DataMismatch = 0;
}
HIPCHECK(hipFree(Ad));
}
HIPCHECK(hipFree(Hmm));
}
free(Ah1);
free(Ah2);
return TestPassed;
}
int main(int argc, char* argv[]) {
HipTest::parseStandardArguments(argc, argv, true);
if ((p_tests <= 0) || (p_tests > 5)) {
failed("Valid arguments are from 1 to 5");
}
int managed_memory = 0;
HIPCHECK(hipDeviceGetAttribute(&managed_memory,
hipDeviceAttributeManagedMemory,
p_gpuDevice));
if (!managed_memory) {
printf("info: managed memory access not supported on device %d\n Skipped\n", p_gpuDevice);
passed();
}
int NumDevices = 0;
HIPCHECK(hipGetDeviceCount(&NumDevices));
bool TestStatus = true, OverAllStatus = true;
if (p_tests == 1) {
TestStatus = TestMallocManaged1<float>(NumDevices);
if (!TestStatus) {
printf("Test Failed with float datatype.\n");
OverAllStatus = false;
}
TestStatus = TestMallocManaged1<int>(NumDevices);
if (!TestStatus) {
printf("Test Failed with int datatype.\n");
OverAllStatus = false;
}
TestStatus = TestMallocManaged1<unsigned char>(NumDevices);
if (!TestStatus) {
printf("Test Failed with unsigned char datatype.\n");
OverAllStatus = false;
}
TestStatus = TestMallocManaged1<double>(NumDevices);
if (!TestStatus) {
printf("Test Failed with double datatype.\n");
OverAllStatus = false;
}
if (!OverAllStatus) {
failed("");
}
}
if (p_tests == 2) {
TestStatus = TestMallocManaged2<float>(NumDevices);
if (!TestStatus) {
failed("Test Failed with float datatype.");
}
}
if (p_tests == 3) {
TestStatus = NegativeTestsMallocManaged(NumDevices);
if (!TestStatus) {
failed("Negative Tests with hipMallocManaged() failed!.");
}
}
if (p_tests == 4) {
TestStatus = MultiChunkSingleDevice(NumDevices);
if (!TestStatus) {
failed("hipMallocManaged: MultiChunkSingleDevice test failed!");
}
}
if (p_tests == 5) {
TestStatus = MultiChunkMultiDevice(NumDevices);
if (!TestStatus) {
failed("hipMallocManaged: MultiChunkMultiDevice test failed!");
}
}
if (p_tests == 6) {
TestStatus = TestOversubscriptionMallocManaged(NumDevices);
if (!TestStatus) {
failed("hipMallocManaged: TestOversubscriptionMallocManaged failed!");
}
}
passed();
}
| 34.69181 | 115 | 0.65478 | parmance |
cb13ab58639a1ba7d858305a3bd9dd9b84965a03 | 42,964 | cpp | C++ | src/strategy/Kidsize_HuroCup/loadparameter.cpp | TKUICLab-humanoid/BB | badb9d2669c4f0dca64c221761c11ea2d56e7412 | [
"MIT"
] | null | null | null | src/strategy/Kidsize_HuroCup/loadparameter.cpp | TKUICLab-humanoid/BB | badb9d2669c4f0dca64c221761c11ea2d56e7412 | [
"MIT"
] | null | null | null | src/strategy/Kidsize_HuroCup/loadparameter.cpp | TKUICLab-humanoid/BB | badb9d2669c4f0dca64c221761c11ea2d56e7412 | [
"MIT"
] | 6 | 2020-09-15T14:13:54.000Z | 2021-01-14T06:45:39.000Z | #include "strategy/loadparameter.h"
LoadParameter *Load = new LoadParameter();
float LoadParameter::readvalue(fstream &fin, string title, int mode)
{
char line[100];
char equal;
switch(mode)
{
case 0:
while(1)
{
fin.getline(line,sizeof(line),' ');
if((string)line == title)
{
fin.get(equal);
if(equal == '=')
{
fin.getline(line,sizeof(line),'\n');
break;
}
}
}
return atoi(line);
break;
case 1:
while(1)
{
fin.getline(line,sizeof(line),' ');
if((string)line == title)
{
fin.get(equal);
if(equal == '=')
{
fin.getline(line,sizeof(line),'\n');
break;
}
}
}
return atof(line);
break;
case 2:
while(1)
{
fin.getline(line,sizeof(line),' ');
if((string)line == title)
{
fin.get(equal);
if(equal == '=')
{
fin.getline(line,sizeof(line),'|');
break;
}
}
}
return atoi(line);
break;
case 3:
while(1)
{
fin.getline(line,sizeof(line),' ');
if((string)line == title)
{
fin.getline(line,sizeof(line),'|');
break;
}
}
return atoi(line);
break;
default:
break;
}
}
void LoadParameter::initparameterpath()
{
while(parameter_path == "N")
{
parameter_path = tool->getPackagePath("strategy");
}
printf("parameter_path is %s\n", parameter_path.c_str());
}
void LoadParameter::LoadParameters()
{
//0->int 1->float
fstream fin;
string sTmp;
char line[100];
char path_stand[200];
char path_stand2[20] = "/sector/";
char path_stand3[20] = "29.ini";
char path_throw[200],path_speed[200],path_continuous[200];
char temp[100];
int packagecnt;
vector<int> StandPackage;
strcpy(path_stand, tool->standPath);
strcat(path_stand, path_stand2);
strcat(path_stand, path_stand3);
fin.open(path_stand, ios::in);
try//計算機器人的身高
{
ROS_INFO("openfile Stand");
packagecnt = tool->readvalue(fin, "PackageCnt", 0);
StandPackage.push_back(tool->readvalue(fin, "Package", 2));
for(int i = 1; i < packagecnt; i++)
{
StandPackage.push_back(tool->readvalue(fin, "|", 3));
}
BasketInfo->M12 = 2048 - (StandPackage[47] + StandPackage[48] * 256);
BasketInfo->M13 = 2048 - (StandPackage[51] + StandPackage[52] * 256);
BasketInfo->M14 = 2048 - (StandPackage[55] + StandPackage[56] * 256);
BasketInfo->M18 = 2048 - (StandPackage[71] + StandPackage[72] * 256);
BasketInfo->M19 = 2048 - (StandPackage[75] + StandPackage[76] * 256);
BasketInfo->M20 = 2048 - (StandPackage[79] + StandPackage[80] * 256);
BasketInfo->theta1 = (abs(BasketInfo->M14) + abs(BasketInfo->M20)) / 2 * Scale2Deg;
BasketInfo->theta2 = (abs(BasketInfo->M13) + abs(BasketInfo->M19)) / 2 * Scale2Deg;
BasketInfo->theta3 = (abs(BasketInfo->M12) + abs(BasketInfo->M18)) / 2 * Scale2Deg;
BasketInfo->RobotHeight1 = cos(BasketInfo->theta1 * Deg2Rad) * L_Calf;
BasketInfo->RobotHeight2 = cos((BasketInfo->theta2 - BasketInfo->theta1) * Deg2Rad) * L_Thigh;
BasketInfo->RobotHeight3 = cos((BasketInfo->theta3 + L_BodyError - BasketInfo->theta2 + BasketInfo->theta1) * Deg2Rad) * L_Body;
BasketInfo->RobotStandFeedBack = (BasketInfo->theta2 - BasketInfo->theta1 - BasketInfo->theta3);
BasketInfo->RobotHeight = BasketInfo->RobotHeight1 + BasketInfo->RobotHeight2 + BasketInfo->RobotHeight3 + L_Foot + L_Shoes - HalfBasketHeight;
fin.close();
ROS_INFO("fileclose Stand");
}
catch(exception e)
{
ROS_INFO("catchfile");
}
StandPackage.clear();
strcpy(path_throw, parameter_path.c_str());
strcat(path_throw, "/Throw.ini");
fin.open(path_throw, ios::in);
//Throw.ini
try//策略中的各項參數
{
ROS_INFO("openfile Throw.ini");
fin.getline(temp, sizeof(temp));
BasketInfo->RobotSearchBasketHeight = this->readvalue(fin,"RobotSearchBasketHeight", 1);
BasketInfo->VisionMiddle = this->readvalue(fin,"VisionMiddle", 1);
BasketInfo->ScreenButtom = this->readvalue(fin,"ScreenButtom", 1);
BasketInfo->Error = this->readvalue(fin,"Error", 1);
fin.getline(temp, sizeof(temp));
BasketInfo->FeedBackError = this->readvalue(fin,"FeedBackError", 1);
BasketInfo->DistanceErrorCount = this->readvalue(fin,"DistanceErrorCount", 1);
BasketInfo->AreaDisError = this->readvalue(fin,"AreaDisError", 1);
fin.getline(temp, sizeof(temp));
BasketInfo->Disspeedfix = this->readvalue(fin,"Disspeedfix", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->HeadVerticalState = this->readvalue(fin,"HeadVerticalState", 0);
BasketInfo->HeadHorizontalState = this->readvalue(fin,"HeadHorizontalState", 0);
BasketInfo->BallVerticalBaseLine = this->readvalue(fin,"BallVerticalBaseLine", 0);
BasketInfo->BallHorizontalBaseLine = this->readvalue(fin,"BallHorizontalBaseLine", 0);
BasketInfo->VerticalMaxAngle = this->readvalue(fin,"VerticalMaxAngle", 0);
BasketInfo->VerticalMinAngle = this->readvalue(fin,"VerticalMinAngle", 0);
BasketInfo->HorizontalMaxAngle = this->readvalue(fin,"HorizontalMaxAngle", 0);
BasketInfo->HorizontalMinAngle = this->readvalue(fin,"HorizontalMinAngle", 0);
BasketInfo->BasketHorizontalMaxAngle = this->readvalue(fin,"BasketHorizontalMaxAngle", 0);
BasketInfo->BasketHorizontalMinAngle = this->readvalue(fin,"BasketHorizontalMinAngle", 0);
BasketInfo->BasketHorizontalBaseLine = this->readvalue(fin,"BasketHorizontalBaseLine", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->BasketVerticalBaseLine = this->readvalue(fin,"BasketVerticalBaseLine", 0);
BasketInfo->BasketVerticalBaseLine90 = this->readvalue(fin,"BasketVerticalBaseLine90", 0);
BasketInfo->BasketVerticalBaseLine80 = this->readvalue(fin,"BasketVerticalBaseLine80", 0);
BasketInfo->BasketVerticalBaseLine70 = this->readvalue(fin,"BasketVerticalBaseLine70", 0);
BasketInfo->BasketVerticalBaseLine60 = this->readvalue(fin,"BasketVerticalBaseLine60", 0);
BasketInfo->BasketVerticalBaseLine50 = this->readvalue(fin,"BasketVerticalBaseLine50", 0);
BasketInfo->BasketLeftBaselineFix = this->readvalue(fin,"BasketLeftBaselineFix", 0);
BasketInfo->BasketRightBaselineFix = this->readvalue(fin,"BasketRightBaselineFix", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->SizeOfDist[0] = this->readvalue(fin,"Size50", 0);
BasketInfo->SizeOfDist[1] = this->readvalue(fin,"Size60", 0);
BasketInfo->SizeOfDist[2] = this->readvalue(fin,"Size70", 0);
BasketInfo->SizeOfDist[3] = this->readvalue(fin,"Size80", 0);
BasketInfo->SizeOfDist[4] = this->readvalue(fin,"Size90", 0);
BasketInfo->SizeOfDist[5] = this->readvalue(fin,"Size100", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->BallVerticalError = this->readvalue(fin,"BallVerticalError", 0);
BasketInfo->BallHorizontalError = this->readvalue(fin,"BallHorizontalError", 0);
BasketInfo->ContinuousSlowLine = this->readvalue(fin,"ContinuousSlowLine", 0);
BasketInfo->CatchBallLine = this->readvalue(fin,"CatchBallLine", 0);
BasketInfo->BallXCenter = this->readvalue(fin,"BallXCenter", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->CatchBallVerticalHeadPosition = this->readvalue(fin,"CatchBallVerticalHeadPosition", 0);
BasketInfo->CatchBallYLine = this->readvalue(fin,"CatchBallYLine", 0);
BasketInfo->backLine = this->readvalue(fin,"backLine", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->WaistError = this->readvalue(fin,"WaistError", 0);
BasketInfo->SpeedError = this->readvalue(fin,"SpeedError", 0);
BasketInfo->Point5DisError = this->readvalue(fin,"Point5DisError", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->UpBasketStopLine = this->readvalue(fin,"UpBasketStopLine", 0);
BasketInfo->ContinuousSlowLine2 = this->readvalue(fin,"ContinuousSlowLine2", 0);
BasketInfo->SlamDunkHorizontalAngle = this->readvalue(fin,"SlamDunkHorizontalAngle", 0);
BasketInfo->BasketXCenter = this->readvalue(fin,"BasketXCenter", 0);
fin.close();
ROS_INFO("fileclose Throw.ini");
}
catch(exception e)
{
ROS_INFO("catchfile");
}
strcpy(path_speed, parameter_path.c_str());
strcat(path_speed, "/Speed.ini");
fin.open(path_speed, ios::in);
//speed.ini
try//投籃力道參數
{
ROS_INFO("openfile Speed.ini");
BasketInfo->dis35_x = this->readvalue(fin, "dis35_x", 1);
BasketInfo->dis40_x = this->readvalue(fin, "dis40_x", 1);
BasketInfo->dis50_x = this->readvalue(fin, "dis50_x", 1);
BasketInfo->dis60_x = this->readvalue(fin, "dis60_x", 1);
BasketInfo->dis65_x = this->readvalue(fin, "dis65_x", 1);
BasketInfo->dis70_x = this->readvalue(fin, "dis70_x", 1);
BasketInfo->dis75_x = this->readvalue(fin, "dis75_x", 1);
BasketInfo->dis80_x = this->readvalue(fin, "dis80_x", 1);
BasketInfo->dis85_x = this->readvalue(fin, "dis85_x", 1);
BasketInfo->dis90_x = this->readvalue(fin, "dis90_x", 1);
BasketInfo->dis35speed = this->readvalue(fin, "dis35speed", 0);
BasketInfo->dis40speed = this->readvalue(fin, "dis40speed", 0);
BasketInfo->dis50speed = this->readvalue(fin, "dis50speed", 0);
BasketInfo->dis60speed = this->readvalue(fin, "dis60speed", 0);
BasketInfo->dis61speed = this->readvalue(fin, "dis61speed", 0);
BasketInfo->dis70speed = this->readvalue(fin, "dis70speed", 0);
BasketInfo->dis71speed = this->readvalue(fin, "dis71speed", 0);
BasketInfo->dis80speed = this->readvalue(fin, "dis80speed", 0);
BasketInfo->dis81speed = this->readvalue(fin, "dis81speed", 0);
BasketInfo->dis90speed = this->readvalue(fin, "dis90speed", 0);
fin.close();
ROS_INFO("fileclose Speed.ini");
}
catch(exception e)
{
ROS_INFO("catchfile");
}
strcpy(path_continuous, parameter_path.c_str());
strcat(path_continuous, "/ContinuousMove.ini");
fin.open(path_continuous, ios::in);
//ContinuousMove.ini
try//連續步態參數
{
ROS_INFO("openfile ContinuousMove.ini");
BasketInfo->AddPeriod = this->readvalue(fin, "AddPeriod", 1);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitX = this->readvalue(fin, "ContinuousStep_InitX", 0);
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitY = this->readvalue(fin, "ContinuousStep_InitY", 0);
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitZ = this->readvalue(fin, "ContinuousStep_InitZ", 0);
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitTheta = this->readvalue(fin, "ContinuousStep_InitTheta", 0);
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.Mode = this->readvalue(fin, "ContinuousStep_Mode", 0);
BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.IMUSet = this->readvalue(fin, "ContinuousStep_IMU", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_StayExpX", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_StayExpY", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_StayExpZ", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_StayExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_StayAddX", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_StayAddY", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_StayAddZ", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_StayAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousStay].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_StayChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_TurnRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_TurnRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_TurnRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_TurnRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_TurnRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_TurnRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_TurnRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_TurnRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousTurnRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_TurnRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_SmallTurnRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_SmallTurnRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_SmallTurnRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_SmallTurnRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_SmallTurnRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_SmallTurnRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_SmallTurnRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_SmallTurnRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_SmallTurnRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_TurnLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_TurnLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_TurnLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_TurnLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_TurnLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_TurnLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_TurnLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_TurnLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousTurnLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_TurnLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_SmallTurnLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_SmallTurnLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_SmallTurnLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_SmallTurnLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_SmallTurnLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_SmallTurnLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_SmallTurnLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_SmallTurnLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallTurnLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_SmallTurnLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_ForwardExpX", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_ForwardExpY", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_ForwardExpZ", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_ForwardExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_ForwardAddX", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_ForwardAddY", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_ForwardAddZ", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_ForwardAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousForward].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_ForwardChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_SmallForwardExpX", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_SmallForwardExpY", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_SmallForwardExpZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_SmallForwardExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_SmallForwardAddX", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_SmallForwardAddY", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_SmallForwardAddZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_SmallForwardAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallForward].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_SmallForwardChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_SmallLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_SmallLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_SmallLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_SmallLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_SmallLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_SmallLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_SmallLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_SmallLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_SmallLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_BigLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_BigLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_BigLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_BigLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_BigLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_BigLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_BigLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_BigLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousBigLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_BigLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_SmallRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_SmallRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_SmallRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_SmallRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_SmallRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_SmallRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_SmallRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_SmallRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousSmallRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_SmallRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_BigRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_BigRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_BigRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_BigRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_BigRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_BigRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_BigRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_BigRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousBigRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_BigRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_FastForwardExpX", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_FastForwardExpY", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_FastForwardExpZ", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_FastForwardExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_FastForwardAddX", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_FastForwardAddY", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_FastForwardAddZ", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_FastForwardAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastForward].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_FastForwardChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_FastSmallLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_FastSmallLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_FastSmallLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_FastSmallLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_FastSmallLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_FastSmallLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_FastSmallLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_FastSmallLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_FastSmallLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_FastBigLeftExpX", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_FastBigLeftExpY", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_FastBigLeftExpZ", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_FastBigLeftExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_FastBigLeftAddX", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_FastBigLeftAddY", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_FastBigLeftAddZ", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_FastBigLeftAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastBigLeft].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_FastBigLeftChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_FastSmallRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_FastSmallRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_FastSmallRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_FastSmallRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_FastSmallRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_FastSmallRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_FastSmallRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_FastSmallRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastSmallRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_FastSmallRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_FastBigRightExpX", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_FastBigRightExpY", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_FastBigRightExpZ", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_FastBigRightExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_FastBigRightAddX", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_FastBigRightAddY", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_FastBigRightAddZ", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_FastBigRightAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousFastBigRight].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_FastBigRightChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.ExpX = this->readvalue(fin, "ContinuousStep_BackwardExpX", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.ExpY = this->readvalue(fin, "ContinuousStep_BackwardExpY", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.ExpZ = this->readvalue(fin, "ContinuousStep_BackwardExpZ", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.ExpTheta = this->readvalue(fin, "ContinuousStep_BackwardExpTheta", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.AddX = this->readvalue(fin, "ContinuousStep_BackwardAddX", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.AddY = this->readvalue(fin, "ContinuousStep_BackwardAddY", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.AddZ = this->readvalue(fin, "ContinuousStep_BackwardAddZ", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.AddTheta = this->readvalue(fin, "ContinuousStep_BackwardAddTheta", 0);
BasketInfo->ContinuousStep[ContinuousBackward].ContinuousMove.ChangeMode = this->readvalue(fin, "ContinuousStep_BackwardChangeMode", 0);
fin.getline(temp, sizeof(temp));
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitX = this->readvalue(fin, "ContinuousStep_BackInitX", 0);
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitY = this->readvalue(fin, "ContinuousStep_BackInitY", 0);
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitZ = this->readvalue(fin, "ContinuousStep_BackInitZ", 0);
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitTheta = this->readvalue(fin, "ContinuousStep_BackInitTheta", 0);
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.Mode = this->readvalue(fin, "ContinuousStep_BackMode", 0);
BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.IMUSet = this->readvalue(fin, "ContinuousStep_BackIMU", 0);
fin.close();
ROS_INFO("fileclose ContinuousMove.ini");
}
catch(exception e)
{
ROS_INFO("catchfile");
}
}
void LoadParameter::TestParameters()
{
ROS_INFO("--------------- Throw ------------------");
ROS_INFO("RobotSearchBasketHeight = %f",BasketInfo->RobotSearchBasketHeight);
ROS_INFO("VisionMiddle = %f",BasketInfo->VisionMiddle);
ROS_INFO("ScreenButtom = %f",BasketInfo->ScreenButtom);
ROS_INFO("Error = %f",BasketInfo->Error);
ROS_INFO("HeadVerticalState = %d",BasketInfo->HeadVerticalState);
ROS_INFO("HeadHorizontalState = %d",BasketInfo->HeadHorizontalState);
ROS_INFO("BallVerticalBaseLine = %d",BasketInfo->BallVerticalBaseLine);
ROS_INFO("BallHorizontalBaseLine = %d",BasketInfo->BallHorizontalBaseLine);
ROS_INFO("VerticalMaxAngle = %d",BasketInfo->VerticalMaxAngle);
ROS_INFO("VerticalMinAngle = %d",BasketInfo->VerticalMinAngle);
ROS_INFO("HorizontalMaxAngle = %d",BasketInfo->HorizontalMaxAngle);
ROS_INFO("HorizontalMinAngle = %d",BasketInfo->HorizontalMinAngle);
ROS_INFO("BasketHorizontalMaxAngle = %d",BasketInfo->BasketHorizontalMaxAngle);
ROS_INFO("BasketHorizontalMinAngle = %d",BasketInfo->BasketHorizontalMinAngle);
ROS_INFO("BasketHorizontalBaseLine = %d",BasketInfo->BasketHorizontalBaseLine);
ROS_INFO("BasketVerticalBaseLine = %d",BasketInfo->BasketVerticalBaseLine);
ROS_INFO("BasketVerticalBaseLine90 = %d",BasketInfo->BasketVerticalBaseLine90);
ROS_INFO("BasketVerticalBaseLine80 = %d",BasketInfo->BasketVerticalBaseLine80);
ROS_INFO("BasketVerticalBaseLine70 = %d",BasketInfo->BasketVerticalBaseLine70);
ROS_INFO("BasketVerticalBaseLine60 = %d",BasketInfo->BasketVerticalBaseLine60);
ROS_INFO("BasketVerticalBaseLine50 = %d",BasketInfo->BasketVerticalBaseLine50);
ROS_INFO("BasketLeftBaselineFix = %d",BasketInfo->BasketLeftBaselineFix);
ROS_INFO("BasketRightBaselineFix = %d",BasketInfo->BasketRightBaselineFix);
ROS_INFO("WaistError = %d",BasketInfo->WaistError);
ROS_INFO("SpeedError = %d",BasketInfo->SpeedError);
ROS_INFO("Point5DisError = %d",BasketInfo->Point5DisError);
ROS_INFO("BallVerticalError = %d",BasketInfo->BallVerticalError);
ROS_INFO("BallHorizontalError = %d",BasketInfo->BallHorizontalError);
ROS_INFO("ContinuousSlowLine = %d",BasketInfo->ContinuousSlowLine);
ROS_INFO("ContinuousSlowLine2 = %d",BasketInfo->ContinuousSlowLine2);
ROS_INFO("CatchBallLine = %d",BasketInfo->CatchBallLine);
ROS_INFO("--------------- Speed ------------------");
ROS_INFO("dis35_x = %f",BasketInfo->dis35_x);
ROS_INFO("dis40_x = %f",BasketInfo->dis40_x);
ROS_INFO("dis50_x = %f",BasketInfo->dis50_x);
ROS_INFO("dis60_x = %f",BasketInfo->dis60_x);
ROS_INFO("dis65_x = %f",BasketInfo->dis65_x);
ROS_INFO("dis70_x = %f",BasketInfo->dis70_x);
ROS_INFO("dis75_x = %f",BasketInfo->dis75_x);
ROS_INFO("dis80_x = %f",BasketInfo->dis80_x);
ROS_INFO("dis85_x = %f",BasketInfo->dis85_x);
ROS_INFO("dis90_x = %f",BasketInfo->dis90_x);
ROS_INFO("dis35speed = %d",BasketInfo->dis35speed);
ROS_INFO("dis40speed = %d",BasketInfo->dis40speed);
ROS_INFO("dis50speed = %d",BasketInfo->dis50speed);
ROS_INFO("dis60speed = %d",BasketInfo->dis60speed);
ROS_INFO("dis61speed = %d",BasketInfo->dis61speed);
ROS_INFO("dis70speed = %d",BasketInfo->dis70speed);
ROS_INFO("dis71speed = %d",BasketInfo->dis71speed);
ROS_INFO("dis80speed = %d",BasketInfo->dis80speed);
ROS_INFO("dis81speed = %d",BasketInfo->dis81speed);
ROS_INFO("dis90speed = %d",BasketInfo->dis90speed);
ROS_INFO("Dispeedfix = %d",BasketInfo->Disspeedfix);
ROS_INFO("---------- Continuous Step -------------");
ROS_INFO("AddPeriod = %f",BasketInfo->AddPeriod);
ROS_INFO("ContinuousInit");
ROS_INFO("InitX = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitX);
ROS_INFO("InitY = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitY);
ROS_INFO("InitZ = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitZ);
ROS_INFO("InitTheta = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.InitTheta);
ROS_INFO("Mode = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.Mode);
ROS_INFO("IMUSet = %d",BasketInfo->ContinuousStep[ContinuousStand].ContinuousInit.IMUSet);
ROS_INFO("etContinuousBackInit");
ROS_INFO("InitX = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitX);
ROS_INFO("InitY = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitY);
ROS_INFO("InitZ = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitZ);
ROS_INFO("InitTheta = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.InitTheta);
ROS_INFO("Mode = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.Mode);
ROS_INFO("IMUSet = %d",BasketInfo->ContinuousStep[ContinuousBackStart].ContinuousInit.IMUSet);
for(int i = ContinuousStand; i <= ContinuousBackStart; i++)
{
switch(i)
{
case ContinuousStand:
ROS_INFO("ContinuousStand");
break;
case ContinuousStay:
ROS_INFO("ContinuousStay");
break;
case ContinuousTurnRight:
ROS_INFO("ContinuousTurnRight");
break;
case ContinuousSmallTurnRight:
ROS_INFO("ContinuousSmallTurnRight");
break;
case ContinuousTurnLeft:
ROS_INFO("ContinuousTurnLeft");
break;
case ContinuousSmallTurnLeft:
ROS_INFO("ContinuousSmallTurnLeft");
break;
case ContinuousForward:
ROS_INFO("ContinuousForward");
break;
case ContinuousSmallForward:
ROS_INFO("ContinuousSmallForward");
break;
case ContinuousSmallLeft:
ROS_INFO("ContinuousSmallLeft");
break;
case ContinuousBigLeft:
ROS_INFO("ContinuousBigLeft");
break;
case ContinuousSmallRight:
ROS_INFO("ContinuousSmallRight");
break;
case ContinuousBigRight:
ROS_INFO("ContinuousBigRight");
break;
case ContinuousFastForward:
ROS_INFO("ContinuousFastForward");
break;
case ContinuousFastSmallLeft:
ROS_INFO("ContinuousFastSmallLeft");
break;
case ContinuousFastBigLeft:
ROS_INFO("ContinuousFastBigLeft");
break;
case ContinuousFastSmallRight:
ROS_INFO("ContinuousFastSmallRight");
break;
case ContinuousFastBigRight:
ROS_INFO("ContinuousFastBigRight");
break;
case ContinuousBackward:
ROS_INFO("ContinuousBackward");
break;
case ContinuousBackStart:
ROS_INFO("ContinuousBackStart");
break;
}
ROS_INFO("ExpX = %d",BasketInfo->ContinuousStep[i].ContinuousMove.ExpX);
ROS_INFO("ExpY = %d",BasketInfo->ContinuousStep[i].ContinuousMove.ExpY);
ROS_INFO("ExpZ = %d",BasketInfo->ContinuousStep[i].ContinuousMove.ExpZ);
ROS_INFO("ExpTheta = %d",BasketInfo->ContinuousStep[i].ContinuousMove.ExpTheta);
ROS_INFO("AddX = %d",BasketInfo->ContinuousStep[i].ContinuousMove.AddX);
ROS_INFO("AddY = %d",BasketInfo->ContinuousStep[i].ContinuousMove.AddY);
ROS_INFO("AddZ = %d",BasketInfo->ContinuousStep[i].ContinuousMove.AddZ);
ROS_INFO("AddTheta = %d",BasketInfo->ContinuousStep[i].ContinuousMove.AddTheta);
}
}
| 72.574324 | 156 | 0.714156 | TKUICLab-humanoid |
cb144a20723458bdeb8057ebbe6c45f5c2319c66 | 2,174 | hpp | C++ | include/memoria/reactor/process.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2021-07-30T16:54:24.000Z | 2021-09-08T15:48:17.000Z | include/memoria/reactor/process.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | null | null | null | include/memoria/reactor/process.hpp | victor-smirnov/memoria | c36a957c63532176b042b411b1646c536e71a658 | [
"BSL-1.0",
"Apache-2.0",
"OLDAP-2.8",
"BSD-3-Clause"
] | 2 | 2020-03-14T15:15:25.000Z | 2020-06-15T11:26:56.000Z |
// Copyright 2018 Victor Smirnov
//
// 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.
#pragma once
#include <memoria/core/types.hpp>
#include <memoria/core/tools/pimpl_base.hpp>
#include <memoria/reactor/pipe_streams.hpp>
#include <memoria/reactor/pipe_streams_reader.hpp>
#include <memoria/filesystem/path.hpp>
#include <ostream>
#include <map>
namespace memoria {
namespace reactor {
filesystem::path get_program_path();
filesystem::path get_image_name();
using EnvironmentMap = std::map<U8String, U8String>;
using EnvironmentList = std::vector<U8String>;
class ProcessImpl;
class Process: public PimplBase<ProcessImpl> {
using Base = PimplBase<ProcessImpl>;
public:
MMA_PIMPL_DECLARE_DEFAULT_FUNCTIONS(Process)
enum class Status {RUNNING, EXITED, TERMINATED, CRASHED, OTHER};
Status join();
void terminate();
void kill();
int32_t exit_code() const;
Status status() const;
PipeInputStream out_stream();
PipeInputStream err_stream();
PipeOutputStream in_stream();
};
std::ostream& operator<<(std::ostream& out, Process::Status status) ;
class ProcessBuilderImpl;
class ProcessBuilder : public PimplBase<ProcessBuilderImpl> {
using Base = PimplBase<ProcessBuilderImpl>;
public:
MMA_PIMPL_DECLARE_DEFAULT_FUNCTIONS(ProcessBuilder)
static ProcessBuilder create(filesystem::path exe_path);
ProcessBuilder& with_args(U8String args);
ProcessBuilder& with_args(std::vector<U8String> args);
ProcessBuilder& with_env(EnvironmentList entries = EnvironmentList());
ProcessBuilder& with_env(EnvironmentMap entries);
ProcessBuilder& with_vfork(bool use_vfork);
Process run();
};
}}
| 24.155556 | 75 | 0.75115 | victor-smirnov |
0e13ffc77544965aa1510564ac983d63d862bcd9 | 944 | cpp | C++ | framework/pixel.cpp | PeteTheN00b/programmiersprachen-raytracer | a2af1c30d5a7be24232e94f7dea834cd6daa3ca4 | [
"MIT"
] | null | null | null | framework/pixel.cpp | PeteTheN00b/programmiersprachen-raytracer | a2af1c30d5a7be24232e94f7dea834cd6daa3ca4 | [
"MIT"
] | null | null | null | framework/pixel.cpp | PeteTheN00b/programmiersprachen-raytracer | a2af1c30d5a7be24232e94f7dea834cd6daa3ca4 | [
"MIT"
] | null | null | null | // -----------------------------------------------------------------------------
// Copyright : (C) 2014-2017 Andre Schollmeyer and Andreas-C. Bernstein
// License : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability : experimental
//
// Pixel
// -----------------------------------------------------------------------------
#include "pixel.hpp"
#include <ostream>
Pixel::Pixel(unsigned int a, unsigned int b)
: x(a),
y(b),
color{0,0,0}
{}
Pixel::Pixel(unsigned int a, unsigned int b, Color const& c)
:
x{ a },
y{ b },
color{ c }
{}
void Pixel::print(std::ostream& os) const
{
os << "Pixel[" << (int)x << ',' << (int)y << "]("
<< color.r << ','
<< color.g << ','
<< color.b << ')';
}
std::ostream& operator<<(std::ostream& os, const Pixel& a)
{
std::ostream::sentry cerberus (os);
if (cerberus)
a.print(os);
return os;
}
| 23.02439 | 80 | 0.474576 | PeteTheN00b |
0e1c5de844dc49926ed705224d04ea4fc7d2f523 | 22,156 | cpp | C++ | lib/Dialect/FIRRTL/Transforms/GrandCentral.cpp | mwachs5/circt | bd7edb5c449921cb36939ebb5943e4fe73f72899 | [
"Apache-2.0"
] | null | null | null | lib/Dialect/FIRRTL/Transforms/GrandCentral.cpp | mwachs5/circt | bd7edb5c449921cb36939ebb5943e4fe73f72899 | [
"Apache-2.0"
] | null | null | null | lib/Dialect/FIRRTL/Transforms/GrandCentral.cpp | mwachs5/circt | bd7edb5c449921cb36939ebb5943e4fe73f72899 | [
"Apache-2.0"
] | null | null | null | //===- GrandCentral.cpp - Ingest black box sources --------------*- C++ -*-===//
//
// 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
//===----------------------------------------------------------------------===//
//
// Implement SiFive's Grand Central transform. Currently, this supports
// SystemVerilog Interface generation.
//
//===----------------------------------------------------------------------===//
#include "PassDetails.h"
#include "circt/Dialect/FIRRTL/FIRRTLAnnotations.h"
#include "circt/Dialect/FIRRTL/FIRRTLVisitors.h"
#include "circt/Dialect/FIRRTL/Passes.h"
#include "circt/Dialect/HW/HWDialect.h"
#include "circt/Dialect/SV/SVOps.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "llvm/ADT/StringSwitch.h"
using namespace circt;
using namespace firrtl;
//===----------------------------------------------------------------------===//
// Pass Implementation
//===----------------------------------------------------------------------===//
namespace {
/// Mutable store of information about an Element in an interface. This is
/// derived from information stored in the "elements" field of an
/// "AugmentedBundleType". This is updated as more information is known about
/// an Element.
struct ElementInfo {
/// Encodes the "tpe" of an element. This is called "Kind" to avoid
/// overloading the meaning of "Type" (which also conflicts with mlir::Type).
enum Kind {
Error = -1,
Ground,
Vector,
Bundle,
String,
Boolean,
Integer,
Double
};
/// The "tpe" field indicating if this element of the interface is a ground
/// type, a vector type, or a bundle type. Bundle types are nested
/// interfaces.
Kind tpe;
/// A string description that will show up as a comment in the output Verilog.
StringRef description;
/// The width of this interface. This is only non-negative for ground or
/// vector types.
int32_t width = -1;
/// The depth of the interface. This is one for ground types and greater
/// than one for vector types.
uint32_t depth = 0;
/// Indicate if this element was found in the circuit.
bool found = false;
/// Trakcs location information about what was used to build this element.
SmallVector<Location> locations = {};
/// True if this is a ground or vector type and it was not (statefully) found.
/// This indicates that an interface element, which is composed of ground and
/// vector types, found no matching, annotated components in the circuit.
bool isMissing() { return !found && (tpe == Ground || tpe == Vector); }
};
/// Stores a decoded Grand Central AugmentedField
struct AugmentedField {
/// The name of the field.
StringRef name;
/// An optional descripton that the user provided for the field. This should
/// become a comment in the Verilog.
StringRef description;
/// The "type" of the field.
ElementInfo::Kind tpe;
};
/// Stores a decoded Grand Central AugmentedBundleType.
struct AugmentedBundleType {
/// The name of the interface.
StringRef defName;
/// The elements that make up the body of the interface.
SmallVector<AugmentedField> elements;
};
/// Convert an arbitrary attributes into an optional AugmentedField. Returns
/// None if the attribute is an invalid AugmentedField.
static Optional<AugmentedField> decodeField(Attribute maybeField) {
auto field = maybeField.dyn_cast_or_null<DictionaryAttr>();
if (!field)
return {};
auto tpeString = field.getAs<StringAttr>("tpe");
auto name = field.getAs<StringAttr>("name");
if (!name || !tpeString)
return {};
auto tpe = llvm::StringSwitch<ElementInfo::Kind>(tpeString.getValue())
.Case("sifive.enterprise.grandcentral.AugmentedBundleType",
ElementInfo::Bundle)
.Case("sifive.enterprise.grandcentral.AugmentedVectorType",
ElementInfo::Vector)
.Case("sifive.enterprise.grandcentral.AugmentedGroundType",
ElementInfo::Ground)
.Case("sifive.enterprise.grandcentral.AugmentedStringType",
ElementInfo::String)
.Case("sifive.enterprise.grandcentral.AugmentedBooleanType",
ElementInfo::Boolean)
.Case("sifive.enterprise.grandcentral.AugmentedIntegerType",
ElementInfo::Integer)
.Case("sifive.enterprise.grandcentral.AugmentedDoubleType",
ElementInfo::Double)
.Default(ElementInfo::Error);
if (tpe == ElementInfo::Error)
return {};
StringRef description = {};
if (auto maybeDescription = field.getAs<StringAttr>("description"))
description = maybeDescription.getValue();
return Optional<AugmentedField>({name.getValue(), description, tpe});
};
/// Convert an Annotation into an optional AugmentedBundleType. Returns None if
/// the annotation is not an AugmentedBundleType.
static Optional<AugmentedBundleType> decodeBundleType(Annotation anno) {
auto defName = anno.getMember<StringAttr>("defName");
auto elements = anno.getMember<ArrayAttr>("elements");
if (!defName || !elements)
return {};
AugmentedBundleType bundle(
{defName.getValue(), SmallVector<AugmentedField>()});
for (auto element : elements) {
auto field = decodeField(element);
if (!field)
return {};
bundle.elements.push_back(field.getValue());
}
return Optional<AugmentedBundleType>(bundle);
};
/// Remove Grand Central Annotations associated with SystemVerilog interfaces
/// that should emitted. This pass works in three major phases:
///
/// 1. The circuit's annotations are examnined to figure out _what_ interfaces
/// there are. This includes information about the name of the interface
/// ("defName") and each of the elements (sv::InterfaceSignalOp) that make up
/// the interface. However, no information about the _type_ of the elements
/// is known.
///
/// 2. With this, information, walk through the circuit to find scattered
/// information about the types of the interface elements. Annotations are
/// scattered during FIRRTL parsing to attach all the annotations associated
/// with elements on the right components.
///
/// 3. Add interface ops and populate the elements.
///
/// Grand Central supports three "normal" element types and four "weird" element
/// types. The normal ones are ground types (SystemVerilog logic), vector types
/// (SystemVerilog unpacked arrays), and nested interface types (another
/// SystemVerilog interface). The Chisel API provides "weird" elements that
/// include: Boolean, Integer, String, and Double. The SFC implementation
/// currently drops these, but this pass emits them as commented out strings.
struct GrandCentralPass : public GrandCentralBase<GrandCentralPass> {
void runOnOperation() override;
// A map storing mutable information about an element in an interface. This
// is keyed using a (defName, name) tuple where defname is the name of the
// interface and name is the name of the element.
typedef DenseMap<std::pair<StringRef, StringRef>, ElementInfo> InterfaceMap;
private:
// Store a mapping of interface name to InterfaceOp.
llvm::StringMap<sv::InterfaceOp> interfaces;
// Discovered interfaces that need to be constructed.
InterfaceMap interfaceMap;
// Track the order that interfaces should be emitted in.
SmallVector<std::pair<StringRef, StringRef>> interfaceKeys;
};
class GrandCentralVisitor : public FIRRTLVisitor<GrandCentralVisitor> {
public:
GrandCentralVisitor(GrandCentralPass::InterfaceMap &interfaceMap)
: interfaceMap(interfaceMap) {}
private:
/// Mutable store tracking each element in an interface. This is indexed by a
/// "defName" -> "name" tuple.
GrandCentralPass::InterfaceMap &interfaceMap;
/// Helper to handle wires, registers, and nodes.
void handleRef(Operation *op);
/// A helper used by handleRef that can also be used to process ports.
void handleRefLike(Operation *op, AnnotationSet &annotations,
FIRRTLType type);
// Helper to handle ports of modules that may have Grand Central annotations.
void handlePorts(Operation *op);
// If true, then some error occurred while the visitor was running. This
// indicates that pass failure should occur.
bool failed = false;
public:
using FIRRTLVisitor<GrandCentralVisitor>::visitDecl;
/// Visit FModuleOp and FExtModuleOp
void visitModule(Operation *op);
/// Visit ops that can make up an interface element.
void visitDecl(RegOp op) { handleRef(op); }
void visitDecl(RegResetOp op) { handleRef(op); }
void visitDecl(WireOp op) { handleRef(op); }
void visitDecl(NodeOp op) { handleRef(op); }
void visitDecl(InstanceOp op);
/// Process all other ops. Error if any of these ops contain annotations that
/// indicate it as being part of an interface.
void visitUnhandledDecl(Operation *op);
/// Returns true if an error condition occurred while visiting ops.
bool hasFailed() { return failed; };
};
} // namespace
void GrandCentralVisitor::visitModule(Operation *op) {
handlePorts(op);
if (isa<FModuleOp>(op))
for (auto &stmt : op->getRegion(0).front())
dispatchVisitor(&stmt);
}
/// Process all other operations. This will throw an error if the operation
/// contains any annotations that indicates that this should be included in an
/// interface. Otherwise, this is a valid nop.
void GrandCentralVisitor::visitUnhandledDecl(Operation *op) {
AnnotationSet annotations(op);
auto anno = annotations.getAnnotation(
"sifive.enterprise.grandcentral.AugmentedGroundType");
if (!anno)
return;
auto diag =
op->emitOpError()
<< "is marked as a an interface element, but this op or its ports are "
"not supposed to be interface elements (Are your annotations "
"malformed? Is this a missing feature that should be supported?)";
diag.attachNote()
<< "this annotation marked the op as an interface element: '" << anno
<< "'";
failed = true;
}
/// Process annotations associated with an operation and having some type.
/// Return the annotations with the processed annotations removed. If all
/// annotations are removed, this returns an empty ArrayAttr.
void GrandCentralVisitor::handleRefLike(mlir::Operation *op,
AnnotationSet &annotations,
FIRRTLType type) {
if (annotations.empty())
return;
bool foundAnnotations = false;
for (auto anno : annotations) {
if (!anno.isClass("sifive.enterprise.grandcentral.AugmentedGroundType"))
continue;
auto defName = anno.getMember<StringAttr>("defName");
auto name = anno.getMember<StringAttr>("name");
if (!defName || !name) {
op->emitOpError(
"is marked as part of an interface, but is missing 'defName' or "
"'name' fields (did you forget to add these?)")
.attachNote()
<< "the full annotation is: " << anno.getDict();
failed = true;
continue;
}
// TODO: This is ignoring situations where the leaves of and interface are
// not ground types. This enforces the requirement that this runs after
// LowerTypes. However, this could eventually be relaxed.
if (!type.isGround()) {
auto diag = op->emitOpError()
<< "cannot be added to interface '" << defName.getValue()
<< "', component '" << name.getValue()
<< "' because it is not a ground type. (Got type '" << type
<< "'.) This will be dropped from the interface. (Did you "
"forget to run LowerTypes?)";
diag.attachNote()
<< "The annotation indicating that this should be added was: '"
<< anno.getDict();
failed = true;
continue;
}
auto &component = interfaceMap[{defName.getValue(), name.getValue()}];
component.found = true;
switch (component.tpe) {
case ElementInfo::Vector:
component.width = type.getBitWidthOrSentinel();
component.depth++;
component.locations.push_back(op->getLoc());
break;
case ElementInfo::Ground:
component.width = type.getBitWidthOrSentinel();
component.locations.push_back(op->getLoc());
break;
case ElementInfo::Bundle:
case ElementInfo::String:
case ElementInfo::Boolean:
case ElementInfo::Integer:
case ElementInfo::Double:
break;
case ElementInfo::Error:
llvm_unreachable("Shouldn't be here");
break;
}
annotations.removeAnnotation(anno);
foundAnnotations = true;
}
}
/// Combined logic to handle Wires, Registers, and Nodes because these all use
/// the same approach.
void GrandCentralVisitor::handleRef(mlir::Operation *op) {
auto annotations = AnnotationSet(op);
handleRefLike(op, annotations, op->getResult(0).getType().cast<FIRRTLType>());
annotations.applyToOperation(op);
}
/// Remove Grand Central Annotations from ports of modules or external modules.
/// Return argument attributes with annotations removed.
void GrandCentralVisitor::handlePorts(Operation *op) {
SmallVector<Attribute> newArgAttrs;
auto ports = getModulePortInfo(op);
for (size_t i = 0, e = ports.size(); i != e; ++i) {
auto port = ports[i];
handleRefLike(op, port.annotations, port.type);
newArgAttrs.push_back(port.annotations.applyToPortDictionaryAttr(
DictionaryAttr::get(op->getContext(), {})));
}
mlir::function_like_impl::setAllArgAttrDicts(op, newArgAttrs);
}
void GrandCentralVisitor::visitDecl(InstanceOp op) {
// If this instance's underlying module has a "companion" annotation, then
// move this onto the actual instance op.
AnnotationSet annotations(op.getReferencedModule());
if (auto anno = annotations.getAnnotation(
"sifive.enterprise.grandcentral.ViewAnnotation")) {
auto tpe = anno.getAs<StringAttr>("type");
if (!tpe) {
op.getReferencedModule()->emitOpError(
"contains a ViewAnnotation that does not contain a \"type\" field");
failed = true;
return;
}
if (tpe.getValue() == "companion")
op->setAttr("lowerToBind", BoolAttr::get(op.getContext(), true));
}
visitUnhandledDecl(op);
}
void GrandCentralPass::runOnOperation() {
CircuitOp circuitOp = getOperation();
AnnotationSet annotations(circuitOp);
if (annotations.empty())
return;
// Setup the builder to create ops _inside the FIRRTL circuit_. This is
// necessary because interfaces and interface instances are created.
// Instances link to their definitions via symbols and we don't want to break
// this.
auto builder = OpBuilder::atBlockEnd(circuitOp.getBody());
// Utility that acts like emitOpError, but does _not_ include a note. The
// note in emitOpError includes the entire op which means the **ENTIRE**
// FIRRTL circuit. This doesn't communicate anything useful to the user other
// than flooding their terminal.
auto emitCircuitError = [&circuitOp](StringRef message = {}) {
return emitError(circuitOp.getLoc(), message);
};
// Examine the Circuit's Annotations doing work to remove Grand Central
// Annotations. Ignore any unprocesssed annotations and rewrite the Circuit's
// Annotations with these when done.
bool removalError = false;
annotations.removeAnnotations([&](auto anno) {
if (!anno.isClass("sifive.enterprise.grandcentral.AugmentedBundleType"))
return false;
AugmentedBundleType bundle;
if (auto maybeBundle = decodeBundleType(anno))
bundle = maybeBundle.getValue();
else {
emitCircuitError(
"'firrtl.circuit' op contained an 'AugmentedBundleType' "
"Annotation which did not conform to the expected format")
.attachNote()
<< "the problematic 'AugmentedBundleType' is: '" << anno.getDict()
<< "'";
removalError = true;
return false;
}
for (auto elt : bundle.elements) {
std::pair<StringRef, StringRef> key = {bundle.defName, elt.name};
interfaceMap[key] = {elt.tpe, elt.description};
interfaceKeys.push_back(key);
}
// If the interface already exists, don't create it.
if (interfaces.count(bundle.defName))
return true;
// Create the interface. This will be populated later.
interfaces[bundle.defName] =
builder.create<sv::InterfaceOp>(circuitOp->getLoc(), bundle.defName);
return true;
});
if (removalError)
return signalPassFailure();
// Remove the processed annotations.
circuitOp->setAttr("annotations", annotations.getArrayAttr());
// Walk through the circuit to collect additional information. If this fails,
// signal pass failure. Walk in reverse order so that annotations can be
// removed from modules after all referring instances have consumed their
// annotations.
for (auto &op : llvm::reverse(circuitOp.getBody()->getOperations())) {
// Only process modules or external modules.
if (!isa<FModuleOp, FExtModuleOp>(op))
continue;
GrandCentralVisitor visitor(interfaceMap);
visitor.visitModule(&op);
if (visitor.hasFailed())
return signalPassFailure();
AnnotationSet annotations(&op);
annotations.removeAnnotations([&](auto anno) {
// Insert an instantiated interface.
if (auto viewAnnotation = annotations.getAnnotation(
"sifive.enterprise.grandcentral.ViewAnnotation")) {
auto tpe = viewAnnotation.getAs<StringAttr>("type");
if (tpe && tpe.getValue() == "parent") {
auto name = viewAnnotation.getAs<StringAttr>("name");
auto defName = viewAnnotation.getAs<StringAttr>("defName");
auto guard = OpBuilder::InsertionGuard(builder);
builder.setInsertionPointToEnd(cast<FModuleOp>(op).getBodyBlock());
auto instance = builder.create<sv::InterfaceInstanceOp>(
circuitOp->getLoc(),
interfaces.lookup(defName.getValue()).getInterfaceType(), name,
builder.getStringAttr(
"__" + op.getAttrOfType<StringAttr>("sym_name").getValue() +
"_" + defName.getValue() + "__"));
instance->setAttr("doNotPrint", builder.getBoolAttr(true));
builder.setInsertionPointToStart(
op.getParentOfType<ModuleOp>().getBody());
auto bind = builder.create<sv::BindInterfaceOp>(
circuitOp->getLoc(),
builder.getSymbolRefAttr(instance.sym_name().getValue()));
bind->setAttr(
"output_file",
hw::OutputFileAttr::get(
builder.getStringAttr(""),
builder.getStringAttr("bindings.sv"),
/*exclude_from_filelist=*/builder.getBoolAttr(true),
/*exclude_replicated_ops=*/builder.getBoolAttr(true),
bind.getContext()));
}
return true;
}
// All other annotations pass through unmodified.
return false;
});
annotations.applyToOperation(&op);
}
// Populate interfaces.
for (auto &a : interfaceKeys) {
auto defName = a.first;
auto name = a.second;
auto &info = interfaceMap[{defName, name}];
if (info.isMissing()) {
emitCircuitError()
<< "'firrtl.circuit' op contained a Grand Central Interface '"
<< defName << "' that had an element '" << name
<< "' which did not have a scattered companion annotation (is there "
"an invalid target in your annotation file?)";
continue;
}
builder.setInsertionPointToEnd(interfaces[defName].getBodyBlock());
auto loc = builder.getFusedLoc(info.locations);
auto description = info.description;
if (!description.empty())
builder.create<sv::VerbatimOp>(loc, "\n// " + description);
switch (info.tpe) {
case ElementInfo::Bundle:
// TODO: Change this to actually use an interface type. This currently
// does not work because: (1) interfaces don't have a defined way to get
// their bit width and (2) interfaces have a symbol table that is used to
// verify internal ops, but this requires looking arbitrarily far upwards
// to find other symbols.
builder.create<sv::VerbatimOp>(loc, name + " " + name + "();");
break;
case ElementInfo::Vector: {
auto type = hw::UnpackedArrayType::get(builder.getIntegerType(info.width),
info.depth);
builder.create<sv::InterfaceSignalOp>(loc, name, type);
break;
}
case ElementInfo::Ground: {
auto type = builder.getIntegerType(info.width);
builder.create<sv::InterfaceSignalOp>(loc, name, type);
break;
}
case ElementInfo::String:
builder.create<sv::VerbatimOp>(loc, "// " + name +
" = <unsupported string type>;");
break;
case ElementInfo::Boolean:
builder.create<sv::VerbatimOp>(loc, "// " + name +
" = <unsupported boolean type>;");
break;
case ElementInfo::Integer:
builder.create<sv::VerbatimOp>(loc, "// " + name +
" = <unsupported integer type>;");
break;
case ElementInfo::Double:
builder.create<sv::VerbatimOp>(loc, "// " + name +
" = <unsupported double type>;");
break;
case ElementInfo::Error:
llvm_unreachable("Shouldn't be here");
break;
}
}
interfaces.clear();
interfaceMap.clear();
interfaceKeys.clear();
}
//===----------------------------------------------------------------------===//
// Pass Creation
//===----------------------------------------------------------------------===//
std::unique_ptr<mlir::Pass> circt::firrtl::createGrandCentralPass() {
return std::make_unique<GrandCentralPass>();
}
| 38.734266 | 80 | 0.653232 | mwachs5 |
0e1f60c976cdc262e0ff5d5281150931fb5722b8 | 1,019 | hh | C++ | include/mithril/handler/message_to_message_decoder.hh | salahsheikh/mithril | 020c9c6ad645e0a2767653cd158460ab1c6c13ca | [
"0BSD"
] | 1 | 2021-08-01T16:31:11.000Z | 2021-08-01T16:31:11.000Z | include/mithril/handler/message_to_message_decoder.hh | salahsheikh/mithril | 020c9c6ad645e0a2767653cd158460ab1c6c13ca | [
"0BSD"
] | null | null | null | include/mithril/handler/message_to_message_decoder.hh | salahsheikh/mithril | 020c9c6ad645e0a2767653cd158460ab1c6c13ca | [
"0BSD"
] | null | null | null | //
// Created by ssheikh on 2021-03-03.
//
#ifndef MITHRIL_INCLUDE_MITHRIL_HANDLER_MESSAGE_TO_MESSAGE_DECODER_HH
#define MITHRIL_INCLUDE_MITHRIL_HANDLER_MESSAGE_TO_MESSAGE_DECODER_HH
#include <mithril/channel/channel_inbound_handler.hh>
#include <mithril/message.hh>
#include <mithril/buffer/composite_buffer.hh>
#include <list>
template<typename Input>
class message_to_message_decoder
: public channel_inbound_handler_adapter
{
private:
std::list<mithril::message> out;
public:
virtual void decode(channel_handler_context&, Input msg, std::list<mithril::message>& out) = 0;
void channel_read(channel_handler_context& ctx, mithril::message msg) override
{
if (msg->template holds<Input>()) {
decode(ctx, msg->unwrap<Input>(), out);
for (auto&& out_msg : out) {
ctx.fire_channel_read(std::move(out_msg));
}
out.clear();
} else {
ctx.fire_channel_read(std::move(msg));
}
}
};
#endif //MITHRIL_INCLUDE_MITHRIL_HANDLER_MESSAGE_TO_MESSAGE_DECODER_HH
| 24.853659 | 97 | 0.737978 | salahsheikh |
0e22fb6281a354efcbaf1d036a83bcffeccb0b89 | 3,447 | hpp | C++ | include/fogl/program.hpp | glasmachers/foglpp | 9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888 | [
"MIT"
] | null | null | null | include/fogl/program.hpp | glasmachers/foglpp | 9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888 | [
"MIT"
] | null | null | null | include/fogl/program.hpp | glasmachers/foglpp | 9a7dee6f1fe6b4d1ea7408f0762c7b32ce891888 | [
"MIT"
] | null | null | null | #pragma once
#include <fogl/shader.hpp>
#include <fogl/cref.hpp>
#include <fogl/obj.hpp>
#include <fogl/flags.hpp>
#include <fogl/check.hpp>
#include <fogl/error.hpp>
#include <fogl/exception.hpp>
#include <fogl/gl.hpp>
#include <cassert>
namespace fogl {
/// C++ wrapper of a reference to a constant opengl program.
struct program_cref : cref {
/// Status of the program.
bool status() const {
this->auto_check_not_null();
GLint res = 0;
glGetProgramiv(id(), GL_LINK_STATUS, &res);
return res != 0;
}
/// Log of the program.
std::string log() const {
this->auto_check_not_null();
int len;
glGetProgramiv(id(), GL_INFO_LOG_LENGTH, &len);
std::vector<char> buf(len + 1);
if (len > 0)
glGetProgramInfoLog(id(), len, nullptr, &buf[0]);
buf[len] = 0;
return std::string(&buf[0]);
}
/// Attribute location by name.
GLuint attribute_location(char const *name) const {
this->auto_check_not_null();
return glGetAttribLocation(id(), name);
}
/// Uniform location by name.
GLuint uniform_location(char const *name) const {
this->auto_check_not_null();
return glGetUniformLocation(id(), name);
}
/// Use the program.
void use() const {
glUseProgram(id());
}
/// Construct with null id.
program_cref() {
}
/// Construct from a given id.
program_cref(from_id, GLuint id) : cref(from_id(), id) {
}
/// Construct with undefined id.
program_cref(undefined) : cref(undefined()) {
}
};
/// C++ wrapper of a reference to a mutable opengl program.
struct program_ref : program_cref {
/// Attach a shader to the program.
template<GLenum type> void attach_shader(shader_ref<type> s) const {
this->auto_check_not_null();
glAttachShader(id(), s.id());
auto_check_error();
}
/// Detach a shader from the program.
template<GLenum type> void detach_shader(shader_ref<type> s) const {
this->auto_check_not_null();
glDetachShader(id(), s.id());
auto_check_error();
}
/// Link the attached shaders.
void link() const {
this->auto_check_not_null();
glLinkProgram(id());
auto_check_error();
}
/// Construct with null id.
program_ref() {
}
/// Construct from a given id.
program_ref(from_id, GLuint id) : program_cref(from_id(), id) {
}
/// Construct with undefined id.
program_ref(undefined) : program_cref(undefined()) {
}
};
/// C++ wrapper of an opengl program.
struct program : obj<program, program_ref, program_cref> {
/// Destroy the program.
void destroy() {
if (this->is_null())
return;
glDeleteProgram(id());
invalidate();
}
/// Create the program
void create() {
id(glCreateProgram());
}
/// Construct with null id.
program() {
}
/// Construct from a given id.
program(from_id, GLuint id) : obj<program, program_ref, program_cref>(from_id(), id) {
}
/// Construct with opengl buffer created
program(struct create) {
create();
}
/// Construct with opengl buffer created
program(vertex_shader_ref& vs, fragment_shader_ref fs) {
create();
(*this)->attach_shader(vs);
(*this)->attach_shader(fs);
(*this)->link();
(*this)->detach_shader(vs);
(*this)->detach_shader(fs);
}
};
}
| 27.141732 | 90 | 0.608645 | glasmachers |
0e25671c58a119dc8069868021fbb21b10ccb57d | 7,233 | hpp | C++ | common/unified/base/kernel_launch.hpp | gfcas/ginkgo | b4fc0c7d8c7e667ea93bae4e3a6791fcdad53485 | [
"BSD-3-Clause"
] | null | null | null | common/unified/base/kernel_launch.hpp | gfcas/ginkgo | b4fc0c7d8c7e667ea93bae4e3a6791fcdad53485 | [
"BSD-3-Clause"
] | 14 | 2020-11-20T09:32:28.000Z | 2021-11-28T09:36:34.000Z | common/unified/base/kernel_launch.hpp | gfcas/ginkgo | b4fc0c7d8c7e667ea93bae4e3a6791fcdad53485 | [
"BSD-3-Clause"
] | 2 | 2020-11-20T09:28:48.000Z | 2020-11-20T13:26:38.000Z | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
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 its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_COMMON_UNIFIED_BASE_KERNEL_LAUNCH_HPP_
#define GKO_COMMON_UNIFIED_BASE_KERNEL_LAUNCH_HPP_
#include <type_traits>
#include <ginkgo/core/base/array.hpp>
#include <ginkgo/core/base/executor.hpp>
#include <ginkgo/core/base/types.hpp>
#include <ginkgo/core/matrix/dense.hpp>
#if defined(GKO_COMPILING_CUDA)
#define GKO_DEVICE_NAMESPACE cuda
#define GKO_KERNEL __device__
#include "cuda/base/types.hpp"
namespace gko {
namespace kernels {
namespace cuda {
template <typename T>
using device_type = typename detail::cuda_type_impl<T>::type;
template <typename T>
device_type<T> as_device_type(T value)
{
return as_cuda_type(value);
}
} // namespace cuda
} // namespace kernels
} // namespace gko
#elif defined(GKO_COMPILING_HIP)
#define GKO_DEVICE_NAMESPACE hip
#define GKO_KERNEL __device__
#include "hip/base/types.hip.hpp"
namespace gko {
namespace kernels {
namespace hip {
template <typename T>
using device_type = typename detail::hip_type_impl<T>::type;
template <typename T>
device_type<T> as_device_type(T value)
{
return as_hip_type(value);
}
} // namespace hip
} // namespace kernels
} // namespace gko
#elif defined(GKO_COMPILING_DPCPP)
#define GKO_DEVICE_NAMESPACE dpcpp
#define GKO_KERNEL
namespace gko {
namespace kernels {
namespace dpcpp {
template <typename T>
using device_type = T;
template <typename T>
device_type<T> as_device_type(T value)
{
return value;
}
} // namespace dpcpp
} // namespace kernels
} // namespace gko
#elif defined(GKO_COMPILING_OMP)
#define GKO_DEVICE_NAMESPACE omp
#define GKO_KERNEL
namespace gko {
namespace kernels {
namespace omp {
template <typename T>
using device_type = T;
template <typename T>
device_type<T> as_device_type(T value)
{
return value;
}
} // namespace omp
} // namespace kernels
} // namespace gko
#else
#error "This file should only be used inside Ginkgo device compilation"
#endif
namespace gko {
namespace kernels {
namespace GKO_DEVICE_NAMESPACE {
/**
* @internal
* A simple row-major accessor as a device representation of gko::matrix::Dense
* objects.
*
* @tparam ValueType the value type of the underlying matrix.
*/
template <typename ValueType>
struct matrix_accessor {
ValueType* data;
int64 stride;
/**
* @internal
* Returns a reference to the element at position (row, col).
*/
GKO_INLINE GKO_ATTRIBUTES ValueType& operator()(int64 row, int64 col)
{
return data[row * stride + col];
}
/**
* @internal
* Returns a reference to the element at position idx in the underlying
* storage.
*/
GKO_INLINE GKO_ATTRIBUTES ValueType& operator[](int64 idx)
{
return data[idx];
}
};
/**
* @internal
* This struct is used to provide mappings from host types like
* gko::matrix::Dense to device representations of the same data, like an
* accessor storing only data pointer and stride.
*
* By default, it only maps std::complex to the corresponding device
* representation of the complex type. There are specializations for dealing
* with gko::Array and gko::matrix::Dense (both const and mutable) that map them
* to plain pointers or matrix_accessor objects.
*
* @tparam T the type being mapped. It will be used based on a
* forwarding-reference, i.e. preserve references in the input
* parameter, so special care must be taken to only return types that
* can be passed to the device, i.e. (structs containing) device
* pointers or values. This means that T will be either a r-value or
* l-value reference.
*/
template <typename T>
struct to_device_type_impl {
using type = std::decay_t<device_type<T>>;
static type map_to_device(T in) { return as_device_type(in); }
};
template <typename ValueType>
struct to_device_type_impl<matrix::Dense<ValueType>*&> {
using type = matrix_accessor<device_type<ValueType>>;
static type map_to_device(matrix::Dense<ValueType>* mtx)
{
return {as_device_type(mtx->get_values()),
static_cast<int64>(mtx->get_stride())};
}
};
template <typename ValueType>
struct to_device_type_impl<const matrix::Dense<ValueType>*&> {
using type = matrix_accessor<const device_type<ValueType>>;
static type map_to_device(const matrix::Dense<ValueType>* mtx)
{
return {as_device_type(mtx->get_const_values()),
static_cast<int64>(mtx->get_stride())};
}
};
template <typename ValueType>
struct to_device_type_impl<Array<ValueType>&> {
using type = device_type<ValueType>*;
static type map_to_device(Array<ValueType>& array)
{
return as_device_type(array.get_data());
}
};
template <typename ValueType>
struct to_device_type_impl<const Array<ValueType>&> {
using type = const device_type<ValueType>*;
static type map_to_device(const Array<ValueType>& array)
{
return as_device_type(array.get_const_data());
}
};
template <typename T>
typename to_device_type_impl<T>::type map_to_device(T&& param)
{
return to_device_type_impl<T>::map_to_device(param);
}
} // namespace GKO_DEVICE_NAMESPACE
} // namespace kernels
} // namespace gko
#if defined(GKO_COMPILING_CUDA)
#include "cuda/base/kernel_launch.cuh"
#elif defined(GKO_COMPILING_HIP)
#include "hip/base/kernel_launch.hip.hpp"
#elif defined(GKO_COMPILING_DPCPP)
#include "dpcpp/base/kernel_launch.dp.hpp"
#elif defined(GKO_COMPILING_OMP)
#include "omp/base/kernel_launch.hpp"
#endif
#endif // GKO_COMMON_UNIFIED_BASE_KERNEL_LAUNCH_HPP_
| 25.558304 | 80 | 0.726116 | gfcas |
0e2573f50c66d02838b4ac091bc6334db7904115 | 19,636 | cpp | C++ | AQI_Detector/AQI_display.cpp | blinker-iot/Blinker_PRO_AQI_Detector | a5bf358de2be6c6efbe8d6d1e2ce354a7fab38fa | [
"MIT"
] | 9 | 2018-07-15T10:00:09.000Z | 2021-02-27T09:45:22.000Z | AQI_Detector/AQI_display.cpp | blinker-iot/Blinker_PRO_AQI_Detector | a5bf358de2be6c6efbe8d6d1e2ce354a7fab38fa | [
"MIT"
] | null | null | null | AQI_Detector/AQI_display.cpp | blinker-iot/Blinker_PRO_AQI_Detector | a5bf358de2be6c6efbe8d6d1e2ce354a7fab38fa | [
"MIT"
] | null | null | null | #include "AQI_display.h"
#include "AQI_font.h"
// #include <ESP8266WiFi.h>
#include <Ticker.h>
// U8g2lib, https://github.com/olikraus/U8g2_Arduino
// Release version 2.24.3
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
// U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /*reset Pin*/ D0);
// U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /*reset Pin*/ BLINKER_OLED_RESET_PIN);
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0,/* reset=*/ BLINKER_OLED_RESET_PIN, BLINKER_IIC_SCK_PIN, BLINKER_IIC_SDA_PIN);
#include <Adafruit_NeoPixel.h>
#define NUMPIXELS 1
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, BLINKER_WS2812_PIN, NEO_GRB + NEO_KHZ800);
static bool isDisplayDetail = true;
static bool isNormalDisplay = true;
static double batGet;
static uint8_t displayLanguage = BLINKER_LANGUAGE_CN;
static uint8_t initProgressBar = 0;
static uint8_t targetContrast = 255;
static uint8_t AQI_BASE = BLINKER_AQI_BASE_CN;
static uint8_t wlanLevel = 0;
static callbackFunction _diplayFunc;
static callbackFunction_arg_u8 _colorFunc;
static uint32_t freshTime = 0;
Ticker ledTicker;
static bool isAuth = false;
static bool isBlink = false;
static bool isConnected = false;
void setContrast(uint8_t _contrast)
{
targetContrast = _contrast;
}
uint8_t getContrast()
{
return targetContrast;
}
void setAQIbase(uint8_t _base)
{
if (_base > BLINKER_AQI_BASE_CN) {
AQI_BASE = BLINKER_AQI_BASE_US;
}
else {
AQI_BASE = _base;
}
}
String getAQIbase()
{
switch(AQI_BASE) {
case BLINKER_AQI_BASE_US :
return "us";
case BLINKER_AQI_BASE_CN :
return "cn";
default :
return "us";
}
}
void setLanguage(uint8_t _lang)
{
if (_lang > BLINKER_LANGUAGE_EN) {
displayLanguage = BLINKER_LANGUAGE_CN;
}
else {
displayLanguage = _lang;
}
}
String getLanguage()
{
switch(displayLanguage) {
case BLINKER_LANGUAGE_CN :
return "cn";
case BLINKER_LANGUAGE_EN :
return "en";
default :
return "cn";
}
}
void attachDisplay(callbackFunction _func)
{
_diplayFunc = _func;
}
void attachColor(callbackFunction_arg_u8 _func)
{
_colorFunc = _func;
}
void freshDisplay()
{
if ((millis() - freshTime) >= 1000 || freshTime == 0) {
u8g2.setContrast(targetContrast);
u8g2.firstPage();
do {
if (_diplayFunc) {
_diplayFunc();
}
} while ( u8g2.nextPage() );
freshTime += 1000;
}
// colorDisplay();
}
void changeDetail()
{
isDisplayDetail = !isDisplayDetail;
}
String display_num_len_3(uint16_t num)
{
num = min(num, (uint16_t)999);
String reNum = "";
for(uint8_t t = 3; t > 0; t--) {
reNum += String((uint16_t)(num / pow(10, t-1)) % 10);
}
return reNum;
}
String display_num_len_2(uint8_t num)
{
String reNum = "";
for(uint8_t t = 2; t > 0; t--) {
reNum += String((uint8_t)(num / pow(10, t-1)) % 10);
}
return reNum;
}
void setSignals(uint8_t level)
{
wlanLevel = level;
}
// uint8_t getSignals()
// {
// if (WiFi.status() == WL_CONNECTED) {
// int32_t wRSSI = WiFi.RSSI();
// // IOT_DEBUG_PRINT2(F("getSignals: "), wRSSI);
// if (wRSSI < -90) {
// return 0;
// }
// else if (wRSSI >= -90 && wRSSI < -80) {
// return 1;
// }
// else if (wRSSI >= -80 && wRSSI < -70) {
// return 2;
// }
// else if (wRSSI >= -70) {
// return 3;
// }
// }
// else {
// return 0;
// }
// }
static String weekDays(uint8_t weekDay)
{
switch (weekDay) {
case 0: return displayLanguage ? F("Sun") : F("星期日");
case 1: return displayLanguage ? F("Mon") : F("星期一");
case 2: return displayLanguage ? F("Tues"): F("星期二");
case 3: return displayLanguage ? F("Wed") : F("星期三");
case 4: return displayLanguage ? F("Thur"): F("星期四");
case 5: return displayLanguage ? F("Fri") : F("星期五");
case 6: return displayLanguage ? F("Sat") : F("星期六");
}
}
static String months(uint8_t mons) {
switch (mons) {
case 0: return F("Jan");
case 1: return F("Feb");
case 2: return F("Mar");
case 3: return F("Apr");
case 4: return F("May");
case 5: return F("Jun");
case 6: return F("July");
case 7: return F("Aug");
case 8: return F("Sept");
case 9: return F("Oct");
case 10: return F("Nov");
case 11: return F("Dec");
}
}
void disconnectBlink()
{
if (isAuth) {
// digitalWrite(PLUGIN_GREEN_LED_PIN, !digitalRead(PLUGIN_GREEN_LED_PIN));
// digitalWrite(PLUGIN_RED_LED_PIN, HIGH);
// uint8_t R = 0, G = 0, B = 0;
uint32_t color = pixels.getPixelColor(0);
if (color >> 8 & 0xFF) {
pixels.setPixelColor(0, pixels.Color(0, 0, 0));
pixels.show();
}
else {
// R = color >> 16 & 0xFF;
// G = color >> 8 & 0xFF;
// B = color & 0xFF;
pixels.setPixelColor(0, pixels.Color(0, 255, 0));
pixels.show();
}
}
else {
if (isConnected) {
uint32_t color = pixels.getPixelColor(0);
if (color >> 16 & 0xFF) {
pixels.setPixelColor(0, pixels.Color(0, 0, 0));
pixels.show();
}
else {
pixels.setPixelColor(0, pixels.Color(255, 255, 0));
pixels.show();
}
}
else {
uint32_t color = pixels.getPixelColor(0);
if (color >> 16 & 0xFF) {
pixels.setPixelColor(0, pixels.Color(0, 0, 0));
pixels.show();
}
else {
pixels.setPixelColor(0, pixels.Color(255, 0, 0));
pixels.show();
}
}
}
ledTicker.once(0.5, disconnectBlink);
}
// void connectBright(bool state)
// {
// detachBlink();
// // if (state && digitalRead(PLUGIN_GREEN_LED_PIN)) {
// if (state) {
// // digitalWrite(PLUGIN_GREEN_LED_PIN, LOW);
// // digitalWrite(PLUGIN_RED_LED_PIN, HIGH);
// pixels.setPixelColor(0, pixels.Color(0, 255, 0));
// pixels.show();
// }
// else if (!state && digitalRead(PLUGIN_RED_LED_PIN)) {
// // digitalWrite(PLUGIN_GREEN_LED_PIN, HIGH);
// // digitalWrite(PLUGIN_RED_LED_PIN, LOW);
// pixels.setPixelColor(0, pixels.Color(255, 0, 0));
// pixels.show();
// }
// }
void attachBlink()
{
if (!isBlink) {
ledTicker.once(0.5, disconnectBlink);
isBlink = true;
}
}
void detachBlink()
{
if (isBlink) {
ledTicker.detach();
isBlink = false;
}
}
void setColorType(uint8_t type)
{
switch (type) {
case NORMAL :
isNormalDisplay = true;
detachBlink();
break;
case WLAN_CONNECTING :
isNormalDisplay = false;
// detachBlink();
isAuth = false;
isConnected = false;
attachBlink();
break;
case WLAN_CONNECTED :
isNormalDisplay = false;
// detachBlink();
isAuth = false;
isConnected = true;
attachBlink();
break;
case DEVICE_CONNECTING :
isNormalDisplay = false;
// detachBlink();
isAuth = true;
isConnected = false;
attachBlink();
break;
case DEVICE_CONNECTED :
isNormalDisplay = true;
detachBlink();
break;
default :
isNormalDisplay = true;
detachBlink();
break;
}
}
void colorDisplay()
{
uint8_t R = 0, G = 0, B = 0;
// switch (AQIBUFFER[AQI_BASE][1]) {
if (isNormalDisplay) {
if (!_colorFunc) {
return;
}
switch(_colorFunc(AQI_BASE)) {
case 0: /*IOT_DEBUG_PRINT1("color Green");*/
R = 0;
G = map(targetContrast, 0, 255, 0, 64);
B = 0;
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
case 1: /*IOT_DEBUG_PRINT1("color Yellow");*/
R = map(targetContrast, 0, 255, 0, 64);
G = map(targetContrast, 0, 255, 0, 64);
B = 0;
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
case 2: /*IOT_DEBUG_PRINT1("color Orange");*/
R = map(targetContrast, 0, 255, 0, 64);
G = map(targetContrast, 0, 255, 0, 32);
B = 0;
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
case 3: /*IOT_DEBUG_PRINT1("color Red");*/
R = map(targetContrast, 0, 255, 0, 64);
G = 0;
B = 0;
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
case 4: /*IOT_DEBUG_PRINT1("color Purple");*/
R = map(targetContrast, 0, 255, 0, 32);
G = 0;
B = map(targetContrast, 0, 255, 0, 32);
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
case 5: /*IOT_DEBUG_PRINT1("color Maroon");*/
R = map(targetContrast, 0, 255, 0, 32);
G = map(targetContrast, 0, 255, 0, 4);
B = map(targetContrast, 0, 255, 0, 6);
pixels.setPixelColor(0, pixels.Color(R, G, B));
pixels.show();
break;
}
}
}
void batDisplay(double _bat)
{
if (_bat > BLINKER_BAT_POWER_HIGH) {
_bat = BLINKER_BAT_POWER_HIGH;
}
batGet = _bat;
uint8_t drawBat = (_bat - BLINKER_BAT_POWER_LOW) / (BLINKER_BAT_POWER_HIGH - BLINKER_BAT_POWER_LOW) * 14;
if (drawBat > 14) drawBat = 14;
u8g2.drawRFrame(108, 52, 18, 10, 2);
u8g2.drawBox(110, 54, drawBat, 6);
u8g2.drawLine(127, 55, 127, 58);
}
void aqiDisplay(uint16_t _pm1_0, uint16_t _pm2_5, uint16_t _pm10_0, double _humi,
double _hcho, double _temp, int8_t _hour, int8_t _min)
{
String pm10data = display_num_len_3(_pm1_0);
String pm25data = display_num_len_3(_pm2_5);
String pm100data = display_num_len_3(_pm10_0);
String tempdata = String((int8_t)_temp);
String humidata = String((int16_t)_humi);
// String fadata = display_num_len_3(random(0,120));
String hour = display_num_len_2(abs(_hour));
String mins = display_num_len_2(abs(_min));
if (isDisplayDetail) {
if (displayLanguage) {
u8g2.setFont(u8g2_font_helvR10_tf);
u8g2.setCursor(0, 13);
u8g2.print("PM1.0:" + pm10data);
u8g2.setCursor(0, 27);
u8g2.print("PM2.5:" + pm25data);
u8g2.setCursor(0, 41);
u8g2.print("PM10:" + pm100data);
u8g2.setCursor(78, 13);
u8g2.print("FA:" + String(_hcho));
u8g2.setCursor(78, 27);
u8g2.print("RH:" + humidata + "%");
u8g2.setCursor(78, 41);
u8g2.print("TP:" + tempdata + "°");//°C
}
else {
u8g2.setFont(u8g2_font_helvR10_tf);
u8g2.setCursor(0, 13);
u8g2.print("PM1.0:" + pm10data);
u8g2.setCursor(0, 27);
u8g2.print("PM2.5:" + pm25data);
u8g2.setCursor(0, 41);
u8g2.print("PM10:" + pm100data);
u8g2.setCursor(98, 13);
u8g2.print(":" + String(_hcho));
u8g2.setCursor(98, 27);
u8g2.print(":" + humidata + "%");
u8g2.setCursor(98, 41);
u8g2.print(":" + tempdata + "°");//°C
u8g2.setFont(u8g2_font_wqy14_cn);//31x34
u8g2.setCursor(72, 12);
u8g2.print("甲醛");
u8g2.setCursor(72, 26);
u8g2.print("湿度");
u8g2.setCursor(72, 40);
u8g2.print("温度");
}
}
else {
u8g2.setFont(u8g2_font_fzht48_tf);//31x34
u8g2.setCursor((128 - 3*fzht48_w)/2, 41);
u8g2.print(pm25data);
}
u8g2.drawLine(0, 46, 128, 46);
u8g2.setFont(u8g2_font_helvR10_tf);//14x15 u8g2_font_helvR10_tf
u8g2.setCursor(0, 63);
u8g2.print(hour + ":" + mins + " " + millis()/1000/60 + ":" + millis()/1000%60);
// u8g2.print(hour + ":" + mins);
// if (getTimerTimingState() == "true")
// u8g2.drawXBMP(95, 51, 11, 12, alarmClock);
// u8g2.drawXBMP(110, 51, 17, 12, signalSymbols[getSignals()]);//signalSymbols[(uint8_t)random(0,4)]
u8g2.drawXBMP(88, 51, 17, 12, signalSymbols[wlanLevel]);//signalSymbols[(uint8_t)random(0,4)]
// batDisplay();
u8g2.sendBuffer();
}
void timeDisplay(uint16_t _pm2_5, int8_t _mon, int8_t _mday,
int8_t _wday, int8_t _hour, int8_t _min)
{
String pm25data = display_num_len_3(_pm2_5);
String weekDay = weekDays(abs(_wday));
String hour = display_num_len_2(abs(_hour));
String mins = display_num_len_2(abs(_min));
String mon;
String day;
if (isDisplayDetail) {
u8g2.setFont(u8g2_font_helvR10_tf);
u8g2.setCursor((128 - ((hour.length() + mins.length())*helvR10_w + 4))/2, 16);
u8g2.print(hour + ":" + mins);
// u8g2.setCursor((128 - (4*helvR10_w))/2, 41);
// u8g2.print(timeDisplay.tm_year + 1900);
uint8_t start_w;
if (displayLanguage) {
mon = months(abs(_mon));
day = String(abs(_mday));
start_w = (128 - ((weekDay.length() + mon.length() + day.length())*helvR10_w + 12))/2;
// String weekDay = weekDaysEN[(uint8_t)random(0,7)];
u8g2.setFont(u8g2_font_helvR10_tf);//14x15 u8g2_font_helvR10_tf
u8g2.setCursor(start_w, 38);
u8g2.print(weekDay+ ", " + mon + " "+ day);
}
else {
mon = String(abs(_mon) + 1);
day = String(abs(_mday));
start_w = (128 - ((mon.length() + day.length())*helvR10_w + 5*wqy14_w + 4))/2;
u8g2.setFont(u8g2_font_helvR10_tf);//14x15 u8g2_font_helvR10_tf
u8g2.setCursor(start_w, 38);
u8g2.print(mon);
u8g2.setCursor(start_w + mon.length()*helvR10_w + wqy14_w, 38);
u8g2.print(day);
u8g2.setFont(u8g2_font_wqy14_cn);//6x13 u8g2_font_helvR10_tf//u8g2_font_wqy14_t_chinese3
u8g2.setCursor(start_w + mon.length()*helvR10_w, 38-1);
u8g2.print(F("月"));
u8g2.setCursor(start_w + (mon.length() + day.length())*helvR10_w + wqy14_w, 38-1);
u8g2.print(F("日"));
u8g2.setCursor(start_w + (mon.length() + day.length())*helvR10_w + wqy14_w*2 + 4, 38-1);
u8g2.print(weekDays(abs(_wday)));//weekDaysCN[(uint8_t)random(0,7)]
}
// displayLanguage = !displayLanguage;
}
else {
u8g2.setFont(u8g2_font_fzht48_tf);//31x34
u8g2.setCursor(63 - 6 - 2*fzht48_w, 38);
u8g2.print(hour);
u8g2.drawXBMP(64 - 3, 12, 6, 24, signal_risk);
u8g2.setCursor(64 + 6, 38);
u8g2.print(mins);
}
u8g2.drawLine(0, 46, 128, 46);
u8g2.setFont(u8g2_font_helvR10_tf);//14x15 u8g2_font_helvR10_tf
u8g2.setCursor(0, 63);
u8g2.print("PM2.5 " + pm25data + " " + millis()/1000/60 + ":" + millis()/1000%60);
// u8g2.print("PM2.5 " + pm25data);
// if (getTimerTimingState() == "true")
// u8g2.drawXBMP(95, 51, 11, 12, alarmClock);
// u8g2.drawXBMP(110, 51, 17, 12, signalSymbols[getSignals()]);
u8g2.drawXBMP(88, 51, 17, 12, signalSymbols[wlanLevel]);
// batDisplay();
u8g2.sendBuffer();
}
void initPage()
{
u8g2.clearBuffer();
u8g2.setFont(u8g2_font_helvR24_tr);
u8g2.setCursor(18, 34);
u8g2.print("blinker");
// u8g2.drawLine(0, 46, 128, 46);
u8g2.setFont(u8g2_font_helvR10_te);
u8g2.setCursor(1, 63);
u8g2.print("blinker AQI detector");
u8g2.sendBuffer();
}
void clearPage()
{
u8g2.clearBuffer();
u8g2.sendBuffer();
}
void resetDisplay(uint16_t _time)
{
detachBlink();
if (displayLanguage) {
pixels.setPixelColor(0, pixels.Color(0, 64, 0));
pixels.show();
u8g2.setFont(u8g2_font_helvR10_te);
u8g2.setCursor(64 - helvR10_w * 5, 20);
u8g2.print("Power down");
u8g2.setCursor(26, 45);
u8g2.print("Realse to reset");
u8g2.setCursor(4, 45);
u8g2.print(String(10 - _time / 1000)+"s");
u8g2.drawLine(0, 54, 128 * _time / 10000, 54);
// u8g2.clearBuffer();
// u8g2.setFont(u8g2_font_helvR24_tr);
// u8g2.setCursor(18, 34);
// u8g2.print("blinker");
// u8g2.drawLine(0, 46, 128, 46);
// u8g2.setFont(u8g2_font_helvR10_te);
// // u8g2.setCursor(40, 63);
// u8g2.setCursor(0, 63);
// u8g2.print("PowerDown / Reset!");
// u8g2.sendBuffer();
}
else {
pixels.setPixelColor(0, pixels.Color(0, 64, 0));
pixels.show();
u8g2.setFont(u8g2_font_wqy14_cn);
u8g2.setCursor(64 - wqy14_w * 3, 20);
u8g2.print("释放即可关机");
u8g2.setCursor(64 - wqy14_w * 2, 45);
u8g2.print("后释放将重置");
u8g2.setFont(u8g2_font_helvR10_tf);//14x15 u8g2_font_helvR10_tf
u8g2.setCursor(64 - wqy14_w * 2 - helvR10_w * 3, 45);
u8g2.print(String(10 - _time / 1000)+"s");
u8g2.drawLine(0, 54, 128 * _time / 10000, 54);
// // u8g2.clearBuffer();
// u8g2.setFont(u8g2_font_helvR24_tr);
// u8g2.setCursor(18, 34);
// u8g2.print("blinker");
// u8g2.drawLine(0, 46, 128, 46);
// u8g2.setFont(u8g2_font_helvR10_te);
// // u8g2.setCursor(40, 63);
// u8g2.setCursor(0, 63);
// u8g2.print("PowerDown / Reset!");
// // u8g2.sendBuffer();
}
}
bool initDisplay()
{
if (initProgressBar > 128) {
return false;
}
u8g2.drawLine(0, 46, initProgressBar, 46);
u8g2.sendBuffer();
initProgressBar += 4;
return true;
}
void u8g2Init()
{
pixels.begin();
u8g2.begin();
u8g2.setFlipMode(0);
u8g2.enableUTF8Print();
pixels.setPixelColor(0, pixels.Color(0, 64, 0));
pixels.show();
initPage();
} | 29.751515 | 127 | 0.517824 | blinker-iot |
0e3297db0d0c889e85707edfce20f49497c323fa | 2,587 | hpp | C++ | Siv3D/src/Siv3D/Texture/GL/CTexture_GL.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | null | null | null | Siv3D/src/Siv3D/Texture/GL/CTexture_GL.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | null | null | null | Siv3D/src/Siv3D/Texture/GL/CTexture_GL.hpp | Fuyutsubaki/OpenSiv3D | 4370f6ebe28addd39bfdd75915c5a18e3e5e9273 | [
"MIT"
] | 1 | 2019-10-06T17:09:26.000Z | 2019-10-06T17:09:26.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2018 Ryo Suzuki
// Copyright (c) 2016-2018 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Platform.hpp>
# if defined(SIV3D_TARGET_MACOS) || defined(SIV3D_TARGET_LINUX)
# include <thread>
# include <atomic>
# include <mutex>
# include "../ITexture.hpp"
# include "Texture_GL.hpp"
# include "../../AssetHandleManager/AssetHandleManager.hpp"
# include <Siv3D/System.hpp>
namespace s3d
{
class CTexture_GL : public ISiv3DTexture
{
private:
AssetHandleManager<TextureID, Texture_GL> m_textures{ U"Texture" };
const std::thread::id m_id = std::this_thread::get_id();
struct Request
{
const Image *pImage = nullptr;
const Array<Image> *pMipmaps = nullptr;
const TextureDesc* pDesc = nullptr;
std::reference_wrapper<TextureID> idResult;
std::reference_wrapper<std::atomic<bool>> waiting;
};
Array<Request> m_requests;
std::mutex m_requestsMutex;
bool isMainThread() const;
TextureID pushRequest(const Image& image, const Array<Image>& mipmaps, const TextureDesc desc);
public:
~CTexture_GL();
bool init();
void update(size_t maxUpdate) override;
TextureID createFromBackBuffer() override;
TextureID create(const Image&, TextureDesc) override;
TextureID create(const Image& image, const Array<Image>& mipmaps, TextureDesc desc) override;
TextureID createDynamic(const Size& size, const void* pData, uint32 stride, TextureFormat format, TextureDesc desc) override;
TextureID createDynamic(const Size& size, const ColorF& color, TextureFormat format, TextureDesc desc) override;
TextureID createRT(const Size& size, uint32 multisampleCount) override;
void release(TextureID handleID) override;
Size getSize(TextureID handleID) override;
TextureDesc getDesc(TextureID handleID) override;
void clearRT(TextureID, const ColorF&) override
{
// [Siv3D ToDo]
}
void beginResize(TextureID) override
{
// [Siv3D ToDo]
}
bool endResizeRT(TextureID, const Size&, const uint32) override
{
// [Siv3D ToDo]
return false;
}
bool endResizeBackBuffer(TextureID) override
{
// [Siv3D ToDo]
return false;
}
void setPS(uint32 slot, TextureID handleID) override;
bool fill(TextureID handleID, const ColorF& color, bool wait) override;
bool fill(TextureID handleID, const void* src, uint32 stride, bool wait) override;
};
}
# endif
| 22.692982 | 127 | 0.689988 | Fuyutsubaki |
0e365245a32f2614518c3ad19d2db8ced87bc859 | 2,597 | hpp | C++ | ChaosGL/tbasis3.hpp | chaosarts/ChaosGL.cpp | 7d851a404824609547fb9261790b87cee7699d5c | [
"Apache-2.0"
] | null | null | null | ChaosGL/tbasis3.hpp | chaosarts/ChaosGL.cpp | 7d851a404824609547fb9261790b87cee7699d5c | [
"Apache-2.0"
] | null | null | null | ChaosGL/tbasis3.hpp | chaosarts/ChaosGL.cpp | 7d851a404824609547fb9261790b87cee7699d5c | [
"Apache-2.0"
] | null | null | null | //
// tbn.hpp
// ChaosGL
//
// Created by Fu Lam Diep on 14.04.16.
// Copyright © 2016 Fu Lam Diep. All rights reserved.
//
#ifndef ChaosGL_tbasis3_hpp
#define ChaosGL_tbasis3_hpp
#include "triangle.hpp"
#include <glm/glm.hpp>
namespace chaosgl
{
template<typename T, glm::precision P = glm::defaultp>
struct tbasis3
{
public:
/** Describes its own type */
typedef tbasis3<T, P> Type;
/** Describes the vector type it holds */
typedef glm::tvec3<T, P> VectorType;
/** Describes the value type of the vector */
typedef T ValueType;
typedef glm::tvec3<T, P> vec3;
typedef glm::tvec2<T, P> vec2;
/** Provides the componentns of the tangent space */
const union {
struct {
/** Provides the x axis of the basis */
VectorType x;
/** Provides the y axis of the basis */
VectorType y;
/** Provides the z axis of the basis */
VectorType z;
};
struct {
/** Provides the tangent of the tangent space. Same as x */
VectorType tangent;
/** Provides the bitangent of the tangent space. Same as y */
VectorType bitangent;
/** Provides the normal of the tangent space. Same as z */
VectorType normal;
};
struct {
/** Provides the tangent of the tangent space */
VectorType t;
/** Provides the bitangent of the tangent space */
VectorType b;
/** Provides the normal of the tangent space */
VectorType n;
};
};
/**
* Creates the standard basis
*/
tbasis3 () : x(VectorType(1, 0, 0)), y(VectorType(0, 1, 0)), z(VectorType(0, 0, 1)) {}
/**
* Creates a new vec3 basis
* @param x: The x asix of the basis
* @param y: The y asix of the basis
* @param z: The z asix of the basis
*/
tbasis3 (VectorType x, VectorType y, VectorType z) : x(x), y(y), z(z) {}
/**
* Creates new tvec3 basis by coping from another
* @param basis: The basis to copy from
*/
tbasis3 (const Type &basis) : x(basis.x), y(basis.y), z(basis.z) {}
/**
* Destroys the basis
*/
virtual ~tbasis3 () {};
private:
static glm::tmat3x2<T, P> _resolve (triangle3 positions, triangle2 texcoords)
{
const vec3 q1 = positions.u();
const vec3 q2 = positions.v();
const vec2 d1 = texcoords.u();
const vec2 d2 = texcoords.v();
const T mul = 1 / (d1.s * d2.t - d1.t * d2.s);
const glm::tmat2x2<T, P> I(mul * d2.t, -(mul * d2.s), -(mul * d1.t), mul * d1.s);
const glm::tmat3x2<T, P> Q(q1.x, q2.x, q1.y, q2.y, q1.z, q2.z);
return I * Q;
}
};
}
#endif /* tbasis3 */
| 22.008475 | 88 | 0.593762 | chaosarts |
0e36765e9a2973bb629ab7fd43ea855f23baa8ed | 1,037 | cpp | C++ | LeetCode/ThousandOne/0820-short_encoding_of_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0820-short_encoding_of_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0820-short_encoding_of_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 820. 单词的压缩编码
给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。
那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
示例:
输入: words = ["time", "me", "bell"]
输出: 10
说明: S = "time#bell#" , indexes = [0, 2, 5] 。
提示:
1 <= words.length <= 2000
1 <= words[i].length <= 7
每个单词都是小写字母 。
*/
int minimumLengthEncoding(vector<string>& words)
{
int len = static_cast<int>(words.size());
int ans = 0;
for (int i = 0; i < len; ++i)
reverse(words[i].begin(), words[i].end());
sort(words.begin(), words.end());
for (int i = 1; i < len; ++i)
{
size_t s0 = words[i - 1].size();
size_t s1 = words[i].size();
if ((s0 > s1)
|| strncmp(words[i - 1].data(), words[i].data(), s0))
ans += static_cast<int>(s0) + 1;
}
ans += static_cast<int>(words[len - 1].size()) + 1;
return ans;
}
int main()
{
vector<string> w = { "time", "me", "bell" };
OutExpr(minimumLengthEncoding(w), "%d");
}
| 19.203704 | 84 | 0.594021 | Ginkgo-Biloba |
0e38459aee89332e39684bf317e40b2989f11c83 | 610 | hxx | C++ | include/nifty/python/graph/undirected_list_graph.hxx | konopczynski/nifty | dc02ac60febaabfaf9b2ee5a854bb61436ebdc97 | [
"MIT"
] | 38 | 2016-06-29T07:42:50.000Z | 2021-12-09T09:25:25.000Z | include/nifty/python/graph/undirected_list_graph.hxx | tbullmann/nifty | 00119fd4753817b931272d6d3120b6ebd334882a | [
"MIT"
] | 62 | 2016-07-27T16:07:53.000Z | 2022-03-30T17:24:36.000Z | include/nifty/python/graph/undirected_list_graph.hxx | tbullmann/nifty | 00119fd4753817b931272d6d3120b6ebd334882a | [
"MIT"
] | 20 | 2016-01-25T21:21:52.000Z | 2021-12-09T09:25:16.000Z | #pragma once
#include <string>
#include "nifty/python/graph/graph_name.hxx"
#include "nifty/graph/undirected_list_graph.hxx"
namespace nifty{
namespace graph{
typedef UndirectedGraph<> PyUndirectedGraph;
template<>
struct GraphName<PyUndirectedGraph>{
static std::string name(){
return std::string("UndirectedGraph");
}
static std::string moduleName(){
return std::string("nifty.graph");
}
static std::string usageExample(){
return std::string(
"import nifty\n"
);
}
};
}
}
| 19.0625 | 50 | 0.590164 | konopczynski |
0e47f8ab2845a1978a682527041ca874f0c4bfc7 | 3,707 | cpp | C++ | DriverLoader/ProppageNT.cpp | JokerRound/DriverLoader | df5371ecbada19fa7beef1a0baf86e756af6da07 | [
"MIT"
] | 1 | 2020-01-31T00:34:16.000Z | 2020-01-31T00:34:16.000Z | DriverLoader/ProppageNT.cpp | c3358/DriverLoader | df5371ecbada19fa7beef1a0baf86e756af6da07 | [
"MIT"
] | null | null | null | DriverLoader/ProppageNT.cpp | c3358/DriverLoader | df5371ecbada19fa7beef1a0baf86e756af6da07 | [
"MIT"
] | 3 | 2019-02-18T01:55:44.000Z | 2022-02-08T09:08:07.000Z | //******************************************************************************
// License: MIT
// Author: Hoffman
// GitHub: https://github.com/JokerRound
// Create Time: 2019-01-24
// Description:
// The achieve file of class CProppageNT.
//
// Modify Log:
// 2019-01-26 Hoffman
// Info: a. Add below member methods.
// a.1. OnBnClickedBtnSearchfile();
// a.1. OnInitDialog();
//******************************************************************************
#include "stdafx.h"
#include "DriverLoader.h"
#include "ProppageNT.h"
#include "afxdialogex.h"
#include "ShareMacro.h"
// CProppageNT 对话框
IMPLEMENT_DYNAMIC(CProppageNT, CDialogEx)
CProppageNT::CProppageNT(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_PROPPAGE_NTDRIVER, pParent)
{
}
CProppageNT::~CProppageNT()
{
}
void CProppageNT::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_DRIVERFILEPATH, m_editFilePath);
DDX_Control(pDX, IDC_EDIT_SERVICE_NAME, m_editServiceName);
DDX_Control(pDX, IDC_EDIT_DISPLAYNAME, m_editDisplayName);
DDX_Control(pDX, IDC_COMBO_SERVICETYPE, m_cmbServiceType);
DDX_Control(pDX, IDC_COMBO_STARTMODE, m_cmbStartType);
DDX_Control(pDX, IDC_COMBO_ERRORCONTROL, m_cmbErrorControl);
}
BEGIN_MESSAGE_MAP(CProppageNT, CDialogEx)
ON_BN_CLICKED(IDC_BTN_SEARCHFILE, &CProppageNT::OnBnClickedBtnSearchfile)
END_MESSAGE_MAP()
//******************************************************************************
// Author: Hoffman
// Create Time: 2019-01-26
// Last Time: 2019-01-26
// Logical Descrition:
// Popup a search file dialog.
//******************************************************************************
void CProppageNT::OnBnClickedBtnSearchfile()
{
CFileDialog dlgSearchFile(TRUE);
CString csFilePath;
// Set buffer.
const int kcntBuffSize = (FILE_NUMBERS_MAX * (MAX_PATH + 1)) + 1;
dlgSearchFile.GetOFN().lpstrFile =
csFilePath.GetBufferSetLength(kcntBuffSize);
dlgSearchFile.GetOFN().nMaxFile = FILE_NUMBERS_MAX;
// Popup the page.
INT_PTR iptrRet = dlgSearchFile.DoModal();
csFilePath.ReleaseBuffer();
if (iptrRet == IDOK)
{
m_editFilePath.SetWindowText(csFilePath);
CPath pathFileName = csFilePath;
pathFileName.StripPath();
pathFileName.RemoveExtension();
m_editServiceName.SetWindowText(pathFileName.m_strPath);
m_editDisplayName.SetWindowText(pathFileName.m_strPath);
m_cmbErrorControl.SetCurSel(ECI_NORMAL);
m_cmbServiceType.SetCurSel(SERVTI_KERNEL);
m_cmbStartType.SetCurSel(STARTCI_DEMAND);
}
} //! OnBnClickedBtnSearchfile() END
//******************************************************************************
// Author: Hoffman
// Create Time: 2019-01-26
// Last Time: 2019-01-26
// Logical Descrition:
// Add initialize for combo box control.
//******************************************************************************
BOOL CProppageNT::OnInitDialog()
{
CDialogEx::OnInitDialog();
for (size_t cntI = 0; cntI < TOTAL_ECI_NUMBER; cntI++)
{
m_cmbErrorControl.AddString(m_acsErrorControl[cntI]);
}
for (size_t cntI = 0; cntI < TOTAL_SERVTI_NUMBER; cntI++)
{
m_cmbServiceType.AddString(m_acsServiceType[cntI]);
}
for (size_t cntI = 0; cntI < TOTAL_STARTCI_NUMBER; cntI++)
{
m_cmbStartType.AddString(m_acsStartType[cntI]);
}
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
} //! m_acsServiceType() END
| 30.138211 | 81 | 0.590504 | JokerRound |
0e482650abd34567cc23ab4b8f3368365920a209 | 7,841 | cpp | C++ | src/cmn/typeVisitor.cpp | cwood77/shtanky | 6e3b7ad5bdc21be8d82b3fcddd882aebbf479fd8 | [
"MIT"
] | null | null | null | src/cmn/typeVisitor.cpp | cwood77/shtanky | 6e3b7ad5bdc21be8d82b3fcddd882aebbf479fd8 | [
"MIT"
] | null | null | null | src/cmn/typeVisitor.cpp | cwood77/shtanky | 6e3b7ad5bdc21be8d82b3fcddd882aebbf479fd8 | [
"MIT"
] | null | null | null | #include "type.hpp"
#include "typeVisitor.hpp"
namespace cmn {
// here, you are guaranteed to get a stub (userTypeVisitor hasn't run yet)
// that allows transforms later to demand a type
void builtInTypeVisitor::visit(classNode& n)
{
m_pBuilder.reset(
type::typeBuilder::open(
type::gTable->fetch(
fullyQualifiedName::build(n))));
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
hNodeVisitor::visit(n);
}
void builtInTypeVisitor::visit(strTypeNode& n)
{
m_pBuilder.reset(type::typeBuilder::createString());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(boolTypeNode& n)
{
m_pBuilder.reset(type::typeBuilder::createBool());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(intTypeNode& n)
{
m_pBuilder.reset(type::typeBuilder::createInt());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(arrayTypeNode& n)
{
m_pBuilder->wrapArray();
hNodeVisitor::visit(n);
}
void builtInTypeVisitor::visit(voidTypeNode& n)
{
m_pBuilder.reset(type::typeBuilder::createVoid());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
// here, you are guaranteed to get a stub (userTypeVisitor hasn't run yet)
// that allows transforms later to demand a type
void builtInTypeVisitor::visit(userTypeNode& n)
{
m_pBuilder.reset(
type::typeBuilder::open(
type::gTable->fetch(
fullyQualifiedName::build(*n.pDef.getRefee()))));
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(ptrTypeNode& n)
{
m_pBuilder.reset(type::typeBuilder::createPtr());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(stringLiteralNode& n)
{
m_pBuilder.reset(type::typeBuilder::createString());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(boolLiteralNode& n)
{
m_pBuilder.reset(type::typeBuilder::createBool());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void builtInTypeVisitor::visit(intLiteralNode& n)
{
m_pBuilder.reset(type::typeBuilder::createInt());
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void userTypeVisitor::visit(classNode& n)
{
m_pBuilder.reset(type::typeBuilder::createClass(fullyQualifiedName::build(n)));
for(auto it=n.baseClasses.begin();it!=n.baseClasses.end();++it)
m_pBuilder->addBase(type::gNodeCache->demand(*it->getRefee()));
hNodeVisitor::visit(n);
m_pBuilder->finish();
// this type was published earlier in the gNodeCache (in builtInTypeVisitor)
m_pBuilder.reset();
}
void userTypeVisitor::visit(methodNode& n)
{
m_pBuilder->addMethod(n.name);
}
void userTypeVisitor::visit(fieldNode& n)
{
auto& fieldType = type::gNodeCache->demand(n.demandSoleChild<typeNode>());
m_pBuilder->addMember(n.name,fieldType);
}
void functionVisitor::visit(classNode& n)
{
m_pClass = &n;
hNodeVisitor::visit(n);
m_pClass = NULL;
}
void functionVisitor::visit(methodNode& n)
{
m_pBuilder.reset(type::typeBuilder::createFunction(fullyQualifiedName::build(n,n.name)));
m_pBuilder->setClassType(type::gNodeCache->demand(*m_pClass));
m_pBuilder->setStatic(n.flags & nodeFlags::kStatic);
m_pBuilder->setReturnType(type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void functionVisitor::visit(funcNode& n)
{
m_pBuilder.reset(type::typeBuilder::createFunction(fullyQualifiedName::build(n,n.name)));
m_pBuilder->setStatic(true);
m_pBuilder->setReturnType(type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,m_pBuilder->finish());
m_pBuilder.reset(NULL);
}
void functionVisitor::visit(argNode& n)
{
m_pBuilder->appendArgType(
n.name,
type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
}
void globalTypePropagator::visit(fieldNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
}
void globalTypePropagator::visit(constNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
}
void typePropagator::visit(argNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,type::gNodeCache->demand(*n.getChildren()[0]));
}
void typePropagator::visit(invokeNode& n)
{
// TODO need function types for this... do I need this? YES! at least, eventually
// defer this until method linking is done in the symbol table
hNodeVisitor::visit(n);
}
void typePropagator::visit(invokeFuncPtrNode& n)
{
hNodeVisitor::visit(n);
// TODO HACK unimplementable until the AST has a way to declare custom func ptr types
// i.e. stops using 'ptr'
if(0) {
auto& instType = type::gNodeCache->demand(*n.getChildren()[0]);
auto& rVal = instType.as<type::iFunctionType>().getReturnType();
type::gNodeCache->publish(n,rVal);
}
}
void typePropagator::visit(fieldAccessNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,
type::gNodeCache->demand(n.demandSoleChild<cmn::node>())
.as<type::iStructType>()
.getField(n.name));
}
void typePropagator::visit(callNode& n)
{
hNodeVisitor::visit(n);
auto fqn = fullyQualifiedName::build(n.pTarget.getRefee()->getNode(),n.pTarget.ref);
auto& rVal = type::gTable->fetch(fqn).as<type::iFunctionType>().getReturnType();
type::gNodeCache->publish(n,rVal);
}
void typePropagator::visit(localDeclNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,type::gNodeCache->demand(n.demandSoleChild<typeNode>()));
}
void typePropagator::visit(varRefNode& n)
{
hNodeVisitor::visit(n);
type::gNodeCache->publish(n,type::gNodeCache->demand(*n.pSrc._getRefee()));
}
void typePropagator::visit(bopNode& n)
{
hNodeVisitor::visit(n);
if(n.op == "+")
type::gNodeCache->publish(n,type::gNodeCache->demand(*n.getChildren()[0]));
else if(n.op == "<")
type::gNodeCache->publish(n,type::gTable->fetch("bool"));
else
cdwTHROW("unknown bop %s",n.op.c_str());
}
void typePropagator::visit(indexNode& n)
{
hNodeVisitor::visit(n);
auto& lhs = type::gNodeCache->demand(*n.getChildren()[0]);
// maybe operator overloading will kick in?
if(lhs.is<type::iStructType>())
{
auto& asStruct = lhs.as<type::iStructType>();
if(asStruct.hasMethod("indexOpGet"))
{
std::string funcFqn = lhs.getName() + ".indexOpGet";
auto& func = type::gTable->fetch(funcFqn).as<type::iFunctionType>();
type::gNodeCache->publish(n,func.getReturnType());
return;
}
}
// otherwise, it's just an erray
std::unique_ptr<type::typeBuilder> pBuilder(type::typeBuilder::open(lhs));
pBuilder->unwrapArray();
type::gNodeCache->publish(n,pBuilder->finish());
}
void propagateTypes(cmn::node& root)
{
{ builtInTypeVisitor v; root.acceptVisitor(v); }
{ userTypeVisitor v; root.acceptVisitor(v); }
{ functionVisitor v; root.acceptVisitor(v); }
{ globalTypePropagator v; root.acceptVisitor(v); }
{ typePropagator v; root.acceptVisitor(v); }
}
} // namespace cmn
| 27.903915 | 92 | 0.695702 | cwood77 |
0e4a20a0a312ecfabda2f1d7cf15f0ce94c3f0fe | 2,141 | hpp | C++ | src/kernel/driver/usb/xhci/device.hpp | KCCTdensan/ddOS | f57cce5ba79afdfaafe7bbf36052196d1eebfaa0 | [
"0BSD"
] | null | null | null | src/kernel/driver/usb/xhci/device.hpp | KCCTdensan/ddOS | f57cce5ba79afdfaafe7bbf36052196d1eebfaa0 | [
"0BSD"
] | null | null | null | src/kernel/driver/usb/xhci/device.hpp | KCCTdensan/ddOS | f57cce5ba79afdfaafe7bbf36052196d1eebfaa0 | [
"0BSD"
] | null | null | null | /**
* @file usb/xhci/device.hpp
*
* USB デバイスを表すクラスと関連機能.
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include "error.hpp"
#include "../device.hpp"
#include "../arraymap.hpp"
#include "context.hpp"
#include "trb.hpp"
#include "registers.hpp"
namespace usb::xhci {
class Device : public usb::Device {
public:
enum class State {
kInvalid,
kBlank,
kSlotAssigning,
kSlotAssigned
};
using OnTransferredCallbackType = void (
Device* dev,
DeviceContextIndex dci,
int completion_code,
int trb_transfer_length,
TRB* issue_trb);
Device(uint8_t slot_id, DoorbellRegister* dbreg);
kError Initialize();
DeviceContext* DeviceContext() { return &ctx_; }
InputContext* InputContext() { return &input_ctx_; }
//usb::Device* USBDevice() { return usb_device_; }
//void SetUSBDevice(usb::Device* value) { usb_device_ = value; }
State State() const { return state_; }
uint8_t SlotID() const { return slot_id_; }
void SelectForSlotAssignment();
Ring* AllocTransferRing(DeviceContextIndex index, size_t buf_size);
kError ControlIn(EndpointID ep_id, SetupData setup_data,
void* buf, int len, ClassDriver* issuer) override;
kError ControlOut(EndpointID ep_id, SetupData setup_data,
const void* buf, int len, ClassDriver* issuer) override;
kError NormalIn(EndpointID ep_id, void* buf, int len) override;
kError NormalOut(EndpointID ep_id, const void* buf, int len) override;
kError OnTransferEventReceived(const TransferEventTRB& trb);
private:
alignas(64) struct DeviceContext ctx_;
alignas(64) struct InputContext input_ctx_;
const uint8_t slot_id_;
DoorbellRegister* const dbreg_;
enum State state_;
std::array<Ring*, 31> transfer_rings_; // index = dci - 1
/** コントロール転送が完了した際に DataStageTRB や StatusStageTRB
* から対応する SetupStageTRB を検索するためのマップ.
*/
ArrayMap<const void*, const SetupStageTRB*, 16> setup_stage_map_{};
kError PushOneTransaction(EndpointID ep_id, const void* buf, int len);
};
}
| 24.329545 | 77 | 0.676319 | KCCTdensan |
0e4ba32acfbde327ce8af1c810645e6c7241d0c6 | 14,104 | hpp | C++ | oss_src/unity/lib/unity_sgraph.hpp | parquette/ParFrame | 0522aa6afdf529b3e91505b70e918f1500aae886 | [
"BSD-3-Clause"
] | null | null | null | oss_src/unity/lib/unity_sgraph.hpp | parquette/ParFrame | 0522aa6afdf529b3e91505b70e918f1500aae886 | [
"BSD-3-Clause"
] | null | null | null | oss_src/unity/lib/unity_sgraph.hpp | parquette/ParFrame | 0522aa6afdf529b3e91505b70e918f1500aae886 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#ifndef GRAPHLAB_UNITY_SGRAPH_HPP
#define GRAPHLAB_UNITY_SGRAPH_HPP
#include <unity/lib/api/unity_graph_interface.hpp>
#include <unity/lib/api/unity_sframe_interface.hpp>
#include <unity/lib/sgraph_triple_apply_typedefs.hpp>
#include <sgraph/sgraph_constants.hpp>
#include <sframe/dataframe.hpp>
#include <memory>
#include <parallel/mutex.hpp>
namespace graphlab {
// forward declarations
template <typename T>
class lazy_eval_operation_dag;
template <typename T>
class lazy_eval_future;
class sframe;
class sgraph;
typedef lazy_eval_operation_dag<sgraph> unity_graph_dag_type;
typedef lazy_eval_future<sgraph> sgraph_future;
/**
* \ingroup unity
* The \ref graphlab::unity_sgraph and \ref graphlab::unity_sgraph_base classes
* implement a graph object on the server side which is exposed to the
* client via the cppipc system.
*
* The unity_sgraph is a lazily evaluated, immutable
* graph datastructure where most operations do not take time, and instead,
* the graph is only fully constructed when accessed. Furthermore we can
* further exploit immutability for efficiency, by allowing graphs to shared
* data/structure/etc through the use of shared_ptr, etc.
*/
class unity_sgraph: public unity_sgraph_base {
public:
/// Global lazy evaluation DAG object
static unity_graph_dag_type* dag_singleton;
/// Gets the lazy evaluation DAG object
static unity_graph_dag_type* get_dag();
static const char* GRAPH_MAGIC_HEADER;
/// Default constructor
explicit unity_sgraph(size_t npartitions = SGRAPH_DEFAULT_NUM_PARTITIONS);
/**
* Constructs a unity_sgraph by taking over an existing sgraph
* object.
*/
unity_sgraph(std::shared_ptr<sgraph>);
/**
* Makes a copy of a graph. (This is a shallow copy. The resultant graphs
* share pointers. But since graphs are immutable, this is safe and can be
* treated like a deep copy.)
*/
explicit unity_sgraph(const unity_sgraph&) = default;
/**
* Copy assignment.
*/
unity_sgraph& operator=(const unity_sgraph&) = default;
/// Destructor
virtual ~unity_sgraph();
/**
* Returns a new copy of this graph object
*/
std::shared_ptr<unity_sgraph_base> clone();
/**************************************************************************/
/* */
/* UNITY GRAPH BASE INTERFACE API */
/* */
/**************************************************************************/
/**
* Returns a sframe of vertices satisfying the certain constraints.
*
* \ref vid_vec A list of vertices. If provided, will only return vertices
* in the list. Otherwise all vertices will be considered.
* \ref field_constraint A mapping of string-->value. Only vertices which
* contain a field with the particular value will be returned.
* value can be UNDEFINED, in which case vertices simply must
* contain the particular field.
* \ref group The vertex group id.
*/
std::shared_ptr<unity_sframe_base> get_vertices(
const std::vector<flexible_type>& vid_vec = std::vector<flexible_type>(),
const options_map_t& field_constraint = options_map_t(),
size_t group = 0);
/**
* Returns a sframe of edges satisfying certain constraints.
* source_vids and target_vids arrays must match up in length, and denote
* source->target edges. For instance: i-->j will return the edge i--> if it
* exists. Wildcards are supported by setting the flexible_type to UNDEFINED.
* For instance, i-->UNDEFINED will match every edge with source i. And
* UNDEFINED-->j will match every edge with target j.
*
* The returned edge will have source vertices from one group and
* target vertices from another group (can be the same).
*
* The edge must further match the values specified by the field_constraint.
*
* \ref source_vids A list of source vertices or wildcards (UNDEFINED).
* Must match the length of target_vids. See above for
* semantics.
* \ref target_vids A list of target vertices or wildcards (UNDEFINED).
* Must match the length of source_vids. See above for
* semantics.
* \ref field_constraint A mapping of string-->value. Only edges which
* contain a field with the particular value will be returned.
* value can be UNDEFINED, in which case edges simply must
* contain the particular field.
*
* \ref groupa The vertex group id for source vertices.
*
* \ref groupb The vertex group id for target vertices.
*/
std::shared_ptr<unity_sframe_base> get_edges(const std::vector<flexible_type>& source_vids=std::vector<flexible_type>(),
const std::vector<flexible_type>& target_vids=std::vector<flexible_type>(),
const options_map_t& field_constraint=options_map_t(),
size_t groupa = 0, size_t groupb = 0);
/**
* Returns a summary of the basic graph information such as the number of
* vertices / number of edges.
*/
options_map_t summary();
/**
* Adds each row of the sframe as a new vertex; A new graph
* corresponding to the current graph with new vertices added will be
* returned. Columns of the dataframes are treated as fields (new fields
* will be created as appropriate). The column with name 'id_field_name'
* will be treated as the vertex ID field. The column with name
* 'id_field_name' must therefore exist in the 'vertices' dataframe. If the
* vertex with the given ID already exists, all field values will
* overwrite. This function can therefore be also used to perform
* modification of graph data. An exception is thrown on failure.
*/
std::shared_ptr<unity_sgraph_base> add_vertices(
std::shared_ptr<unity_sframe_base> vertices,
const std::string& id_field_name, size_t group = 0);
/**
* Adds each row of the sframe as a new edge; A new graph
* corresponding to the current graph with new edges added will be
* returned. Columns of the dataframes are treated as fields (new fields
* will be created as appropriate). The columns with name 'source_field_name'
* and 'target_field_name' will be used to denote the source
* and target vertex IDs for the edge. These columns must therefore exist
* in the 'edges' dataframe. If the vertex does not exist, it will be
* created. Unlike add_vertices, edge "merging" is not performed, but
* instead, multiple edges can be created between any pair of vertices.
* Throws an exception on failure.
*/
std::shared_ptr<unity_sgraph_base> add_edges(
std::shared_ptr<unity_sframe_base> edges,
const std::string& source_field_name,
const std::string& target_field_name,
size_t groupa = 0, size_t groupb = 0);
/**
* Returns a list of of the vertex fields in the graph
*/
std::vector<std::string> get_vertex_fields(size_t group = 0);
/**
* Returns a list of of the vertex fields in the graph
*/
std::vector<flex_type_enum> get_vertex_field_types(size_t group = 0);
/**
* Returns a list of of the edge fields in the graph
*/
std::vector<std::string> get_edge_fields(size_t groupa = 0, size_t groupb = 0);
/**
* Returns a list of of the edge field types in the graph
*/
std::vector<flex_type_enum> get_edge_field_types(size_t groupa = 0, size_t groupb = 0);
/**
* Returns a new graph corresponding to the curent graph with only
* the fields listed in "fields".
*/
std::shared_ptr<unity_sgraph_base> select_vertex_fields(
const std::vector<std::string>& fields, size_t group=0);
/**
* Returns a new graph corresponding to the current graph with the field
* "field" renamed to "newfield".
*/
std::shared_ptr<unity_sgraph_base> copy_vertex_field(
std::string field, std::string newfield, size_t group=0);
/**
* Returns a new graph corresponding to the curent graph with the field
* "field" deleted.
*/
std::shared_ptr<unity_sgraph_base> delete_vertex_field(
std::string field, size_t group=0);
/**
* Add a new vertex field with column_data and return as a new graph.
*/
std::shared_ptr<unity_sgraph_base> add_vertex_field(
std::shared_ptr<unity_sarray_base> column_data, std::string field);
/**
* Rename the edge fields whoes names are in oldnames to the corresponding new names.
* Return the new graph.
*/
std::shared_ptr<unity_sgraph_base> rename_vertex_fields(
const std::vector<std::string>& oldnames,
const std::vector<std::string>& newnames);
/**
* Switch the column order of field1 and field2 in the vertex data.
* Return the new graph.
*/
std::shared_ptr<unity_sgraph_base> swap_vertex_fields(
const std::string& field1, const std::string& field2);
/**
* Returns a new graph corresponding to the curent graph with only
* the fields listed in "fields".
*/
std::shared_ptr<unity_sgraph_base> select_edge_fields(
const std::vector<std::string>& fields,
size_t groupa=0, size_t groupb=0);
/**
* Returns a new graph corresponding to the current graph with the field
* "field" renamed to "newfield".
*/
std::shared_ptr<unity_sgraph_base> copy_edge_field(
std::string field, std::string newfield,
size_t groupa=0, size_t groupb=0);
/**
* Returns a new graph corresponding to the curent graph with the field
* "field" deleted.
*/
std::shared_ptr<unity_sgraph_base> delete_edge_field(
std::string field, size_t groupa=0, size_t groupb=0);
/**
* Add a new edge field with column_data and return as a new graph.
*/
std::shared_ptr<unity_sgraph_base> add_edge_field(
std::shared_ptr<unity_sarray_base> column_data, std::string field);
/**
* Rename the edge fields whoes names are in oldnames to the corresponding new names.
* Return the new graph.
*/
std::shared_ptr<unity_sgraph_base> rename_edge_fields(
const std::vector<std::string>& oldnames,
const std::vector<std::string>& newnames);
/**
* Switch the column order of field1 and field2 in the vertex data.
* Return the new graph.
*/
std::shared_ptr<unity_sgraph_base> swap_edge_fields(const std::string& field1, const std::string& field2);
std::shared_ptr<unity_sgraph_base> lambda_triple_apply(const std::string& lambda_str,
const std::vector<std::string>& mutated_fields);
std::shared_ptr<unity_sgraph_base> lambda_triple_apply_native(
const lambda_triple_apply_fn& lambda,
const std::vector<std::string>& mutated_fields);
std::shared_ptr<unity_sgraph_base> lambda_triple_apply_native(
const function_closure_info& toolkit_fn_name,
const std::vector<std::string>& mutated_fields);
/**************************************************************************/
/* */
/* Internal Functions */
/* */
/**************************************************************************/
/**
* Internal
*
* Returns a reference to the underlying sgraph.
*
* Note: This operation willforce the lazy operations to be performed.
*/
sgraph& get_graph() const;
/**
* Internal
*
* Deep serialization.
*/
void save(oarchive& oarc) const;
/**
* Internal
*
* Save to oarchive using sframe reference save.
*/
void save_reference(oarchive& oarc) const;
/**
* Internal
*
* Deep deserialization.
*/
void load(iarchive& iarc);
/**
* Save the sgraph using reference to SFrames in other locations.
*
* \see unity_sframe::save_frame_reference
*/
void save_reference(std::string target_dir) const;
/**
* Saves the graph with the specified name to a given file in a
* non-portable binary format. File can be on disk, or on HDFS.
*
* Supported formats are 'bin', 'json', 'csv'.
*
* Returns true on success, false on failure.
*/
bool save_graph(std::string target_dir, std::string format);
/**
* Loads the graph from the given file in a
* non-portable binary format. File can be on disk, or on HDFS.
* Returns true on success, false on failure.
*/
bool load_graph(std::string target_dir);
private:
mutable std::shared_ptr<sgraph_future> m_graph;
mutex dag_mtx;
private:
void fast_validate_add_vertices(const sframe& vertices,
std::string id_field,
size_t group) const;
void fast_validate_add_edges(const sframe& vertices,
std::string src_field,
std::string dst_field,
size_t groupa, size_t groupb) const;
/**
* Returns an lazy edge sframe containing all the edges from groupa to groupb.
*/
std::shared_ptr<unity_sframe_base> get_edges_lazy(size_t groupa = 0, size_t groupb = 0);
};
} // namespace graphlab
#endif
| 37.510638 | 124 | 0.626773 | parquette |
0e5570e1edac6d166e0bea37108587f365c4fd71 | 1,835 | cpp | C++ | cpp/863. All Nodes Distance K in Binary Tree.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | 3 | 2021-08-07T07:01:34.000Z | 2021-08-07T07:03:02.000Z | cpp/863. All Nodes Distance K in Binary Tree.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | null | null | null | cpp/863. All Nodes Distance K in Binary Tree.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
// We are given a binary tree (with root node root), a target node, and an integer
// value k.
// Return a list of the values of all nodes that have a distance k from the target
// node. The answer can be returned in any order.
////////////////////////////////////////////////////////////////////////////////
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// graph[node value] = set of neighbor node values
unordered_map<int, unordered_set<int>> graph;
void buildGraph(TreeNode* parent, TreeNode* child) {
if (parent and child) {
graph[parent->val].insert(child->val);
graph[child->val].insert(parent->val);
}
if (child->left) buildGraph(child, child->left);
if (child->right) buildGraph(child, child->right);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
buildGraph(nullptr, root);
queue<int> q; q.push(target->val);
unordered_set<int> visited; visited.insert(target->val);
int steps = 0;
while (steps < k) {
int nThisLayer = q.size();
while (nThisLayer--) {
int node = q.front(); q.pop();
for (auto neigh : graph[node]) {
if (visited.find(neigh) == visited.end()) {
q.push(neigh);
visited.insert(neigh);
}
}
}
++steps;
}
vector<int> ans;
while (!q.empty()) { ans.push_back(q.front()); q.pop(); }
return ans;
}
};
| 32.192982 | 82 | 0.514986 | longwangjhu |
0e5615a9858f7786d9f22ab46266a3a7f72ca1da | 20,052 | cpp | C++ | PS4Engine/PS4Engine/api_gnm/stencil-sample/stencil-sample.cpp | Enderderder/SonyEngine | ee8b3726d293c667d2e2a849808b993e954b84c7 | [
"MIT"
] | 2 | 2020-02-22T01:27:28.000Z | 2021-12-20T08:41:43.000Z | PS4Engine/PS4Engine/api_gnm/stencil-sample/stencil-sample.cpp | Enderderder/SonyEngine | ee8b3726d293c667d2e2a849808b993e954b84c7 | [
"MIT"
] | null | null | null | PS4Engine/PS4Engine/api_gnm/stencil-sample/stencil-sample.cpp | Enderderder/SonyEngine | ee8b3726d293c667d2e2a849808b993e954b84c7 | [
"MIT"
] | 2 | 2019-09-17T19:54:00.000Z | 2020-03-06T15:08:52.000Z | /* SIE CONFIDENTIAL
PlayStation(R)4 Programmer Tool Runtime Library Release 05.008.001
* Copyright (C) 2016 Sony Interactive Entertainment Inc.
* All Rights Reserved.
*/
#include "../framework/sample_framework.h"
#include "../framework/simple_mesh.h"
#include "../framework/gnf_loader.h"
#include "../framework/frame.h"
#include "std_cbuffer.h"
using namespace sce;
namespace
{
uint32_t spinningTestVal;
Matrix4 spinningRotation;
void spin(float seconds)
{
Framework::Random random = {static_cast<uint64_t>(seconds)};
spinningTestVal = random.GetUShort() & 0xFFF;
const Vector3 axis[6] = {Vector3::xAxis(), Vector3::yAxis(), Vector3::zAxis(), -Vector3::xAxis(), -Vector3::yAxis(), -Vector3::zAxis()};
const Vector3 spinningAxis = axis[random.GetUint() % 6];
const float spinningAmount = seconds-(int)seconds;
const float spinningRadians = float(Framework::smoothStep(0,1,Framework::smoothStep(0, 1, spinningAmount)) * 3.1415926535897932384626433832795*2);
spinningRotation = Matrix4::rotation(spinningRadians, spinningAxis);
}
class Stencil
{
public:
uint32_t m_compareFunc;
uint32_t m_stencilFail;
uint32_t m_stencilZPass;
uint32_t m_stencilZFail;
Gnm::StencilControl m_stencilControl;
Stencil()
: m_compareFunc(7)
, m_stencilFail(0)
, m_stencilZPass(0)
, m_stencilZFail(0)
{
m_stencilControl.m_testVal = 1;
m_stencilControl.m_opVal = 1;
m_stencilControl.m_mask = 0xFF;
m_stencilControl.m_writeMask = 0xFF;
}
};
Vector2 g_cubePosition = Vector2(0,0);
int32_t g_clearVal = 0;
bool g_separateStencilEnable;
Stencil g_stencilFront;
Stencil g_stencilBack;
Framework::MenuItemText stencilOpText[16] = {
{"Keep", "Dest = src"},
{"Zero", "Dest = 0x00"},
{"Ones", "Dest = 0xFF"},
{"ReplaceTest", "Dest = testVal"},
{"ReplaceOp", "Dest = opVal"},
{"AddClamp", "Dest = src + opVal (clamp)"},
{"SubClamp", "Dest = src - opVal (clamp)"},
{"Invert", "Dest = ~src"},
{"AddWrap", "Dest = src + opVal (wrap)"},
{"SubWrap", "Dest = src - opVal (wrap)"},
{"And", "Dest = src & opVal"},
{"Or", "Dest = src | opVal"},
{"Xor", "Dest = src ^ opVal"},
{"Nand", "Dest = ~(src & opVal)"},
{"Nor", "Dest = ~(src | opVal)"},
{"Xnor", "Dest = ~(src ^ opVal)"},
};
Framework::MenuItemText compareFuncText[8] =
{
{"Never", "Test never passes"},
{"Less", "Test passes if incoming value is <"},
{"Equal", "Test passes if incoming value is =="},
{"LEqual", "Test passes if incoming value is <="},
{"Greater", "Test passes if incoming value is >"},
{"NotEqual", "Test passes if incoming value is !="},
{"GEqual", "Test passes if incoming value is >="},
{"Always", "Test always passes"},
};
class MenuCommandStencil : public Framework::MenuCommand
{
Stencil* m_stencil;
Framework::Menu m_menu;
Framework::MenuCommandEnum m_compareFunc;
Framework::MenuCommandUint8 m_testVal;
Framework::MenuCommandUint8 m_opVal;
Framework::MenuCommandUint8 m_mask;
Framework::MenuCommandUint8 m_writeMask;
Framework::MenuCommandEnum m_stencilFail;
Framework::MenuCommandEnum m_stencilZPass;
Framework::MenuCommandEnum m_stencilZFail;
public:
MenuCommandStencil(Stencil* stencil)
: m_stencil(stencil)
, m_compareFunc(compareFuncText, sizeof(compareFuncText)/sizeof(compareFuncText[0]), &m_stencil->m_compareFunc)
, m_testVal(&m_stencil->m_stencilControl.m_testVal, 0, 0xFF, "0x%02X")
, m_opVal(&m_stencil->m_stencilControl.m_opVal, 0, 0xFF, "0x%02X")
, m_mask(&m_stencil->m_stencilControl.m_mask, 0, 0xFF, "0x%02X")
, m_writeMask(&m_stencil->m_stencilControl.m_writeMask, 0, 0xFF, "0x%02X")
, m_stencilFail(stencilOpText, sizeof(stencilOpText)/sizeof(stencilOpText[0]), &m_stencil->m_stencilFail)
, m_stencilZPass(stencilOpText, sizeof(stencilOpText)/sizeof(stencilOpText[0]), &m_stencil->m_stencilZPass)
, m_stencilZFail(stencilOpText, sizeof(stencilOpText)/sizeof(stencilOpText[0]), &m_stencil->m_stencilZFail)
{
const Framework::MenuItem menuItem[] =
{
{{"CompareFunc", "Comparison function for stencil test"}, &m_compareFunc},
{{"TestVal", "TestVal for stencil test"}, &m_testVal},
{{"OpVal", "OpVal for stencil test"}, &m_opVal},
{{"Mask", "Mask for stencil test"}, &m_mask},
{{"WriteMask", "Mask for stencil write"}, &m_writeMask},
{{"StencilFail", "Op for when stencil fails"}, &m_stencilFail},
{{"StencilZPass", "Op for when Z passes"}, &m_stencilZPass},
{{"StencilZFail", "Op for when Z fails"}, &m_stencilZFail},
};
m_menu.appendMenuItems(sizeof(menuItem)/sizeof(menuItem[0]), &menuItem[0]);
}
virtual Framework::Menu* getMenu()
{
return &m_menu;
}
virtual void adjust(int) const {}
};
Framework::MenuCommandVector2 iceCube(&g_cubePosition, Vector2(-1,-1), Vector2(1,1), Vector2(1,-1));
Framework::MenuCommandInt clearVal(&g_clearVal, 0, 0xFF, "0x%02X");
Framework::MenuCommandBool separateStencilEnable(&g_separateStencilEnable);
MenuCommandStencil stencilFront(&g_stencilFront);
MenuCommandStencil stencilBack(&g_stencilBack);
const Framework::MenuItem menuItem[] =
{
{{"ICE Cube Controls", "Use the left analog stick to move the ICE cube around the world. As the ICE cube passes in front of stencil cubes, it interacts with them according to the rules of stencil testing hardware"}, &iceCube},
{{"ClearVal", "Adjust the value which the stencil buffer is cleared to, before either the stencil cubes or ICE cubes are rendered"}, &clearVal},
{{"Separate Front and Back", "It is possible to specify different stencil options for front-facing primitives and back-facing primitives. Unless this option is enabled, the stencil test options for front-facing primitives will be used for back-facing primitives, too"}, &separateStencilEnable},
{{"Front-Facing Options", "These are the stencil options for front-facing primitives (or all primitives, if separate front and back options are not enabled.) They include stencil test AND stencil write options"}, &stencilFront},
{{"Back-Facing Options", "These are the stencil options for back-facing primitives (only if separate front and back options are enabled.) They include stencil test AND stencil write options"}, &stencilBack},
};
enum { kMenuItems = sizeof(menuItem)/sizeof(menuItem[0]) };
Framework::GnmSampleFramework framework;
}
int main(int argc, const char *argv[])
{
framework.m_config.m_lightPositionX = Vector3(0,0,1.3f);
const Vector3 ideal(1.f, 0.f, 0.f);
const Vector3 forward = normalize(framework.m_config.m_lightTargetX - framework.m_config.m_lightPositionX);
framework.m_config.m_lightUpX = normalize(ideal - forward * dot(forward, ideal));
framework.processCommandLine(argc, argv);
framework.m_config.m_stencil = true;
framework.m_config.m_lightingIsMeaningful = true;
framework.initialize( "Stencil",
"Sample code to illustrate the operation of stencil hardware functions.",
"This sample program renders 256 cubes, each with a different stencil value. Then, another cube "
"is rendered on top of them with user-specified stencil testing parameters.");
framework.appendMenuItems(kMenuItems, menuItem);
class Frame
{
public:
sce::Gnmx::GnmxGfxContext m_commandBuffer;
Constants *m_box;
Constants *m_iceCube;
};
Frame frames[3];
SCE_GNM_ASSERT(framework.m_config.m_buffers <= 3);
for(unsigned buffer = 0; buffer < framework.m_config.m_buffers; ++buffer)
{
Frame *frame = &frames[buffer];
createCommandBuffer(&frame->m_commandBuffer,&framework,buffer);
framework.m_allocators.allocate((void**)&frame->m_box,SCE_KERNEL_WB_ONION,sizeof(*frame->m_box)*256,4,Gnm::kResourceTypeConstantBufferBaseAddress,"Buffer %d box constant buffers",buffer);
framework.m_allocators.allocate((void**)&frame->m_iceCube,SCE_KERNEL_WB_ONION,sizeof(*frame->m_iceCube),4,Gnm::kResourceTypeConstantBufferBaseAddress,"Buffer %d ICE cube constant buffer",buffer);
}
int error = 0;
Framework::VsShader vertexShader;
Framework::PsShader pixelShader, simplePixelShader;
error = Framework::LoadVsMakeFetchShader(&vertexShader, Framework::ReadFile("/app0/stencil-sample/shader_vv.sb"), &framework.m_allocators);
error = Framework::LoadPsShader(&pixelShader, Framework::ReadFile("/app0/stencil-sample/shader_p.sb"), &framework.m_allocators);
error = Framework::LoadPsShader(&simplePixelShader, Framework::ReadFile("/app0/stencil-sample/simple_p.sb"), &framework.m_allocators);
const Vector3 scale( (float)framework.m_config.m_targetWidth/2, -(float)framework.m_config.m_targetHeight/2, 0.5f );
const Vector3 offset( (float)framework.m_config.m_targetWidth/2, (float)framework.m_config.m_targetHeight/2, 0.5f );
Gnm::Texture textures[2];
error = Framework::loadTextureFromGnf(&textures[0], Framework::ReadFile("/app0/assets/icelogo-color.gnf"), 0, &framework.m_allocators);
SCE_GNM_ASSERT(error == Framework::kGnfErrorNone );
error = Framework::loadTextureFromGnf(&textures[1], Framework::ReadFile("/app0/assets/icelogo-normal.gnf"), 0, &framework.m_allocators);
SCE_GNM_ASSERT(error == Framework::kGnfErrorNone );
textures[0].setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // this texture is never bound as an RWTexture, so it's safe to declare as read-only.
textures[1].setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // this texture is never bound as an RWTexture, so it's safe to declare as read-only.
Gnm::Sampler samplers[2];
for(uint32_t i=0; i<2; ++i)
{
samplers[i].init();
samplers[i].setXyFilterMode(Gnm::kFilterModeBilinear, Gnm::kFilterModeBilinear);
samplers[i].setMipFilterMode(Gnm::kMipFilterModeLinear);
samplers[i].setAnisotropyRatio(Gnm::kAnisotropyRatio16);
}
Framework::SimpleMesh cubeMesh;
BuildCubeMesh(&framework.m_allocators, "Cube", &cubeMesh, 1.0f);
enum {kCharactersPerCellWide = 4};
enum {kCharactersPerCellHigh = 3};
const uint32_t kNumberTextureCellWidth = (1 << framework.m_config.m_log2CharacterWidth) * kCharactersPerCellWide;
const uint32_t kNumberTextureCellHeight = (1 << framework.m_config.m_log2CharacterHeight) * kCharactersPerCellHigh;
const uint32_t kNumberTextureWidth = kNumberTextureCellWidth * 16;
const uint32_t kNumberTextureHeight = kNumberTextureCellHeight * 16;
// Make a texture to hold an image of the hex values 00 to FF, for use in labeling objects that write stencil with the stencil value they write
Gnm::Texture numberTexture;
Gnm::TileMode numberTextureTileMode;
Gnm::DataFormat numberTextureFormat = Gnm::kDataFormatR8G8B8A8Unorm;
uint32_t mips = 1;
uint32_t pixels = std::max(uint32_t(kNumberTextureWidth), uint32_t(kNumberTextureHeight));
while(pixels >>= 1)
++mips;
GpuAddress::computeSurfaceTileMode(Gnm::getGpuMode(), &numberTextureTileMode, GpuAddress::kSurfaceTypeRwTextureFlat, numberTextureFormat, 1);
Gnm::SizeAlign sizeAlign = Gnmx::Toolkit::initAs2d(&numberTexture, kNumberTextureWidth, kNumberTextureHeight, mips, numberTextureFormat, numberTextureTileMode, Gnm::kNumFragments1);
void *numberTextureAddress;
framework.m_allocators.allocate(&numberTextureAddress, SCE_KERNEL_WC_GARLIC, sizeAlign, Gnm::kResourceTypeTextureBaseAddress, "Number Texture");
numberTexture.setBaseAddress(numberTextureAddress);
numberTexture.setResourceMemoryType(Gnm::kResourceMemoryTypeGC); // this texture is bound as an RWTexture, so GPU coherent it is.
uint32_t screenWidthInCharacters = 1024;
uint32_t screenHeightInCharacters = 1024;
DbgFont::Screen screen;
Gnm::SizeAlign screenSizeAlign = screen.calculateRequiredBufferSizeAlign(screenWidthInCharacters, screenHeightInCharacters);
void *screenAddr;
framework.m_allocators.allocate(&screenAddr, SCE_KERNEL_WB_ONION, screenSizeAlign, Gnm::kResourceTypeBufferBaseAddress, "Character Cell Screen");
screen.initialize(screenAddr, screenWidthInCharacters, screenHeightInCharacters);
DbgFont::Window window;
window.initialize(&screen);
DbgFont::Cell clearCell;
clearCell.m_character = 0;
clearCell.m_foregroundColor = DbgFont::kWhite;
clearCell.m_foregroundAlpha = 15;
clearCell.m_backgroundColor = DbgFont::kBlack;
clearCell.m_backgroundAlpha = 0;
window.clear(clearCell);
for(uint32_t y=0; y<16; ++y)
for(uint32_t x=0; x<16; ++x)
{
window.setCursor(x * kCharactersPerCellWide + 1, y * kCharactersPerCellHigh + 1);
window.printf("%02X", y*16+x);
}
const Vector4 darkOliveGreen = Vector4(0x55, 0x6B, 0x2F, 0xFF) / 255.f;
{
Frame *frame = frames + framework.getIndexOfBufferCpuIsWriting();
Gnmx::GnmxGfxContext *gfxc = &frame->m_commandBuffer; // one GfxContext (command buffer) object is required for each frame that can simultaneously be in flight.
gfxc->reset();
Gnmx::Toolkit::SurfaceUtil::clearTexture(*gfxc, &numberTexture, darkOliveGreen);
screen.render(*gfxc, &numberTexture, framework.m_config.m_log2CharacterWidth, framework.m_config.m_log2CharacterHeight);
Gnmx::Toolkit::SurfaceUtil::generateMipMaps(*gfxc, &numberTexture);
Gnmx::Toolkit::submitAndStall(*gfxc);
}
framework.SetViewToWorldMatrix(inverse(Matrix4::lookAt(Point3(0,0,1.3f), Point3(0,0,0), Vector3(-1,0,0))));
while (!framework.m_shutdownRequested)
{
Framework::GnmSampleFramework::Buffer *bufferCpuIsWriting = framework.m_buffer + framework.getIndexOfBufferCpuIsWriting();
Frame *frame = frames + framework.getIndexOfBufferCpuIsWriting();
Gnmx::GnmxGfxContext *gfxc = &frame->m_commandBuffer;
gfxc->reset();
framework.BeginFrame(*gfxc);
Gnm::PrimitiveSetup primSetupReg;
primSetupReg.init();
primSetupReg.setCullFace( Gnm::kPrimitiveSetupCullFaceBack);
primSetupReg.setFrontFace( Gnm::kPrimitiveSetupFrontFaceCcw );
gfxc->setPrimitiveSetup( primSetupReg );
Gnmx::Toolkit::SurfaceUtil::clearRenderTarget(*gfxc, &bufferCpuIsWriting->m_renderTarget, framework.getClearColor());
Gnmx::Toolkit::SurfaceUtil::clearDepthStencilTarget(*gfxc, &bufferCpuIsWriting->m_depthTarget, 1.f, (uint8_t)g_clearVal);
gfxc->setRenderTargetMask(0xF);
gfxc->setRenderTarget(0, &bufferCpuIsWriting->m_renderTarget);
gfxc->setDepthRenderTarget(&bufferCpuIsWriting->m_depthTarget);
gfxc->setupScreenViewport( 0, 0, bufferCpuIsWriting->m_renderTarget.getWidth(), bufferCpuIsWriting->m_renderTarget.getHeight(), 0.5f, 0.5f );
gfxc->setVsShader(vertexShader.m_shader, 0, vertexShader.m_fetchShader, &vertexShader.m_offsetsTable);
gfxc->setPsShader(simplePixelShader.m_shader, &simplePixelShader.m_offsetsTable);
cubeMesh.SetVertexBuffer(*gfxc, Gnm::kShaderStageVs);
gfxc->setPrimitiveType(cubeMesh.m_primitiveType);
gfxc->setIndexSize(cubeMesh.m_indexType);
gfxc->setTextures(Gnm::kShaderStagePs, 0, 1, &numberTexture);
gfxc->setTextures(Gnm::kShaderStagePs, 1, 1, &textures[1]);
gfxc->setSamplers(Gnm::kShaderStagePs, 0, 2, samplers);
Gnm::DepthStencilControl depthControl;
depthControl.init();
Gnm::StencilOpControl stencilControl;
stencilControl.init();
depthControl.setDepthControl( Gnm::kDepthControlZWriteEnable, Gnm::kCompareFuncLessEqual );
depthControl.setDepthEnable(true);
depthControl.setStencilEnable(true);
stencilControl.setStencilOps(Gnm::kStencilOpReplaceTest, Gnm::kStencilOpReplaceTest, Gnm::kStencilOpReplaceTest);
depthControl.setStencilFunction( Gnm::kCompareFuncAlways );
gfxc->setDepthStencilControl( depthControl );
gfxc->setStencilOpControl( stencilControl );
spin(framework.GetSecondsElapsedApparent());
for( uint32_t testVal=0; testVal<256; ++testVal )
{
Constants *constants = &frame->m_box[testVal];
Gnm::Buffer constantBuffer;
constantBuffer.initAsConstantBuffer(constants, sizeof(*constants));
constantBuffer.setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // it's a constant buffer, so read-only is OK
gfxc->setConstantBuffers(Gnm::kShaderStageVs, 0, 1, &constantBuffer);
gfxc->setConstantBuffers(Gnm::kShaderStagePs, 0, 1, &constantBuffer);
const Matrix4 translation = Matrix4::translation(Vector3((testVal/16)/7.5f-1.f,(testVal%16)/7.5f-1.f,0));
const Matrix4 scale = Matrix4::scale( Vector3(0.1f,0.1f,0.1f) );
Matrix4 rotation = Matrix4::identity();
if(testVal == spinningTestVal)
rotation = spinningRotation;
const Matrix4 model = translation * scale * rotation;
constants->m_modelViewProjection = transpose(framework.m_viewProjectionMatrix*model);
constants->m_modelView = transpose(framework.m_worldToViewMatrix*model);
constants->m_lightColor = framework.getLightColor();
constants->m_ambientColor = framework.getAmbientColor();
constants->m_lightAttenuation = Vector4(1, 0, 0, 0);
constants->m_lightPosition = framework.getLightPositionInViewSpace();
float testValX = float((testVal>>0) & 0xF);
float testValY = float((testVal>>4) & 0xF);
constants->m_uv = transpose(Matrix4::scale(Vector3(kNumberTextureCellWidth/(float)kNumberTextureWidth, kNumberTextureCellHeight/(float)kNumberTextureHeight,1)) * Matrix4::translation(Vector3(testValX, testValY, 0)));
Gnm::StencilControl stencilControl;
stencilControl.m_testVal = static_cast<uint8_t>(testVal);
stencilControl.m_mask = 0xFF;
stencilControl.m_writeMask = 0xFF;
stencilControl.m_opVal = static_cast<uint8_t>(testVal);
gfxc->setStencil(stencilControl);
gfxc->drawIndex(cubeMesh.m_indexCount, cubeMesh.m_indexBuffer);
}
gfxc->setPsShader(pixelShader.m_shader, &pixelShader.m_offsetsTable);
gfxc->setTextures(Gnm::kShaderStagePs, 0, 2, textures);
Constants *constants = frame->m_iceCube;
Gnm::Buffer constantBuffer;
constantBuffer.initAsConstantBuffer(constants, sizeof(*constants) );
constantBuffer.setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // it's a constant buffer, so read-only is OK
gfxc->setConstantBuffers(Gnm::kShaderStageVs, 0, 1, &constantBuffer);
gfxc->setConstantBuffers(Gnm::kShaderStagePs, 0, 1, &constantBuffer);
const Matrix4 translation = Matrix4::translation(Vector3(-g_cubePosition.getY(), g_cubePosition.getX(), 0.f));
const Matrix4 scale = Matrix4::scale( Vector3(0.2f,0.2f,0.2f) );
const Matrix4 model = translation * scale;
constants->m_modelViewProjection = transpose(framework.m_viewProjectionMatrix*model);
constants->m_modelView = transpose(framework.m_worldToViewMatrix*model);
constants->m_lightColor = framework.getLightColor();
constants->m_ambientColor = framework.getAmbientColor();
constants->m_lightAttenuation = Vector4(1, 0, 0, 0);
constants->m_lightPosition = framework.m_worldToViewMatrix * Vector4(-framework.m_worldToLightMatrix.getCol3().getXYZ(),1.f);
constants->m_uv = Matrix4::identity();
gfxc->setStencilSeparate(g_stencilFront.m_stencilControl, g_stencilBack.m_stencilControl);
stencilControl.setStencilOps((Gnm::StencilOp)g_stencilFront.m_stencilFail, (Gnm::StencilOp)g_stencilFront.m_stencilZPass, (Gnm::StencilOp)g_stencilFront.m_stencilZFail);
stencilControl.setStencilOpsBack((Gnm::StencilOp)g_stencilBack.m_stencilFail, (Gnm::StencilOp)g_stencilBack.m_stencilZPass, (Gnm::StencilOp)g_stencilBack.m_stencilZFail);
depthControl.setStencilFunction((Gnm::CompareFunc)g_stencilFront.m_compareFunc);
depthControl.setStencilFunctionBack((Gnm::CompareFunc)g_stencilBack.m_compareFunc);
depthControl.setSeparateStencilEnable(g_separateStencilEnable);
gfxc->setDepthStencilControl( depthControl );
gfxc->setStencilOpControl( stencilControl );
primSetupReg.setCullFace(Gnm::kPrimitiveSetupCullFaceNone);
gfxc->setPrimitiveSetup(primSetupReg);
gfxc->drawIndex(cubeMesh.m_indexCount, cubeMesh.m_indexBuffer);
primSetupReg.setCullFace(Gnm::kPrimitiveSetupCullFaceBack);
gfxc->setPrimitiveSetup(primSetupReg);
{
Gnm::DepthStencilControl depthControl;
depthControl.init();
depthControl.setDepthControl( Gnm::kDepthControlZWriteEnable, Gnm::kCompareFuncLessEqual );
depthControl.setDepthEnable(true);
gfxc->setDepthStencilControl( depthControl );
}
framework.EndFrame(*gfxc);
}
Frame *frame = frames + framework.getIndexOfBufferCpuIsWriting();
Gnmx::GnmxGfxContext *gfxc = &frame->m_commandBuffer;
framework.terminate(*gfxc);
return 0;
}
| 47.181176 | 296 | 0.756882 | Enderderder |
0e573113506ec9fde4d1a475838a9315be2bba03 | 754 | hpp | C++ | Accolade/src/Screens/RoomSelectorScreen.hpp | Tackwin/BossRoom | ecad5853e591b9edc54e75448547e20e14964f72 | [
"MIT"
] | null | null | null | Accolade/src/Screens/RoomSelectorScreen.hpp | Tackwin/BossRoom | ecad5853e591b9edc54e75448547e20e14964f72 | [
"MIT"
] | null | null | null | Accolade/src/Screens/RoomSelectorScreen.hpp | Tackwin/BossRoom | ecad5853e591b9edc54e75448547e20e14964f72 | [
"MIT"
] | null | null | null | #pragma once
#include "Screen.hpp"
#include <SFML/Graphics.hpp>
#include "./../Common.hpp"
#include "./../3rd/json.hpp"
class RoomSelectorScreen : public Screen {
public: //TODO:Make this private
sf::Text _roomNumberText;
sf::Text _infoText;
sf::Text _triesInfoText;
sf::RectangleShape _bossArtworkSprite;
sf::Text _goTextButton; //TODO: Make a proper UI infrastructure
sf::RectangleShape _goSpriteButton;
nlohmann::json _json;
u32 _n;
public:
RoomSelectorScreen(u32 n);
~RoomSelectorScreen();
virtual Type getType() const noexcept override { return edit_screen; }
virtual void onEnter(std::any) override;
virtual std::any onExit() override;
virtual void update(float dt);
virtual void render(sf::RenderTarget& target);
}; | 20.378378 | 71 | 0.737401 | Tackwin |
0e594ad9d66ed63d91ced7ebaedab58028bf3b67 | 26,615 | cpp | C++ | hphp/runtime/vm/jit/tc-internal.cpp | divinity76/hhvm | cfde9bb3d7d49740d0ca0228e2d714637b155a13 | [
"PHP-3.01",
"Zend-2.0"
] | 9,491 | 2015-01-01T00:30:28.000Z | 2022-03-31T20:22:11.000Z | hphp/runtime/vm/jit/tc-internal.cpp | divinity76/hhvm | cfde9bb3d7d49740d0ca0228e2d714637b155a13 | [
"PHP-3.01",
"Zend-2.0"
] | 4,796 | 2015-01-01T00:26:31.000Z | 2022-03-31T01:09:05.000Z | hphp/runtime/vm/jit/tc-internal.cpp | divinity76/hhvm | cfde9bb3d7d49740d0ca0228e2d714637b155a13 | [
"PHP-3.01",
"Zend-2.0"
] | 2,126 | 2015-01-01T11:13:29.000Z | 2022-03-28T19:58:15.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/tc-internal.h"
#include "hphp/runtime/vm/jit/tc.h"
#include "hphp/runtime/base/init-fini-node.h"
#include "hphp/runtime/base/perf-warning.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/stats.h"
#include "hphp/runtime/base/bespoke/layout.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/vm/workload-stats.h"
#include "hphp/runtime/vm/jit/code-cache.h"
#include "hphp/runtime/vm/jit/guard-type-profile.h"
#include "hphp/runtime/vm/jit/mcgen-translate.h"
#include "hphp/runtime/vm/jit/mcgen.h"
#include "hphp/runtime/vm/jit/perf-counters.h"
#include "hphp/runtime/vm/jit/prof-data.h"
#include "hphp/runtime/vm/jit/relocation.h"
#include "hphp/runtime/vm/jit/service-requests.h"
#include "hphp/runtime/vm/jit/srcdb.h"
#include "hphp/runtime/vm/jit/tc-prologue.h"
#include "hphp/runtime/vm/jit/tc-record.h"
#include "hphp/runtime/vm/jit/timer.h"
#include "hphp/runtime/vm/jit/trans-db.h"
#include "hphp/runtime/vm/jit/unique-stubs.h"
#include "hphp/runtime/vm/jit/unwind-itanium.h"
#include "hphp/runtime/vm/jit/vasm-emit.h"
#include "hphp/runtime/vm/jit/write-lease.h"
#include "hphp/util/disasm.h"
#include "hphp/util/logger.h"
#include "hphp/util/mutex.h"
#include "hphp/util/rds-local.h"
#include "hphp/util/trace.h"
#include <tbb/concurrent_hash_map.h>
#include <atomic>
extern "C" _Unwind_Reason_Code
__gxx_personality_v0(int, _Unwind_Action, uint64_t, _Unwind_Exception*,
_Unwind_Context*);
TRACE_SET_MOD(mcg);
namespace HPHP { namespace jit { namespace tc {
__thread bool tl_is_jitting = false;
CodeCache* g_code{nullptr};
SrcDB g_srcDB;
UniqueStubs g_ustubs;
///////////////////////////////////////////////////////////////////////////////
namespace {
std::atomic<uint64_t> s_numTrans;
SimpleMutex s_codeLock{false, RankCodeCache};
SimpleMutex s_metadataLock{false, RankCodeMetadata};
RDS_LOCAL_NO_CHECK(size_t, s_initialTCSize);
bool shouldPGOFunc(const Func* func) {
return profData() != nullptr;
}
// A code reuse block owns temporary code blocks used to emit into a reused
// segment of another view.
struct CodeReuseBlock {
CodeBlock reusedMain, reusedCold, reusedFrozen;
// Get a view into possibly reused code blocks (if there is space, and
// reusable TC is enabled).
CodeCache::View getMaybeReusedView(CodeCache::View& src,
const TransRange& range) {
if (!RuntimeOption::EvalEnableReusableTC) return src;
auto main = &src.main();
auto cold = &src.cold();
auto frozen = &src.frozen();
auto const pad = RuntimeOption::EvalReusableTCPadding;
size_t mainSize = range.main.size() + pad;
size_t coldSize = range.cold.size() + pad;
size_t frozenSize = range.frozen.size() + pad;
if (auto const s = (TCA)main->allocInner(mainSize)) {
reusedMain.init(s, mainSize, "Reused main");
main = &reusedMain;
}
if (auto const s = (TCA)cold->allocInner(coldSize)) {
reusedCold.init(s, coldSize, "Reused cold");
cold = &reusedCold;
}
if (cold != frozen) {
if (auto const s = (TCA)frozen->allocInner(frozenSize)) {
reusedFrozen.init(s, frozenSize, "Reused frozen");
frozen = &reusedFrozen;
}
}
return CodeCache::View(*main, *cold, *frozen, src.data(), false);
}
};
}
///////////////////////////////////////////////////////////////////////////////
TransLoc TransRange::loc() const {
TransLoc loc;
loc.setMainStart(main.begin());
loc.setColdStart(cold.begin() - sizeof(uint32_t));
loc.setFrozenStart(frozen.begin() - sizeof(uint32_t));
loc.setMainSize(main.size());
assertx(loc.coldCodeSize() == cold.size());
assertx(loc.frozenCodeSize() == frozen.size());
return loc;
}
bool canTranslate() {
return s_numTrans.load(std::memory_order_relaxed) <
RuntimeOption::EvalJitGlobalTranslationLimit;
}
using FuncCounterMap = tbb::concurrent_hash_map<FuncId, uint32_t,
FuncIdHashCompare>;
static FuncCounterMap s_func_counters;
using SrcKeyCounters = tbb::concurrent_hash_map<SrcKey, uint32_t,
SrcKey::TbbHashCompare>;
static SrcKeyCounters s_sk_counters;
static RDS_LOCAL_NO_CHECK(bool, s_jittingTimeLimitExceeded);
TranslationResult::Scope shouldTranslateNoSizeLimit(SrcKey sk, TransKind kind) {
// If we've hit Eval.JitGlobalTranslationLimit, then we stop translating.
if (!canTranslate()) return TranslationResult::Scope::Process;
if (*s_jittingTimeLimitExceeded) return TranslationResult::Scope::Request;
auto const maxTransTime = RuntimeOption::EvalJitMaxRequestTranslationTime;
if (maxTransTime >= 0 && RuntimeOption::ServerExecutionMode()) {
auto const transCounter = Timer::CounterValue(Timer::mcg_translate);
if (transCounter.wall_time_elapsed >= maxTransTime) {
if (Trace::moduleEnabledRelease(Trace::mcg, 1)) {
Trace::traceRelease("Skipping translation. "
"Time budget of %" PRId64 " exceeded. "
"%" PRId64 "us elapsed. "
"%" PRId64 " translations completed\n",
maxTransTime,
transCounter.wall_time_elapsed,
transCounter.count);
}
*s_jittingTimeLimitExceeded = true;
return TranslationResult::Scope::Request;
}
}
auto const func = sk.func();
// Do not translate functions from units marked as interpret-only.
if (func->unit()->isInterpretOnly()) {
return TranslationResult::Scope::Transient;
}
// Refuse to JIT Live translations if Eval.JitPGOOnly is enabled.
if (RuntimeOption::EvalJitPGOOnly &&
(kind == TransKind::Live || kind == TransKind::LivePrologue)) {
return TranslationResult::Scope::Transient;
}
// Refuse to JIT Live / Profile translations for a function until
// Eval.JitLiveThreshold / Eval.JitProfileThreshold is hit.
auto const isLive = kind == TransKind::Live ||
kind == TransKind::LivePrologue;
auto const isProf = kind == TransKind::Profile ||
kind == TransKind::ProfPrologue;
if (isLive || isProf) {
uint32_t skCount = 1;
if (RuntimeOption::EvalJitSrcKeyThreshold > 1) {
SrcKeyCounters::accessor acc;
if (!s_sk_counters.insert(acc, SrcKeyCounters::value_type(sk, 1))) {
skCount = ++acc->second;
}
}
{
FuncCounterMap::accessor acc;
if (!s_func_counters.insert(acc, {func->getFuncId(), 1})) ++acc->second;
auto const funcThreshold = isLive ? RuntimeOption::EvalJitLiveThreshold
: RuntimeOption::EvalJitProfileThreshold;
if (acc->second < funcThreshold) {
return TranslationResult::Scope::Transient;
}
}
if (skCount < RuntimeOption::EvalJitSrcKeyThreshold) {
return TranslationResult::Scope::Transient;
}
}
return TranslationResult::Scope::Success;
}
static std::atomic_flag s_did_log = ATOMIC_FLAG_INIT;
static std::atomic<bool> s_TCisFull{false};
TranslationResult::Scope shouldTranslate(SrcKey sk, TransKind kind) {
if (s_TCisFull.load(std::memory_order_relaxed)) {
return TranslationResult::Scope::Process;
}
if (*s_jittingTimeLimitExceeded) {
return TranslationResult::Scope::Request;
}
const bool reachedMaxLiveMainLimit =
getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage;
auto const main_under = code().main().used() < CodeCache::AMaxUsage;
auto const cold_under = code().cold().used() < CodeCache::AColdMaxUsage;
auto const froz_under = code().frozen().used() < CodeCache::AFrozenMaxUsage;
if (!reachedMaxLiveMainLimit && main_under && cold_under && froz_under) {
return shouldTranslateNoSizeLimit(sk, kind);
}
// Set a flag so we quickly bail from trying to generate new
// translations next time.
s_TCisFull.store(true, std::memory_order_relaxed);
Treadmill::enqueue([] { s_sk_counters.clear(); });
if (main_under && !s_did_log.test_and_set() &&
RuntimeOption::EvalProfBranchSampleFreq == 0) {
// If we ran out of TC space in cold or frozen but not in main,
// something unexpected is happening and we should take note of
// it. We skip this logging if TC branch profiling is on, since
// it fills up code and frozen at a much higher rate.
if (!cold_under) {
logPerfWarning("cold_full", 1, [] (StructuredLogEntry&) {});
}
if (!froz_under) {
logPerfWarning("frozen_full", 1, [] (StructuredLogEntry&) {});
}
}
return TranslationResult::Scope::Process;
}
bool newTranslation() {
if (s_numTrans.fetch_add(1, std::memory_order_relaxed) >=
RuntimeOption::EvalJitGlobalTranslationLimit) {
return false;
}
return true;
}
std::unique_lock<SimpleMutex> lockCode(bool lock) {
if (lock) return std::unique_lock<SimpleMutex>{ s_codeLock };
return std::unique_lock<SimpleMutex>{s_codeLock, std::defer_lock};
}
std::unique_lock<SimpleMutex> lockMetadata(bool lock) {
if (lock) return std::unique_lock<SimpleMutex>{s_metadataLock};
return std::unique_lock<SimpleMutex>{s_metadataLock, std::defer_lock};
}
CodeMetaLock::CodeMetaLock(bool f) :
m_code(lockCode(f)),
m_meta(lockMetadata(f)) {
}
void CodeMetaLock::lock() {
m_code.lock();
m_meta.lock();
}
void CodeMetaLock::unlock() {
m_meta.unlock();
m_code.unlock();
}
void assertOwnsCodeLock(OptView v) {
if (!v || !v->isLocal()) s_codeLock.assertOwnedBySelf();
}
void assertOwnsMetadataLock() { s_metadataLock.assertOwnedBySelf(); }
void requestInit() {
regState() = VMRegState::CLEAN;
Timer::RequestInit();
memset(rl_perf_counters.getCheck(), 0, sizeof(PerfCounters));
Stats::init();
requestInitProfData();
*s_initialTCSize.getCheck() = g_code->totalUsed();
assertx(!g_unwind_rds.isInit());
memset(g_unwind_rds.get(), 0, sizeof(UnwindRDS));
g_unwind_rds.markInit();
*s_jittingTimeLimitExceeded.getCheck() = false;
}
void requestExit() {
Stats::dump();
Stats::clear();
if (RuntimeOption::EvalJitProfileGuardTypes) {
logGuardProfileData();
}
Timer::RequestExit();
if (profData()) profData()->maybeResetCounters();
requestExitProfData();
reportJitMaturity();
if (Trace::moduleEnabledRelease(Trace::mcgstats, 1)) {
Trace::traceRelease("MCGenerator perf counters for %s:\n",
g_context->getRequestUrl(50).c_str());
for (int i = 0; i < tpc_num_counters; i++) {
Trace::traceRelease("%-20s %10" PRId64 "\n",
kPerfCounterNames[i], rl_perf_counters[i]);
}
Trace::traceRelease("\n");
}
}
void codeEmittedThisRequest(size_t& requestEntry, size_t& now) {
requestEntry = *s_initialTCSize;
now = g_code->totalUsed();
}
void processInit() {
auto codeLock = lockCode();
auto metaLock = lockMetadata();
g_code = new(low_malloc(sizeof(CodeCache))) CodeCache();
g_ustubs.emitAll(*g_code, *Debug::DebugInfo::Get());
// Write an .eh_frame section that covers the JIT portion of the TC.
initUnwinder(g_code->base(), g_code->tcSize(),
tc_unwind_personality);
if (auto cti_cap = g_code->bytecode().capacity()) {
// write an .eh_frame for cti code using default personality
initUnwinder(g_code->bytecode().base(), cti_cap, __gxx_personality_v0);
}
Disasm::ExcludedAddressRange(g_code->base(), g_code->codeSize());
recycleInit();
}
void processExit() {
recycleStop();
}
bool isValidCodeAddress(TCA addr) {
return g_code->isValidCodeAddress(addr);
}
void checkFreeProfData() {
// In PGO mode, we free all the profiling data once the main code area reaches
// its maximum usage.
//
// However, we keep the data around indefinitely in a few special modes:
// * Eval.EnableReusableTC
// * TC dumping enabled (Eval.DumpTC/DumpIR/etc.)
//
// Finally, when the RetranslateAll mode is enabled, the ProfData is discarded
// via a different mechanism, after all the optimized translations are
// generated.
if (profData() &&
!RuntimeOption::EvalEnableReusableTC &&
(code().main().used() >= CodeCache::AMaxUsage ||
getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage) &&
!transdb::enabled() &&
!mcgen::retranslateAllEnabled()) {
discardProfData();
}
}
bool shouldProfileNewFuncs() {
if (profData() == nullptr) return false;
// We have two knobs to control the number of functions we're allowed to
// profile: Eval.JitProfileRequests and Eval.JitProfileBCSize. We profile new
// functions until either of these limits is exceeded. In practice, we expect
// to hit the bytecode size limit first, but we keep the request limit around
// as a safety net.
return profData()->profilingBCSize() < RuntimeOption::EvalJitProfileBCSize &&
requestCount() < RuntimeOption::EvalJitProfileRequests;
}
bool profileFunc(const Func* func) {
// If retranslateAll has been scheduled (including cases when it is going on,
// or has finished), we can't emit more Profile translations. This is to
// ensure that, when retranslateAll() runs, no more Profile translations are
// being added to ProfData.
if (mcgen::retranslateAllScheduled()) return false;
if (code().main().used() >= CodeCache::AMaxUsage) return false;
if (getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage) {
return false;
}
if (!shouldPGOFunc(func)) return false;
if (profData()->optimized(func->getFuncId())) return false;
// If we already started profiling `func', then we return true and skip the
// other checks below.
if (profData()->profiling(func->getFuncId())) return true;
return shouldProfileNewFuncs();
}
///////////////////////////////////////////////////////////////////////////////
LocalTCBuffer::LocalTCBuffer(Address start, size_t initialSize) {
TCA fakeStart = code().threadLocalStart();
auto const sz = initialSize / 4;
auto initBlock = [&] (DataBlock& block, size_t mxSz, const char* nm) {
always_assert(sz <= mxSz);
block.init(fakeStart, start, sz, mxSz, nm);
fakeStart += mxSz;
start += sz;
};
initBlock(m_main, RuntimeOption::EvalThreadTCMainBufferSize,
"thread local main");
initBlock(m_cold, RuntimeOption::EvalThreadTCColdBufferSize,
"thread local cold");
initBlock(m_frozen, RuntimeOption::EvalThreadTCFrozenBufferSize,
"thread local frozen");
initBlock(m_data, RuntimeOption::EvalThreadTCDataBufferSize,
"thread local data");
}
OptView LocalTCBuffer::view() {
if (!valid()) return std::nullopt;
return CodeCache::View(m_main, m_cold, m_frozen, m_data, true);
}
////////////////////////////////////////////////////////////////////////////////
// Translator internals
Translator::Translator(SrcKey sk, TransKind kind)
: sk(sk), kind(kind), unit(), vunit()
{}
Translator::~Translator() = default;
Optional<TranslationResult>
Translator::acquireLeaseAndRequisitePaperwork() {
computeKind();
// Avoid a race where we would create a Live translation while
// retranslateAll is in flight and we haven't generated an
// Optimized translation yet.
auto const shouldEmitLiveTranslation = [&] {
if (mcgen::retranslateAllPending() && !isProfiling(kind) && profData()) {
// When bespokes are enabled, we can't emit live translations until the
// bespoke hierarchy is finalized.
if (allowBespokeArrayLikes() && !bespoke::Layout::HierarchyFinalized()) {
return false;
}
// Functions that are marked as being profiled or marked as having been
// optimized are about to have their translations invalidated during the
// publish phase of retranslate all. Don't allow live translations to be
// emitted in this scenario.
auto const fid = sk.func()->getFuncId();
return !profData()->profiling(fid) &&
!profData()->optimized(fid);
}
return true;
};
if (!shouldEmitLiveTranslation()) {
return TranslationResult::failTransiently();
}
if (auto const p = getCached()) return *p;
// Acquire the appropriate lease otherwise bail to a fallback
// execution mode (eg. interpreter) by returning a nullptr
// translation address.
m_lease.emplace(sk.func(), kind);
if (!(*m_lease)) return TranslationResult::failTransiently();
computeKind(); // Recompute the kind in case we are no longer profiling.
if (!m_lease->checkKind(kind)) return TranslationResult::failTransiently();
// Check again if we can emit live translations for the given
// func now that we have the lock.
if (!shouldEmitLiveTranslation()) {
return TranslationResult::failTransiently();
}
if (auto const s = shouldTranslate();
s != TranslationResult::Scope::Success) {
if (s == TranslationResult::Scope::Process) setCachedForProcessFail();
return TranslationResult{s};
}
if (UNLIKELY(RID().isJittingDisabled())) {
TRACE(2, "punting because jitting code was disabled\n");
return TranslationResult::failTransiently();
}
// Check for cached one last time since we have all the locks now.
return getCached();
}
TranslationResult::Scope Translator::shouldTranslate(bool noSizeLimit) {
if (kind == TransKind::Invalid) computeKind();
if (noSizeLimit) {
return shouldTranslateNoSizeLimit(sk, kind);
}
return ::HPHP::jit::tc::shouldTranslate(sk, kind);
}
Optional<TranslationResult>
Translator::translate(Optional<CodeCache::View> view) {
// If the TransDB is enabled, we allocate TransIDs for all translations in
// ProfData to keep each translation's ID the same in both ProfData and
// TransDB.
if (profData() && (isProfiling(kind) || transdb::enabled())) {
transId = profData()->allocTransID();
}
if (!newTranslation()) return TranslationResult::failForProcess();
WorkloadStats::EnsureInit();
WorkloadStats guard(WorkloadStats::InTrans);
SCOPE_EXIT {
unit.reset();
vunit.reset();
};
{
tl_is_jitting = true;
this->gen();
SCOPE_EXIT {
tl_is_jitting = false;
};
}
// Check for translation failure.
// TODO: categorize failure
if (!vunit) return TranslationResult::failTransiently();
Timer timer(Timer::mcg_finishTranslation);
tracing::Block _b{
"emit-translation",
[&] {
return traceProps(*vunit);
}
};
auto codeLock = lockCode(false);
if (!view.has_value()) {
if (RuntimeOption::EvalEnableReusableTC) {
auto const initialSize = 256;
m_localBuffer = std::make_unique<uint8_t[]>(initialSize);
m_localTCBuffer =
std::make_unique<LocalTCBuffer>(m_localBuffer.get(), initialSize);
view = m_localTCBuffer->view();
} else {
// Using the global TC view. Better lock things.
codeLock.lock();
}
}
// Tag the translation start, and build the trans meta.
// Generate vasm into the code view, retrying if we fill hot.
while (true) {
if (!view.has_value() || !view->isLocal()) {
view.emplace(code().view(kind));
}
CGMeta fixups;
TransLocMaker maker{*view};
const bool align = isPrologue(kind);
try {
view->alignForTranslation(align);
maker.markStart();
emitVunit(*vunit, unit.get(), *view, fixups,
mcgen::dumpTCAnnotation(kind) ? getAnnotations()
: nullptr);
} catch (const DataBlockFull& dbFull) {
// Rollback so the area can be used by something else.
auto const range = maker.rollback();
auto const bytes = range.main.size() + range.cold.size() +
range.frozen.size();
// There should be few of these. They mean there is wasted work
// performing translation for functions that don't have space in the TC.
logPerfWarning("translation_overflow", 1, [&] (StructuredLogEntry& e) {
e.setStr("kind", show(kind));
e.setStr("srckey", show(sk));
e.setStr("data_block", dbFull.name);
e.setInt("bytes_dropped", bytes);
});
if (RuntimeOption::ServerExecutionMode()) {
Logger::Warning("TC area %s filled up!", dbFull.name.c_str());
}
reset();
return TranslationResult::failForProcess();
}
transMeta.emplace(*view);
transMeta->fixups = std::move(fixups);
transMeta->range = maker.markEnd();
break;
}
if (isProfiling(kind)) {
profData()->setProfiling(sk.func());
}
Timer metaTimer(Timer::mcg_finishTranslation_metadata);
if (unit && unit->logEntry()) {
auto metaLock = lockMetadata();
logTranslation(this, transMeta->range);
}
if (!RuntimeOption::EvalJitLogAllInlineRegions.empty()) {
logFrames(*vunit);
}
return std::nullopt;
}
bool Translator::translateSuccess() const {
return transMeta.has_value();
}
Optional<TranslationResult> Translator::relocate(bool alignMain) {
assertx(transMeta.has_value());
// Code emitted directly is relocated during emission (or emitted
// directly in place).
if (!transMeta->view.isLocal()) {
assertx(!RuntimeOption::EvalEnableReusableTC);
return std::nullopt;
}
WorkloadStats::EnsureInit();
WorkloadStats guard(WorkloadStats::InTrans);
auto const& range = transMeta->range;
auto& fixups = transMeta->fixups;
RelocationInfo rel;
{
auto codeLock = lockCode();
while (true) {
auto finalView = code().view(kind);
CodeReuseBlock crb;
auto dstView = crb.getMaybeReusedView(finalView, range);
auto& srcView = transMeta->view;
TransLocMaker maker{dstView};
try {
dstView.alignForTranslation(alignMain);
maker.markStart();
auto origin = range.data;
if (!origin.empty()) {
dstView.data().bytes(origin.size(),
srcView.data().toDestAddress(origin.begin()));
auto dest = maker.dataRange();
auto oAddr = origin.begin();
auto dAddr = dest.begin();
while (oAddr != origin.end()) {
assertx(dAddr != dest.end());
rel.recordAddress(oAddr++, dAddr++, 0);
}
}
jit::relocate(rel, dstView.main(), range.main.begin(), range.main.end(),
srcView.main(), fixups, nullptr, AreaIndex::Main);
jit::relocate(rel, dstView.cold(), range.cold.begin(), range.cold.end(),
srcView.cold(), fixups, nullptr, AreaIndex::Cold);
if (&srcView.cold() != &srcView.frozen()) {
jit::relocate(rel, dstView.frozen(), range.frozen.begin(),
range.frozen.end(), srcView.frozen(), fixups, nullptr,
AreaIndex::Frozen);
}
} catch (const DataBlockFull& dbFull) {
// Rollback so the area can be used by something else.
maker.rollback();
auto const bytes = range.main.size() + range.cold.size() +
range.frozen.size();
// There should be few of these. They mean there is wasted work
// performing translation for functions that don't have space in the TC.
logPerfWarning("translation_overflow", 1, [&] (StructuredLogEntry& e) {
e.setStr("kind", show(kind));
e.setStr("srckey", show(sk));
e.setStr("data_block", dbFull.name);
e.setInt("bytes_dropped", bytes);
});
reset();
return TranslationResult::failForProcess();
}
transMeta->range = maker.markEnd();
transMeta->view = finalView;
break;
}
}
adjustForRelocation(rel);
adjustMetaDataForRelocation(rel, nullptr, fixups);
adjustCodeForRelocation(rel, fixups);
return std::nullopt;
}
Optional<TranslationResult> Translator::bindOutgoingEdges() {
assertx(transMeta.has_value());
auto& meta = transMeta->fixups;
for (auto& b : meta.smashableBinds) {
// We can't bind to fallback translations, so use the stub. they do not
// exist yet outside of retranslate all, which has a different mechanism
// to achieve that.
if (b.fallback) {
auto const stub = svcreq::getOrEmitStub(
svcreq::StubType::Retranslate, b.sk, b.spOff);
if (stub == nullptr) {
reset();
return TranslationResult::failForProcess();
}
b.smashable.patch(stub);
continue;
}
auto sr = createSrcRec(b.sk, b.spOff);
if (sr == nullptr) {
reset();
return TranslationResult::failForProcess();
}
// If the target is translated, bind it.
if (sr->getTopTranslation()) {
auto srLock = sr->writelock();
if (sr->getTopTranslation()) {
sr->chainFrom(b.smashable);
continue;
}
}
// May need a stub, so create it.
auto const stub = svcreq::getOrEmitStub(
svcreq::StubType::Translate, b.sk, b.spOff);
if (stub == nullptr) {
reset();
return TranslationResult::failForProcess();
}
auto srLock = sr->writelock();
sr->chainFrom(b.smashable, stub);
}
return std::nullopt;
}
TranslationResult Translator::publish() {
assertx(transMeta.has_value());
auto codeLock = lockCode();
auto metaLock = lockMetadata();
publishMetaInternal();
publishCodeInternal();
return TranslationResult{transMeta->range.loc().entry()};
}
void Translator::publishMetaInternal() {
assertx(transMeta.has_value());
this->publishMetaImpl();
}
void Translator::publishCodeInternal() {
assertx(transMeta.has_value());
this->publishCodeImpl();
updateCodeSizeCounters();
}
////////////////////////////////////////////////////////////////////////////////
}}}
| 33.477987 | 81 | 0.646215 | divinity76 |
0e5a9f9bc45f062f0be08f0a18a12e67bb72ddce | 266 | cpp | C++ | tests/ValidPalindromeTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | tests/ValidPalindromeTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | tests/ValidPalindromeTest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "catch.hpp"
#include "ValidPalindrome.hpp"
TEST_CASE("Valid Palindrome") {
ValidPalindrome s;
SECTION("Sample test") {
REQUIRE(s.isPalindrome("A man, a plan, a canal: Panama"));
REQUIRE_FALSE(s.isPalindrome("race a car"));
}
}
| 22.166667 | 66 | 0.646617 | yanzhe-chen |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.