hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
169d114b7698c727df7232e5c53f0f361cdb2488 | 11,361 | cc | C++ | chrome/browser/ui/webui/discards/discards_ui.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/ui/webui/discards/discards_ui.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/ui/webui/discards/discards_ui.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/discards/discards_ui.h"
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/check.h"
#include "base/containers/flat_map.h"
#include "base/notreached.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resource_coordinator/lifecycle_unit.h"
#include "chrome/browser/resource_coordinator/lifecycle_unit_state.mojom.h"
#include "chrome/browser/resource_coordinator/tab_activity_watcher.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h"
#include "chrome/browser/resource_coordinator/tab_manager.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/ui/webui/discards/discards.mojom.h"
#include "chrome/browser/ui/webui/discards/graph_dump_impl.h"
#include "chrome/browser/ui/webui/discards/site_data.mojom-forward.h"
#include "chrome/browser/ui/webui/discards/site_data_provider_impl.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/browser/ui/webui/webui_util.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "components/performance_manager/public/performance_manager.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/resources/grit/ui_resources_map.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace {
discards::mojom::LifecycleUnitVisibility GetLifecycleUnitVisibility(
content::Visibility visibility) {
switch (visibility) {
case content::Visibility::HIDDEN:
return discards::mojom::LifecycleUnitVisibility::HIDDEN;
case content::Visibility::OCCLUDED:
return discards::mojom::LifecycleUnitVisibility::OCCLUDED;
case content::Visibility::VISIBLE:
return discards::mojom::LifecycleUnitVisibility::VISIBLE;
}
#if defined(COMPILER_MSVC)
NOTREACHED();
return discards::mojom::LifecycleUnitVisibility::VISIBLE;
#endif
}
resource_coordinator::LifecycleUnit* GetLifecycleUnitById(int32_t id) {
for (resource_coordinator::LifecycleUnit* lifecycle_unit :
g_browser_process->GetTabManager()->GetSortedLifecycleUnits()) {
if (lifecycle_unit->GetID() == id)
return lifecycle_unit;
}
return nullptr;
}
double GetSiteEngagementScore(content::WebContents* contents) {
// Get the active navigation entry. Restored tabs should always have one.
auto& controller = contents->GetController();
const int current_entry_index = controller.GetCurrentEntryIndex();
// A WebContents which hasn't navigated yet does not have a NavigationEntry.
if (current_entry_index == -1)
return 0;
auto* nav_entry = controller.GetEntryAtIndex(current_entry_index);
DCHECK(nav_entry);
auto* engagement_svc = site_engagement::SiteEngagementService::Get(
Profile::FromBrowserContext(contents->GetBrowserContext()));
return engagement_svc->GetDetails(nav_entry->GetURL()).total_score;
}
class DiscardsDetailsProviderImpl : public discards::mojom::DetailsProvider {
public:
// This instance is deleted when the supplied pipe is destroyed.
explicit DiscardsDetailsProviderImpl(
mojo::PendingReceiver<discards::mojom::DetailsProvider> receiver)
: receiver_(this, std::move(receiver)) {}
~DiscardsDetailsProviderImpl() override {}
// discards::mojom::DetailsProvider overrides:
void GetTabDiscardsInfo(GetTabDiscardsInfoCallback callback) override {
resource_coordinator::TabManager* tab_manager =
g_browser_process->GetTabManager();
const resource_coordinator::LifecycleUnitVector lifecycle_units =
tab_manager->GetSortedLifecycleUnits();
std::vector<discards::mojom::TabDiscardsInfoPtr> infos;
infos.reserve(lifecycle_units.size());
const base::TimeTicks now = resource_coordinator::NowTicks();
// Convert the LifecycleUnits to a vector of TabDiscardsInfos.
size_t rank = 1;
for (auto* lifecycle_unit : lifecycle_units) {
discards::mojom::TabDiscardsInfoPtr info(
discards::mojom::TabDiscardsInfo::New());
resource_coordinator::TabLifecycleUnitExternal*
tab_lifecycle_unit_external =
lifecycle_unit->AsTabLifecycleUnitExternal();
content::WebContents* contents =
tab_lifecycle_unit_external->GetWebContents();
info->tab_url = contents->GetLastCommittedURL().spec();
info->title = base::UTF16ToUTF8(lifecycle_unit->GetTitle());
info->visibility =
GetLifecycleUnitVisibility(lifecycle_unit->GetVisibility());
info->loading_state = lifecycle_unit->GetLoadingState();
info->state = lifecycle_unit->GetState();
resource_coordinator::DecisionDetails discard_details;
info->cannot_discard_reasons = discard_details.GetFailureReasonStrings();
info->discard_reason = lifecycle_unit->GetDiscardReason();
info->discard_count = lifecycle_unit->GetDiscardCount();
info->utility_rank = rank++;
const base::TimeTicks last_focused_time =
lifecycle_unit->GetLastFocusedTime();
const base::TimeDelta elapsed =
(last_focused_time == base::TimeTicks::Max())
? base::TimeDelta()
: (now - last_focused_time);
info->last_active_seconds = static_cast<int32_t>(elapsed.InSeconds());
info->is_auto_discardable =
tab_lifecycle_unit_external->IsAutoDiscardable();
info->id = lifecycle_unit->GetID();
absl::optional<float> reactivation_score =
resource_coordinator::TabActivityWatcher::GetInstance()
->CalculateReactivationScore(contents);
info->has_reactivation_score = reactivation_score.has_value();
if (info->has_reactivation_score)
info->reactivation_score = reactivation_score.value();
info->site_engagement_score = GetSiteEngagementScore(contents);
info->state_change_time =
lifecycle_unit->GetStateChangeTime() - base::TimeTicks::UnixEpoch();
// TODO(crbug.com/876340): The focus is used to compute the page lifecycle
// state. This should be replaced with the actual page lifecycle state
// information from Blink, but this depends on implementing the passive
// state and plumbing it to the browser.
info->has_focus = lifecycle_unit->GetLastFocusedTime().is_max();
infos.push_back(std::move(info));
}
std::move(callback).Run(std::move(infos));
}
void SetAutoDiscardable(int32_t id,
bool is_auto_discardable,
SetAutoDiscardableCallback callback) override {
auto* lifecycle_unit = GetLifecycleUnitById(id);
if (lifecycle_unit) {
auto* tab_lifecycle_unit_external =
lifecycle_unit->AsTabLifecycleUnitExternal();
if (tab_lifecycle_unit_external)
tab_lifecycle_unit_external->SetAutoDiscardable(is_auto_discardable);
}
std::move(callback).Run();
}
void DiscardById(int32_t id,
DiscardByIdCallback callback) override {
auto* lifecycle_unit = GetLifecycleUnitById(id);
if (lifecycle_unit)
lifecycle_unit->Discard(mojom::LifecycleUnitDiscardReason::URGENT);
std::move(callback).Run();
}
void LoadById(int32_t id) override {
auto* lifecycle_unit = GetLifecycleUnitById(id);
if (lifecycle_unit)
lifecycle_unit->Load();
}
void Discard(DiscardCallback callback) override {
resource_coordinator::TabManager* tab_manager =
g_browser_process->GetTabManager();
tab_manager->DiscardTab(mojom::LifecycleUnitDiscardReason::URGENT);
std::move(callback).Run();
}
private:
mojo::Receiver<discards::mojom::DetailsProvider> receiver_;
DISALLOW_COPY_AND_ASSIGN(DiscardsDetailsProviderImpl);
};
} // namespace
DiscardsUI::DiscardsUI(content::WebUI* web_ui)
: ui::MojoWebUIController(web_ui) {
std::unique_ptr<content::WebUIDataSource> source(
content::WebUIDataSource::Create(chrome::kChromeUIDiscardsHost));
source->OverrideContentSecurityPolicy(
network::mojom::CSPDirectiveName::ScriptSrc,
"script-src chrome://resources chrome://test 'self';");
source->DisableTrustedTypesCSP();
const webui::ResourcePath kResources[] = {
{"discards.js", IDR_DISCARDS_JS},
{"discards_main.js", IDR_DISCARDS_DISCARDS_MAIN_JS},
{"database_tab.js", IDR_DISCARDS_DATABASE_TAB_JS},
{"discards_tab.js", IDR_DISCARDS_DISCARDS_TAB_JS},
{"sorted_table_behavior.js", IDR_DISCARDS_SORTED_TABLE_BEHAVIOR_JS},
{"graph_tab.js", IDR_DISCARDS_GRAPH_TAB_JS},
// Full paths (relative to source) for mojom generated files.
{"chrome/browser/ui/webui/discards/discards.mojom-webui.js",
IDR_DISCARDS_MOJOM_WEBUI_JS},
{"chrome/browser/resource_coordinator/"
"lifecycle_unit_state.mojom-webui.js",
IDR_DISCARDS_LIFECYCLE_UNIT_STATE_MOJOM_WEBUI_JS},
{"chrome/browser/ui/webui/discards/site_data.mojom-webui.js",
IDR_DISCARDS_SITE_DATA_MOJOM_WEBUI_JS},
};
webui::SetupWebUIDataSource(source.get(), kResources, IDR_DISCARDS_HTML);
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, source.release());
content::URLDataSource::Add(
profile, std::make_unique<FaviconSource>(
profile, chrome::FaviconUrlFormat::kFavicon2));
profile_id_ = profile->UniqueId();
}
WEB_UI_CONTROLLER_TYPE_IMPL(DiscardsUI)
DiscardsUI::~DiscardsUI() {}
void DiscardsUI::BindInterface(
mojo::PendingReceiver<discards::mojom::DetailsProvider> receiver) {
ui_handler_ =
std::make_unique<DiscardsDetailsProviderImpl>(std::move(receiver));
}
void DiscardsUI::BindInterface(
mojo::PendingReceiver<discards::mojom::SiteDataProvider> receiver) {
if (performance_manager::PerformanceManager::IsAvailable()) {
// Forward the interface receiver directly to the service.
performance_manager::PerformanceManager::CallOnGraph(
FROM_HERE, base::BindOnce(&SiteDataProviderImpl::CreateAndBind,
std::move(receiver), profile_id_));
}
}
void DiscardsUI::BindInterface(
mojo::PendingReceiver<discards::mojom::GraphDump> receiver) {
if (performance_manager::PerformanceManager::IsAvailable()) {
// Forward the interface receiver directly to the service.
performance_manager::PerformanceManager::CallOnGraph(
FROM_HERE, base::BindOnce(&DiscardsGraphDumpImpl::CreateAndBind,
std::move(receiver)));
}
}
| 40.72043 | 80 | 0.739988 | [
"vector"
] |
169d2d79d74ddc0cc2594a97652486cb4286d59d | 1,922 | hpp | C++ | src/game/world/level_model.hpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/game/world/level_model.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/game/world/level_model.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #pragma once
#include "math/vector.hpp"
#include "math/color.hpp"
#include "libold/content/assets/level.hpp"
#include "ecs/entity_component_system.hpp"
#include "components/thing.hpp"
#include "surface.hpp"
#include "jk/cog/vm/executor.hpp"
#include "game/world/sounds/sound_model.hpp"
#include "game/world/camera/camera_model.hpp"
#include "value_mapping.hpp"
#include <vector>
namespace gorc {
namespace game {
namespace world {
class level_model {
public:
asset_ref<content::assets::level> level;
content::assets::level_header header;
std::vector<content::assets::level_adjoin> adjoins;
std::vector<surface> surfaces;
std::vector<content::assets::level_sector> sectors;
service_registry services;
entity_component_system<thing_id> ecs;
cog::executor script_model;
sounds::sound_model sound_model;
camera::camera_model camera_model;
world_value_mapping value_mapping;
thing_id local_player_thing_id;
std::vector<content::assets::thing_template const*> spawn_points;
size_t current_spawn_point = 0UL;
double level_time = 0.0;
double game_time = 0.0;
color_rgb dynamic_tint = make_color(0.0f, 0.0f, 0.0f);
level_model(content_manager& manager, service_registry const &,
asset_ref<content::assets::level> level);
components::thing& get_thing(thing_id id);
cog::source_type get_thing_source_type(cog::value id);
// Level specific send_to_linked wrapper.
// Automatically includes correct source type and calls thing class/capture cogs.
void send_to_linked(cog::message_type msg,
cog::value sender,
cog::value source,
cog::value param0 = cog::value(),
cog::value param1 = cog::value(),
cog::value param2 = cog::value(),
cog::value param3 = cog::value());
};
}
}
}
| 29.569231 | 85 | 0.676379 | [
"vector"
] |
169fdbafc93729e53eedb7bd383465eb11da0b8a | 6,635 | cpp | C++ | src/xray/editor/world/sources/property_vec3f_base.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/editor/world/sources/property_vec3f_base.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/editor/world/sources/property_vec3f_base.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 29.12.2007
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "property_vec3f_base.h"
#include "property_container.h"
#include "property_float_limited.h"
using System::Object;
using System::String;
using Flobbster::Windows::Forms::PropertySpec;
using System::Collections::DictionaryEntry;
ref class property_converter_float;
vec3f_components::vec3f_components (property_vec3f_base^ holder) :
m_holder (holder)
{
}
float vec3f_components::x_getter ()
{
return (m_holder->get_value_raw().x);
}
void vec3f_components::x_setter (float value)
{
m_holder->x (value);
}
float vec3f_components::y_getter ()
{
return (m_holder->get_value_raw().y);
}
void vec3f_components::y_setter (float value)
{
m_holder->y (value);
}
float vec3f_components::z_getter ()
{
return (m_holder->get_value_raw().z);
}
void vec3f_components::z_setter (float value)
{
m_holder->z (value);
}
property_vec3f_base::property_vec3f_base (float3 const% vec3f,
property_holder::readonly_enum read_only,
property_holder::notify_parent_on_change_enum notify_parent,
property_holder::password_char_enum password,
property_holder::refresh_grid_on_change_enum refresh_grid)
{
XRAY_UNREFERENCED_PARAMETER ( notify_parent );
m_container = gcnew property_container_Vec3f(nullptr, this);
m_components = gcnew vec3f_components(this);
m_container->add_property (
gcnew PropertySpec(
"x",
float::typeid,
"components",
"X component",
vec3f.x,
(String^)nullptr,
property_converter_float::typeid
),
gcnew property_float(
gcnew float_getter_type(m_components, &vec3f_components::x_getter),
gcnew float_setter_type(m_components, &vec3f_components::x_setter),
.01f
),
read_only,
property_holder::notify_parent_on_change,
password,
refresh_grid
);
m_container->add_property (
gcnew PropertySpec(
"y",
float::typeid,
"components",
"Y component",
vec3f.y,
(String^)nullptr,
property_converter_float::typeid
),
gcnew property_float(
gcnew float_getter_type(m_components, &vec3f_components::y_getter),
gcnew float_setter_type(m_components, &vec3f_components::y_setter),
.01f
),
read_only,
property_holder::notify_parent_on_change,
password,
refresh_grid
);
m_container->add_property (
gcnew PropertySpec(
"z",
float::typeid,
"components",
"Z component",
vec3f.z,
(String^)nullptr,
property_converter_float::typeid
),
gcnew property_float(
gcnew float_getter_type(m_components, &vec3f_components::z_getter),
gcnew float_setter_type(m_components, &vec3f_components::z_setter),
.01f
),
read_only,
property_holder::notify_parent_on_change,
password,
refresh_grid
);
}
property_vec3f_base::~property_vec3f_base ()
{
this->!property_vec3f_base();
}
property_vec3f_base::!property_vec3f_base ()
{
delete (m_container);
}
Object^ property_vec3f_base::get_value ()
{
return (m_container);
}
void property_vec3f_base::set_value (Object ^object)
{
Vec3f vec3f = safe_cast<Vec3f>(object);
float3 value;
value.x = vec3f.x;
value.y = vec3f.y;
value.z = vec3f.z;
set_value_raw (value);
}
void property_vec3f_base::x (float value)
{
float3 current = get_value_raw();
current.x = value;
set_value_raw (current);
}
void property_vec3f_base::y (float value)
{
float3 current = get_value_raw();
current.y = value;
set_value_raw (current);
}
void property_vec3f_base::z (float value)
{
float3 current = get_value_raw();
current.z = value;
set_value_raw (current);
}
//vec2f
vec2f_components::vec2f_components (property_vec2f_base^ holder) :
m_holder (holder)
{
}
float vec2f_components::x_getter ()
{
return (m_holder->get_value_raw().x);
}
void vec2f_components::x_setter (float value)
{
m_holder->x (value);
}
float vec2f_components::y_getter ()
{
return (m_holder->get_value_raw().y);
}
void vec2f_components::y_setter (float value)
{
m_holder->y (value);
}
property_vec2f_base::property_vec2f_base (float2 const% vec2f,
property_holder::readonly_enum read_only,
property_holder::notify_parent_on_change_enum notify_parent,
property_holder::password_char_enum password,
property_holder::refresh_grid_on_change_enum refresh_grid)
{
XRAY_UNREFERENCED_PARAMETER ( notify_parent );
m_container = gcnew property_container_Vec2f(nullptr, this);
m_components = gcnew vec2f_components(this);
m_container->add_property (
gcnew PropertySpec(
"x",
float::typeid,
"components",
"X component",
vec2f.x,
(String^)nullptr,
property_converter_float::typeid
),
gcnew property_float(
gcnew float_getter_type(m_components, &vec2f_components::x_getter),
gcnew float_setter_type(m_components, &vec2f_components::x_setter),
.01f
),
read_only,
property_holder::notify_parent_on_change,
password,
refresh_grid
);
m_container->add_property (
gcnew PropertySpec(
"y",
float::typeid,
"components",
"Y component",
vec2f.y,
(String^)nullptr,
property_converter_float::typeid
),
gcnew property_float(
gcnew float_getter_type(m_components, &vec2f_components::y_getter),
gcnew float_setter_type(m_components, &vec2f_components::y_setter),
.01f
),
read_only,
property_holder::notify_parent_on_change,
password,
refresh_grid
);
}
property_vec2f_base::~property_vec2f_base ()
{
this->!property_vec2f_base();
}
property_vec2f_base::!property_vec2f_base ()
{
delete (m_container);
}
Object^ property_vec2f_base::get_value ()
{
return (m_container);
}
void property_vec2f_base::set_value (Object ^object)
{
Vec2f vec2f = safe_cast<Vec2f>(object);
float2 value;
value.x = vec2f.x;
value.y = vec2f.y;
set_value_raw (value);
}
void property_vec2f_base::x (float value)
{
float2 current = get_value_raw();
current.x = value;
set_value_raw (current);
}
void property_vec2f_base::y (float value)
{
float2 current = get_value_raw();
current.y = value;
set_value_raw (current);
} | 22.722603 | 77 | 0.666767 | [
"object"
] |
16a5b468076f7fb4dfb67bdd05a410b4b71c0bd5 | 1,890 | cc | C++ | src/cuts/Trainingcut.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | 3 | 2020-01-16T17:15:54.000Z | 2020-01-17T10:59:39.000Z | src/cuts/Trainingcut.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | null | null | null | src/cuts/Trainingcut.cc | vbertone/NangaParbat | 49529d0a2e810dfe0ec676c8e96081be39a8800d | [
"MIT"
] | 3 | 2020-01-18T22:10:02.000Z | 2020-08-01T18:42:36.000Z | //
// Authors: Valerio Bertone: valerio.bertone@cern.ch
//
#include "NangaParbat/Trainingcut.h"
namespace NangaParbat
{
//_________________________________________________________________________________
TrainingCut::TrainingCut(DataHandler const& dataset,
std::vector<std::shared_ptr<NangaParbat::Cut>> const& kincuts,
double const& TrainingFrac,
gsl_rng* rng,
int const& NMin):
Cut{dataset, TrainingFrac, 1 - TrainingFrac},
_rng(rng),
_NMin(NMin)
{
_mask.resize(dataset.GetBinning().size(), true);
for (auto const& c : kincuts)
_mask *= c->GetMask();
EnforceCut();
}
//_________________________________________________________________________________
TrainingCut::TrainingCut(TrainingCut const& cut, bool const& invert, std::vector<std::shared_ptr<NangaParbat::Cut>> const& kincuts):
Cut{cut},
_rng(nullptr),
_NMin(cut._NMin)
{
if (invert)
_mask = !_mask;
for (auto const& c : kincuts)
_mask *= c->GetMask();
}
//_________________________________________________________________________________
void TrainingCut::EnforceCut()
{
const int Ndat_aftercut = std::count(std::begin(_mask), std::end(_mask), true);
if (Ndat_aftercut <= _NMin || _min == 1)
return;
std::vector<bool> random_mask(floor(Ndat_aftercut * ( 1 - _min )), false);
random_mask.resize(Ndat_aftercut, true);
std::random_shuffle(random_mask.begin(), random_mask.end(), [=] (long unsigned n) -> long unsigned { return gsl_rng_uniform_int(_rng, n); });
int j = 0;
for (bool & m : _mask)
m = (m ? random_mask[j++] : m);
}
}
| 35.660377 | 145 | 0.593122 | [
"vector"
] |
16aaf66ea9fd5d0e7e5969cd7b9b20cbb79f66df | 2,016 | cpp | C++ | modules/demos/painlessmesh-start.cpp | ipepe-oss/esp32-elm327-cruise-control | cf7c35d64e3bdaf639f447505cf2a0a3c967c471 | [
"MIT"
] | 2 | 2021-08-04T13:41:09.000Z | 2022-01-06T00:26:34.000Z | modules/demos/painlessmesh-start.cpp | ipepe-oss/esp32-elm327-cruise-control | cf7c35d64e3bdaf639f447505cf2a0a3c967c471 | [
"MIT"
] | null | null | null | modules/demos/painlessmesh-start.cpp | ipepe-oss/esp32-elm327-cruise-control | cf7c35d64e3bdaf639f447505cf2a0a3c967c471 | [
"MIT"
] | null | null | null | /*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp-mesh-esp32-esp8266-painlessmesh/
This is a simple example that uses the painlessMesh library: https://github.com/gmag11/painlessMesh/blob/master/examples/basic/basic.ino
*/
#include "painlessMesh.h"
#define MESH_PREFIX "whateverYouLike"
#define MESH_PASSWORD "somethingSneaky"
#define MESH_PORT 5555
Scheduler userScheduler; // to control your personal task
painlessMesh mesh;
// User stub
void sendMessage() ; // Prototype so PlatformIO doesn't complain
Task taskSendMessage( TASK_SECOND * 1 , TASK_FOREVER, &sendMessage );
void sendMessage() {
String msg = "Hi from node1";
msg += mesh.getNodeId();
mesh.sendBroadcast( msg );
taskSendMessage.setInterval( random( TASK_SECOND * 1, TASK_SECOND * 5 ));
}
// Needed for painless library
void receivedCallback( uint32_t from, String &msg ) {
Serial.printf("startHere: Received from %u msg=%s\n", from, msg.c_str());
}
void newConnectionCallback(uint32_t nodeId) {
Serial.printf("--> startHere: New Connection, nodeId = %u\n", nodeId);
}
void changedConnectionCallback() {
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset) {
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(),offset);
}
void setup() {
Serial.begin(115200);
//mesh.setDebugMsgTypes( ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE ); // all types on
mesh.setDebugMsgTypes( ERROR | STARTUP ); // set before init() so that you can see startup messages
mesh.init( MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT );
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
userScheduler.addTask( taskSendMessage );
taskSendMessage.enable();
}
void loop() {
// it will run the user scheduler as well
mesh.update();
} | 31.015385 | 138 | 0.738095 | [
"mesh"
] |
16ab92f23fb30cc767f266c1cce563f6cf309b09 | 2,426 | cpp | C++ | sources/window_functions.cpp | indjev99/Pong | bb5eb346c025172f21bf537ba47501ad55fe3f3f | [
"MIT"
] | null | null | null | sources/window_functions.cpp | indjev99/Pong | bb5eb346c025172f21bf537ba47501ad55fe3f3f | [
"MIT"
] | null | null | null | sources/window_functions.cpp | indjev99/Pong | bb5eb346c025172f21bf537ba47501ad55fe3f3f | [
"MIT"
] | null | null | null | #include "../headers/window_functions.h"
#include "../headers/window_size.h"
#include<iostream>
#include<queue>
std::queue<int> presses;
int pressed;
double mxpos=0,mypos=0;
bool paused=0;
int p1M=0;
int p2M=0;
void errorCallback(int error, const char* description)
{
std::cout<<error<<": "<<description<<std::endl;
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
//if (key==GLFW_KEY_ESCAPE && action==GLFW_PRESS) glfwSetWindowShouldClose(window,1);
if (key==GLFW_KEY_W && action==GLFW_PRESS) p1M+=1;
if (key==GLFW_KEY_W && action==GLFW_RELEASE) p1M-=1;
if (key==GLFW_KEY_S && action==GLFW_PRESS) p1M-=1;
if (key==GLFW_KEY_S && action==GLFW_RELEASE) p1M+=1;
if (key==GLFW_KEY_UP && action==GLFW_PRESS) p2M+=1;
if (key==GLFW_KEY_UP && action==GLFW_RELEASE) p2M-=1;
if (key==GLFW_KEY_DOWN && action==GLFW_PRESS) p2M-=1;
if (key==GLFW_KEY_DOWN && action==GLFW_RELEASE) p2M+=1;
if (key==GLFW_KEY_P && action==GLFW_PRESS)
{
paused=!paused;
}
}
void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (action==GLFW_PRESS)
{
pressed=button;
glfwGetCursorPos(window,&mxpos,&mypos);
mxpos=mxpos*2-WINDOWS_WIDTH;
mypos=-mypos*2+WINDOWS_HEIGHT;
mxpos/=ORIGINAL_WINDOWS_HEIGHT;
mypos/=ORIGINAL_WINDOWS_HEIGHT;
}
}
void windowSizeCallback(GLFWwindow* window, int width, int height)
{
WINDOWS_WIDTH=width;
WINDOWS_HEIGHT=height;
pressed=-2;
}
std::string setCallbacks(GLFWwindow* w)
{
glfwSetErrorCallback(errorCallback);
glfwSetKeyCallback(w,keyCallback);
glfwSetMouseButtonCallback(w,mouseButtonCallback);
glfwSetWindowSizeCallback(w,windowSizeCallback);
return "Callbacks for game window set successfully.";
}
std::string initializeGLFW()
{
if (!glfwInit())
return "Unable to initialize GLFW.";
return "GLFW initialized successfully.";
}
std::string createWindow(GLFWwindow*& w)
{
std::string name;
name="Ping Pong";
w=glfwCreateWindow(WINDOWS_WIDTH,WINDOWS_HEIGHT,name.c_str(),NULL,NULL);
if (!w)
{
glfwTerminate();
return "Unable to create game window.";
}
return "Game window created successfully.";
}
void stopGraphics(std::vector<GLFWwindow*> w)
{
for (int i=0;i<w.size();++i)
{
glfwDestroyWindow(w[i]);
}
glfwTerminate();
}
| 27.568182 | 89 | 0.674773 | [
"vector"
] |
16abc08c338332bf9298cee01eb064eaf777c592 | 14,513 | cpp | C++ | pacman.cpp | jatinverma12/PacMan | 6168c79b708b1091c78e6b6fdfb7ef041699e2f3 | [
"MIT"
] | null | null | null | pacman.cpp | jatinverma12/PacMan | 6168c79b708b1091c78e6b6fdfb7ef041699e2f3 | [
"MIT"
] | null | null | null | pacman.cpp | jatinverma12/PacMan | 6168c79b708b1091c78e6b6fdfb7ef041699e2f3 | [
"MIT"
] | 2 | 2021-01-13T07:33:41.000Z | 2021-01-13T10:37:05.000Z | #ifdef __APPLE__
#include <GLUT/glut.h> // if we are on a Mac
#else
#include <GL/glut.h> // on linux
#endif
#include <math.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <png.h>
#include <stdlib.h>
#include <vector>
#include <fstream>
// User- Defined header files
#include "png_load.h"
#include "load_and_bind_texture.h"
#include "textures.h"
#include "maze.h"
#include "base.h"
#include "pacman.h"
#include "ghost.h"
#include "interface.h"
int gameTick = 0;
int deathTick = 0;
int frightenTick = 0;
int timestamp;
int score = 0;
int pills = 244;
int lives = 3;
int eatenCount = 0;
bool frighten;
float eatenX;
float eatenY;
int eatStamp;
Pacman pacman;
bool paused = false;
bool dead = false;
int fruitCounter = 0;
int tempFruitCounter = 0;
int eatFruitStamp = 0;
int eatenFruitX;
int eatenFruitY;
int fruitSpawned = 0;
using namespace std;
// Decleration of each of the ghosts.at their respective starting X and Y coordinates and their colour.
Ghost ghosts[4] = {
Ghost(13.5f, 19.0f, RED),
Ghost(11.5f, 16.0f, BLUE),
Ghost(13.5f, 16.0f, PINK),
Ghost(15.5f, 16.0f, YELLOW),
};
typedef enum {BEGIN, PLAY, DIE, OVER} gameState; // Enum defining each of the states the game can be in
gameState stateGame = BEGIN; // Initially the game in begin mode
void detectPill()
// Detects whether the pill is Bigg pill(O), then ghosts go to Frigthen mode or if pill is Fruit
{
if(pacman.getTile(pacman.get_X(), pacman.get_Y()) == O)
{
frighten = true; // Set the flag to know that frigthen mode is on
frightenTick = 0; // Set the counter to 0
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() == CHASE || ghosts[i].get_moveType() == SCATTER)
{
ghosts[i].set_eaten(false);
ghosts[i].set_moveType(FRIGHTEN);
if(ghosts[i].get_currentDir() == LEFT)
ghosts[i].set_currentDir(RIGHT);
else if(ghosts[i].get_currentDir() == UP)
ghosts[i].set_currentDir(DOWN);
else if(ghosts[i].get_currentDir() == RIGHT)
ghosts[i].set_currentDir(LEFT);
else
ghosts[i].set_currentDir(UP);
}
}
}
else if(pacman.getTile(pacman.get_X(), pacman.get_Y()) == F)
{
eatenFruitX = pacman.get_X();
eatenFruitY = pacman.get_Y();
}
}
void detectGhost()
// Check if Pacman has encountered a Ghost (i.e. both are on the same tile)
{
// Check pacmans position against all of the ghosts
for(int i = 0; i < 4; i++)
{
if(pacman.get_X() == ghosts[i].get_X() && pacman.get_Y() == ghosts[i].get_Y())
// If he is on the same tile as any ghost
{
if(ghosts[i].get_moveType() != FRIGHTEN && ghosts[i].get_moveType() != DEATH) // Check if they are in a mode which can eat Pacman
{
// Execute the DIE gameType as the ghost has caught pacman
stateGame = DIE;
timestamp = gameTick;
}
else {
if(!ghosts[i].check_eaten())
// Check the ghost hasnt already been eaten
{
eatenCount++;
eatStamp = gameTick;
switch(eatenCount)
// Check what eaten number the ghost is in order to increment the score correctly
{
case 1: score += 200;
break;
case 2: score += 400;
break;
case 3: score += 800;
break;
case 4: score += 1600;
break;
}
// Store the position of the eating in order to draw the eating score tex in the correct place
eatenX = ghosts[i].get_X();
eatenY = ghosts[i].get_Y();
ghosts[i].set_eaten(true); // Set the flag for that specifc ghost to have been eaten so it cannot be eaten again in this frighten cycle
}
ghosts[i].set_moveType(DEATH); // Set the ghosts mode to DEATh as it has been eaten
}
}
}
if(stateGame == DIE && !dead)
// Check to see if pacman was indeed caught by the ghost and if so take away a life
{
lives--;
dead = true;
}
}
void setMode()
// Sets the ghosts movement technique depending on what the gameTick is
{
if(gameTick >= 4450)
{
for (int i = 0; i < 4; i++)
{
if (ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
// As long as the ghosts are only in SCATTER or CHASE and frighten mode is not on
ghosts[i].set_moveType(CHASE); // Set the correct move type for all ghosts
}
}
else if(gameTick >= 4200)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(SCATTER);
}
}
else if(gameTick >= 3200)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(CHASE);
}
}
else if(gameTick >= 2950)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(SCATTER);
}
}
else if(gameTick >= 1950)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(CHASE);
}
}
else if (gameTick >= 1600)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(SCATTER);
}
}
else if(gameTick >= 600)
{
for(int i = 0; i < 4; i++)
{
if(ghosts[i].get_moveType() != PEN && ghosts[i].get_moveType() != LEAVE && !frighten && ghosts[i].get_moveType() != DEATH)
ghosts[i].set_moveType(CHASE);
}
}
}
void idle()
// All options are altered when game is in idle state
{
if(!paused)
{ // If the game is not paused
switch (stateGame)
// Check what state the game is in
{
case BEGIN:
if (gameTick >= 250)
// After a certain amount of time switch the game into PLAY mode
stateGame = PLAY;
break;
case PLAY:
setMode(); // Set the movement mode for Ghosts
detectPill(); // Check if pacman has eaten a super pill
pacman.checkTile(); // Check if pacman has eaten a regular pill to increase score if he is in a portal
detectGhost(); // Check if pacman has hit a ghost
pacman.move(); // Move pacman in the maze
detectGhost();
// Move the ghosts in the maze
for (int i = 0; i < 4; i++)
{
ghosts[i].move(ghosts[0]);
}
detectGhost();
// If frighten mode is on and not expired, increment the counter
if (frightenTick <= 450 && frighten)
frightenTick++;
else if (frighten)
// If frighten mode is on but needs to expire, run correct expirary code
{
frighten = false;
eatenCount = 0;
frightenTick = 0;
for (int i = 0; i < 4; i++)
{
if (ghosts[i].get_moveType() == FRIGHTEN)
ghosts[i].set_eaten(false);
}
setMode(); // Set the ghosts back into the correct mode after frighten mode has finished
}
if (pills <= 0)
// If all the pills have been eaten reset the level so pacman can continue
{
fruitReset();
resetMaze();
pacman.reset();
pills = 244;
fruitSpawned = 0;
fruitCounter = 0;
tempFruitCounter = 0;
for (int i = 0; i < 4; i++) {
ghosts[i].reset();
}
gameTick = 0;
stateGame = BEGIN;
}
break;
case DIE:
if (gameTick - timestamp >= 150)
// Play pacmans death animation
deathTick++;
break;
}
gameTick++;
glutPostRedisplay(); // Force a redraw at the end
}
}
void special(int key, int, int)
// to handle special keys such as directions and assign them
{
switch (key)
{
case GLUT_KEY_LEFT: pacman.setDirStore(LEFT); // If left key press set pacmans next direction to left
break;
case GLUT_KEY_UP: pacman.setDirStore(UP); // If up key press set pacmans next direction to up
break;
case GLUT_KEY_RIGHT: pacman.setDirStore(RIGHT); // If right key press set pacmans next direction to right
break;
case GLUT_KEY_DOWN: pacman.setDirStore(DOWN); // If down key press set pacmans next direction to down
break;
}
}
void init()
// Method run at the very beginning to initiale certain aspects of the game
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 300, 0, 300);
loadAndBindTextures();
}
void display()
// Function to display objects on the screen (using draw)
{
glClear (GL_COLOR_BUFFER_BIT);
switch(stateGame)
// Check what state the game is in
{
case BEGIN:
drawMaze();
pacman.draw();
for(int i = 0; i < 4; i++)
ghosts[i].draw();
drawInterface();
drawReady();
break;
case PLAY:
drawMaze();
pacman.draw();
if(pills <= 174 && fruitSpawned == 0)
locationFruit();
if(pills <= 74 && fruitSpawned == 1)
locationFruit();
if(fruitCounter > tempFruitCounter)
eatFruitStamp = gameTick;
if(gameTick - eatFruitStamp <= 200)
eatFruitScore(eatenFruitX, eatenFruitY);
for(int i = 0; i < 4; i++)
{
ghosts[i].draw();
if(frighten && gameTick - eatStamp <= 200)
ghosts[i].drawEatScore(eatenX, eatenY);
}
drawInterface();
tempFruitCounter = fruitCounter;
break;
case DIE:
fruitReset();
drawMaze();
if(gameTick - timestamp < 150)
// Freeze pacman momentarily after he is hit by a ghost
{
pacman.draw();
for(int i = 0; i < 4; i++)
ghosts[i].draw();
}
if(gameTick - timestamp >= 150 && deathTick < 110)
// After that time has passed play pacmans death animation
pacman.death();
if(gameTick - timestamp >= 310)
// After the death animation, reset pacman
{
pacman.reset();
for(int i = 0; i < 4; i++)
ghosts[i].reset(); // Reset the ghosts also
gameTick = 0;
eatFruitStamp = -9999999;
deathTick = 0;
if(lives > 0)
// If pacman has lives left begin the game again
stateGame = BEGIN;
else
{
// Otherwise show the gameover screen
setHighScore(score); // If the game is finished check if the high score needs to be updated
stateGame = OVER;
}
}
drawInterface();
break;
case OVER:
drawMaze();
drawInterface();
drawGameOver();
}
glutSwapBuffers(); // Force a redraw at the end
}
void resetGame()
// Function to reset the game if the player wants to play the game again
{
gameTick = 0;
deathTick = 0;
score = 0;
lives = 4;
pills = 244;
fruitCounter = 0;
fruitSpawned = 0;
tempFruitCounter = 0;
stateGame = BEGIN;
}
void keyboard(unsigned char key, int, int)
// Function to assign keyboard buttons other than special ones
{
switch (key)
{
case 'q': exit(1); // quit!
case 'p':// Key to pause the game
if(paused)
paused = false;
else
paused = true;
break;
case 'r':
if(stateGame == OVER)
{
resetGame();
pacman.reset();
fruitReset();
resetMaze();
for(int i = 0; i < 4; i++)
ghosts[i].reset(); // Reset the ghosts also
}
break;
}
glutPostRedisplay(); // force a redraw
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv); // we can pass certain X windows attributes to GLUT
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(750,725);
glutCreateWindow("Pacman"); // a named window of default size and position
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutSpecialFunc(special);
glutIdleFunc(idle);
init();
glutMainLoop(); // go into the main loop and wait for window events...
return 0; // safe to return 0 to shell unless error
}
| 32.037528 | 155 | 0.502308 | [
"vector"
] |
16ae45d11a7270bf329612a33b8f881585e1c8e5 | 1,526 | cpp | C++ | Algorithms/1260.Shift2DGrid/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/1260.Shift2DGrid/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/1260.Shift2DGrid/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
std::vector<std::vector<int>> shiftGrid(std::vector<std::vector<int>> const &grid, int k) const
{
const size_t rowCount = grid.size();
const size_t columnCount = grid.front().size();
std::vector<int> data;
data.reserve(rowCount * columnCount);
for (size_t row = 0; row < rowCount; ++row)
{
for (size_t column = 0; column < columnCount; ++column)
{
data.push_back(grid[row][column]);
}
}
std::vector<std::vector<int>> result(rowCount, std::vector<int>(columnCount, 0));
for (size_t index = 0; index < data.size(); ++index)
{
const size_t shiftedIndex = (index + k) % data.size();
result[shiftedIndex / columnCount][shiftedIndex % columnCount] = data[index];
}
return result;
}
};
}
namespace Shift2DGridTask
{
TEST(Shift2DGridTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<std::vector<int>>({{9, 1, 2}, {3, 4, 5}, {6, 7, 8}}), solution.shiftGrid({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 1));
ASSERT_EQ(std::vector<std::vector<int>>({{12, 0, 21, 13}, {3, 8, 1, 9}, {19, 7, 2, 5}, {4, 6, 11, 10}}), solution.shiftGrid({{3, 8, 1, 9}, {19, 7, 2, 5}, {4, 6, 11, 10}, {12, 0, 21, 13}}, 4));
ASSERT_EQ(std::vector<std::vector<int>>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}), solution.shiftGrid({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 9));
}
} | 32.468085 | 196 | 0.544561 | [
"vector"
] |
16aee438603f93eeee970e67933c3a555d1918b8 | 1,017 | cpp | C++ | GameSystem/ostream.cpp | Popcron-s/BaseFramework | c2746748531c4912ea2b400cc0d77131ca2934d8 | [
"Unlicense"
] | null | null | null | GameSystem/ostream.cpp | Popcron-s/BaseFramework | c2746748531c4912ea2b400cc0d77131ca2934d8 | [
"Unlicense"
] | null | null | null | GameSystem/ostream.cpp | Popcron-s/BaseFramework | c2746748531c4912ea2b400cc0d77131ca2934d8 | [
"Unlicense"
] | null | null | null | #include "ostream.h"
_oStream* _oStream::m_pSingleton = 0x00;
CREATE_LIST_FUNTION(_oStream,_CCamera,Camera);
_oStream::_oStream() :
m_Size_x(0), m_Size_y(0),
m_Camera_List(0x00), m_Camera_num(0)
{}
_oStream::~_oStream(){
ReleaseAllCamera();
}
UINT _oStream::GetSizeX() const{return m_Size_x;}
UINT _oStream::GetSizeY() const{return m_Size_y;}
void _oStream::SetSize(UINT x, UINT y){m_Size_x = x; m_Size_y = y;}
void _oStream::render_graphic(){
_LIST<_CCamera>* t_node = m_Camera_List;
UINT able_cam = 0;
while(t_node != 0x00){
if(t_node->_node->Getable()){++able_cam;}
t_node = t_node->_next;
}
if(able_cam == 0){return;}
t_node = m_Camera_List;
_DISPLAY* t_disp = new _DISPLAY[able_cam];
for(UINT i = 0 ; i<able_cam ; ){
if(t_node->_node->Getable()){
t_node->_node->Render(&(t_disp[i]));
++i;
}
}
DrawDisplay(m_Size_x, m_Size_y, t_disp, able_cam);
for(UINT i = 0 ; i<able_cam ; ++i){
delete [] t_disp[i].buf;
}
delete [] t_disp;
}
void _oStream::render(){
render_graphic();
} | 23.113636 | 67 | 0.680433 | [
"render"
] |
16b59eebd50bf213219f3a70d4ff36f525a91988 | 7,246 | cpp | C++ | src/DispRefine/CProcBlock.cpp | mssl-imaging/CASP-GO | 809eabbaf3eee2d690f16f5b784c04acfae87191 | [
"Apache-2.0"
] | 3 | 2019-12-17T13:46:19.000Z | 2021-07-02T13:35:33.000Z | src/DispRefine/CProcBlock.cpp | mssl-imaging/CASP-GO | 809eabbaf3eee2d690f16f5b784c04acfae87191 | [
"Apache-2.0"
] | null | null | null | src/DispRefine/CProcBlock.cpp | mssl-imaging/CASP-GO | 809eabbaf3eee2d690f16f5b784c04acfae87191 | [
"Apache-2.0"
] | 2 | 2021-04-19T10:28:48.000Z | 2021-07-02T13:35:37.000Z | #include "CProcBlock.h"
CProcBlock::CProcBlock()
{
}
void CProcBlock::setImages(string strImgL, string strImgR, bool bGrey){
// read image as a grey -> vital for alsc and gotcha
if (bGrey){
m_imgL = imread(strImgL, CV_LOAD_IMAGE_ANYDEPTH); //IMARS
m_imgR = imread(strImgR, CV_LOAD_IMAGE_ANYDEPTH); //IMARS
}
else{
m_imgL = imread(strImgL, 1);
m_imgR = imread(strImgR, 1);
}
}
bool CProcBlock::saveTP(const vector<CTiePt>& vecTPs, const string strFile){
ofstream sfTP;
sfTP.open(strFile.c_str());
int nLen = vecTPs.size();
int nEle = 11;
if (sfTP.is_open()){
// header
sfTP << nLen << " " << nEle << endl;
// data
for (int i = 0 ; i < nLen ;i++){
CTiePt tp = vecTPs.at(i);
sfTP << tp.m_ptL.x << " "<< tp.m_ptL.y << " "
<< tp.m_ptR.x << " "<< tp.m_ptR.y << " "
<< tp.m_fSimVal << " "<< tp.m_pfAffine[0] << " "
<< tp.m_pfAffine[1] << " "<< tp.m_pfAffine[2] << " "
<< tp.m_pfAffine[3] << " " << tp.m_ptOffset.x << " "
<< tp.m_ptOffset.y << endl;
}
sfTP.close();
}
else
return false;
return true;
}
bool CProcBlock::loadTP(const string strFile, const int* pnIndx, const int nSzIdx){
// Really terrible code!!! I feel like a git.
// Please correct this function to make it more efficient!
loadTP(strFile);
if ((int)m_vecTPs.size() < nSzIdx || (int)m_vecTPs.size() <= 0) return false;
vector<CTiePt> vecTP;
for (int i = 0; i < nSzIdx; i++){
int nID = pnIndx[i];
vecTP.push_back(m_vecTPs.at(nID));
}
// m_vecTPs.clear();
m_vecTPs = vecTP;
return true;
}
bool CProcBlock::loadTP(const string strFile){
ifstream sfTPFile;
sfTPFile.open(strFile.c_str());
m_vecTPs.clear();
//m_vecRefTPs.clear();
int nTotLen = 0;
if (sfTPFile.is_open()){
// total num of TPs (i.e., lines)
int nElement; // total num of elements in a TP
sfTPFile >> nTotLen >> nElement;
for (int i = 0 ; i < nTotLen; i++){
CTiePt tp;
sfTPFile >> tp.m_ptL.x >> tp.m_ptL.y >> tp.m_ptR.x >> tp.m_ptR.y >> tp.m_fSimVal;
if (nElement > 5){
float fDummy;
for (int k = 0 ; k < 6; k++) sfTPFile >> fDummy;
}
if (nElement > 11){
float fDummy;
double dDummy;
for (int k = 0 ; k < 6; k++) sfTPFile >> fDummy;
for (int k = 0 ; k < 8; k++) sfTPFile >> dDummy;
}
m_vecTPs.push_back(tp);
}
sfTPFile.close();
}
else
return false;
if (nTotLen < 8) {
//cerr << "TP should be more than 8 pts" << endl;
return false;
}
return true;
}
bool CProcBlock::saveMatrix(const Mat& matData, const string strFile){
ofstream sfOut;
sfOut.open(strFile.c_str());
if (sfOut.is_open()){
sfOut << "ncols " << matData.cols << endl;
sfOut << "nrows " << matData.rows << endl;
sfOut << "xllcorner 0" << endl;
sfOut << "yllcorner 0" << endl;
sfOut << "cellsize 1" << endl;
for (int i = 0; i < matData.rows; i++){
for (int j = 0; j < matData.cols; j++){
if (matData.depth() == CV_32F)
sfOut << matData.at<float>(i,j) << " ";
else if (matData.depth() == CV_64F)
sfOut << matData.at<double>(i,j) << " ";
else if (matData.depth() == CV_8U)
sfOut << matData.at<uchar>(i,j) << " ";
}
sfOut << endl;
}
sfOut.close();
}
else
return false;
return true;
}
bool CProcBlock::loadMatrix(Mat &matData, const string strFile, bool bDoublePrecision){
if (bDoublePrecision){
ifstream sfIn;
sfIn.open(strFile.c_str());
if (sfIn.is_open()){
int nRow;
int nCol;
sfIn >> nRow >> nCol;
matData = Mat::zeros(nRow, nCol, CV_64F);
for (int i = 0; i < matData.rows; i++){
for (int j = 0; j < matData.cols; j++){
sfIn >> matData.at<double>(i,j);
}
}
sfIn.close();
}
else
return false;
return true;
}
else{
return loadMatrix(matData, strFile);
}
}
bool CProcBlock::loadMatrix(Mat &matData, const string strFile){
ifstream sfIn;
sfIn.open(strFile.c_str());
if (sfIn.is_open()){
int nRow;
int nCol;
sfIn >> nRow >> nCol;
matData = Mat::zeros(nRow, nCol, CV_32F);
for (int i = 0; i < matData.rows; i++){
for (int j = 0; j < matData.cols; j++){
sfIn >> matData.at<float>(i,j);
}
}
sfIn.close();
}
else
return false;
return true;
}
bool CProcBlock::loadMatrix(string strFile){
ifstream sfIn;
sfIn.open(strFile.c_str());
if (sfIn.is_open()){
int nRow;
int nCol;
sfIn >> nRow >> nCol;
m_dispX = Mat::zeros(nRow, nCol, CV_32F);
for (int i = 0; i < m_dispX.rows; i++){
for (int j = 0; j < m_dispX.cols; j++){
sfIn >> m_dispX.at<float>(i,j);
}
}
sfIn.close();
}
else
return false;
return true;
}
bool CProcBlock::saveALSCParam(const CALSCParam& paramALSC, const string strOut){
ofstream sfLog;
sfLog.open(strOut.c_str(), ios::app | ios::out);
if (sfLog.is_open()){
sfLog << "<ALSC parameters>" << endl;
sfLog << "The size of a matching patch: " << paramALSC.m_nPatch << endl;
sfLog << "Maximum eigenval: " << paramALSC.m_fEigThr << endl;
sfLog << "Maximum iteration: " << paramALSC.m_nMaxIter << endl;
sfLog << "Affine distortion limit: " << paramALSC.m_fAffThr << endl;
sfLog << "Translation limit: " << paramALSC.m_fDriftThr << endl;
sfLog << "Use intensity offset parameter: " << paramALSC.m_bIntOffset << endl;
sfLog << "Use weighting coefficients: " << paramALSC.m_bWeighting << endl;
sfLog << endl;
sfLog.close();
}
else
return false;
return true;
}
bool CProcBlock::saveGOTCHAParam(CGOTCHAParam& paramGOTCHA, const string strOut){
ofstream sfLog;
sfLog.open(strOut.c_str(), ios::app | ios::out);
if (sfLog.is_open()){
sfLog << "<GOTCHA parameters>" << endl;
sfLog << "Neighbour type: " << paramGOTCHA.getNeiType()<< endl;
sfLog << "Diffusion iteration: " << paramGOTCHA.m_nDiffIter << endl;
sfLog << "Diffusion threshold: " << paramGOTCHA.m_fDiffThr << endl;
sfLog << "Diffusion coefficient: " << paramGOTCHA.m_fDiffCoef << endl;
//sfLog << "Minimum image tile size: " << paramGOTCHA.m_nMinTile << endl;
sfLog << "Need initial ALSC on seed TPs: " << paramGOTCHA.m_bNeedInitALSC << endl;
sfLog << endl;
sfLog.close();
}
else
return false;
return true;
}
| 26.738007 | 93 | 0.514905 | [
"vector"
] |
16bf409e601cf1c09c76d3d99496affde0485f53 | 1,281 | cpp | C++ | Mathematical Challenges/Largest Num Divisible By 3.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Mathematical Challenges/Largest Num Divisible By 3.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Mathematical Challenges/Largest Num Divisible By 3.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // ## Problem Description
// Given a non-negative number up to 10 digits long, find the largest number that can be
// formed with the digits and is divisible by 3. If no number can be formed that is divisible by 3, return 0.
// Input: int
// Output int
// Examples:
// - largest_div_by_three(0) -> 0
// - largest_div_by_three(24) -> 42
// - largest_div_by_three(319) -> 93
// - largest_div_by_three(113) -> 3
// - largest_div_by_three(111) -> 111
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
string input;
cin >> input;
vector<int> digits;
for (size_t i = 0; i < input.length(); i++)
{
int d = input[i] - '0';
digits.push_back(d);
}
unsigned long long max = 0;
for (size_t i = 0; i < digits.size(); i++)
{
sort(digits.begin(), digits.end(), [](int a, int b) { return a < b; });
while (next_permutation(digits.begin(), digits.end()))
{
int sum = 0;
string str = "";
for (size_t j = 0; j < digits.size() - i; j++)
{
sum += digits[j];
str += to_string(digits[j]);
}
if (sum % 3 == 0)
{
sort(str.begin(), str.end(), [](char a, char b) { return a > b; });
int n = stoi(str);
if (n > max) max = n;
}
}
}
cout << max << endl;
return 0;
}
| 21.35 | 109 | 0.589383 | [
"vector"
] |
16c173c277f781f8525fa5535cfb5bba02b17b10 | 2,898 | cpp | C++ | marsyas-vamp/marsyas/src/marsyas/sched/TmTimerManager.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/marsyas/sched/TmTimerManager.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/marsyas/sched/TmTimerManager.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | /*
** Copyright (C) 1998-2005 George Tzanetakis <gtzan@cs.uvic.ca>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <marsyas/sched/TmTimerManager.h>
using namespace std;
using namespace Marsyas;
/** Adding new Timers:
New timers are added by first making them...
Basically, a map is created from "TimerName"=>TimerConstructorObject.
This makes it possible to use a map for fast access to specific timers and it
prevents having to instantiate each Timer type. The constructor object simply
wraps the new operator so that it constructs objects only when requested.
1. Add the timer's include file.
2. Wrap the object using the macro:
TimerCreateWrapper(TmSomeTimerName);
3. Register the timer in the map:
in function TmTimerManager::addTimers() add the line
registerTimer(TmSomeTimerName);
*/
#define TimerCreateWrapper(_NAME) \
struct Make##_NAME : public MakeTimer { \
Make##_NAME() {}; ~Make##_NAME() {}; \
TmTimer* make(std::string ident) { return new _NAME (ident); }; \
}
#define registerTimer(_NAME) registry_[#_NAME] = new Make##_NAME();
# include "TmRealTime.h"
# include "TmVirtualTime.h"
TimerCreateWrapper(TmRealTime);
TimerCreateWrapper(TmVirtualTime);
TmTimerManager* TmTimerManager::instance_ = NULL;
TmTimerManager::TmTimerManager()
{
addTimers();
}
TmTimerManager::~TmTimerManager()
{
delete instance_;
instance_=NULL;
}
void TmTimerManager::addTimers()
{
// register your timers here!
registerTimer(TmRealTime);
registerTimer(TmVirtualTime);
}
TmTimerManager*
TmTimerManager::getInstance()
{
if (instance_==NULL) {
instance_=new TmTimerManager();
}
return instance_;
}
TmTimer*
TmTimerManager::make(std::string class_name, std::string identifier)
{
MakeTimer* m = registry_[class_name];
if (m==NULL) { // does the map always return NULL when key is not in the map??
MRSWARN("TmTimerManager::make(string,string) name '"+class_name+"' does not name a timer");
return NULL;
}
return m->make(identifier);
}
TmTimer*
TmTimerManager::make(std::string class_name, std::string identifier, std::vector<TmParam> params)
{
TmTimer* tmr = make(class_name,identifier);
if(tmr!=NULL) {
tmr->updtimer(params);
}
return tmr;
}
| 28.693069 | 97 | 0.733609 | [
"object",
"vector"
] |
16cc1896e2d9a467bc4e6e63c3c2a467bbd0a0e6 | 6,013 | hpp | C++ | alpaka/include/alpaka/kernel/TaskKernelCpuTbbBlocks.hpp | ComputationalRadiationPhysics/mallocMC | bb2b32a4a56f7c892e14454bf6aa373a4870c32c | [
"MIT"
] | 25 | 2015-01-30T12:19:48.000Z | 2020-10-30T07:52:45.000Z | alpaka/include/alpaka/kernel/TaskKernelCpuTbbBlocks.hpp | ComputationalRadiationPhysics/mallocMC | bb2b32a4a56f7c892e14454bf6aa373a4870c32c | [
"MIT"
] | 101 | 2015-01-06T11:31:26.000Z | 2020-11-09T13:51:19.000Z | alpaka/include/alpaka/kernel/TaskKernelCpuTbbBlocks.hpp | ComputationalRadiationPhysics/mallocMC | bb2b32a4a56f7c892e14454bf6aa373a4870c32c | [
"MIT"
] | 10 | 2015-06-10T07:54:30.000Z | 2020-05-06T10:07:39.000Z | /* Copyright 2022 Benjamin Worpitz, Erik Zenker, René Widera, Felice Pantaleo, Bernhard Manfred Gruber
*
* This file is part of alpaka.
*
* 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/.
*/
#pragma once
#ifdef ALPAKA_ACC_CPU_B_TBB_T_SEQ_ENABLED
// Specialized traits.
# include <alpaka/acc/Traits.hpp>
# include <alpaka/dev/Traits.hpp>
# include <alpaka/dim/Traits.hpp>
# include <alpaka/idx/Traits.hpp>
# include <alpaka/pltf/Traits.hpp>
// Implementation details.
# include <alpaka/acc/AccCpuTbbBlocks.hpp>
# include <alpaka/core/Decay.hpp>
# include <alpaka/dev/DevCpu.hpp>
# include <alpaka/idx/MapIdx.hpp>
# include <alpaka/kernel/Traits.hpp>
# include <alpaka/meta/NdLoop.hpp>
# include <alpaka/workdiv/WorkDivMembers.hpp>
# include <functional>
# include <stdexcept>
# include <tuple>
# include <type_traits>
# if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL
# include <iostream>
# endif
# include <tbb/blocked_range.h>
# include <tbb/parallel_for.h>
# include <tbb/task_group.h>
namespace alpaka
{
//! The CPU TBB block accelerator execution task.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
class TaskKernelCpuTbbBlocks final : public WorkDivMembers<TDim, TIdx>
{
public:
template<typename TWorkDiv>
ALPAKA_FN_HOST TaskKernelCpuTbbBlocks(TWorkDiv&& workDiv, TKernelFnObj const& kernelFnObj, TArgs&&... args)
: WorkDivMembers<TDim, TIdx>(std::forward<TWorkDiv>(workDiv))
, m_kernelFnObj(kernelFnObj)
, m_args(std::forward<TArgs>(args)...)
{
static_assert(
Dim<std::decay_t<TWorkDiv>>::value == TDim::value,
"The work division and the execution task have to be of the same dimensionality!");
}
//! Executes the kernel function object.
ALPAKA_FN_HOST auto operator()() const -> void
{
ALPAKA_DEBUG_MINIMAL_LOG_SCOPE;
auto const gridBlockExtent = getWorkDiv<Grid, Blocks>(*this);
auto const blockThreadExtent = getWorkDiv<Block, Threads>(*this);
auto const threadElemExtent = getWorkDiv<Thread, Elems>(*this);
// Get the size of the block shared dynamic memory.
auto const blockSharedMemDynSizeBytes = std::apply(
[&](ALPAKA_DECAY_T(TArgs) const&... args)
{
return getBlockSharedMemDynSizeBytes<AccCpuTbbBlocks<TDim, TIdx>>(
m_kernelFnObj,
blockThreadExtent,
threadElemExtent,
args...);
},
m_args);
# if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
std::cout << __func__ << " blockSharedMemDynSizeBytes: " << blockSharedMemDynSizeBytes << " B"
<< std::endl;
# endif
// The number of blocks in the grid.
TIdx const numBlocksInGrid = gridBlockExtent.prod();
if(blockThreadExtent.prod() != static_cast<TIdx>(1u))
{
throw std::runtime_error("A block for the TBB accelerator can only ever have one single thread!");
}
tbb::this_task_arena::isolate(
[&]
{
tbb::parallel_for(
static_cast<TIdx>(0),
static_cast<TIdx>(numBlocksInGrid),
[&](TIdx i)
{
AccCpuTbbBlocks<TDim, TIdx> acc(
*static_cast<WorkDivMembers<TDim, TIdx> const*>(this),
blockSharedMemDynSizeBytes);
acc.m_gridBlockIdx
= mapIdx<TDim::value>(Vec<DimInt<1u>, TIdx>(static_cast<TIdx>(i)), gridBlockExtent);
std::apply(m_kernelFnObj, std::tuple_cat(std::tie(acc), m_args));
freeSharedVars(acc);
});
});
}
private:
TKernelFnObj m_kernelFnObj;
std::tuple<std::decay_t<TArgs>...> m_args;
};
namespace trait
{
//! The CPU TBB block execution task accelerator type trait specialization.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
struct AccType<TaskKernelCpuTbbBlocks<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = AccCpuTbbBlocks<TDim, TIdx>;
};
//! The CPU TBB block execution task device type trait specialization.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
struct DevType<TaskKernelCpuTbbBlocks<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = DevCpu;
};
//! The CPU TBB block execution task dimension getter trait specialization.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
struct DimType<TaskKernelCpuTbbBlocks<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TDim;
};
//! The CPU TBB block execution task platform type trait specialization.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
struct PltfType<TaskKernelCpuTbbBlocks<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = PltfCpu;
};
//! The CPU TBB block execution task idx type trait specialization.
template<typename TDim, typename TIdx, typename TKernelFnObj, typename... TArgs>
struct IdxType<TaskKernelCpuTbbBlocks<TDim, TIdx, TKernelFnObj, TArgs...>>
{
using type = TIdx;
};
} // namespace trait
} // namespace alpaka
#endif
| 37.347826 | 116 | 0.592217 | [
"object"
] |
16d0be846b9fe6cbd1f65d9ad72aa86fefc92f25 | 33,887 | cpp | C++ | src/dos/drive_cache.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | 3 | 2022-02-20T11:06:29.000Z | 2022-03-11T08:16:55.000Z | src/dos/drive_cache.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | null | null | null | src/dos/drive_cache.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2002-2021 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "drives.h"
#include "dos_inc.h"
#include "logging.h"
#include "support.h"
#include "cross.h"
// STL stuff
#include <vector>
#include <iterator>
#include <algorithm>
#if defined (WIN32) /* Win 32 */
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from
#include <windows.h>
#endif
#if defined (OS2)
#define INCL_DOSERRORS
#define INCL_DOSFILEMGR
#include <os2.h>
#endif
int fileInfoCounter = 0;
bool SortByName(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
return strcmp(a->shortname,b->shortname)<0;
}
bool SortByNameRev(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
return strcmp(a->shortname,b->shortname)>0;
}
bool SortByDirName(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
// Directories first...
if (a->isDir!=b->isDir) return (a->isDir>b->isDir);
return strcmp(a->shortname,b->shortname)<0;
}
bool SortByDirNameRev(DOS_Drive_Cache::CFileInfo* const &a, DOS_Drive_Cache::CFileInfo* const &b) {
// Directories first...
if (a->isDir!=b->isDir) return (a->isDir>b->isDir);
return strcmp(a->shortname,b->shortname)>0;
}
DOS_Drive_Cache::DOS_Drive_Cache(void) {
dirBase = new CFileInfo;
save_dir = 0;
srchNr = 0;
label[0] = 0;
basePath[0] = 0;
nextFreeFindFirst = 0;
for (uint32_t i=0; i<MAX_OPENDIRS; i++) { dirSearch[i] = 0; dirFindFirst[i] = 0; }
SetDirSort(DIRALPHABETICAL);
updatelabel = true;
}
DOS_Drive_Cache::DOS_Drive_Cache(const char* path, DOS_Drive *drive) {
dirBase = new CFileInfo;
save_dir = 0;
srchNr = 0;
label[0] = 0;
basePath[0] = 0;
nextFreeFindFirst = 0;
for (uint32_t i=0; i<MAX_OPENDIRS; i++) { dirSearch[i] = 0; dirFindFirst[i] = 0; }
SetDirSort(DIRALPHABETICAL);
SetBaseDir(path,drive);
updatelabel = true;
}
DOS_Drive_Cache::~DOS_Drive_Cache(void) {
Clear();
for (uint32_t i=0; i<MAX_OPENDIRS; i++) { DeleteFileInfo(dirFindFirst[i]); dirFindFirst[i]=0; }
}
void DOS_Drive_Cache::Clear(void) {
DeleteFileInfo(dirBase); dirBase = 0;
nextFreeFindFirst = 0;
for (uint32_t i=0; i<MAX_OPENDIRS; i++) dirSearch[i] = 0;
}
void DOS_Drive_Cache::EmptyCache(void) {
// Empty Cache and reinit
Clear();
dirBase = new CFileInfo;
save_dir = 0;
srchNr = 0;
if (basePath[0] != 0) SetBaseDir(basePath,drive);
}
void DOS_Drive_Cache::SetLabel(const char* vname,bool cdrom,bool allowupdate) {
/* allowupdate defaults to true. if mount sets a label then allowupdate is
* false and will this function return at once after the first call.
* The label will be set at the first call. */
if(!this->updatelabel) return;
this->updatelabel = allowupdate;
Set_Label(vname,label,cdrom);
LOG(LOG_DOSMISC,LOG_NORMAL)("DIRCACHE: Set volume label to %s",label);
}
uint16_t DOS_Drive_Cache::GetFreeID(CFileInfo* dir) {
if (dir->id != MAX_OPENDIRS)
return dir->id;
for (uint16_t i=0; i<MAX_OPENDIRS; i++) {
if (!dirSearch[i]) {
dir->id = i;
return i;
}
}
LOG(LOG_FILES,LOG_NORMAL)("DIRCACHE: Too many open directories!");
dir->id = 0;
return 0;
}
void DOS_Drive_Cache::SetBaseDir(const char* baseDir, DOS_Drive *drive) {
if (strlen(baseDir) == 0) return;
uint16_t id;
strcpy(basePath,baseDir);
this->drive = drive;
if (OpenDir(baseDir,id)) {
char* result = 0, *lresult = 0;
ReadDir(id,result,lresult);
}
// Get Volume Label
#if defined (WIN32) || defined (OS2)
char labellocal[256]={ 0 };
char drives[4] = "C:\\";
drives[0] = basePath[0];
#if defined (WIN32)
if (GetVolumeInformation(drives,labellocal,256,NULL,NULL,NULL,NULL,0)) {
bool cdrom = false;
UINT test = GetDriveType(drives);
if(test == DRIVE_CDROM) cdrom = true;
#else // OS2
//TODO determine wether cdrom or not!
FSINFO fsinfo;
ULONG drivenumber = drive[0];
if (drivenumber > 26) { // drive letter was lowercase
drivenumber = drive[0] - 'a' + 1;
}
APIRET rc = DosQueryFSInfo(drivenumber, FSIL_VOLSER, &fsinfo, sizeof(FSINFO));
if (rc == NO_ERROR) {
bool cdrom = false;
#endif
/* Set label and allow being updated */
SetLabel(labellocal,cdrom,true);
}
#endif
}
void DOS_Drive_Cache::ExpandName(char* path) {
strcpy(path,GetExpandName(path));
}
char* DOS_Drive_Cache::GetExpandName(const char* path) {
static char work [CROSS_LEN] = { 0 };
char dir [CROSS_LEN];
work[0] = 0;
strcpy (dir,path);
const char* pos = strrchr_dbcs((char *)path,CROSS_FILESPLIT);
if (pos) dir[pos-path+1] = 0;
CFileInfo* dirInfo = FindDirInfo(dir, work);
if (pos) {
// Last Entry = File
strcpy(dir,pos+1);
GetLongName(dirInfo, dir);
strcat(work,dir);
}
if (*work) {
size_t len = strlen(work);
#if defined (WIN32)
//What about OS/2
if((work[len-1] == CROSS_FILESPLIT ) && (len >= 2) && (work[len-2] != ':')) {
#else
if((len > 1) && (work[len-1] == CROSS_FILESPLIT )) {
#endif
work[len-1] = 0; // Remove trailing slashes except when in root
}
}
return work;
}
void DOS_Drive_Cache::AddEntry(const char* path, bool checkExists) {
// Get Last part...
char expand [CROSS_LEN];
CFileInfo* dir = FindDirInfo(path,expand);
const char* pos = strrchr_dbcs((char *)path,CROSS_FILESPLIT);
if (pos) {
char file [CROSS_LEN];
strcpy(file,pos+1);
// Check if file already exists, then don't add new entry...
if (checkExists) {
if (GetLongName(dir,file)>=0) return;
}
char sfile[DOS_NAMELENGTH];
sfile[0]=0;
CreateEntry(dir,file,sfile,false);
Bits index = GetLongName(dir,file);
if (index>=0) {
// Check if there are any open search dir that are affected by this...
if (dir) for (uint32_t i=0; i<MAX_OPENDIRS; i++) {
if ((dirSearch[i]==dir) && ((uint32_t)index<=dirSearch[i]->nextEntry))
dirSearch[i]->nextEntry++;
}
}
// LOG_DEBUG("DIR: Added Entry %s",path);
} else {
// LOG_DEBUG("DIR: Error: Failed to add %s",path);
}
}
bool filename_not_strict_8x3(const char *n);
void DOS_Drive_Cache::AddEntryDirOverlay(const char* path, char *sfile, bool checkExists) {
// Get Last part...
char file [CROSS_LEN];
char expand [CROSS_LEN];
char dironly[CROSS_LEN + 1];
//When adding a directory, the directory we want to operate inside in is the above it. (which can go wrong if the directory already exists.)
strcpy(dironly,path);
char* post = strrchr_dbcs(dironly,CROSS_FILESPLIT);
if (post) {
#if defined (WIN32)
//OS2 ?
if (post > dironly && *(post - 1) == ':' && (post - dironly) == 2)
post++; //move away from X: as need to end up with "x:\"
#else
//Lets hope this is not really used.. (root folder specified as overlay)
if (post == dironly)
post++; //move away from /
#endif
*post = 0; //TODO take care of AddEntryDIR D:\\piet) (so mount d d:\ as base)
*(post + 1) = 0; //As FindDirInfo is skipping over the base directory
}
CFileInfo* dir = FindDirInfo(dironly,expand);
const char* pos = strrchr_dbcs((char *)path,CROSS_FILESPLIT);
char sname[CROSS_LEN], *p=strrchr_dbcs(sfile, '\\');
if (p!=NULL)
strcpy(sname, p+1);
else
strcpy(sname, sfile);
if (pos) {
strcpy(file,pos + 1);
// Check if directory already exists, then don't add new entry...
if (checkExists) {
Bits index = GetLongName(dir,(char *)(!strlen(sname)||filename_not_strict_8x3(sname)?file:sname));
if (index >= 0) {
//directory already exists, but most likely empty.
dir = dir->fileList[index];
if (dir->isOverlayDir && dir->fileList.empty()) {
//maybe care about searches ? but this function should only run on cache inits/refreshes.
//add dot entries
CreateEntry(dir,".",".",true);
CreateEntry(dir,"..","..",true);
}
return;
}
}
if (filename_not_strict_8x3(sname)) sname[0]=0;
char* genname=CreateEntry(dir,file,sname,true);
Bits index = GetLongName(dir,(char *)(!strlen(sname)||filename_not_strict_8x3(sname)?file:sname));
if (strlen(genname)) {
strcpy(sfile, sname);
p=strrchr_dbcs(sfile, '\\');
if (p!=NULL) {
*(p+1)=0;
strcat(sfile, genname);
} else
strcpy(sfile, genname);
}
if (index>=0) {
uint32_t i;
// Check if there are any open search dir that are affected by this...
if (dir) for (i=0; i<MAX_OPENDIRS; i++) {
if ((dirSearch[i]==dir) && ((uint32_t)index<=dirSearch[i]->nextEntry))
dirSearch[i]->nextEntry++;
}
dir = dir->fileList[index];
dir->isOverlayDir = true;
CreateEntry(dir,".",".",true);
CreateEntry(dir,"..","..",true);
}
// LOG_DEBUG("DIR: Added Entry %s",path);
} else {
// LOG_DEBUG("DIR: Error: Failed to add %s",path);
}
}
void DOS_Drive_Cache::DeleteEntry(const char* path, bool ignoreLastDir) {
CacheOut(path,ignoreLastDir);
if (dirSearch[srchNr] && (dirSearch[srchNr]->nextEntry>0)) dirSearch[srchNr]->nextEntry--;
if (!ignoreLastDir) {
// Check if there are any open search dir that are affected by this...
char expand [CROSS_LEN];
CFileInfo* dir = FindDirInfo(path,expand);
if (dir) for (uint32_t i=0; i<MAX_OPENDIRS; i++) {
if ((dirSearch[i]==dir) && (dirSearch[i]->nextEntry>0))
dirSearch[i]->nextEntry--;
}
}
}
void DOS_Drive_Cache::CacheOut(const char* path, bool ignoreLastDir) {
char expand[CROSS_LEN] = { 0 };
CFileInfo* dir;
if (ignoreLastDir) {
char tmp[CROSS_LEN] = { 0 };
int32_t len=0;
const char* pos = strrchr_dbcs((char *)path,CROSS_FILESPLIT);
if (pos) len = (int32_t)(pos - path);
if (len>0) {
safe_strncpy(tmp,path,len+1);
} else {
strcpy(tmp,path);
}
dir = FindDirInfo(tmp,expand);
} else {
dir = FindDirInfo(path,expand);
}
// LOG_DEBUG("DIR: Caching out %s : dir %s",expand,dir->orgname);
// clear cache first?
for (uint32_t i=0; i<MAX_OPENDIRS; i++) {
dirSearch[i] = 0; //free[i] = true;
}
// delete file objects...
//Maybe check if it is a file and then only delete the file and possibly the long name. instead of all objects in the dir.
for(uint32_t i=0; i<dir->fileList.size(); i++) {
if (dirSearch[srchNr]==dir->fileList[i]) dirSearch[srchNr] = 0;
DeleteFileInfo(dir->fileList[i]); dir->fileList[i] = 0;
}
// clear lists
dir->fileList.clear();
dir->longNameList.clear();
save_dir = 0;
}
bool DOS_Drive_Cache::IsCachedIn(CFileInfo* curDir) {
return (curDir->isOverlayDir || curDir->fileList.size()>0);
}
bool DOS_Drive_Cache::GetShortName(const char* fullname, char* shortname) {
// Get Dir Info
char expand[CROSS_LEN] = {0};
CFileInfo* curDir = FindDirInfo(fullname,expand);
const char* pos = strrchr_dbcs((char *)fullname,CROSS_FILESPLIT);
if (pos) pos++; else return false;
std::vector<CFileInfo*>::size_type filelist_size = curDir->longNameList.size();
if (GCC_UNLIKELY(filelist_size<=0)) return false;
// The orgname part of the list is not sorted (shortname is)! So we can only walk through it.
for(Bitu i = 0; i < filelist_size; i++) {
#if defined (WIN32) || defined (OS2) /* Win 32 & OS/2*/
if (strcmp(pos,curDir->longNameList[i]->orgname) == 0) {
#else
if (strcmp(pos,curDir->longNameList[i]->orgname) == 0) {
#endif
strcpy(shortname,curDir->longNameList[i]->shortname);
return true;
}
}
return false;
}
int DOS_Drive_Cache::CompareShortname(const char* compareName, const char* shortName) {
char const* cpos = strchr(shortName,'~');
if (cpos) {
/* the following code is replaced as it's not safe when char* is 64 bits */
/* Bits compareCount1 = (int)cpos - (int)shortName;
char* endPos = strchr(cpos,'.');
Bitu numberSize = endPos ? int(endPos)-int(cpos) : strlen(cpos);
char* lpos = strchr(compareName,'.');
Bits compareCount2 = lpos ? int(lpos)-int(compareName) : strlen(compareName);
if (compareCount2>8) compareCount2 = 8;
compareCount2 -= numberSize;
if (compareCount2>compareCount1) compareCount1 = compareCount2;
*/
size_t compareCount1 = strcspn(shortName,"~");
size_t numberSize = strcspn(cpos,".");
size_t compareCount2 = strcspn(compareName,".");
if(compareCount2 > 8) compareCount2 = 8;
/* We want
* compareCount2 -= numberSize;
* if (compareCount2>compareCount1) compareCount1 = compareCount2;
* but to prevent negative numbers:
*/
if(compareCount2 > compareCount1 + numberSize)
compareCount1 = compareCount2 - numberSize;
return strncmp(compareName,shortName,compareCount1);
}
return strcmp(compareName,shortName);
}
Bitu DOS_Drive_Cache::CreateShortNameID(CFileInfo* curDir, const char* name) {
std::vector<CFileInfo*>::size_type filelist_size = curDir->longNameList.size();
if (GCC_UNLIKELY(filelist_size<=0)) return 1; // shortener IDs start with 1
Bitu foundNr = 0;
Bits low = 0;
Bits high = (Bits)(filelist_size-1);
while (low<=high) {
Bits mid = (low+high)/2;
Bits res = CompareShortname(name,curDir->longNameList[(size_t)mid]->shortname);
if (res>0) low = mid+1; else
if (res<0) high = mid-1;
else {
// any more same x chars in next entries ?
do {
foundNr = curDir->longNameList[(size_t)mid]->shortNr;
mid++;
} while((Bitu)mid<curDir->longNameList.size() && (CompareShortname(name,curDir->longNameList[(size_t)mid]->shortname)==0));
break;
}
}
return foundNr+1;
}
bool DOS_Drive_Cache::RemoveTrailingDot(char* shortname) {
// remove trailing '.' if no extension is available (Linux compatibility)
size_t len = strlen(shortname);
if (len && (shortname[len-1]=='.')) {
if (len==1) return false;
if ((len==2) && (shortname[0]=='.')) return false;
shortname[len-1] = 0;
return true;
}
return false;
}
#define WINE_DRIVE_SUPPORT 1
#if WINE_DRIVE_SUPPORT
//Changes to interact with WINE by supporting their namemangling.
//The code is rather slow, because orglist is unordered, so it needs to be avoided if possible.
//Hence the tests in GetLongFileName
// From the Wine project
static Bits wine_hash_short_file_name( char* name, char* buffer )
{
static const char hash_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
static const char invalid_chars[] = { '*','?','<','>','|','"','+','=',',',';','[',']',' ','\345','~','.',0 };
char* p;
char* ext;
char* end = name + strlen(name);
char* dst;
unsigned short hash;
int i;
// Compute the hash code of the file name
for (p = name, hash = 0xbeef; p < end - 1; p++)
hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); // Last character
// Find last dot for start of the extension
for (p = name + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
// Copy first 4 chars, replacing invalid chars with '_'
for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
{
if (p == end || p == ext) break;
*dst++ = (*p < 0 || strchr( invalid_chars, *p ) != NULL) ? '_' : toupper(*p);
}
// Pad to 5 chars with '~'
while (i-- >= 0) *dst++ = '~';
// Insert hash code converted to 3 ASCII chars
*dst++ = hash_chars[(hash >> 10) & 0x1f];
*dst++ = hash_chars[(hash >> 5) & 0x1f];
*dst++ = hash_chars[hash & 0x1f];
// Copy the first 3 chars of the extension (if any)
if (ext)
{
*dst++ = '.';
for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
*dst++ = (*ext < 0 || strchr( invalid_chars, *ext ) != NULL) ? '_' : toupper(*ext);
}
return (Bits)(dst - buffer);
}
#endif
Bits DOS_Drive_Cache::GetLongName(CFileInfo* curDir, char* shortName) {
std::vector<CFileInfo*>::size_type filelist_size = curDir->fileList.size();
if (GCC_UNLIKELY(filelist_size<=0)) return -1;
// Remove dot, if no extension...
RemoveTrailingDot(shortName);
// Search long name and return array number of element
Bits res;
if (!uselfn) {
Bits low = 0;
Bits high = (Bits)(filelist_size-1);
Bits mid;
while (low<=high) {
mid = (low+high)/2;
res = strcmp(shortName,curDir->fileList[mid]->shortname);
if (res>0) low = mid+1; else
if (res<0) high = mid-1; else
{ // Found
strcpy(shortName,curDir->fileList[mid]->orgname);
return mid;
};
}
} else if (strlen(shortName)) {
for (Bitu i=0; i<filelist_size; i++) {
if (!strcasecmp(shortName,curDir->fileList[i]->orgname) || !strcasecmp(shortName,curDir->fileList[i]->shortname)) {
strcpy(shortName,curDir->fileList[i]->orgname);
return (Bits)i;
}
}
}
#ifdef WINE_DRIVE_SUPPORT
if (strlen(shortName) < 8 || shortName[4] != '~' || shortName[5] == '.' || shortName[6] == '.' || shortName[7] == '.') return -1; // not available
// else it's most likely a Wine style short name ABCD~###, # = not dot (length at least 8)
// The above test is rather strict as the following loop can be really slow if filelist_size is large.
char buff[CROSS_LEN];
for (Bitu i = 0; i < filelist_size; i++) {
res = wine_hash_short_file_name(curDir->fileList[i]->orgname,buff);
buff[res] = 0;
if (!strcmp(shortName,buff)) {
// Found
strcpy(shortName,curDir->fileList[i]->orgname);
return (Bits)i;
}
}
#endif
// not available
return -1;
}
bool DOS_Drive_Cache::RemoveSpaces(char* str) {
// Removes all spaces
char* curpos = str;
char* chkpos = str;
while (*chkpos!=0) {
if (*chkpos==' ') chkpos++; else *curpos++ = *chkpos++;
}
*curpos = 0;
return (curpos!=chkpos);
}
bool isDBCSCP();
char * DBCS_upcase(char * str);
void DOS_Drive_Cache::CreateShortName(CFileInfo* curDir, CFileInfo* info) {
Bits len = 0;
bool createShort = false;
char tmpNameBuffer[CROSS_LEN];
char* tmpName = tmpNameBuffer;
// Remove Spaces
strcpy(tmpName,info->orgname);
if (IS_PC98_ARCH || isDBCSCP())
DBCS_upcase(tmpName);
else
upcase(tmpName);
createShort = RemoveSpaces(tmpName);
// Get Length of filename
char* pos = strchr(tmpName,'.');
if (pos) {
// ignore preceding '.' if extension is longer than "3"
if (strlen(pos)>4) {
while (*tmpName=='.') tmpName++;
createShort = true;
}
pos = strchr(tmpName,'.');
if (pos) len = (Bits)(pos - tmpName);
else len = (Bits)strlen(tmpName);
} else {
len = (Bits)strlen(tmpName);
}
// Should shortname version be created ?
createShort = createShort || (len>8);
if (!createShort) {
char buffer[CROSS_LEN];
strcpy(buffer,tmpName);
createShort = (GetLongName(curDir,buffer)>=0);
}
if (createShort) {
// Create number
char buffer[8];
info->shortNr = CreateShortNameID(curDir,tmpName);
if (GCC_UNLIKELY(info->shortNr > 9999999)) E_Exit("~9999999 same name files overflow");
sprintf(buffer, "%d", static_cast<unsigned int>(info->shortNr));
// Copy first letters
Bits tocopy = 0;
size_t buflen = strlen(buffer);
if ((size_t)len+buflen+1u>8u) tocopy = (Bits)(8u - buflen - 1u);
else tocopy = len;
safe_strncpy(info->shortname,tmpName,tocopy+1);
// Copy number
strcat(info->shortname,"~");
strcat(info->shortname,buffer);
// Add (and cut) Extension, if available
if (pos) {
// Step to last extension...
pos = strrchr(tmpName, '.');
// add extension
strncat(info->shortname,pos,4);
info->shortname[DOS_NAMELENGTH] = 0;
}
// keep list sorted for CreateShortNameID to work correctly
if (curDir->longNameList.size()>0) {
if (!(strcmp(info->shortname,curDir->longNameList.back()->shortname)<0)) {
// append at end of list
curDir->longNameList.push_back(info);
} else {
// look for position where to insert this element
bool found=false;
std::vector<CFileInfo*>::iterator it;
for (it=curDir->longNameList.begin(); it!=curDir->longNameList.end(); ++it) {
if (strcmp(info->shortname,(*it)->shortname)<0) {
found = true;
break;
}
}
// Put it in longname list...
if (found) curDir->longNameList.insert(it,info);
else curDir->longNameList.push_back(info);
}
} else {
// empty file list, append
curDir->longNameList.push_back(info);
}
} else {
strcpy(info->shortname,tmpName);
}
RemoveTrailingDot(info->shortname);
}
DOS_Drive_Cache::CFileInfo* DOS_Drive_Cache::FindDirInfo(const char* path, char* expandedPath) {
// statics
static char split[2] = { CROSS_FILESPLIT,0 };
char dir [CROSS_LEN];
const char* start = path;
const char* pos;
CFileInfo* curDir = dirBase;
uint16_t id;
if (save_dir && (strcmp(path,save_path)==0)) {
strcpy(expandedPath,save_expanded);
return save_dir;
}
// LOG_DEBUG("DIR: Find %s",path);
// Remove base dir path
start += strlen(basePath);
strcpy(expandedPath,basePath);
// hehe, baseDir should be cached in...
if (!IsCachedIn(curDir)) {
char work [CROSS_LEN];
strcpy(work,basePath);
if (OpenDir(curDir,work,id)) {
char buffer[CROSS_LEN];
char *result = 0, *lresult = 0;
strcpy(buffer,dirPath);
ReadDir(id,result,lresult);
strcpy(dirPath,buffer);
if (dirSearch[id]) {
dirSearch[id]->id = MAX_OPENDIRS;
dirSearch[id] = 0;
}
}
}
do {
// bool errorcheck = false;
pos = strchr_dbcs((char *)start,CROSS_FILESPLIT);
if (pos) { safe_strncpy(dir,start,pos-start+1); /*errorcheck = true;*/ }
else { strcpy(dir,start); }
// Path found
Bits nextDir = GetLongName(curDir,dir);
strcat(expandedPath,dir);
// Error check
/* if ((errorcheck) && (nextDir<0)) {
LOG_DEBUG("DIR: Error: %s not found.",expandedPath);
};
*/
// Follow Directory
if ((nextDir>=0) && curDir->fileList[(size_t)nextDir]->isDir) {
curDir = curDir->fileList[(size_t)nextDir];
strcpy (curDir->orgname,dir);
if (!IsCachedIn(curDir)) {
if (OpenDir(curDir,expandedPath,id)) {
char buffer[CROSS_LEN];
char *result = 0, *lresult = 0;
strcpy(buffer,dirPath);
ReadDir(id,result,lresult);
strcpy(dirPath,buffer);
if (dirSearch[id]) {
dirSearch[id]->id = MAX_OPENDIRS;
dirSearch[id] = 0;
}
}
}
}
if (pos) {
strcat(expandedPath,split);
start = pos+1;
}
} while (pos);
// Save last result for faster access next time
strcpy(save_path,path);
strcpy(save_expanded,expandedPath);
save_dir = curDir;
return curDir;
}
bool DOS_Drive_Cache::OpenDir(const char* path, uint16_t& id) {
char expand[CROSS_LEN] = {0};
CFileInfo* dir = FindDirInfo(path,expand);
if (OpenDir(dir,expand,id)) {
dirSearch[id]->nextEntry = 0;
return true;
}
return false;
}
bool DOS_Drive_Cache::OpenDir(CFileInfo* dir, const char* expand, uint16_t& id) {
id = GetFreeID(dir);
dirSearch[id] = dir;
char expandcopy [CROSS_LEN];
strcpy(expandcopy,expand);
// Add "/"
size_t expandcopylen = strlen(expandcopy);
if (expandcopylen > 0 && expandcopy[expandcopylen - 1] != CROSS_FILESPLIT) {
char end[2]={CROSS_FILESPLIT,0};
strcat(expandcopy,end);
}
// open dir
if (dirSearch[id]) {
// open dir
void* dirp = drive->opendir(expandcopy);
if (dirp || dir->isOverlayDir) {
// Reset it..
if (dirp) drive->closedir(dirp);
strcpy(dirPath,expandcopy);
return true;
}
if (dirSearch[id]) {
dirSearch[id]->id = MAX_OPENDIRS;
dirSearch[id] = 0;
}
}
return false;
}
char* DOS_Drive_Cache::CreateEntry(CFileInfo* dir, const char* name, const char* sname, bool is_directory) {
CFileInfo* info = new CFileInfo;
strcpy(info->shortname, sname);
strcpy(info->orgname, name);
info->shortNr = 0;
info->isDir = is_directory;
// Check for long filenames...
if (sname[0]==0) CreateShortName(dir, info);
// keep list sorted (so GetLongName works correctly, used by CreateShortName in this routine)
if (dir->fileList.size()>0) {
if (!(strcmp(info->shortname,dir->fileList.back()->shortname)<0)) {
// append at end of list
dir->fileList.push_back(info);
} else {
bool found = false;
// look for position where to insert this element
std::vector<CFileInfo*>::iterator it;
for (it=dir->fileList.begin(); it!=dir->fileList.end(); ++it) {
if (strcmp(info->shortname,(*it)->shortname)<0) {
found = true;
break;
}
}
// Put file in lists
if (found) dir->fileList.insert(it,info);
else dir->fileList.push_back(info);
}
} else {
// empty file list, append
dir->fileList.push_back(info);
}
static char sgenname[DOS_NAMELENGTH+1];
strcpy(sgenname, info->shortname);
return sgenname;
}
void DOS_Drive_Cache::CopyEntry(CFileInfo* dir, CFileInfo* from) {
CFileInfo* info = new CFileInfo;
// just copy things into new fileinfo
strcpy(info->orgname, from->orgname);
strcpy(info->shortname, from->shortname);
info->shortNr = from->shortNr;
info->isDir = from->isDir;
dir->fileList.push_back(info);
}
bool DOS_Drive_Cache::ReadDir(uint16_t id, char* &result, char * &lresult) {
// shouldnt happen...
if (id>=MAX_OPENDIRS) return false;
if (!IsCachedIn(dirSearch[id])) {
// Try to open directory
void* dirp = drive->opendir(dirPath);
if (!dirp) {
if (dirSearch[id]) {
dirSearch[id]->id = MAX_OPENDIRS;
dirSearch[id] = 0;
}
return false;
}
// Read complete directory
char dir_name[CROSS_LEN], dir_sname[DOS_NAMELENGTH+1];
bool is_directory;
if (drive->read_directory_first(dirp, dir_name, dir_sname, is_directory)) {
CreateEntry(dirSearch[id], dir_name, dir_sname, is_directory);
while (drive->read_directory_next(dirp, dir_name, dir_sname, is_directory)) {
CreateEntry(dirSearch[id], dir_name, dir_sname, is_directory);
}
}
// close dir
drive->closedir(dirp);
// Info
/* if (!dirp) {
LOG_DEBUG("DIR: Error Caching in %s",dirPath);
return false;
} else {
char buffer[128];
sprintf(buffer,"DIR: Caching in %s (%d Files)",dirPath,dirSearch[srchNr]->fileList.size());
LOG_DEBUG(buffer);
};*/
}
if (SetResult(dirSearch[id], result, lresult, dirSearch[id]->nextEntry)) return true;
if (dirSearch[id]) {
dirSearch[id]->id = MAX_OPENDIRS;
dirSearch[id] = 0;
}
return false;
}
bool DOS_Drive_Cache::SetResult(CFileInfo* dir, char* &result, char* &lresult, Bitu entryNr)
{
static char res[CROSS_LEN] = { 0 };
static char lres[CROSS_LEN] = { 0 };
result = res;
lresult = lres;
if (entryNr>=dir->fileList.size()) return false;
CFileInfo* info = dir->fileList[entryNr];
// copy filename, short version
strcpy(res,info->shortname);
strcpy(lres,info->orgname);
// Set to next Entry
dir->nextEntry = entryNr+1;
return true;
}
// FindFirst / FindNext
bool DOS_Drive_Cache::FindFirst(char* path, uint16_t& id) {
uint16_t dirID;
// Cache directory in
if (!OpenDir(path,dirID)) return false;
//Find a free slot.
//If the next one isn't free, move on to the next, if none is free => reset and assume the worst
uint16_t local_findcounter = 0;
while ( local_findcounter < MAX_OPENDIRS ) {
if (dirFindFirst[this->nextFreeFindFirst] == 0) break;
if (++this->nextFreeFindFirst >= MAX_OPENDIRS) this->nextFreeFindFirst = 0; //Wrap around
local_findcounter++;
}
uint16_t dirFindFirstID = this->nextFreeFindFirst++;
if (this->nextFreeFindFirst >= MAX_OPENDIRS) this->nextFreeFindFirst = 0; //Increase and wrap around for the next search.
if (local_findcounter == MAX_OPENDIRS) { //Here is the reset from above.
// no free slot found...
LOG(LOG_DOSMISC,LOG_ERROR)("DIRCACHE: FindFirst/Next: All slots full. Resetting");
// Clear the internal list then.
dirFindFirstID = 0;
this->nextFreeFindFirst = 1; //the next free one after this search
for(Bitu n=0; n<MAX_OPENDIRS;n++) {
// Clear and reuse slot
DeleteFileInfo(dirFindFirst[n]);
dirFindFirst[n]=0;
}
}
dirFindFirst[dirFindFirstID] = new CFileInfo();
dirFindFirst[dirFindFirstID]-> nextEntry = 0;
// Copy entries to use with FindNext
for (Bitu i=0; i<dirSearch[dirID]->fileList.size(); i++) {
CopyEntry(dirFindFirst[dirFindFirstID],dirSearch[dirID]->fileList[i]);
}
// Now re-sort the fileList accordingly to output
switch (sortDirType) {
case ALPHABETICAL : break;
// case ALPHABETICAL : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByName); break;
case DIRALPHABETICAL : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByDirName); break;
case ALPHABETICALREV : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByNameRev); break;
case DIRALPHABETICALREV : std::sort(dirFindFirst[dirFindFirstID]->fileList.begin(), dirFindFirst[dirFindFirstID]->fileList.end(), SortByDirNameRev); break;
case NOSORT : break;
}
// LOG(LOG_DOSMISC,LOG_ERROR)("DIRCACHE: FindFirst : %s (ID:%02X)",path,dirFindFirstID);
id = dirFindFirstID;
return true;
}
bool DOS_Drive_Cache::FindNext(uint16_t id, char* &result, char* &lresult) {
// out of range ?
if ((id>=MAX_OPENDIRS) || !dirFindFirst[id]) {
LOG(LOG_DOSMISC,LOG_ERROR)("DIRCACHE: FindFirst/Next failure : ID out of range: %04X",id);
return false;
}
if (!SetResult(dirFindFirst[id], result, lresult, dirFindFirst[id]->nextEntry)) {
// free slot
DeleteFileInfo(dirFindFirst[id]); dirFindFirst[id] = 0;
return false;
}
return true;
}
void DOS_Drive_Cache::ClearFileInfo(CFileInfo *dir) {
for(uint32_t i=0; i<dir->fileList.size(); i++) {
if (CFileInfo *info = dir->fileList[i])
ClearFileInfo(info);
}
if (dir->id != MAX_OPENDIRS) {
dirSearch[dir->id] = 0;
dir->id = MAX_OPENDIRS;
}
}
void DOS_Drive_Cache::DeleteFileInfo(CFileInfo *dir) {
if (dir)
ClearFileInfo(dir);
delete dir;
}
| 33.853147 | 166 | 0.586183 | [
"vector"
] |
16d343acf9d621afbb5ecb3141e1dfd19e09ae8a | 3,674 | cxx | C++ | lib/seldon/vector/TinyVector.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 7 | 2021-01-31T23:20:07.000Z | 2021-09-09T20:54:15.000Z | lib/seldon/vector/TinyVector.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | 1 | 2021-06-07T07:52:38.000Z | 2021-08-13T20:40:55.000Z | lib/seldon/vector/TinyVector.cxx | HongyuHe/lsolver | c791bf192308ba6b564cb60cb3991d2e72093cd7 | [
"Apache-2.0"
] | null | null | null | #ifndef SELDON_FILE_TINY_VECTOR_CXX
#include "TinyVector.hxx"
namespace Seldon
{
//! intersection of edges [pointA,pointB] and [pt1,pt2]
/*!
\param[in] pointA first extremity of the first edge
\param[in] pointB second extremity of the first edge
\param[in] pt1 first extremity of the second edge
\param[in] pt2 second extremity of the second edge
\param[out] res intersection
\param[in] threshold accuracy of points
\return 0 if no intersection, 1 if intersection and 2 if edges are on the same line
*/
template<class T>
int IntersectionEdges(const TinyVector<T,2>& pointA, const TinyVector<T,2>& pointB,
const TinyVector<T,2>& pt1, const TinyVector<T,2>& pt2,
TinyVector<T,2>& res, const T& threshold)
{
T dx = pointB(0)-pointA(0);
T dy = pointB(1)-pointA(1);
T dxj = pt2(0)-pt1(0);
T dyj = pt2(1)-pt1(1);
T delta = dx*dyj-dy*dxj;
T x, y, zero;
SetComplexZero(zero);
if (delta != zero)
{
x = (dxj*dx*(pointA(1)-pt1(1))+pt1(0)*dyj*dx-pointA(0)*dy*dxj)/delta;
y = -(dyj*dy*(pointA(0)-pt1(0))+pt1(1)*dxj*dy-pointA(1)*dx*dyj)/delta;
// DISP(x); DISP(y); DISP((x-pt1(0))*(x-pt2(0)));
// DISP((y-pt1(1))*(y-pt2(1)));DISP((x-pointA(0))*(x-pointB(0)));
// DISP((y-pointA(1))*(y-pointB(1)));
if (((x-pt1(0))*(x-pt2(0)))<=threshold)
{
if (((y-pt1(1))*(y-pt2(1)))<=threshold)
{
if (((x-pointA(0))*(x-pointB(0)))<=threshold)
{
if (((y-pointA(1))*(y-pointB(1)))<=threshold)
{
res.Init(x,y);
return 1;
}
}
}
}
}
else
{
if (abs(dx*(pt1(1)-pointA(1))-dy*(pt1(0)-pointA(0)))<=threshold)
{
return 2;
}
}
return 0;
}
//! intersection of lines [pointA,pointB] and [pt1,pt2]
/*!
\param[in] pointA a point of the first line
\param[in] pointB a point of the first line
\param[in] pt1 a point of the second line
\param[in] pt2 a point of the second line
\param[out] res intersection
\param[in] threshold accuracy of points
\return 0 if no intersection, 1 if intersection and 2 if lines are equal
*/
template<class T>
int IntersectionDroites(const TinyVector<T,2>& pointA, const TinyVector<T,2>& pointB,
const TinyVector<T,2>& pt1, const TinyVector<T,2>& pt2,
TinyVector<T,2>& res, const T& threshold)
{
T dx = pointB(0)-pointA(0);
T dy = pointB(1)-pointA(1);
T dxj = pt2(0)-pt1(0);
T dyj = pt2(1)-pt1(1);
T delta = dx*dyj-dy*dxj;
T x,y, zero;
SetComplexZero(zero);
if (abs(delta) > threshold)
{
x=(dxj*dx*(pointA(1)-pt1(1))+pt1(0)*dyj*dx-pointA(0)*dy*dxj)/delta;
if (abs(dx) > abs(dxj))
y = dy/dx*(x-pointA(0)) + pointA(1);
else
y = dyj/dxj*(x-pt1(0)) + pt1(1);
res.Init(x,y);
return 1;
}
else
{
if (abs(dx*(pt1(1)-pointA(1))-dy*(pt1(0)-pointA(0))) <= threshold)
{
return 2;
}
}
return 0;
}
//! constructing tangent vectors u1 and u2, from normale to a plane
template<class T>
void GetVectorPlane(const TinyVector<T,3>& normale,
TinyVector<T, 3>& u1, TinyVector<T, 3>& u2)
{
Vector<T> coord(3); IVect perm(3);
perm.Fill();
for (int i = 0; i < 3; i++)
coord(i) = abs(normale(i));
Sort(3, coord, perm);
u1.Zero(); u1(perm(2)) = -normale(perm(1));
u1(perm(1)) = normale(perm(2));
// le dernier vecteur est obtenu avec un produit vectoriel
TimesProd(normale, u1, u2);
typename ClassComplexType<T>::Treal one;
SetComplexOne(one);
Mlt(one/Norm2(u1), u1); Mlt(one/Norm2(u2), u2);
}
} // end namespace
#define SELDON_FILE_TINY_VECTOR_CXX
#endif
| 27.41791 | 87 | 0.58601 | [
"vector"
] |
16d3ad70fae33831c4cc8ee779355166de2a80b5 | 4,863 | cpp | C++ | src/caffe/util/OpenCL/OpenCLManager.cpp | lunochod/caffe | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 20 | 2015-06-20T18:08:42.000Z | 2018-05-27T09:28:34.000Z | src/caffe/util/OpenCL/OpenCLManager.cpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 3 | 2015-03-30T16:40:42.000Z | 2015-06-03T10:31:51.000Z | src/caffe/util/OpenCL/OpenCLManager.cpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 6 | 2015-05-09T02:06:20.000Z | 2015-10-19T07:13:47.000Z | #ifdef USE_OPENCL
#include <CL/cl.h>
#include <glog/logging.h>
#include <caffe/util/OpenCL/OpenCLManager.hpp>
#include <caffe/util/OpenCL/OpenCLSupport.hpp>
#include <memory>
#include <string>
#include <vector>
namespace caffe {
OpenCLManager OpenCLManager::instance_;
OpenCLManager::OpenCLManager() : initialized_(
false) {
}
OpenCLManager::~OpenCLManager() {
}
bool OpenCLManager::Init() {
if (instance_.initialized_) {
return true;
}
LOG(INFO)<< "Initialize OpenCL";
instance_.Query();
if (OpenCLManager::GetNumPlatforms() <= 0) {
LOG(FATAL)<< "No OpenCL platforms found.";
return false;
}
// TODO: mechanism for choosing the correct platform.
instance_.current_platform_index_ = 0;
std::tr1::shared_ptr<OpenCLPlatform> pf = CurrentPlatform();
pf->print();
if (!pf->createContext()) {
LOG(FATAL)<< "failed to create OpenCL context for platform "
<< pf->name();
return false;
}
std::vector<std::string> cl_files;
cl_files.push_back(
"src/caffe/util/OpenCL/gemm.cl");
cl_files.push_back(
"src/caffe/util/OpenCL/math_functions.cl");
cl_files.push_back(
"src/caffe/util/OpenCL/im2col.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/pooling_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/relu_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/prelu_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/sigmoid_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/tanh_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/dropout_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/bnll_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/contrastive_loss_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/eltwise_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/lrn_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/softmax_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/softmax_loss_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/threshold_layer.cl");
cl_files.push_back(
"src/caffe/layers/OpenCL/mvn_layer.cl");
std::vector<std::string>::iterator it;
for (it = cl_files.begin(); it != cl_files.end(); it++) {
if (!pf->compile(
*it)) {
LOG(FATAL)<< "failed to create to create OpenCL program for platform "
<< pf->name();
return false;
}
}
if (pf->getNumGPUDevices() < 1) {
LOG(FATAL)<< "No GPU devices available at platform " << pf->name();
return false;
}
pf->SetCurrentDevice(
CL_DEVICE_TYPE_GPU,
instance_.device_id_);
OpenCLDevice& device = pf->CurrentDevice();
if (!device.createQueue()) {
LOG(FATAL)<< "failed to create OpenCL command queue for device "
<< device.name();
return false;
}
if (clblasSetup() != CL_SUCCESS) {
LOG(FATAL)<< "failed to initialize clBlas";
return false;
}
device.print();
instance_.initialized_ = true;
return true;
}
bool OpenCLManager::Query() {
typedef std::vector<cl::Platform> ClPlatforms;
typedef ClPlatforms::iterator ClPlatformsIter;
ClPlatforms cl_platforms;
cl::Platform::get(
&cl_platforms);
if (cl_platforms.empty()) {
LOG(INFO)<< "found no OpenCL platforms.";
return false;
}
for (ClPlatformsIter it = cl_platforms.begin(); it != cl_platforms.end();
++it) {
std::tr1::shared_ptr<OpenCLPlatform> pp = std::tr1::shared_ptr<
OpenCLPlatform>(
new OpenCLPlatform(
*it));
if (!pp->Query()) {
LOG(ERROR)<< "failed to query platform.";
return false;
}
platforms_.push_back(
pp);
}
LOG(INFO)<< "found " << platforms_.size() << " OpenCL platforms";
// FIXME: platform is the first one.
current_platform_index_ = 0;
return true;
}
void OpenCLManager::Print() {
std::cout << "-- OpenCL Manager Information -------------------------------"
<< std::endl;
for (PlatformIter it = instance_.platforms_.begin();
it != instance_.platforms_.end(); it++) {
(*it)->print();
}
}
int OpenCLManager::GetNumPlatforms() {
return instance_.platforms_.size();
}
std::tr1::shared_ptr<OpenCLPlatform> OpenCLManager::getPlatform(
unsigned int idx) {
if (idx >= platforms_.size()) {
LOG(ERROR)<< "platform idx = " << idx << " out of range.";
std::tr1::shared_ptr<OpenCLPlatform> ptr;
return ptr;
}
return platforms_[idx];
}
std::tr1::shared_ptr<OpenCLPlatform> OpenCLManager::CurrentPlatform() {
if (instance_.current_platform_index_ < 0) {
LOG(FATAL)<< "No current platform.";
}
return instance_.platforms_[instance_.current_platform_index_];
}
void OpenCLManager::SetDeviceId(int device_id) {
instance_.device_id_ = device_id;
}
} // namespace caffe
#endif // USE_OPENCL
| 25.867021 | 78 | 0.659881 | [
"vector"
] |
16dddffd0bef3ec5b7142e765d96653e66e59ff6 | 2,791 | cpp | C++ | src/external/boost/boost_1_68_0/libs/geometry/example/with_external_libs/x01_qt_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/external/boost/boost_1_68_0/libs/geometry/example/with_external_libs/x01_qt_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/external/boost/boost_1_68_0/libs/geometry/example/with_external_libs/x01_qt_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Qt Example
// Qt is a well-known and often used platform independent windows library
// To build and run this example:
// 1) download (from http://qt.nokia.com), configure and make QT
// 2) if necessary, adapt Qt clause in include path (note there is a Qt property sheet)
#include <sstream>
#include <QtGui>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
// Adapt a QPointF such that it can be handled by Boost.Geometry
BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPointF, double, cs::cartesian, x, y, setX, setY)
// Adapt a QPolygonF as well.
// A QPolygonF has no holes (interiors) so it is similar to a Boost.Geometry ring
BOOST_GEOMETRY_REGISTER_RING(QPolygonF)
int main(int argc, char *argv[])
{
// This usage QApplication and QLabel is adapted from
// http://en.wikipedia.org/wiki/Qt_(toolkit)#Qt_hello_world
QApplication app(argc, argv);
// Declare a Qt polygon. The Qt Polygon can be used
// in Boost.Geometry, just by its oneline registration above.
QPolygonF polygon;
// Use Qt to add points to polygon
polygon
<< QPointF(10, 20) << QPointF(20, 30)
<< QPointF(30, 20) << QPointF(20, 10)
<< QPointF(10, 20);
// Use Boost.Geometry e.g. to calculate area
std::ostringstream out;
out << "Boost.Geometry area: " << boost::geometry::area(polygon) << std::endl;
// Some functionality is defined in both Qt and Boost.Geometry
QPointF p(20,20);
out << "Qt contains: "
<< (polygon.containsPoint(p, Qt::WindingFill) ? "yes" : "no")
<< std::endl
<< "Boost.Geometry within: "
<< (boost::geometry::within(p, polygon) ? "yes" : "no")
<< std::endl;
// Detail: if point is ON boundary, Qt says yes, Boost.Geometry says no.
// Qt defines an iterator
// (which is required for of the Boost.Geometry ring-concept)
// such that Boost.Geometry can use the points of this polygon
QPolygonF::const_iterator it;
for (it = polygon.begin(); it != polygon.end(); ++it)
{
// Stream Delimiter-Separated, just to show something Boost.Geometry can do
out << boost::geometry::dsv(*it) << std::endl;
}
// Stream the polygon as well
out << boost::geometry::dsv(polygon) << std::endl;
// Just show what we did in a label
QLabel label(out.str().c_str());
label.show();
return app.exec();
}
| 34.45679 | 90 | 0.671444 | [
"geometry"
] |
16e788879284045818c6aa7f1753dbff06741a05 | 39,823 | cpp | C++ | CrazyCanvas/Source/RenderStages/PlayerRenderer.cpp | IbexOmega/CrazyCanvas | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 18 | 2020-09-04T08:00:54.000Z | 2021-08-29T23:04:45.000Z | CrazyCanvas/Source/RenderStages/PlayerRenderer.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 32 | 2020-09-12T19:24:50.000Z | 2020-12-11T14:29:44.000Z | CrazyCanvas/Source/RenderStages/PlayerRenderer.cpp | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 2 | 2020-12-15T15:36:13.000Z | 2021-03-27T14:27:02.000Z | #include "RenderStages/PlayerRenderer.h"
#include "RenderStages/PlayerRenderer.h"
#include "Rendering/Core/API/CommandAllocator.h"
#include "Rendering/Core/API/DescriptorHeap.h"
#include "Rendering/Core/API/DescriptorSet.h"
#include "Rendering/Core/API/PipelineState.h"
#include "Rendering/Core/API/TextureView.h"
#include "Rendering/EntityMaskManager.h"
#include "Rendering/RenderAPI.h"
#include "Engine/EngineConfig.h"
#include "ECS/ECSCore.h"
#include "Game/ECS/Components/Team/TeamComponent.h"
#include "ECS/Components/Player/Player.h"
#include "ECS/Components/Player/WeaponComponent.h"
#include "Game/ECS/Components/Player/PlayerRelatedComponent.h"
#include "Game/ECS/Systems/Rendering/RenderSystem.h"
#include "Game/ECS/Components/Rendering/MeshPaintComponent.h"
#include <algorithm>
#include <numeric> // std::iota
namespace LambdaEngine
{
PlayerRenderer* PlayerRenderer::s_pInstance = nullptr;
PlayerRenderer::PlayerRenderer() :
m_Viewer()
{
VALIDATE(s_pInstance == nullptr);
s_pInstance = this;
}
PlayerRenderer::~PlayerRenderer()
{
VALIDATE(s_pInstance != nullptr);
s_pInstance = nullptr;
if (m_ppGraphicCommandAllocators != nullptr && m_ppGraphicCommandLists != nullptr)
{
for (uint32 b = 0; b < m_BackBufferCount; b++)
{
SAFERELEASE(m_ppGraphicCommandLists[b]);
SAFERELEASE(m_ppGraphicCommandAllocators[b]);
}
SAFEDELETE_ARRAY(m_ppGraphicCommandLists);
SAFEDELETE_ARRAY(m_ppGraphicCommandAllocators);
}
}
bool PlayerRenderer::Init()
{
m_BackBufferCount = BACK_BUFFER_COUNT;
m_UsingMeshShader = EngineConfig::GetBoolProperty(EConfigOption::CONFIG_OPTION_MESH_SHADER);
if (!CreatePipelineLayout())
{
LOG_ERROR("[PlayerRenderer]: Failed to create PipelineLayout");
return false;
}
if (!CreateDescriptorSets())
{
LOG_ERROR("[PlayerRenderer]: Failed to create DescriptorSet");
return false;
}
if (!CreateShaders())
{
LOG_ERROR("[PlayerRenderer]: Failed to create Shaders");
return false;
}
return true;
}
bool PlayerRenderer::RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc)
{
VALIDATE(pPreInitDesc);
VALIDATE(pPreInitDesc->pDepthStencilAttachmentDesc != nullptr);
if (!m_Initilized)
{
if (!CreateCommandLists())
{
LOG_ERROR("[PlayerRenderer]: Failed to create render command lists");
return false;
}
if (!CreateRenderPass(pPreInitDesc->pColorAttachmentDesc, pPreInitDesc->pDepthStencilAttachmentDesc))
{
LOG_ERROR("[PlayerRenderer]: Failed to create RenderPass");
return false;
}
if (!CreatePipelineState())
{
LOG_ERROR("[PlayerRenderer]: Failed to create PipelineState");
return false;
}
m_Initilized = true;
}
return true;
}
void PlayerRenderer::Update(LambdaEngine::Timestamp delta, uint32 modFrameIndex, uint32 backBufferIndex)
{
UNREFERENCED_VARIABLE(delta);
UNREFERENCED_VARIABLE(backBufferIndex);
m_DescriptorCache.HandleUnavailableDescriptors(modFrameIndex);
m_CurrModFrameIndex = modFrameIndex;
}
void PlayerRenderer::UpdateTextureResource(
const String& resourceName,
const TextureView* const* ppPerImageTextureViews,
const TextureView* const* ppPerSubImageTextureViews,
const Sampler* const* ppPerImageSamplers,
uint32 imageCount,
uint32 subImageCount,
bool backBufferBound)
{
UNREFERENCED_VARIABLE(ppPerImageSamplers);
UNREFERENCED_VARIABLE(ppPerSubImageTextureViews);
UNREFERENCED_VARIABLE(subImageCount);
UNREFERENCED_VARIABLE(backBufferBound);
// Fetching render targets
if (resourceName == "INTERMEDIATE_OUTPUT_IMAGE")
{
m_IntermediateOutputImage = MakeSharedRef(ppPerImageTextureViews[0]);
}
// Writing textures to DescriptorSets
if (resourceName == SCENE_ALBEDO_MAPS)
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 0;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_ALBEDO_MAPS", setIndex);
}
}
else if (resourceName == SCENE_NORMAL_MAPS)
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 1;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_NORMAL_MAPS", setIndex);
}
}
else if (resourceName == SCENE_COMBINED_MATERIAL_MAPS)
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 2;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_COMBINED_MATERIAL_MAPS", setIndex);
}
}
else if (resourceName == "G_BUFFER_DEPTH_STENCIL")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 3;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] G_BUFFER_DEPTH_STENCIL", setIndex);
}
for (uint32 i = 0; i < imageCount; i++)
{
// Not sure if this the correct textureView
m_DepthStencil = MakeSharedRef(ppPerImageTextureViews[0]); // used in beginRenderPass
}
}
else if (resourceName == "DIRL_SHADOWMAP")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 4;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] DIRL_SHADOWMAP", setIndex);
}
}
else if (resourceName == "SCENE_POINT_SHADOWMAPS")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 5;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_POINT_SHADOWMAPS", setIndex);
}
}
else if (resourceName == "GLOBAL_SPECULAR_PROBE")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 6;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] GLOBAL_SPECULAR_PROBE", setIndex);
}
}
else if (resourceName == "GLOBAL_DIFFUSE_PROBE")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 7;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] GLOBAL_DIFFUSE_PROBE", setIndex);
}
}
else if (resourceName == "INTEGRATION_LUT")
{
constexpr DescriptorSetIndex setIndex = 1U;
m_DescriptorSet1 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet1 != nullptr)
{
Sampler* pSampler = Sampler::GetLinearSampler();
uint32 bindingIndex = 8;
m_DescriptorSet1->WriteTextureDescriptors(ppPerImageTextureViews, &pSampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, bindingIndex, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] INTEGRATION_LUT", setIndex);
}
}
}
void PlayerRenderer::UpdateBufferResource(const String& resourceName, const Buffer* const* ppBuffers, uint64* pOffsets, uint64* pSizesInBytes, uint32 count, bool backBufferBound)
{
UNREFERENCED_VARIABLE(backBufferBound);
UNREFERENCED_VARIABLE(count);
UNREFERENCED_VARIABLE(pOffsets);
UNREFERENCED_VARIABLE(ppBuffers);
// create the descriptors that we described in CreatePipelineLayout()
if (resourceName == SCENE_MAT_PARAM_BUFFER)
{
constexpr DescriptorSetIndex setIndex = 0U;
m_DescriptorSet0 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet0 != nullptr)
{
m_DescriptorSet0->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
1,
1,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_MAT_PARAM_BUFFER", setIndex);
}
}
else if (resourceName == PAINT_MASK_COLORS)
{
constexpr DescriptorSetIndex setIndex = 0U;
m_DescriptorSet0 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet0 != nullptr)
{
m_DescriptorSet0->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
2,
1,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] PAINT_MASK_COLORS", setIndex);
}
}
else if (resourceName == SCENE_LIGHTS_BUFFER)
{
constexpr DescriptorSetIndex setIndex = 0U;
m_DescriptorSet0 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet0 != nullptr)
{
m_DescriptorSet0->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
3,
count,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] SCENE_LIGHTS_BUFFER", setIndex);
}
}
if (resourceName == PER_FRAME_BUFFER)
{
constexpr DescriptorSetIndex setIndex = 0U;
m_DescriptorSet0 = m_DescriptorCache.GetDescriptorSet("Player Renderer Buffer Descriptor Set 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get());
if (m_DescriptorSet0 != nullptr)
{
m_DescriptorSet0->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizesInBytes,
0,
1,
EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER
);
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update DescriptorSet[%d] PER_FRAME_BUFFER", setIndex);
}
}
}
void PlayerRenderer::UpdateDrawArgsResource(const String& resourceName, const DrawArg* pDrawArgs, uint32 count)
{
if (resourceName == SCENE_DRAW_ARGS)
{
if (count > 0U && pDrawArgs != nullptr)
{
m_pDrawArgs = pDrawArgs;
m_DrawCount = count;
m_DescriptorSetList2.Clear();
m_DescriptorSetList2.Resize(m_DrawCount);
m_DescriptorSetList3.Clear();
m_DescriptorSetList3.Resize(m_DrawCount);
m_DirtyUniformBuffers = true;
ECSCore* pECSCore = ECSCore::GetInstance();
const ComponentArray<TeamComponent>* pTeamComponents = pECSCore->GetComponentArray<TeamComponent>();
const ComponentArray<WeaponComponent>* pWeaponComponents = pECSCore->GetComponentArray<WeaponComponent>();
const ComponentArray<PositionComponent>* pPositionComponents = pECSCore->GetComponentArray<PositionComponent>();
const ComponentArray<PlayerLocalComponent>* pPlayerLocalComponents = pECSCore->GetComponentArray<PlayerLocalComponent>();
const ComponentArray<PlayerRelatedComponent>* pPlayerRelatedComponents = pECSCore->GetComponentArray<PlayerRelatedComponent>();
m_PlayerData.Clear();
TArray<WeaponData> weapons;
for (uint32 d = 0; d < m_DrawCount; d++)
{
constexpr DescriptorSetIndex setIndex = 2U;
// Create a new descriptor or use an old descriptor
m_DescriptorSetList2[d] = m_DescriptorCache.GetDescriptorSet("Player Renderer Descriptor Set 2 - Draw arg-" + std::to_string(d), m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get(), false);
if (m_DescriptorSetList2[d] != nullptr)
{
for (uint32 i = 0; i < m_pDrawArgs[d].EntityIDs.GetSize(); i++)
{
Entity entity = m_pDrawArgs[d].EntityIDs[i];
if (pPlayerRelatedComponents->HasComponent(entity))
{
// Store weapons for later use. Easier to map to players
if (pWeaponComponents->HasComponent(entity))
{
weapons.PushBack({ .EntityId = entity, .DrawArgIndex = d, .InstanceIndex = i});
}
else
{
// Set player data for distance and weapon sorting
PlayerData playerData;
playerData.DrawArgIndex = d;
playerData.EntityId = entity;
playerData.TeamId = pTeamComponents->GetConstData(entity).TeamIndex;
playerData.Position = pPositionComponents->GetConstData(entity).Position;
m_PlayerData.PushBack(playerData);
}
// Set viewer data
if (pPlayerLocalComponents && pPlayerLocalComponents->HasComponent(entity))
{
m_Viewer.DrawArgIndex = d;
m_Viewer.EntityId = entity;
m_Viewer.TeamId = pTeamComponents->GetConstData(entity).TeamIndex;
m_Viewer.Position = pPositionComponents->GetConstData(entity).Position;
}
else
{
// Set Vertex and Instance buffer for rendering
Buffer* ppBuffers[2] = { m_pDrawArgs[d].pVertexBuffer, m_pDrawArgs[d].pInstanceBuffer };
uint64 pOffsets[2] = { 0, 0 };
uint64 pSizes[2] = { m_pDrawArgs[d].pVertexBuffer->GetDesc().SizeInBytes, m_pDrawArgs[d].pInstanceBuffer->GetDesc().SizeInBytes };
m_DescriptorSetList2[d]->WriteBufferDescriptors(
ppBuffers,
pOffsets,
pSizes,
0,
2,
EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER
);
}
}
else
{
LOG_ERROR("[PlayerRenderer]: A entity must have a TeamComponent for it to be processed by PlayerRenderer!");
}
}
}
else
{
LOG_ERROR("[PlayerRenderer]: Failed to update descriptors for drawArgs vertices and instance buffers");
}
}
// Decide weapon for all players
for (auto const& weapon : weapons)
{
auto weaponOwner = pWeaponComponents->GetConstData(weapon.EntityId).WeaponOwner;
auto it = std::find_if(m_PlayerData.Begin(), m_PlayerData.End(),
[&weaponOwner](const PlayerData& pd) { return pd.EntityId == weaponOwner; });
if (it != m_PlayerData.end())
{
it->Weapon = weapon;
it->HasWeapon = true;
}
else
{
LOG_WARNING("[PlayerRenderer] A Weapon %d without a player is present.", weapon.EntityId);
}
}
// Map player not same team as viewer to 1. Shader will filter
for (PlayerData& player : m_PlayerData)
{
if (player.TeamId == m_Viewer.TeamId || IsLocalPlayerSpectator())
{
player.TeamId = 0;
}
else
{
player.TeamId = 1;
}
}
}
else
{
m_DrawCount = 0;
}
}
}
void PlayerRenderer::Render(uint32 modFrameIndex, uint32 backBufferIndex, CommandList** ppFirstExecutionStage, CommandList** ppSecondaryExecutionStage, bool Sleeping)
{
UNREFERENCED_VARIABLE(backBufferIndex);
UNREFERENCED_VARIABLE(ppSecondaryExecutionStage);
uint32 width = m_IntermediateOutputImage->GetDesc().pTexture->GetDesc().Width;
uint32 height = m_IntermediateOutputImage->GetDesc().pTexture->GetDesc().Height;
BeginRenderPassDesc beginRenderPassDesc = {};
beginRenderPassDesc.pRenderPass = m_RenderPass.Get();
beginRenderPassDesc.ppRenderTargets = m_IntermediateOutputImage.GetAddressOf();
beginRenderPassDesc.pDepthStencil = m_DepthStencil.Get();
beginRenderPassDesc.RenderTargetCount = 1;
beginRenderPassDesc.Width = width;
beginRenderPassDesc.Height = height;
beginRenderPassDesc.Flags = FRenderPassBeginFlag::RENDER_PASS_BEGIN_FLAG_INLINE;
beginRenderPassDesc.pClearColors = nullptr;
beginRenderPassDesc.ClearColorCount = 0;
beginRenderPassDesc.Offset.x = 0;
beginRenderPassDesc.Offset.y = 0;
Viewport viewport = {};
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.Width = (float32)width;
viewport.Height = -(float32)height;
viewport.x = 0.0f;
viewport.y = (float32)height;
ScissorRect scissorRect = {};
scissorRect.Width = width;
scissorRect.Height = height;
CommandList* pCommandList = m_ppGraphicCommandLists[modFrameIndex];
m_ppGraphicCommandAllocators[modFrameIndex]->Reset();
pCommandList->Begin(nullptr);
pCommandList->BeginRenderPass(&beginRenderPassDesc);
if (!Sleeping)
{
pCommandList->SetViewports(&viewport, 0, 1);
pCommandList->SetScissorRects(&scissorRect, 0, 1);
if (m_DrawCount > 0)
{
// Render enemy with no culling to see backface of paint
bool renderEnemies = true;
RenderCull(renderEnemies, pCommandList, m_PipelineStateIDNoCull);
// Team members are transparent, Front Culling- and Back Culling is needed
renderEnemies = false;
RenderCull(renderEnemies, pCommandList, m_PipelineStateIDFrontCull);
RenderCull(renderEnemies, pCommandList, m_PipelineStateIDBackCull);
}
}
pCommandList->EndRenderPass();
pCommandList->End();
(*ppFirstExecutionStage) = pCommandList;
}
void PlayerRenderer::RenderCull(bool renderEnemy,
CommandList* pCommandList,
uint64& pipelineId)
{
pCommandList->BindGraphicsPipeline(PipelineStateManager::GetPipelineState(pipelineId));
pCommandList->BindDescriptorSetGraphics(m_DescriptorSet0.Get(), m_PipelineLayout.Get(), 0); // BUFFER_SET_INDEX
pCommandList->BindDescriptorSetGraphics(m_DescriptorSet1.Get(), m_PipelineLayout.Get(), 1); // TEXTURE_SET_INDEX
// Sort player rendering front to back
for (uint32 i = 0; i < m_PlayerData.GetSize(); i++)
{
m_PlayerData[i].Distance2ToViewer = glm::distance2(m_Viewer.Position, m_PlayerData[i].Position);
}
std::sort(m_PlayerData.Begin(), m_PlayerData.End(),
[&](const PlayerData pd1, PlayerData pd2) {return pd1.Distance2ToViewer < pd2.Distance2ToViewer; });
for (auto& player : m_PlayerData)
{
bool drawingVisiblePlayer = player.DrawArgIndex != m_Viewer.DrawArgIndex;
// Skip drawing local player
if (drawingVisiblePlayer || IsLocalPlayerSpectator())
{
bool isEnemy = (player.TeamId == 1);
bool isTeamMate = (player.TeamId == 0);
// Remove enemies if rendering teamates
if (!renderEnemy && isEnemy) {
continue;
}
// Remove teammates if rendering enemies
if (renderEnemy && isTeamMate) {
continue;
}
// Draw player
const DrawArg& drawArg = m_pDrawArgs[player.DrawArgIndex];
pCommandList->SetConstantRange(m_PipelineLayout.Get(), FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER, &player.TeamId, sizeof(uint32), 0);
pCommandList->BindIndexBuffer(drawArg.pIndexBuffer, 0, EIndexType::INDEX_TYPE_UINT32);
pCommandList->BindDescriptorSetGraphics(m_DescriptorSetList2[player.DrawArgIndex].Get(), m_PipelineLayout.Get(), 2); // Mesh data (Vertices and instance buffers)
pCommandList->DrawIndexInstanced(drawArg.IndexCount, drawArg.InstanceCount, 0, 0, 0);
// Draw player weapon
if (player.HasWeapon)
{
const DrawArg& drawArgWeapon = m_pDrawArgs[player.Weapon.DrawArgIndex];
pCommandList->SetConstantRange(m_PipelineLayout.Get(), FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER, &player.TeamId, sizeof(uint32), 0);
pCommandList->BindIndexBuffer(drawArgWeapon.pIndexBuffer, 0, EIndexType::INDEX_TYPE_UINT32);
pCommandList->BindDescriptorSetGraphics(m_DescriptorSetList2[player.Weapon.DrawArgIndex].Get(), m_PipelineLayout.Get(), 2); // Mesh data (Vertices and instance buffers)
pCommandList->DrawIndexInstanced(drawArgWeapon.IndexCount, 1, 0, 0, player.Weapon.InstanceIndex);
}
}
}
}
bool PlayerRenderer::IsLocalPlayerSpectator() const
{
return m_Viewer.TeamId == 0;
}
bool PlayerRenderer::CreatePipelineLayout()
{
/* VERTEX SHADER */
// PerFrameBuffer
DescriptorBindingDesc perFrameBufferDesc = {};
perFrameBufferDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER;
perFrameBufferDesc.DescriptorCount = 1;
perFrameBufferDesc.Binding = 0;
perFrameBufferDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER | FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
DescriptorBindingDesc verticesBindingDesc = {};
verticesBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
verticesBindingDesc.DescriptorCount = 1;
verticesBindingDesc.Binding = 0;
verticesBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
DescriptorBindingDesc instanceBindingDesc = {};
instanceBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
instanceBindingDesc.DescriptorCount = 1;
instanceBindingDesc.Binding = 1;
instanceBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER;
/* PIXEL SHADER */
// MaterialParameters
DescriptorBindingDesc materialParametersBufferDesc = {};
materialParametersBufferDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
materialParametersBufferDesc.DescriptorCount = 1;
materialParametersBufferDesc.Binding = 1;
materialParametersBufferDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
DescriptorBindingDesc paintMaskColorsBufferDesc = {};
paintMaskColorsBufferDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
paintMaskColorsBufferDesc.DescriptorCount = 1;
paintMaskColorsBufferDesc.Binding = 2;
paintMaskColorsBufferDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
// u_AlbedoMaps
DescriptorBindingDesc albedoMapsDesc = {};
albedoMapsDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
albedoMapsDesc.DescriptorCount = 6000;
albedoMapsDesc.Binding = 0;
albedoMapsDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
albedoMapsDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// NormalMapsDesc
DescriptorBindingDesc normalMapsDesc = {};
normalMapsDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
normalMapsDesc.DescriptorCount = 6000;
normalMapsDesc.Binding = 1;
normalMapsDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
normalMapsDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// CombinedMaterialMaps
DescriptorBindingDesc combinedMaterialMapsDesc = {};
combinedMaterialMapsDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
combinedMaterialMapsDesc.DescriptorCount = 6000;
combinedMaterialMapsDesc.Binding = 2;
combinedMaterialMapsDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
combinedMaterialMapsDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// LightBuffer
DescriptorBindingDesc lightBufferDesc = {};
lightBufferDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER;
lightBufferDesc.DescriptorCount = 6000;
lightBufferDesc.Binding = 3;
lightBufferDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
lightBufferDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// u_GBufferDepthStencil
DescriptorBindingDesc depthStencilDesc = {};
depthStencilDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
depthStencilDesc.DescriptorCount = 6000;
depthStencilDesc.Binding = 3;
depthStencilDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
depthStencilDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// u_DirLShadowMap
DescriptorBindingDesc dirLightShadowMapDesc = {};
dirLightShadowMapDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
dirLightShadowMapDesc.DescriptorCount = 6000;
dirLightShadowMapDesc.Binding = 4;
dirLightShadowMapDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
dirLightShadowMapDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// u_PointLShadowMap
DescriptorBindingDesc pointLightShadowMapDesc = {};
pointLightShadowMapDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
pointLightShadowMapDesc.DescriptorCount = 6000;
pointLightShadowMapDesc.Binding = 5;
pointLightShadowMapDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
pointLightShadowMapDesc.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND;
// u_GlobalSpecularProbe
DescriptorBindingDesc globalSpecularProbeDesc = {};
globalSpecularProbeDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
globalSpecularProbeDesc.DescriptorCount = 1;
globalSpecularProbeDesc.Binding = 6;
globalSpecularProbeDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
// u_GlobalDiffuseProbe
DescriptorBindingDesc globalDiffuseProbeDesc = {};
globalDiffuseProbeDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
globalDiffuseProbeDesc.DescriptorCount = 1;
globalDiffuseProbeDesc.Binding = 7;
globalDiffuseProbeDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
// u_IntegrationLUT
DescriptorBindingDesc integrationLUTDesc = {};
integrationLUTDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER;
integrationLUTDesc.DescriptorCount = 1;
integrationLUTDesc.Binding = 8;
integrationLUTDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
// maps to SET = 0 (BUFFER_SET_INDEX)
DescriptorSetLayoutDesc descriptorSetLayoutDesc0 = {};
descriptorSetLayoutDesc0.DescriptorBindings = { perFrameBufferDesc, materialParametersBufferDesc, paintMaskColorsBufferDesc, lightBufferDesc };
// maps to SET = 1 (TEXTURE_SET_INDEX)
DescriptorSetLayoutDesc descriptorSetLayoutDesc1 = {};
descriptorSetLayoutDesc1.DescriptorBindings = { albedoMapsDesc, normalMapsDesc, combinedMaterialMapsDesc, depthStencilDesc,
dirLightShadowMapDesc, pointLightShadowMapDesc, globalSpecularProbeDesc, globalDiffuseProbeDesc, integrationLUTDesc };
// maps to SET = 2 (DRAW_SET_INDEX)
DescriptorSetLayoutDesc descriptorSetLayoutDesc2 = {};
descriptorSetLayoutDesc2.DescriptorBindings = { verticesBindingDesc, instanceBindingDesc };
ConstantRangeDesc constantRangeFragmentDesc = { };
constantRangeFragmentDesc.ShaderStageFlags = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER;
constantRangeFragmentDesc.SizeInBytes = sizeof(uint32);
constantRangeFragmentDesc.OffsetInBytes = 0;
PipelineLayoutDesc pipelineLayoutDesc = { };
pipelineLayoutDesc.DebugName = "Player Renderer Pipeline Layout";
pipelineLayoutDesc.DescriptorSetLayouts = { descriptorSetLayoutDesc0, descriptorSetLayoutDesc1, descriptorSetLayoutDesc2 };
pipelineLayoutDesc.ConstantRanges = { constantRangeFragmentDesc };
m_PipelineLayout = RenderAPI::GetDevice()->CreatePipelineLayout(&pipelineLayoutDesc);
return m_PipelineLayout != nullptr;
}
bool PlayerRenderer::CreateDescriptorSets()
{
DescriptorHeapInfo descriptorCountDesc = { };
descriptorCountDesc.SamplerDescriptorCount = 0;
descriptorCountDesc.TextureDescriptorCount = 0;
descriptorCountDesc.TextureCombinedSamplerDescriptorCount = 7;
descriptorCountDesc.ConstantBufferDescriptorCount = 1;
descriptorCountDesc.UnorderedAccessBufferDescriptorCount = 4;
descriptorCountDesc.UnorderedAccessTextureDescriptorCount = 0;
descriptorCountDesc.AccelerationStructureDescriptorCount = 0;
DescriptorHeapDesc descriptorHeapDesc = { };
descriptorHeapDesc.DebugName = "Player Renderer Descriptor Heap";
descriptorHeapDesc.DescriptorSetCount = 512;
descriptorHeapDesc.DescriptorCount = descriptorCountDesc;
m_DescriptorHeap = RenderAPI::GetDevice()->CreateDescriptorHeap(&descriptorHeapDesc);
if (!m_DescriptorHeap)
{
return false;
}
return true;
}
bool PlayerRenderer::CreateShaders()
{
m_VertexShaderPointGUID = ResourceManager::LoadShaderFromFile("/Players/Players.vert", FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER, EShaderLang::SHADER_LANG_GLSL);
m_PixelShaderPointGUID = ResourceManager::LoadShaderFromFile("/Players/Players.frag", FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER, EShaderLang::SHADER_LANG_GLSL);
return m_VertexShaderPointGUID != GUID_NONE && m_PixelShaderPointGUID != GUID_NONE;
}
bool PlayerRenderer::CreateCommandLists()
{
m_ppGraphicCommandAllocators = DBG_NEW CommandAllocator * [m_BackBufferCount];
m_ppGraphicCommandLists = DBG_NEW CommandList * [m_BackBufferCount];
for (uint32 b = 0; b < m_BackBufferCount; b++)
{
m_ppGraphicCommandAllocators[b] = RenderAPI::GetDevice()->CreateCommandAllocator("Player Renderer Graphics Command Allocator " + std::to_string(b), ECommandQueueType::COMMAND_QUEUE_TYPE_GRAPHICS);
if (!m_ppGraphicCommandAllocators[b])
{
return false;
}
CommandListDesc commandListDesc = {};
commandListDesc.DebugName = "Player Renderer Graphics Command List " + std::to_string(b);
commandListDesc.CommandListType = ECommandListType::COMMAND_LIST_TYPE_PRIMARY;
commandListDesc.Flags = FCommandListFlag::COMMAND_LIST_FLAG_ONE_TIME_SUBMIT;
m_ppGraphicCommandLists[b] = RenderAPI::GetDevice()->CreateCommandList(m_ppGraphicCommandAllocators[b], &commandListDesc);
if (!m_ppGraphicCommandLists[b])
{
return false;
}
}
return true;
}
bool PlayerRenderer::CreateRenderPass(RenderPassAttachmentDesc* pColorAttachmentDesc, RenderPassAttachmentDesc* pDepthStencilAttachmentDesc)
{
// explain state of incoming texture
// CHANGE: get one color attachment, one depth attachment
// CHANGE: parameters to get the incomcing textures
RenderPassAttachmentDesc colorAttachmentDesc = {};
colorAttachmentDesc.Format = pColorAttachmentDesc->Format; //VK_FORMAT_R8G8B8A8_UNORM
colorAttachmentDesc.SampleCount = 1;
colorAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_LOAD;
colorAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE;
colorAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE;
colorAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE;
colorAttachmentDesc.InitialState = pColorAttachmentDesc->InitialState;
colorAttachmentDesc.FinalState = pColorAttachmentDesc->FinalState;
RenderPassAttachmentDesc depthAttachmentDesc = {};
depthAttachmentDesc.Format = pDepthStencilAttachmentDesc->Format; // FORMAT_D24_UNORM_S8_UINT
depthAttachmentDesc.SampleCount = 1;
depthAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_LOAD;
depthAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE;
depthAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE;
depthAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE;
depthAttachmentDesc.InitialState = pDepthStencilAttachmentDesc->InitialState;
depthAttachmentDesc.FinalState = pDepthStencilAttachmentDesc->FinalState;
RenderPassSubpassDesc subpassDesc = {};
subpassDesc.RenderTargetStates = { ETextureState::TEXTURE_STATE_RENDER_TARGET }; // specify render targets state
subpassDesc.DepthStencilAttachmentState = ETextureState::TEXTURE_STATE_DEPTH_STENCIL_ATTACHMENT; // special case for depth
RenderPassSubpassDependencyDesc subpassDependencyDesc = {};
subpassDependencyDesc.SrcSubpass = EXTERNAL_SUBPASS;
subpassDependencyDesc.DstSubpass = 0;
subpassDependencyDesc.SrcAccessMask = 0;
subpassDependencyDesc.DstAccessMask = FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_READ | FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_WRITE;
subpassDependencyDesc.SrcStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT;
subpassDependencyDesc.DstStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT;
RenderPassDesc renderPassDesc = {};
renderPassDesc.DebugName = "Player Renderer Render Pass";
renderPassDesc.Attachments = { colorAttachmentDesc, depthAttachmentDesc };
renderPassDesc.Subpasses = { subpassDesc };
renderPassDesc.SubpassDependencies = { subpassDependencyDesc };
m_RenderPass = RenderAPI::GetDevice()->CreateRenderPass(&renderPassDesc);
return true;
}
bool PlayerRenderer::CreatePipelineState()
{
ManagedGraphicsPipelineStateDesc pipelineStateDesc = {};
pipelineStateDesc.DebugName = "Player Renderer Pipeline Back Cull State";
pipelineStateDesc.RenderPass = m_RenderPass;
pipelineStateDesc.PipelineLayout = m_PipelineLayout;
pipelineStateDesc.InputAssembly.PrimitiveTopology = EPrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipelineStateDesc.RasterizerState.LineWidth = 1.f;
pipelineStateDesc.RasterizerState.PolygonMode = EPolygonMode::POLYGON_MODE_FILL;
pipelineStateDesc.RasterizerState.CullMode = ECullMode::CULL_MODE_BACK;
pipelineStateDesc.DepthStencilState = {};
pipelineStateDesc.DepthStencilState.DepthTestEnable = true;
pipelineStateDesc.DepthStencilState.DepthWriteEnable = true;
pipelineStateDesc.BlendState.BlendAttachmentStates =
{
{
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
COLOR_COMPONENT_FLAG_R | COLOR_COMPONENT_FLAG_G | COLOR_COMPONENT_FLAG_B | COLOR_COMPONENT_FLAG_A,
true
}
};
pipelineStateDesc.VertexShader.ShaderGUID = m_VertexShaderPointGUID;
pipelineStateDesc.PixelShader.ShaderGUID = m_PixelShaderPointGUID;
m_PipelineStateIDBackCull = PipelineStateManager::CreateGraphicsPipelineState(&pipelineStateDesc);
ManagedGraphicsPipelineStateDesc pipelineStateDesc2 = {};
pipelineStateDesc2.DebugName = "Player Renderer Pipeline Front Cull State";
pipelineStateDesc2.RenderPass = m_RenderPass;
pipelineStateDesc2.PipelineLayout = m_PipelineLayout;
pipelineStateDesc2.InputAssembly.PrimitiveTopology = EPrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipelineStateDesc2.RasterizerState.LineWidth = 1.f;
pipelineStateDesc2.RasterizerState.PolygonMode = EPolygonMode::POLYGON_MODE_FILL;
pipelineStateDesc2.RasterizerState.CullMode = ECullMode::CULL_MODE_FRONT;
pipelineStateDesc2.DepthStencilState = {};
pipelineStateDesc2.DepthStencilState.DepthTestEnable = true;
pipelineStateDesc2.DepthStencilState.DepthWriteEnable = true;
pipelineStateDesc2.BlendState.BlendAttachmentStates =
{
{
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
COLOR_COMPONENT_FLAG_R | COLOR_COMPONENT_FLAG_G | COLOR_COMPONENT_FLAG_B | COLOR_COMPONENT_FLAG_A,
true
}
};
pipelineStateDesc2.VertexShader.ShaderGUID = m_VertexShaderPointGUID;
pipelineStateDesc2.PixelShader.ShaderGUID = m_PixelShaderPointGUID;
m_PipelineStateIDFrontCull = PipelineStateManager::CreateGraphicsPipelineState(&pipelineStateDesc2);
ManagedGraphicsPipelineStateDesc pipelineStateDesc3 = {};
pipelineStateDesc3.DebugName = "Player Renderer Pipeline No Cull State";
pipelineStateDesc3.RenderPass = m_RenderPass;
pipelineStateDesc3.PipelineLayout = m_PipelineLayout;
pipelineStateDesc3.InputAssembly.PrimitiveTopology = EPrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipelineStateDesc3.RasterizerState.LineWidth = 1.f;
pipelineStateDesc3.RasterizerState.PolygonMode = EPolygonMode::POLYGON_MODE_FILL;
pipelineStateDesc3.RasterizerState.CullMode = ECullMode::CULL_MODE_NONE;
pipelineStateDesc3.DepthStencilState = {};
pipelineStateDesc3.DepthStencilState.DepthTestEnable = true;
pipelineStateDesc3.DepthStencilState.DepthWriteEnable = true;
pipelineStateDesc3.BlendState.BlendAttachmentStates =
{
{
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendOp::BLEND_OP_ADD,
EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA,
EBlendFactor::BLEND_FACTOR_SRC_ALPHA,
COLOR_COMPONENT_FLAG_R | COLOR_COMPONENT_FLAG_G | COLOR_COMPONENT_FLAG_B | COLOR_COMPONENT_FLAG_A,
true
}
};
pipelineStateDesc3.VertexShader.ShaderGUID = m_VertexShaderPointGUID;
pipelineStateDesc3.PixelShader.ShaderGUID = m_PixelShaderPointGUID;
m_PipelineStateIDNoCull = PipelineStateManager::CreateGraphicsPipelineState(&pipelineStateDesc3);
return true;
}
}
| 39.311945 | 228 | 0.775858 | [
"mesh",
"render"
] |
16f11747d059a04b98709f179e0e6b902afffbbb | 5,046 | cpp | C++ | poprithms/tests/testutil/src/testutil/schedule/base/randomdag.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | 24 | 2020-07-06T17:11:30.000Z | 2022-01-01T07:39:12.000Z | poprithms/tests/testutil/src/testutil/schedule/base/randomdag.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | null | null | null | poprithms/tests/testutil/src/testutil/schedule/base/randomdag.cpp | graphcore/poprithms | 9975a6a343891e3c5f8968a9507261c1185029ed | [
"MIT"
] | 2 | 2020-07-15T12:33:22.000Z | 2021-07-27T06:07:16.000Z | // Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include <algorithm>
#include <random>
#include <sstream>
#include <unordered_set>
#include <vector>
#include <testutil/schedule/base/randomdag.hpp>
#include <poprithms/schedule/transitiveclosure/transitiveclosure.hpp>
namespace poprithms {
namespace schedule {
namespace baseutil {
namespace {
std::vector<std::vector<uint64_t>>
withRedundantsRemoved(const std::vector<std::vector<uint64_t>> &fwdsIn) {
auto fwds = fwdsIn;
poprithms::schedule::transitiveclosure::TransitiveClosure too(fwds);
auto reds = too.getRedundants(fwds);
for (uint64_t i = 0; i < reds.size(); ++i) {
auto olds = fwds[i];
fwds[i].clear();
for (auto x : olds) {
if (std::find(reds[i].cbegin(), reds[i].cend(), x) == reds[i].cend()) {
fwds[i].push_back(x);
}
}
}
return fwds;
}
} // namespace
std::vector<std::vector<uint64_t>> randomConnectedDagToFinal(uint64_t N,
uint32_t seed) {
std::mt19937 gen(seed);
// forward and backward edges. initially empty.
std::vector<std::vector<uint64_t>> fwd(N);
std::vector<std::vector<uint64_t>> bwd(N);
// is there a path (not necessarily direct) to the final node? Initially,
// only if the node IS the final node, as initially there are no edges.
std::vector<bool> isPath(N, false);
isPath[N - 1] = true;
// how many nodes have a path to the final node?
// initially just 1, the final node.
// We well add edges randomly until this is N.
uint64_t nPaths{1};
// depth first search, filling in where there is a path to the final node.
auto flowBack = [&isPath, &nPaths, &bwd](uint64_t x) {
std::vector<uint64_t> toProcess{x};
std::unordered_set<uint64_t> visited;
while (!toProcess.empty()) {
auto nxt = toProcess.back();
toProcess.pop_back();
if (!isPath[nxt]) {
isPath[nxt] = true;
++nPaths;
for (auto src : bwd[nxt]) {
toProcess.push_back(src);
visited.insert(src);
}
}
}
};
while (nPaths < N) {
// generate a random edge a->b, 0 <= a < b < N.
auto a = gen() % N;
auto b = gen() % (N - 1);
b += (b >= a ? 1 : 0);
if (a > b) {
std::swap(a, b);
}
// if it's a new edges, insert it.
if (std::find(fwd[a].cbegin(), fwd[a].cend(), b) == fwd[a].cend()) {
if (!isPath[a]) {
fwd[a].push_back(b);
bwd[b].push_back(a);
// if moreover there's a path from b to the end, but not from a, then
// by adding a->b we've created a path from a to the end. Register
// this, and also register that there is a path for any node which
// already has a path a.
if (isPath[b] && !isPath[a]) {
flowBack(a);
}
}
}
}
return withRedundantsRemoved(fwd);
}
std::vector<std::vector<uint64_t>> randomConnectedDag(uint64_t N,
uint32_t seed) {
// If there are no nodes in the DAG, return the unique solution.
if (N == 0) {
return {};
}
// We first build a bidirectional connected graph, initialized with no
// edges.
std::vector<std::vector<uint64_t>> bidir(N);
// Which nodes are connected to node 0? We'll add edges randomly until all
// nodes are connected to node 0.
std::vector<bool> connectedToNode0(N, false);
connectedToNode0[0] = true;
uint64_t nConnectedToNode0{1};
std::mt19937 gen(seed);
// starting from node 'i' which is connected to '0', perform a depth-first
// search to find any nodes which are newly connected to node '0'.
const auto update =
[&bidir, &connectedToNode0, &nConnectedToNode0](uint64_t i) {
std::vector<uint64_t> toProcess{i};
while (!toProcess.empty()) {
auto nxt = toProcess.back();
toProcess.pop_back();
// For all neighbors, if neightbor is already known to be connected
// to node '0', do nothing. Otherwise, register its connection and
// continue the search.
for (auto node : bidir[nxt]) {
if (!connectedToNode0[node]) {
connectedToNode0[node] = true;
++nConnectedToNode0;
toProcess.push_back(node);
}
}
}
};
while (nConnectedToNode0 < N) {
auto a = gen() % N;
auto b = gen() % N;
if (a != b &&
std::find(bidir[a].cbegin(), bidir[a].cend(), b) == bidir[a].cend()) {
bidir[a].push_back(b);
bidir[b].push_back(a);
if (connectedToNode0[a] && !connectedToNode0[b]) {
update(a);
} else if (!connectedToNode0[a] && connectedToNode0[b]) {
update(b);
}
}
}
std::vector<std::vector<uint64_t>> fwds(N);
for (uint64_t i = 0; i < N; ++i) {
for (auto x : bidir[i]) {
if (x > i) {
fwds[i].push_back(x);
}
}
}
return withRedundantsRemoved(fwds);
}
} // namespace baseutil
} // namespace schedule
} // namespace poprithms
| 28.670455 | 78 | 0.584423 | [
"vector"
] |
16f189c64a67cff15d4152dee0fd056006694e07 | 483 | cpp | C++ | Code-Chef/contests/COOK102/3.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | 1 | 2019-05-20T14:38:05.000Z | 2019-05-20T14:38:05.000Z | Code-Chef/contests/COOK102/3.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | Code-Chef/contests/COOK102/3.cpp | kishorevarma369/Competitive-Programming | f2fd01b0168cb2908f2cc1794ba2c8a461b06838 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void perform()
{
string s;
cin>>s;
vector<int> v;
int val=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='.') val++;
else
{
v.push_back(val);
val=0;
}
}
int ans=0;
for(int i=0;i<v.size();i++)
{
ans^=v[i];
}
if(ans%3) cout<<"Yes\n";
}
int main(int argc, char const *argv[])
{
return 0;
}
| 13.416667 | 38 | 0.434783 | [
"vector"
] |
a84dd30f1e5075d0937e0326238afbb6892d9bc1 | 1,798 | cpp | C++ | snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Methods1/CPP/htw2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2020-02-22T09:30:21.000Z | 2021-08-02T23:44:31.000Z | snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Methods1/CPP/htw2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 555 | 2019-09-23T22:22:58.000Z | 2021-07-15T18:51:12.000Z | snippets/cpp/VS_Snippets_WebNet/HtmlTextWriter_Methods1/CPP/htw2.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 3 | 2020-01-29T16:31:15.000Z | 2021-08-24T07:00:15.000Z | // <snippet1>
// Create a custom HtmlTextWriter class that overrides
// the RenderBeforeContent and RenderAfterContent methods.
#using <System.dll>
#using <System.Web.dll>
using namespace System;
using namespace System::IO;
using namespace System::Web::UI;
using namespace System::Security::Permissions;
using namespace System::Web;
public ref class cstmHtmlTW: public HtmlTextWriter
{
public:
cstmHtmlTW( TextWriter^ writer )
: HtmlTextWriter( writer )
{}
cstmHtmlTW( TextWriter^ writer, String^ tabString )
: HtmlTextWriter( writer, tabString )
{}
protected:
// <snippet2>
// Override the RenderBeforeContent method to write
// a font element that applies red to the text in a Label element.
virtual String^ RenderBeforeContent() override
{
// Check to determine whether the element being rendered
// is a label element. If so, render the opening tag
// of the font element; otherwise, call the base method.
if ( TagKey == HtmlTextWriterTag::Label )
{
return "<font color=\"red\">";
}
else
{
return __super::RenderBeforeContent();
}
}
// </snippet2>
// <snippet3>
// Override the RenderAfterContent method to render
// the closing tag of a font element if the
// rendered tag is a label element.
virtual String^ RenderAfterContent() override
{
// Check to determine whether the element being rendered
// is a label element. If so, render the closing tag
// of the font element; otherwise, call the base method.
if ( TagKey == HtmlTextWriterTag::Label )
{
return "</font>";
}
else
{
return __super::RenderAfterContent();
}
}
// </snippet3>
};
// </snippet1>
| 24.297297 | 69 | 0.646274 | [
"render"
] |
a84fc3f00fa904d0d3e6c23f41262f87ae7432c9 | 7,726 | cpp | C++ | src/Rounding.cpp | oanda/libfixed | 9b7b4ebe28784704276226df42349aa63dfd8acd | [
"MIT"
] | 11 | 2015-03-27T15:41:18.000Z | 2021-04-18T09:56:37.000Z | src/Rounding.cpp | oanda/libfixed | 9b7b4ebe28784704276226df42349aa63dfd8acd | [
"MIT"
] | null | null | null | src/Rounding.cpp | oanda/libfixed | 9b7b4ebe28784704276226df42349aa63dfd8acd | [
"MIT"
] | 6 | 2015-06-24T11:20:36.000Z | 2021-06-16T00:42:15.000Z | //
// The MIT License (MIT)
//
//
// Copyright (c) 2013 OANDA 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.
//
#include "fixed/Rounding.h"
#include <cassert>
namespace fixed {
const std::vector<std::string> Rounding::modeStrings_ = {
{
"DOWN",
"UP",
"TOWARDS_ZERO",
"AWAY_FROM_ZERO",
"TO_NEAREST_HALF_UP",
"TO_NEAREST_HALF_DOWN",
"TO_NEAREST_HALF_AWAY_FROM_ZERO",
"TO_NEAREST_HALF_TOWARDS_ZERO",
"TO_NEAREST_HALF_TO_EVEN",
"TO_NEAREST_HALF_TO_ODD"
}
};
const Rounding::RunTimeModeStringsCheck Rounding::runTimeModeStringsCheck_;
template <typename T>
static T roundDownAdjustment (
const T&, // integerVal
const T& decimalVal,
const T&, // halfRangeVal
const bool negativeFlag
)
{
if (negativeFlag && decimalVal)
{
return -1;
}
return 0;
}
template <typename T>
static T roundUpAdjustment (
const T&, // integerVal
const T& decimalVal,
const T&, // halfRangeVal
const bool negativeFlag
)
{
if (! negativeFlag && decimalVal)
{
return 1;
}
return 0;
}
template <typename T>
static T roundTowardsZeroAdjustment (
const T&, // integerVal
const T&, // decimalVal
const T&, // halfRangeVal
const bool // negativeFlag
)
{
return 0;
}
template <typename T>
static T roundAwayFromZeroAdjustment (
const T&, // integerVal
const T& decimalVal,
const T&, // halfRangeVal
const bool negativeFlag
)
{
if (decimalVal)
{
return negativeFlag ? -1 : 1;
}
return 0;
}
template <typename T>
static T roundToNearestHalfUpAdjustment (
const T&, // integerVal
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
if (negativeFlag)
{
if (decimalVal > halfRangeVal)
{
return -1;
}
}
else
{
if (decimalVal >= halfRangeVal)
{
return 1;
}
}
return 0;
}
template <typename T>
static T roundToNearestHalfDownAdjustment (
const T&, // integerVal
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
if (negativeFlag)
{
if (decimalVal >= halfRangeVal)
{
return -1;
}
}
else
{
if (decimalVal > halfRangeVal)
{
return 1;
}
}
return 0;
}
template <typename T>
static T roundToNearestHalfAwayFromZeroAdjustment (
const T&, // integerVal
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
if (negativeFlag)
{
if (decimalVal >= halfRangeVal)
{
return -1;
}
}
else
{
if (decimalVal >= halfRangeVal)
{
return 1;
}
}
return 0;
}
template <typename T>
static T roundToNearestHalfTowardsZeroAdjustment (
const T&, // integerVal
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
if (negativeFlag)
{
if (decimalVal > halfRangeVal)
{
return -1;
}
}
else
{
if (decimalVal > halfRangeVal)
{
return 1;
}
}
return 0;
}
template <typename T>
static T roundToNearestHalfToEvenAdjustment (
const T& integerVal,
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
const bool odd = integerVal & 0x1;
if (negativeFlag)
{
if (odd)
{
if (decimalVal >= halfRangeVal)
{
return -1;
}
}
else // even
{
if (decimalVal > halfRangeVal)
{
return -1;
}
}
}
else
{
if (odd)
{
if (decimalVal >= halfRangeVal)
{
return 1;
}
}
else // even
{
if (decimalVal > halfRangeVal)
{
return 1;
}
}
}
return 0;
}
template <typename T>
static T roundToNearestHalfToOddAdjustment (
const T& integerVal,
const T& decimalVal,
const T& halfRangeVal,
const bool negativeFlag
)
{
const bool odd = integerVal & 0x1;
if (negativeFlag)
{
if (odd)
{
if (decimalVal > halfRangeVal)
{
return -1;
}
}
else // even
{
if (decimalVal >= halfRangeVal)
{
return -1;
}
}
}
else
{
if (odd)
{
if (decimalVal > halfRangeVal)
{
return 1;
}
}
else // even
{
if (decimalVal >= halfRangeVal)
{
return 1;
}
}
}
return 0;
}
const std::vector<
std::function<
int64_t (
const int64_t& integerVal,
const int64_t& decimalVal,
const int64_t& halfRangeVal,
const bool negativeFlag
)
>
> Rounding::roundingAdjustments64_ = {
roundDownAdjustment<int64_t>,
roundUpAdjustment<int64_t>,
roundTowardsZeroAdjustment<int64_t>,
roundAwayFromZeroAdjustment<int64_t>,
roundToNearestHalfUpAdjustment<int64_t>,
roundToNearestHalfDownAdjustment<int64_t>,
roundToNearestHalfAwayFromZeroAdjustment<int64_t>,
roundToNearestHalfTowardsZeroAdjustment<int64_t>,
roundToNearestHalfToEvenAdjustment<int64_t>,
roundToNearestHalfToOddAdjustment<int64_t>
};
const std::vector<
std::function<
__int128_t (
const __int128_t& integerVal,
const __int128_t& decimalVal,
const __int128_t& halfRangeVal,
const bool negativeFlag
)
>
> Rounding::roundingAdjustments128_ = {
roundDownAdjustment<__int128_t>,
roundUpAdjustment<__int128_t>,
roundTowardsZeroAdjustment<__int128_t>,
roundAwayFromZeroAdjustment<__int128_t>,
roundToNearestHalfUpAdjustment<__int128_t>,
roundToNearestHalfDownAdjustment<__int128_t>,
roundToNearestHalfAwayFromZeroAdjustment<__int128_t>,
roundToNearestHalfTowardsZeroAdjustment<__int128_t>,
roundToNearestHalfToEvenAdjustment<__int128_t>,
roundToNearestHalfToOddAdjustment<__int128_t>
};
Rounding::RunTimeModeStringsCheck::RunTimeModeStringsCheck ()
{
size_t expectedSize =
static_cast<size_t> (
static_cast<std::underlying_type<Mode>::type> (
Mode::MODE_MAX_VAL
)
);
assert (expectedSize == modeStrings_.size ());
}
} // namespace fixed
| 21.167123 | 79 | 0.594227 | [
"vector"
] |
a850b2c6493b0de8f37c726d359e306d500364eb | 3,558 | cpp | C++ | Engine/Src/SFEngineDLL/Interfaces/SFNetRelayInterface.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFEngineDLL/Interfaces/SFNetRelayInterface.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFEngineDLL/Interfaces/SFNetRelayInterface.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2019 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Public Interfaces
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEngineDLLPCH.h"
#include "SFAssert.h"
#include "Util/SFUtility.h"
#include "Util/SFLog.h"
#include "Object/SFObject.h"
#include "Service/SFEngineService.h"
#include "Interfaces/SFNetRelayInterface.h"
#include "Net/SFNetRelayNetwork.h"
#include "Protocol/Message/PlayInstanceMsgClass.h"
namespace SF
{
//////////////////////////////////////////////////////////////////////////////////////
//
//
//
NetRelayNetwork::NetRelayNetwork()
{
m_Impl = NewObject<Net::RelayNetwork>(Service::NetSystem->GetHeap());
}
NetRelayNetwork::~NetRelayNetwork()
{
if (m_Impl == nullptr)
return;
m_Impl->Disconnect("Destroy");
m_Impl->CloseConnection("Destroy");
m_Impl->SetTickFlags(0);
m_Impl = nullptr;
}
RelayNetworkState NetRelayNetwork::GetRelayNetworkState()
{
return m_Impl->GetRelayNetworkState();
}
uint32_t NetRelayNetwork::GetRelayInstanceID() const
{
return m_Impl->GetRelayInstanceID();
}
uint64_t NetRelayNetwork::GetLocalPlayerID() const
{
return m_Impl->GetLocalPlayerID();
}
uint32_t NetRelayNetwork::GetLocalEndpointID() const
{
return m_Impl->GetLocalEndpointID();
}
// Connect to remote. InitConnection + Connect
// @relayServerAddr: relay server address
// @relayInstanceID: relay server instance id
// @myPlayerID: my player id,
uint32_t NetRelayNetwork::Connect(const char* relayServerAddr, uint32_t port, uint32_t relayInstanceID, uint64_t myPlayerID)
{
return m_Impl->Connect(NetAddress(relayServerAddr, port), relayInstanceID, myPlayerID);
}
// Disconnect connection
uint32_t NetRelayNetwork::Disconnect(const char* reason)
{
return m_Impl->Disconnect(reason);
}
// Close connection
uint32_t NetRelayNetwork::CloseConnection(const char* reason)
{
return m_Impl->CloseConnection(reason);
}
// Send message to connected entity
uint32_t NetRelayNetwork::Send(uint32_t targetEndpointMask, uint32_t payloadSize, const void* payloadData)
{
return m_Impl->Send(targetEndpointMask, payloadSize, payloadData);
}
size_t NetRelayNetwork::GetRecvMessageCount()
{
return m_Impl->GetRecvMessageCount();
}
size_t NetRelayNetwork::GetRecvDataSize()
{
MessageDataPtr pMsg;
if (!m_Impl->GetFrontRecvMessage(pMsg))
return 0;
// Hum, shouldn't be happened
if (pMsg->GetMessageSize() < sizeof(uint32_t) * 3)
{
assert(0);
return 1;
}
return pMsg->GetMessageSize() - sizeof(uint32_t) * 3;
}
size_t NetRelayNetwork::RecvData(size_t bufferSize, void* dataBuffer)
{
MessageDataPtr pMsg;
if (!m_Impl->GetRecvMessage(pMsg))
return 0;
Message::PlayInstance::PlayPacketC2SEvt message(std::forward<MessageDataPtr>(pMsg));
auto hr = message.ParseMsg();
if (!hr)
{
SFLog(Net, Error, "NetRelayNetwork::RecvData, : parse error {0}", hr);
return 0;
}
if (dataBuffer == nullptr || bufferSize < message.GetPayload().size())
{
SFLog(Net, Error, "NetRelayNetwork::RecvData, : Not enough buffer size: required:{0}", message.GetPayload().size());
return 0;
}
memcpy(dataBuffer, message.GetPayload().data(), message.GetPayload().size());
return message.GetPayload().size();
}
}
| 23.72 | 126 | 0.639966 | [
"object"
] |
a8542e298bd196f17b32eb5fa4fc546247bac58a | 1,449 | cpp | C++ | DSA/Cpp/test/dsa/lib/algo/sort/radix_sort_test.cpp | JackieMa000/problems | c521558830a0bbf67f94109af92d7be4397d0a43 | [
"BSD-3-Clause"
] | null | null | null | DSA/Cpp/test/dsa/lib/algo/sort/radix_sort_test.cpp | JackieMa000/problems | c521558830a0bbf67f94109af92d7be4397d0a43 | [
"BSD-3-Clause"
] | 1 | 2020-10-23T04:06:56.000Z | 2020-10-23T04:06:56.000Z | DSA/Cpp/test/dsa/lib/algo/sort/radix_sort_test.cpp | JackieMa000/problems | c521558830a0bbf67f94109af92d7be4397d0a43 | [
"BSD-3-Clause"
] | null | null | null | #include <vector>
#include <list>
#include <forward_list>
#include <dsa/lib/algo/sort/radix_sort.hpp>
namespace dsa::lib::algo::sort::rs {
namespace {
void expectRadixSort(std::vector<int> &&expected, std::vector<int> &&nums) {
rs::sort(nums);
EXPECT_EQ(expected, nums);
}
TEST(RadixSortTest, emptyArray) {
expectRadixSort({}, {});
}
TEST(RadixSortTest, oneElement) {
expectRadixSort({1}, {1});
}
TEST(RadixSortTest, sorts) {
expectRadixSort({1, 23, 45, 121, 432, 564, 788}, {121, 432, 564, 23, 1, 45, 788});
}
TEST(RadixSortTest, iterator) {
std::vector<int> nums = {121, 432, 564, 23, 1, 45, 788};
std::vector<int> expected = {1, 23, 45, 121, 432, 564, 788};
rs::sort(nums.begin(), nums.end());
EXPECT_EQ(expected, nums);
}
void expectRadixSortStr(std::vector<std::string> &&expected, std::vector<std::string> &&ss) {
rs::sort(ss);
EXPECT_EQ(expected, ss);
}
TEST(RadixSortStrTest, emptyArray) {
expectRadixSortStr({}, {});
}
TEST(RadixSortStrTest, oneElement) {
expectRadixSortStr({"ab"}, {"ab"});
}
TEST(RadixSortStrTest, sorts) {
expectRadixSortStr({"hac", "hke", "hzg", "iba", "ikf"}, {"hke", "iba", "hzg", "ikf", "hac"});
}
TEST(RadixSortStrTest, iterator) {
std::vector<std::string> ss = {"hke", "iba", "hzg", "ikf", "hac"};
std::vector<std::string> expected = {"hac", "hke", "hzg", "iba", "ikf"};
rs::sortStr(ss.begin(), ss.end());
EXPECT_EQ(expected, ss);
}
}
}
| 27.865385 | 97 | 0.623879 | [
"vector"
] |
a855b727ced01dc807fca2d57ad00145b678a72f | 926 | cpp | C++ | atcoder/abc124/D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc124/D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc124/D/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
int solve(int N, int K, string const& S) {
vector<pair<int,int>> W;
W.reserve(N);
if (S[0] == '0') {
W.push_back({ 0, 0 });
}
int i = 0;
while (i < N) {
if (S[i] == '0') {
++i;
continue;
}
int j;
for (j = i + 1; j < N; ++j) {
if (S[j] == '0') break;
}
W.push_back({ i, j });
i = j;
}
if (W.back().second < N) {
W.push_back({ N, N });
}
if (W.size() <= K + 1) {
return S.size();
}
int ans = 0;
for (int i = 0; i + K < W.size(); ++i) {
ans = max(ans, W[i+K].second - W[i].first);
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int N, K;
string S;
cin >> N >> K;
cin >> S;
cout << solve(N, K, S) << endl;
return 0;
} | 17.471698 | 51 | 0.393089 | [
"vector"
] |
a862fe13f59af645077676227ceac8ee0a8f2bae | 7,335 | cpp | C++ | generator/raw_generator.cpp | mapsme/geocore | 346fceb020cd909b37706ab6ad454aec1a11f52e | [
"Apache-2.0"
] | 13 | 2019-09-16T17:45:31.000Z | 2022-01-29T15:51:52.000Z | generator/raw_generator.cpp | mapsme/geocore | 346fceb020cd909b37706ab6ad454aec1a11f52e | [
"Apache-2.0"
] | 37 | 2019-10-04T00:55:46.000Z | 2019-12-27T15:13:19.000Z | generator/raw_generator.cpp | mapsme/geocore | 346fceb020cd909b37706ab6ad454aec1a11f52e | [
"Apache-2.0"
] | 13 | 2019-10-02T15:03:58.000Z | 2020-12-28T13:06:22.000Z | #include "generator/raw_generator.hpp"
#include "generator/osm_source.hpp"
#include "generator/processor_factory.hpp"
#include "generator/raw_generator_writer.hpp"
#include "generator/translator_factory.hpp"
#include "base/thread_pool_computational.hpp"
#include <future>
#include <string>
#include <vector>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <sys/mman.h>
using namespace std;
namespace generator
{
RawGenerator::RawGenerator(feature::GenerateInfo & genInfo, size_t chunkSize)
: m_genInfo(genInfo)
, m_chunkSize(chunkSize)
, m_cache(std::make_shared<generator::cache::IntermediateData>(genInfo))
, m_queue(std::make_shared<FeatureProcessorQueue>())
, m_translators(std::make_shared<TranslatorCollection>())
{
}
std::shared_ptr<FeatureProcessorQueue> RawGenerator::GetQueue()
{
return m_queue;
}
void RawGenerator::GenerateRegionFeatures(
string const & regionsFeaturesPath, std::string const & regionsInfoPath)
{
auto processor = CreateProcessor(ProcessorType::Simple, m_queue, regionsFeaturesPath);
m_translators->Append(
CreateTranslator(TranslatorType::Regions, processor, m_cache, regionsInfoPath));
}
void RawGenerator::GenerateStreetsFeatures(string const & filename)
{
auto processor = CreateProcessor(ProcessorType::Simple, m_queue, filename);
m_translators->Append(CreateTranslator(TranslatorType::Streets, processor, m_cache));
}
void RawGenerator::GenerateGeoObjectsFeatures(string const & filename)
{
auto processor = CreateProcessor(ProcessorType::Simple, m_queue, filename);
m_translators->Append(CreateTranslator(TranslatorType::GeoObjects, processor, m_cache));
}
void RawGenerator::GenerateCustom(std::shared_ptr<TranslatorInterface> const & translator)
{
m_translators->Append(translator);
}
void RawGenerator::GenerateCustom(std::shared_ptr<TranslatorInterface> const & translator,
std::shared_ptr<FinalProcessorIntermediateMwmInterface> const & finalProcessor)
{
m_translators->Append(translator);
m_finalProcessors.emplace(finalProcessor);
}
bool RawGenerator::Execute()
{
if (!GenerateFilteredFeatures())
return false;
while (!m_finalProcessors.empty())
{
base::thread_pool::computational::ThreadPool threadPool(m_genInfo.m_threadsCount);
while (true)
{
auto const finalProcessor = m_finalProcessors.top();
m_finalProcessors.pop();
threadPool.SubmitWork([finalProcessor{finalProcessor}]() {
finalProcessor->Process();
});
if (m_finalProcessors.empty() || *finalProcessor != *m_finalProcessors.top())
break;
}
}
LOG(LINFO, ("Final processing is finished."));
return true;
}
std::vector<std::string> const & RawGenerator::GetNames() const
{
return m_names;
}
bool RawGenerator::GenerateFilteredFeatures()
{
RawGeneratorWriter rawGeneratorWriter(m_queue);
rawGeneratorWriter.Run();
auto processorThreadsCount = std::max(m_genInfo.m_threadsCount, 2u) - 1 /* writer */;
if (m_genInfo.m_osmFileName.empty()) // stdin
processorThreadsCount = 1;
if (!GenerateFeatures(processorThreadsCount, rawGeneratorWriter))
return false;
rawGeneratorWriter.ShutdownAndJoin();
m_names = rawGeneratorWriter.GetNames();
LOG(LINFO, ("Names:", m_names));
return true;
}
bool RawGenerator::GenerateFeatures(
unsigned int threadsCount, RawGeneratorWriter & /* rawGeneratorWriter */)
{
auto translators = std::vector<std::shared_ptr<TranslatorInterface>>{};
auto sourceMap = boost::optional<boost::iostreams::mapped_file_source>{};
if (!m_genInfo.m_osmFileName.empty())
{
sourceMap = MakeFileMap(m_genInfo.m_osmFileName);
LOG_SHORT(LINFO, ("Reading OSM data from", m_genInfo.m_osmFileName));
}
std::vector<std::thread> threads;
for (unsigned int i = 0; i < threadsCount; ++i)
{
auto translator = m_translators->Clone();
translators.push_back(translator);
constexpr size_t chunkSize = 10'000;
auto processorMaker =
[osmFileType = m_genInfo.m_osmFileType, threadsCount, i, chunkSize] (auto & reader)
-> std::unique_ptr<ProcessorOsmElementsInterface>
{
switch (osmFileType)
{
case feature::GenerateInfo::OsmSourceType::O5M:
return std::make_unique<ProcessorOsmElementsFromO5M>(reader, threadsCount, i, chunkSize);
case feature::GenerateInfo::OsmSourceType::XML:
return std::make_unique<ProcessorOsmElementsFromXml>(reader);
}
UNREACHABLE();
};
threads.emplace_back([translator, processorMaker, &sourceMap] {
if (!sourceMap)
{
auto reader = SourceReader{};
auto processor = processorMaker(reader);
TranslateToFeatures(*processor, *translator);
return;
}
namespace io = boost::iostreams;
auto && sourceArray = io::array_source{sourceMap->data(), sourceMap->size()};
auto && stream = io::stream<io::array_source>{sourceArray, std::ios::binary};
auto && reader = SourceReader(stream);
auto processor = processorMaker(reader);
TranslateToFeatures(*processor, *translator);
});
}
for (auto & thread : threads)
thread.join();
LOG(LINFO, ("Input was processed."));
return FinishTranslation(translators);
}
// static
void RawGenerator::TranslateToFeatures(ProcessorOsmElementsInterface & sourceProcessor,
TranslatorInterface & translator)
{
OsmElement osmElement{};
while (sourceProcessor.TryRead(osmElement))
translator.Emit(osmElement);
}
bool RawGenerator::FinishTranslation(
std::vector<std::shared_ptr<TranslatorInterface>> & translators)
{
using TranslatorPtr = std::shared_ptr<TranslatorInterface>;
base::threads::ThreadSafeQueue<std::future<TranslatorPtr>> queue;
for (auto const & translator : translators)
{
std::promise<TranslatorPtr> p;
p.set_value(translator);
queue.Push(p.get_future());
}
CHECK_GREATER_OR_EQUAL(queue.Size(), 1, ());
base::thread_pool::computational::ThreadPool pool(queue.Size() / 2 + 1);
while (queue.Size() != 1)
{
std::future<TranslatorPtr> left;
std::future<TranslatorPtr> right;
queue.WaitAndPop(left);
queue.WaitAndPop(right);
queue.Push(pool.Submit([left{move(left)}, right{move(right)}]() mutable {
auto leftTranslator = left.get();
auto rigthTranslator = right.get();
rigthTranslator->Finish();
leftTranslator->Finish();
leftTranslator->Merge(*rigthTranslator);
return leftTranslator;
}));
}
std::future<TranslatorPtr> translatorFuture;
queue.WaitAndPop(translatorFuture);
auto translator = translatorFuture.get();
translator->Finish();
return translator->Save();
}
boost::iostreams::mapped_file_source RawGenerator::MakeFileMap(std::string const & filename)
{
CHECK(!filename.empty(), ());
auto fileMap = boost::iostreams::mapped_file_source{filename};
if (!fileMap.is_open())
MYTHROW(Writer::OpenException, ("Failed to open", filename));
// Try aggressively (MADV_WILLNEED) and asynchronously read ahead the o5m-file.
auto readaheadTask = std::thread([data = fileMap.data(), size = fileMap.size()] {
::madvise(const_cast<char*>(data), size, MADV_WILLNEED);
});
readaheadTask.detach();
return fileMap;
}
} // namespace generator
| 31.080508 | 113 | 0.715746 | [
"vector"
] |
a8631c1585576519cfc548ad71b04cb7fc11f96f | 6,708 | cpp | C++ | test/KOMO/komo/main.cpp | v4hn/rai | 0638426c2c4a240863de4f39778d48e48fd8f5d7 | [
"MIT"
] | null | null | null | test/KOMO/komo/main.cpp | v4hn/rai | 0638426c2c4a240863de4f39778d48e48fd8f5d7 | [
"MIT"
] | null | null | null | test/KOMO/komo/main.cpp | v4hn/rai | 0638426c2c4a240863de4f39778d48e48fd8f5d7 | [
"MIT"
] | null | null | null | #include <KOMO/komo.h>
#include <Kin/TM_default.h>
#include <Kin/F_PairCollision.h>
#include <Kin/viewer.h>
//===========================================================================
void TEST(Easy){
rai::Configuration C("arm.g");
cout <<"configuration space dim=" <<C.getJointStateDimension() <<endl;
KOMO komo;
komo.setModel(C);
komo.setTiming(1., 100, 5., 2);
komo.add_qControlObjective({}, 2, 1.);
//-- set a time optim objective
// komo.addObjective({}, make_shared<TM_Time>(), OT_sos, {1e2}, {}, 1); //smooth time evolution
// komo.addObjective({}, make_shared<TM_Time>(), OT_sos, {1e1}, {komo.tau}, 0); //prior on timing
komo.addObjective({1.}, FS_positionDiff, {"endeff", "target"}, OT_sos, {1e1});
komo.addObjective({.98,1.}, FS_qItself, {}, OT_sos, {1e1}, {}, 1);
komo.addObjective({}, FS_accumulatedCollisions, {}, OT_eq, {1.});
komo.reportProblem();
// komo.setSpline(5);
komo.optimize();
cout <<"TIME OPTIM: total=" <<sum(komo.getPath_times()) <<komo.getPath_times() <<endl;
komo.plotTrajectory();
// komo.reportProxies();
komo.checkGradients();
for(uint i=0;i<2;i++) komo.displayTrajectory();
}
//===========================================================================
void TEST(Align){
rai::Configuration C("arm.g");
cout <<"configuration space dim=" <<C.getJointStateDimension() <<endl;
KOMO komo;
// komo.solver = rai::KS_sparseStructured;
// komo.solver = rai::KS_sparse;
komo.solver = rai::KS_banded;
komo.verbose=1;
komo.setModel(C);
komo.setTiming(1., 100, 5., 2);
komo.add_qControlObjective({}, 2, 1.);
komo.addObjective({1.}, FS_positionDiff, {"endeff", "target"}, OT_eq, {1e1});
komo.addObjective({1.}, FS_quaternionDiff, {"endeff", "target"}, OT_eq, {1e1});
komo.addObjective({.98,1.}, FS_qItself, {}, OT_sos, {1e1}, {}, 1);
komo.addObjective({}, FS_accumulatedCollisions, {}, OT_eq, {1.});
komo.optimize();
// komo.checkGradients();
komo.plotTrajectory();
rai::ConfigurationViewer V;
V.setPath(C, komo.x, "result", true);
// for(uint i=0;i<2;i++) komo.displayTrajectory();
}
//===========================================================================
struct MyFeature : Feature {
int i, j; ///< which shapes does it refer to?
MyFeature(int _i, int _j)
: i(_i), j(_j) {}
MyFeature(const rai::Configuration& K, const char* s1, const char* s2)
: i(initIdArg(K, s1)), j(initIdArg(K, s2)) {}
virtual void phi(arr& y, arr& J, const ConfigurationL& Ctuple){
CHECK_EQ(order, 1, "");
auto V = TM_Default(TMT_posDiff, i, NoVector, j).setOrder(1).eval(Ctuple);
auto C = F_PairCollision(i, j, F_PairCollision::_normal, false).eval(Ctuple);
auto D = F_PairCollision(i, j, F_PairCollision::_negScalar, false).eval(Ctuple);
//penalizing velocity whenever close
double range=.2;
if(-D.y.scalar() > range){
y = zeros(3);
if(!!J) J = zeros(3, V.J.d1);
return;
}
double weight = 1. + D.y.scalar()/range;
double normalWeight = 1.;
arr P = eye(3) + normalWeight*(C.y*~C.y);
y = weight * P * V.y;
if(!!J){
J = weight * P * V.J;
J += P * V.y.reshape(3,1) * (1./range)*D.J;
J += (weight * 2. * normalWeight * scalarProduct(C.y,V.y)) * C.J;
}
#if 0
//penalizing normal velocity
double normalVel = scalarProduct(V.y, C.y);
if(normalVel>0.){
y = 0.;
if(!!J) J = zeros(1, V.J.d1);
return;
}
double scale = 3.;
double weight = ::exp(scale * D.y.scalar());
weight = 1.; scale=0.;
y.resize(1);
y(0) = weight * normalVel;
if(!!J){
J = weight * ( ~V.y * C.J + ~C.y * V.J );
J += (normalVel * weight * scale) * D.J;
}
#if 0
normalVel += 1.;
y = D.y / normalVel;
if(!!J){
J = D.J / normalVel;
J += (-D.y.scalar() / (normalVel*normalVel)) * ( ~V.y * C.J + ~C.y * V.J );
}
#endif
#endif
}
virtual uint dim_phi(const ConfigurationL& Ctuple) {
return 3;
}
};
void TEST(Thin){
rai::Configuration C("thin.g");
cout <<"configuration space dim=" <<C.getJointStateDimension() <<endl;
KOMO komo;
komo.setModel(C);
komo.setTiming(1., 60, 5., 2);
komo.add_qControlObjective({}, 2, 1.);
//-- set a time optim objective
// komo.addObjective({}, make_shared<TM_Time>(), OT_sos, {1e2}, {}, 1); //smooth time evolution
// komo.addObjective({}, make_shared<TM_Time>(), OT_sos, {1e1}, {komo.tau}, 0); //prior on timing
komo.addObjective({1.}, FS_positionDiff, {"ball", "target"}, OT_eq, {1e1});
komo.addObjective({1.}, FS_qItself, {}, OT_eq, {1e1}, {}, 1);
komo.addObjective({}, FS_distance, {"wall", "ball"}, OT_ineq, {1.});
komo.addObjective({}, make_shared<MyFeature>(komo.world, "ball", "wall"), OT_sos, {1e1}, {}, 1);
komo.reportProblem();
komo.animateOptimization=1;
// komo.setSpline(5);
komo.optimize(1e-2);
komo.plotTrajectory();
// komo.reportProxies();
komo.checkGradients();
while(komo.displayTrajectory());
}
//===========================================================================
void TEST(PR2){
rai::Configuration C("model.g");
C.optimizeTree(true);
cout <<"configuration space dim=" <<C.getJointStateDimension() <<endl;
double rand = rai::getParameter<double>("KOMO/moveTo/randomizeInitialPose", .0);
if(rand){
rnd.seed(rai::getParameter<uint>("rndSeed", 0));
rndGauss(C.q,rand,true);
C.setJointState(C.q);
}
KOMO komo;
// komo.logFile = new ofstream("z.dat");
// komo.denseOptimization=true;
// komo.sparseOptimization=true;
komo.setModel(C);
komo.setTiming(1., 100, 10., 2);
komo.add_qControlObjective({}, 2, 1.);
komo.addObjective({1.}, FS_positionDiff, {"endeff", "target"}, OT_eq, {1e1});
komo.addObjective({.98,1.}, FS_qItself, {}, OT_sos, {1e1}, {}, 1);
komo.addObjective({}, FS_accumulatedCollisions, {}, OT_eq, {1.});
// komo.setSpline(10);
komo.optimize();
komo.plotTrajectory();
// komo.checkGradients();
for(uint i=0;i<2;i++) komo.displayTrajectory();
}
//===========================================================================
// void TEST(FinalPosePR2){
// rai::Configuration K("model.g");
// K.pruneRigidJoints();
// K.optimizeTree();
// makeConvexHulls(K.frames);
// cout <<"configuration space dim=" <<K.getJointStateDimension() <<endl;
// arr x = finalPoseTo(K, *K.getFrameByName("endeff"), *K.getFrameByName("target"));
// K.setJointState(x.reshape(x.N));
// K.watch(true);
// }
//===========================================================================
int main(int argc,char** argv){
rai::initCmdLine(argc,argv);
// rnd.clockSeed();
// testEasy();
testAlign();
// testThin();
// testPR2();
return 0;
}
| 28.913793 | 98 | 0.571855 | [
"model"
] |
a86cddb79eae1883de679775591ccf16c5704abd | 912 | cpp | C++ | pg_answer/79958e08b44c415b83a1bf5fe1a37ec8.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | 8 | 2019-10-09T14:33:42.000Z | 2020-12-03T00:49:29.000Z | pg_answer/79958e08b44c415b83a1bf5fe1a37ec8.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | pg_answer/79958e08b44c415b83a1bf5fe1a37ec8.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::vector<int> mentioned[101]{};
for (int i{0}; i < n; i++) {
int x;
std::cin >> x;
std::cin.ignore();
int delim{std::cin.get()};
while ((delim = std::cin.get()) != '\n') {
int mentionee;
std::cin >> mentionee;
mentioned[mentionee].push_back(x);
}
}
auto maximum{std::max_element(mentioned, mentioned + 101,
[](auto a, auto b) { return a.size() < b.size(); })};
std::cout << maximum - mentioned << std::endl;
std::sort(maximum->begin(), maximum->end());
maximum->erase(std::unique(maximum->begin(), maximum->end()), maximum->end());
bool isFirst{true};
for (auto i : *maximum) {
std::cout << " " + isFirst << i;
isFirst = false;
}
} | 29.419355 | 87 | 0.496711 | [
"vector"
] |
a86ce16182aa1f30dd3a019425e244321c029d27 | 595 | cpp | C++ | leetcode/uncrossed_lines.cpp | alexandru-dinu/competitive-programming | 4515d221a649b3ab8bc012d01f38b9e4659e2e76 | [
"MIT"
] | null | null | null | leetcode/uncrossed_lines.cpp | alexandru-dinu/competitive-programming | 4515d221a649b3ab8bc012d01f38b9e4659e2e76 | [
"MIT"
] | 6 | 2021-10-12T09:14:30.000Z | 2021-10-16T19:29:08.000Z | leetcode/uncrossed_lines.cpp | alexandru-dinu/competitive-programming | 4515d221a649b3ab8bc012d01f38b9e4659e2e76 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/uncrossed-lines
class Solution
{
public:
int maxUncrossedLines(vector<int> &A, vector<int> &B)
{
const int na = A.size();
const int nb = B.size();
vector<vector<int>> dp(na + 1, vector<int>(nb + 1, 0));
for (int i = 0; i < na; ++i) {
for (int j = 0; j < nb; ++j) {
if (A[i] == B[j])
dp[i + 1][j + 1] = 1 + dp[i][j];
else
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
}
}
return dp[na][nb];
}
}; | 24.791667 | 71 | 0.396639 | [
"vector"
] |
a87111d47da9a4b787ab46bae971b53e3c9b4a59 | 9,232 | cpp | C++ | Compiler/src/Lexer.cpp | Vyraax/BirdLang | d7cd193531965e35e55fa26b2d3d27ec642d81a5 | [
"MIT"
] | 3 | 2020-06-21T15:21:34.000Z | 2020-09-02T07:56:48.000Z | Compiler/src/Lexer.cpp | Vyraax/BirdLang | d7cd193531965e35e55fa26b2d3d27ec642d81a5 | [
"MIT"
] | 7 | 2020-06-28T12:56:16.000Z | 2020-07-15T11:17:53.000Z | Compiler/src/Lexer.cpp | Vyraax/BirdLang | d7cd193531965e35e55fa26b2d3d27ec642d81a5 | [
"MIT"
] | null | null | null | #include "pch.h"
#include <sstream>
#include "Lexer.h"
#include "Profiler.h"
#include "ConsoleTable.h"
#include "Utils.h"
using ConsoleTable = samilton::ConsoleTable;
const std::string digits = "0123456789";
const std::string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const std::string letters_digits = letters + digits;
Lexer::Lexer(const std::string& filename, bool debug) :
filename(filename),
tokens({}),
current_char('\0'),
debug(false),
lexing_time(0.0)
{
cursor = std::make_shared<Cursor>(-1, 0, -1, filename, input);
}
void Lexer::advance()
{
cursor->advance(current_char);
current_char = cursor->index < input.size()
? input.at(cursor->index)
: '\0';
}
void Lexer::create_token(const Token::Type& type, char value)
{
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
tokens.push_back(new Token(type, value, start, cursor));
}
std::vector<Token*> Lexer::index_tokens(const std::string& str)
{
Profiler profiler;
profiler.start = clock();
this->input = str;
tokens.clear();
cursor.reset(new Cursor(-1, 0, -1, filename, input));
advance();
while (current_char != '\0') {
if (current_char == ' ' || current_char == '\t') {
advance();
}
else if (digits.find(current_char) != std::string::npos) {
tokens.push_back(create_numeric_token());
}
else if (letters.find(current_char) != std::string::npos) {
tokens.push_back(create_identifier());
}
else if (current_char == '"') {
tokens.push_back(create_string());
}
else if (current_char == '+') {
create_token(Token::Type::PLUS, current_char);
}
else if (current_char == '-') {
tokens.push_back(create_minus_arrow_operator());
}
else if (current_char == '*') {
create_token(Token::Type::MUL, current_char);
}
else if (current_char == '%') {
create_token(Token::Type::MOD, current_char);
}
else if (current_char == '/') {
create_token(Token::Type::DIV, current_char);
}
else if (current_char == '^') {
create_token(Token::Type::POW, current_char);
}
else if (current_char == '(') {
create_token(Token::Type::LPAREN, current_char);
}
else if (current_char == ')') {
create_token(Token::Type::RPAREN, current_char);
}
else if (current_char == '[') {
create_token(Token::Type::LSBRACKET, current_char);
}
else if (current_char == ']') {
create_token(Token::Type::RSBRACKET, current_char);
}
else if (current_char == '{') {
create_token(Token::Type::LCBRACKET, current_char);
}
else if (current_char == '}') {
create_token(Token::Type::RCBRACKET, current_char);
}
else if (current_char == ':') {
create_token(Token::Type::COLON, current_char);
}
else if (current_char == ';') {
create_token(Token::Type::SEMI_COLON, current_char);
}
else if (current_char == '!') {
Token* token = create_not_equals_operator();
if (token == nullptr) {
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
ExpectedCharacterError* error = new ExpectedCharacterError(
start,
cursor,
"'=' (after '!')"
);
std::cout << error << "\n";
return std::vector<Token*>();
}
tokens.push_back(token);
}
else if (current_char == '=') {
tokens.push_back(create_equals_operator());
}
else if (current_char == '<') {
tokens.push_back(create_less_operator());
}
else if (current_char == '>') {
tokens.push_back(create_greater_operator());
}
else if (current_char == ',') {
create_token(Token::Type::COMMA, current_char);
}
else if (current_char == '.') {
create_token(Token::Type::DOT, current_char);
}
else {
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
char c = current_char;
advance();
IllegarCharError* error = new IllegarCharError(
start,
cursor,
std::string(1, c)
);
std::cout << error << "\n";
return std::vector<Token*>();
}
}
cursor->column = (int)tokens.size();
tokens.push_back(new Token(Token::Type::EOL, char(0x04)));
profiler.end = clock();
lexing_time = profiler.getReport();
if (debug) {
ConsoleTable table(1, 2);
ConsoleTable::TableChars chars;
chars.topLeft = '+';
chars.topRight = '+';
chars.downLeft = '+';
chars.downRight = '+';
chars.topDownSimple = '-';
chars.leftRightSimple = '|';
chars.leftSeparation = '+';
chars.rightSeparation = '+';
chars.centreSeparation = '+';
chars.topSeparation = '+';
chars.downSeparation = '+';
table.setTableChars(chars);
table[0][0] = "Identifier";
table[0][1] = "Character";
table[0][2] = "Line";
table[0][3] = "Column";
for (unsigned int i = 0; i < tokens.size(); i++) {
auto token = tokens.at(i);
std::stringstream str;
switch (token->value.index()) {
case 0:
try { str << std::get<double>(token->value); }
catch (const std::bad_variant_access&) {}
break;
case 1:
try { str << std::get<int>(token->value); }
catch (const std::bad_variant_access&) {}
break;
case 2:
try { str << std::get<char>(token->value); }
catch (const std::bad_variant_access&) {}
break;
case 3:
try { str << std::get<std::string>(token->value); }
catch (const std::bad_variant_access&) {}
break;
}
table[i + 1][0] = Token::toString(token->type);
table[i + 1][1] = str.str();
size_t line = 0;
size_t column = tokens.size();
if (token->start != nullptr) {
line = token->start->line;
column = token->start->column;
}
table[i + 1][2] = std::to_string(line);
table[i + 1][3] = std::to_string(column);
}
Utils::title("TOKENS", 32, false);
std::cout << table << "\n";
}
return tokens;
}
Token* Lexer::create_numeric_token()
{
std::string str;
unsigned int dots = 0;
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
auto numbers = digits + ".";
auto hasDot = [=]() {
return numbers.find(current_char) != std::string::npos;
};
while (current_char != '\0' && hasDot()) {
if (current_char == '.') {
if (dots == 1)
break;
++dots;
str += '.';
}
else {
str += current_char;
}
advance();
}
if (dots == 0) {
return new Token(
Token::Type::INT,
(int)std::atoi(str.c_str()),
start,
cursor
);
}
else {
return new Token(
Token::Type::DOUBLE,
std::atof(str.c_str()),
start,
cursor
);
}
}
Token* Lexer::create_identifier()
{
std::string id;
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
auto str = letters_digits + "_";
auto isLetterOrDigit = [=]() {
return str.find(current_char) != std::string::npos;
};
while (current_char != '\0' && isLetterOrDigit()) {
id += current_char;
advance();
}
Token::Type type = Token::Type::NONE;
std::vector<std::string>::iterator it = std::find(
Token::keywords.begin(),
Token::keywords.end(),
id
);
type = it != Token::keywords.end()
? Token::Type::KEYWORD
: Token::Type::IDENTIFIER;
return new Token(type, id, start, cursor);
}
Token* Lexer::create_equals_operator()
{
Token::Type type = Token::Type::EQ;
std::string value = "=";
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
if (current_char == '=') {
advance();
type = Token::Type::EE;
value = "==";
}
return new Token(type, value, start, cursor);
}
Token* Lexer::create_not_equals_operator()
{
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
if (current_char == '=') {
advance();
return new Token(Token::Type::NE, "!=", start, cursor);
}
advance();
return nullptr;
}
Token* Lexer::create_less_operator()
{
Token::Type type = Token::Type::LT;
std::string value = "<";
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
if (current_char == '=') {
advance();
type = Token::Type::LTE;
value = "<=";
}
return new Token(type, value, start, cursor);
}
Token* Lexer::create_greater_operator()
{
Token::Type type = Token::Type::GT;
std::string value = ">";
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
if (current_char == '=') {
advance();
type = Token::Type::GTE;
value = ">=";
}
return new Token(type, value, start, cursor);
}
Token* Lexer::create_minus_arrow_operator()
{
Token::Type type = Token::Type::MINUS;
std::string value = "-";
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
advance();
if (current_char == '>') {
advance();
type = Token::Type::ARROW;
value = "->";
}
return new Token(type, value, start, cursor);
}
Token* Lexer::create_string()
{
std::string str;
std::shared_ptr<Cursor> start = std::make_shared<Cursor>(*cursor);
bool escape = false;
advance();
std::unordered_map<char, char> escape_chars = {
{'n', '\n'},
{'t', '\t'}
};
while (current_char != '\0' && (current_char != '"' || escape)) {
if (escape) {
auto it = escape_chars.find(current_char);
str += it != escape_chars.end()
? it->second
: current_char;
escape = false;
}
else {
if (current_char == '\\')
escape = true;
else
str += current_char;
}
advance();
}
advance();
return new Token(Token::Type::STRING, str, start, cursor);
}
| 22.086124 | 83 | 0.619801 | [
"vector"
] |
a87e3e84796258c955fb0462fec6f1155da30c7a | 3,044 | cpp | C++ | PairCopulaAIC.cpp | MalteKurz/VineCopulaCPP | 742e8762ef7a61666b97fd8a381cf7c759d96cfe | [
"MIT"
] | 7 | 2015-04-07T12:55:42.000Z | 2021-11-17T14:41:43.000Z | PairCopulaAIC.cpp | MalteKurz/VineCopulaCPP | 742e8762ef7a61666b97fd8a381cf7c759d96cfe | [
"MIT"
] | 2 | 2015-01-31T13:59:05.000Z | 2015-02-07T11:58:49.000Z | PairCopulaAIC.cpp | MalteKurz/VineCopulaCPP | 742e8762ef7a61666b97fd8a381cf7c759d96cfe | [
"MIT"
] | 7 | 2015-01-22T13:16:52.000Z | 2021-11-17T14:41:44.000Z | #include "VineCopulaCPP_header.hpp"
void PairCopulaAIC_Rotated_Obs(double *AIC, double *theta,int family, int rotation, double *U,double *V,unsigned int n)
{
std::vector<double> bounds(120);
LoadDefaultBounds(&bounds[0]);
PairCopulaAIC_Rotated_Obs(&bounds[0],AIC,theta,family,rotation,U,V,n);
return;
}
void PairCopulaAIC_Rotated_Obs(double *bounds,double *AIC, double *theta,int family, int rotation, double *U,double *V,unsigned int n)
{
PairCopulaFit_Rotated_Obs(bounds,theta,family,rotation,U,V,n);
double CLL = PairCopulaNegLL_Rotated_Obs(family,rotation,theta,U,V,n);
switch(family){
case 3: case 4: case 5: case 6: case 12: case 16: case 17: case 19:
{
//*AIC = 2*CLL+4;
*AIC = 2*CLL+4+12/(n-3);
break;
}
case 18:
{
//*AIC = 2*CLL+6;
*AIC = 2*CLL+6+24/(n-4);
break;
}
default:
{
//*AIC = 2*CLL+2;
*AIC = 2*CLL+2+4/(n-2);
break;
}
}
return;
}
void PairCopulaAIC(double *AIC, double *theta,int family, int rotation, double *U,double *V,unsigned int n)
{
std::vector<double> bounds(120);
LoadDefaultBounds(&bounds[0]);
PairCopulaAIC(&bounds[0],AIC,theta,family,rotation,U,V,n);
return;
}
void PairCopulaAIC(double *bounds,double *AIC, double *theta,int family, int rotation, double *U,double *V,unsigned int n)
{
PairCopulaFit(theta,family,rotation,U,V,n);
double CLL = PairCopulaNegLL_Rotated_Obs(family,rotation,theta,U,V,n);
switch(family){
case 3: case 4: case 5: case 6: case 12: case 16: case 17: case 19:
{
//*AIC = 2*CLL+4;
*AIC = 2*CLL+4+12/(n-3);
break;
}
case 18:
{
//*AIC = 2*CLL+6;
*AIC = 2*CLL+6+24/(n-4);
break;
}
default:
{
//*AIC = 2*CLL+2;
*AIC = 2*CLL+2+4/(n-2);
break;
}
}
return;
}
void PairCopulaAIC(double *AIC, double *theta,int family, double *U,double *V,unsigned int n)
{
std::vector<double> bounds(120);
LoadDefaultBounds(&bounds[0]);
PairCopulaAIC(&bounds[0],AIC,theta,family,U,V,n);
return;
}
void PairCopulaAIC(double *bounds, double *AIC, double *theta,int family, double *U,double *V,unsigned int n)
{
PairCopulaFit(bounds,theta,family,U,V,n);
double CLL = PairCopulaNegLL(family,theta,U,V,n);
switch(family){
case 3: case 4: case 5: case 6: case 12: case 16: case 17: case 19:
{
//*AIC = 2*CLL+4;
*AIC = 2*CLL+4+12/(n-3);
break;
}
case 18:
{
//*AIC = 2*CLL+6;
*AIC = 2*CLL+6+24/(n-4);
break;
}
default:
{
//*AIC = 2*CLL+2;
*AIC = 2*CLL+2+4/(n-2);
break;
}
}
return;
}
| 25.579832 | 134 | 0.522011 | [
"vector"
] |
a885a2844b1879e299b89fe05a621aa20b197d02 | 8,600 | hpp | C++ | modules/reg/include/opencv2/reg/map.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/reg/include/opencv2/reg/map.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/reg/include/opencv2/reg/map.hpp | Nondzu/opencv_contrib | 0b0616a25d4239ee81fda965818b49b721620f56 | [
"BSD-3-Clause"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
// Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 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.
//
//M*/
#ifndef MAP_H_
#define MAP_H_
#include <opencv2/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
/** @defgroup reg Image Registration
The Registration module implements parametric image registration. The implemented method is direct
alignment, that is, it uses directly the pixel values for calculating the registration between a
pair of images, as opposed to feature-based registration. The implementation follows essentially the
corresponding part of @cite Szeliski06 .
Feature based methods have some advantages over pixel based methods when we are trying to register
pictures that have been shoot under different lighting conditions or exposition times, or when the
images overlap only partially. On the other hand, the main advantage of pixel-based methods when
compared to feature based methods is their better precision for some pictures (those shoot under
similar lighting conditions and that have a significative overlap), due to the fact that we are
using all the information available in the image, which allows us to achieve subpixel accuracy. This
is particularly important for certain applications like multi-frame denoising or super-resolution.
In fact, pixel and feature registration methods can complement each other: an application could
first obtain a coarse registration using features and then refine the registration using a pixel
based method on the overlapping area of the images. The code developed allows this use case.
The module implements classes derived from the abstract classes cv::reg::Map or cv::reg::Mapper. The
former models a coordinate transformation between two reference frames, while the later encapsulates
a way of invoking a method that calculates a Map between two images. Although the objective has been
to implement pixel based methods, the module can be extended to support other methods that can
calculate transformations between images (feature methods, optical flow, etc.).
Each class derived from Map implements a motion model, as follows:
- MapShift: Models a simple translation
- MapAffine: Models an affine transformation
- MapProjec: Models a projective transformation
MapProject can also be used to model affine motion or translations, but some operations on it are
more costly, and that is the reason for defining the other two classes.
The classes derived from Mapper are
- MapperGradShift: Gradient based alignment for calculating translations. It produces a MapShift
(two parameters that correspond to the shift vector).
- MapperGradEuclid: Gradient based alignment for euclidean motions, that is, rotations and
translations. It calculates three parameters (angle and shift vector), although the result is
stored in a MapAffine object for convenience.
- MapperGradSimilar: Gradient based alignment for calculating similarities, which adds scaling to
the euclidean motion. It calculates four parameters (two for the anti-symmetric matrix and two
for the shift vector), although the result is stored in a MapAffine object for better
convenience.
- MapperGradAffine: Gradient based alignment for an affine motion model. The number of parameters
is six and the result is stored in a MapAffine object.
- MapperGradProj: Gradient based alignment for calculating projective transformations. The number
of parameters is eight and the result is stored in a MapProject object.
- MapperPyramid: It implements hyerarchical motion estimation using a Gaussian pyramid. Its
constructor accepts as argument any other object that implements the Mapper interface, and it is
that mapper the one called by MapperPyramid for each scale of the pyramid.
If the motion between the images is not very small, the normal way of using these classes is to
create a MapperGrad\* object and use it as input to create a MapperPyramid, which in turn is called
to perform the calculation. However, if the motion between the images is small enough, we can use
directly the MapperGrad\* classes. Another possibility is to use first a feature based method to
perform a coarse registration and then do a refinement through MapperPyramid or directly a
MapperGrad\* object. The "calculate" method of the mappers accepts an initial estimation of the
motion as input.
When deciding which MapperGrad to use we must take into account that mappers with more parameters
can handle more complex motions, but involve more calculations and are therefore slower. Also, if we
are confident on the motion model that is followed by the sequence, increasing the number of
parameters beyond what we need will decrease the accuracy: it is better to use the least number of
degrees of freedom that we can.
In the module tests there are examples that show how to register a pair of images using any of the
implemented mappers.
*/
namespace cv {
namespace reg {
//! @addtogroup reg
//! @{
/** @brief Base class for modelling a Map between two images.
The class is only used to define the common interface for any possible map.
*/
class CV_EXPORTS_W Map
{
public:
/*!
* Virtual destructor
*/
virtual ~Map();
/*!
* Warps image to a new coordinate frame. The calculation is img2(x)=img1(T^{-1}(x)), as we
* have to apply the inverse transformation to the points to move them to were the values
* of img2 are.
* \param[in] img1 Original image
* \param[out] img2 Warped image
*/
CV_WRAP virtual void warp(InputArray img1, OutputArray img2) const;
/*!
* Warps image to a new coordinate frame. The calculation is img2(x)=img1(T(x)), so in fact
* this is the inverse warping as we are taking the value of img1 with the forward
* transformation of the points.
* \param[in] img1 Original image
* \param[out] img2 Warped image
*/
CV_WRAP virtual void inverseWarp(InputArray img1, OutputArray img2) const = 0;
/*!
* Calculates the inverse map
* \return Inverse map
*/
CV_WRAP virtual cv::Ptr<Map> inverseMap() const = 0;
/*!
* Changes the map composing the current transformation with the one provided in the call.
* The order is first the current transformation, then the input argument.
* \param[in] map Transformation to compose with.
*/
CV_WRAP virtual void compose(cv::Ptr<Map> map) = 0;
/*!
* Scales the map by a given factor as if the coordinates system is expanded/compressed
* by that factor.
* \param[in] factor Expansion if bigger than one, compression if smaller than one
*/
CV_WRAP virtual void scale(double factor) = 0;
};
//! @}
}} // namespace cv::reg
#endif // MAP_H_
| 48.863636 | 100 | 0.755233 | [
"object",
"vector",
"model"
] |
a88c25cfec7377f6103dde4c2602ca9479377d00 | 21,997 | cpp | C++ | contracts/payout.cpp | cc32d9/eosio_payout | 467bec5b7768f687d95995118dd04b9142351961 | [
"Apache-2.0"
] | 19 | 2020-12-26T19:25:14.000Z | 2022-03-20T08:21:08.000Z | contracts/payout.cpp | cc32d9/eosio_payout | 467bec5b7768f687d95995118dd04b9142351961 | [
"Apache-2.0"
] | null | null | null | contracts/payout.cpp | cc32d9/eosio_payout | 467bec5b7768f687d95995118dd04b9142351961 | [
"Apache-2.0"
] | 7 | 2021-12-15T12:07:58.000Z | 2022-03-31T09:58:35.000Z | /*
Copyright 2020 cc32d9@gmail.com
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 <eosio/eosio.hpp>
#include <eosio/multi_index.hpp>
#include <eosio/action.hpp>
#include <eosio/transaction.hpp>
#include <eosio/asset.hpp>
#include <eosio/crypto.hpp>
#include <eosio/time.hpp>
using namespace eosio;
using std::string;
using std::vector;
CONTRACT payout : public eosio::contract {
public:
const uint16_t MAX_WALK = 30; // maximum walk through unapproved accounts
payout( name self, name code, datastream<const char*> ds ):
contract(self, code, ds)
{}
// sets the admin account
ACTION setadmin(name newadmin)
{
req_admin();
check(is_account(newadmin), "admin account does not exist");
set_name_prop(name("adminacc"), newadmin);
}
// the account will receive the fee from every incoming deposit
ACTION setfee(name feeacc, uint16_t permille)
{
req_admin();
check(is_account(feeacc), "fee account does not exist");
check(permille < 1000, "permille must be less than 1000");
set_name_prop(name("feeacc"), feeacc);
set_uint_prop(name("feepermille"), permille);
}
// new payout recipients need to be approved for automatic payments
ACTION approveacc(vector<name> accounts)
{
req_admin();
bool done_something = false;
approvals appr(_self, 0);
for( name& acc: accounts ) {
auto itr = appr.find(acc.value);
check(itr != appr.end(), "Account not found in approval list");
if( !itr->approved ) {
appr.modify( *itr, same_payer, [&]( auto& row ) {
row.approved = 1;
});
done_something = true;
}
}
check(done_something, "Nothing to do");
inc_revision();
}
ACTION unapproveacc(vector<name> accounts)
{
req_admin();
bool done_something = false;
approvals appr(_self, 0);
for( name& acc: accounts ) {
auto itr = appr.find(acc.value);
check(itr != appr.end(), "Account not found in approval list");
if( itr->approved ) {
appr.modify( *itr, same_payer, [&]( auto& row ) {
row.approved = 0;
});
done_something = true;
}
}
check(done_something, "Nothing to do");
inc_revision();
}
ACTION newschedule(name payer, name schedule_name, name tkcontract, asset currency, string memo)
{
require_auth(payer);
check(schedule_name != name(""), "Schedule name cannot be empty");
schedules sched(_self, 0);
auto scitr = sched.find(schedule_name.value);
check(scitr == sched.end(), "A schedule with this name already exists");
check(is_account(tkcontract), "Token contract account does not exist");
check(currency.is_valid(), "invalid currency" );
check(memo.size() <= 256, "memo has more than 256 bytes");
// validate that such token exists
{
stats_table statstbl(tkcontract, currency.symbol.code().raw());
auto statsitr = statstbl.find(currency.symbol.code().raw());
check(statsitr != statstbl.end(), "This currency symbol does not exist");
check(statsitr->supply.symbol.precision() == currency.symbol.precision(), "Wrong currency precision");
}
currency.amount = 0;
funds fnd(_self, payer.value);
auto fndidx = fnd.get_index<name("token")>();
auto fnditr = fndidx.find(token_index_val(tkcontract, currency));
if( fnditr == fndidx.end() ) {
// register a new currency in payer funds
fnd.emplace(payer, [&]( auto& row ) {
row.id = fnd.available_primary_key();
row.tkcontract = tkcontract;
row.currency = currency;
row.dues = currency;
row.deposited = currency;
});
}
sched.emplace(payer, [&]( auto& row ) {
row.schedule_name = schedule_name;
row.payer = payer;
row.tkcontract = tkcontract;
row.currency = currency;
row.memo = memo;
row.dues = currency;
row.last_processed.value = 1; // the dues index position
});
inc_revision();
}
// record new totals for recipients
struct book_record {
name recipient;
asset new_total;
};
ACTION book(name schedule_name, vector<book_record> records)
{
schedules sched(_self, 0);
auto scitr = sched.find(schedule_name.value);
check(scitr != sched.end(), "Cannot find the schedule");
name payer = scitr->payer;
require_auth(payer);
asset new_dues = scitr->currency;
approvals appr(_self, 0);
bool done_something = false;
recipients rcpts(_self, schedule_name.value);
for( auto& rec: records ) {
check(rec.new_total.symbol == scitr->currency.symbol, "Invalid currency symbol");
auto rcitr = rcpts.find(rec.recipient.value);
if( rcitr == rcpts.end() ) {
// register a new recipient
check(is_account(rec.recipient), "recipient account does not exist");
new_dues += rec.new_total;
rcpts.emplace(payer, [&]( auto& row ) {
row.account = rec.recipient;
row.booked_total = rec.new_total.amount;
row.paid_total = 0;
});
// new recipients go to unapproved list unless approved in another schedule
if( appr.find(rec.recipient.value) == appr.end() ) {
appr.emplace(payer, [&]( auto& row ) {
row.account = rec.recipient;
row.approved = 0;
});
}
done_something = true;
}
else if( rec.new_total.amount > rcitr->booked_total ) {
// update an existing recipient if the new_total is higher than before
new_dues.amount += (rec.new_total.amount - rcitr->booked_total);
rcpts.modify( *rcitr, same_payer, [&]( auto& row ) {
row.booked_total = rec.new_total.amount;
});
done_something = true;
}
}
check(done_something, "No totals were updated");
funds fnd(_self, payer.value);
auto fndidx = fnd.get_index<name("token")>();
auto fnditr = fndidx.find(token_index_val(scitr->tkcontract, scitr->currency));
check(fnditr != fndidx.end(), "This must never happen 1");
check(fnditr->deposited >= fnditr->dues + new_dues, "Insufficient funds on the deposit");
sched.modify( *scitr, same_payer, [&]( auto& row ) {
row.dues += new_dues;
});
fnd.modify( *fnditr, same_payer, [&]( auto& row ) {
row.dues += new_dues;
});
inc_revision();
}
struct bookm_record {
name recipient;
asset new_total;
string memo;
};
ACTION bookm(name schedule_name, vector<bookm_record> records)
{
vector<book_record> newrecords;
for( auto& rec: records ) {
newrecords.push_back({.recipient = rec.recipient, .new_total = rec.new_total});
}
book(schedule_name, newrecords);
schedules sched(_self, 0);
auto scitr = sched.find(schedule_name.value);
check(scitr != sched.end(), "This must never happen 5");
name payer = scitr->payer;
memos memtbl(_self, schedule_name.value);
for( auto& rec: records ) {
check(rec.memo.size() <= 256, "memo has more than 256 bytes");
auto memitr = memtbl.find(rec.recipient.value);
if( memitr == memtbl.end() ) {
memtbl.emplace(payer, [&]( auto& row ) {
row.account = rec.recipient;
row.memo = rec.memo;
});
}
else if( memitr->memo != rec.memo ) {
memtbl.modify( *memitr, payer, [&]( auto& row ) {
row.memo = rec.memo;
});
}
}
}
// recipient can claim the transfer instead of waiting for automatic job (no authorization needed)
ACTION claim(name schedule_name, name recipient)
{
schedules sched(_self, 0);
auto scitr = sched.find(schedule_name.value);
check(scitr != sched.end(), "Cannot find the schedule");
recipients rcpts(_self, schedule_name.value);
auto rcitr = rcpts.find(recipient.value);
check(rcitr != rcpts.end(), "Cannot find this recipient in the schedule");
check(rcitr->booked_total > rcitr->paid_total, "All dues are paid already");
_pay_due(schedule_name, recipient);
}
// payout job that serves up to so many payments (no authorization needed)
ACTION runpayouts(uint16_t count)
{
bool done_something = false;
approvals appr(_self, 0);
uint16_t sched_loopcount = 0;
bool paid_something_in_last_loop = false;
while( count-- > 0 ) {
name last_schedule = get_name_prop(name("lastschedule"));
name old_last_schedule = last_schedule;
last_schedule.value++;
schedules sched(_self, 0);
auto schedidx = sched.get_index<name("dues")>();
auto scitr = schedidx.lower_bound(last_schedule.value);
if( scitr == schedidx.end() ) {
// we're at the end of active schedules
last_schedule.value = 0;
if( sched_loopcount > 1 && !paid_something_in_last_loop ) {
// nothing to do more, abort the loop
count = 0;
}
sched_loopcount++;
}
else {
paid_something_in_last_loop = false;
name schedule_name = scitr->schedule_name;
last_schedule = schedule_name;
uint64_t last_processed = scitr->last_processed.value;
uint64_t old_last_processed = last_processed;
recipients rcpts(_self, schedule_name.value);
auto rcdidx = rcpts.get_index<name("dues")>();
auto rcitr = rcdidx.lower_bound(last_processed);
uint16_t walk_limit = MAX_WALK;
bool will_pay = false;
name pay_to;
while( !will_pay && walk_limit-- > 0 ) {
if( rcitr == rcdidx.end() ) {
// end of recpients list
last_processed = 1;
walk_limit = 0; //abort the loop
}
else {
last_processed = rcitr->account.value;
auto apritr = appr.find(rcitr->account.value);
check(apritr != appr.end(), "This should never happen 2");
if( apritr->approved ) {
will_pay = true;
pay_to = rcitr->account;
}
else {
// this is an unapproved account, skip to the next
rcitr++;
}
}
}
if( last_processed != old_last_processed ) {
sched.modify( *scitr, same_payer, [&]( auto& row ) {
row.last_processed.value = last_processed;
});
done_something = true;
}
// _pay_due modifies the same table outside of this index, so we execute it last.
if( will_pay ) {
_pay_due(schedule_name, pay_to);
paid_something_in_last_loop = true;
}
}
if( last_schedule != old_last_schedule ) {
set_name_prop(name("lastschedule"), last_schedule);
done_something = true;
}
}
check(done_something, "Nothing to do");
}
[[eosio::on_notify("*::transfer")]] void on_payment (name from, name to, asset quantity, string memo) {
if(to == _self) {
funds fnd(_self, from.value);
auto fndidx = fnd.get_index<name("token")>();
auto fnditr = fndidx.find(token_index_val(name{get_first_receiver()}, quantity));
check(fnditr != fndidx.end(), "There are no schedules with this currency for this payer");
check(quantity.amount > 0, "expected a positive amount");
uint64_t feepermille = get_uint_prop(name("feepermille"));
name feeacc = get_name_prop(name("feeacc"));
if( feepermille > 0 && feeacc != name("") ) {
asset fee = quantity * feepermille / 1000;
quantity -= fee;
extended_asset xfee(fee, fnditr->tkcontract);
send_payment(feeacc, xfee, "fees");
}
fnd.modify( *fnditr, same_payer, [&]( auto& row ) {
row.deposited += quantity;
});
inc_revision();
}
}
/*
// for testing purposes only!
ACTION wipeall(uint16_t count)
{
require_auth(_self);
schedules sched(_self, 0);
auto scitr = sched.begin();
while( scitr != sched.end() && count-- > 0 ) {
funds fnd(_self, scitr->payer.value);
auto fnditr = fnd.begin();
while( fnditr != fnd.end() ) {
fnditr = fnd.erase(fnditr);
}
recipients rcpts(_self, scitr->schedule_name.value);
auto rcitr = rcpts.begin();
while( rcitr != rcpts.end() ) {
rcitr = rcpts.erase(rcitr);
}
scitr = sched.erase(scitr);
}
{
approvals appr(_self, 0);
auto itr = appr.begin();
while( itr != appr.end() ) {
itr = appr.erase(itr);
}
}
{
props p(_self, 0);
auto itr = p.begin();
while( itr != p.end() ) {
itr = p.erase(itr);
}
}
}
*/
private:
// properties table for keeping contract settings
struct [[eosio::table("props")]] prop {
name key;
name val_name;
uint64_t val_uint = 0;
auto primary_key()const { return key.value; }
};
typedef eosio::multi_index<
name("props"), prop> props;
void set_name_prop(name key, name value)
{
props p(_self, 0);
auto itr = p.find(key.value);
if( itr != p.end() ) {
p.modify( *itr, same_payer, [&]( auto& row ) {
row.val_name = value;
});
}
else {
p.emplace(_self, [&]( auto& row ) {
row.key = key;
row.val_name = value;
});
}
}
name get_name_prop(name key)
{
props p(_self, 0);
auto itr = p.find(key.value);
if( itr != p.end() ) {
return itr->val_name;
}
else {
p.emplace(_self, [&]( auto& row ) {
row.key = key;
});
return name();
}
}
void set_uint_prop(name key, uint64_t value)
{
props p(_self, 0);
auto itr = p.find(key.value);
if( itr != p.end() ) {
p.modify( *itr, same_payer, [&]( auto& row ) {
row.val_uint = value;
});
}
else {
p.emplace(_self, [&]( auto& row ) {
row.key = key;
row.val_uint = value;
});
}
}
uint64_t get_uint_prop(name key)
{
props p(_self, 0);
auto itr = p.find(key.value);
if( itr != p.end() ) {
return itr->val_uint;
}
else {
p.emplace(_self, [&]( auto& row ) {
row.key = key;
});
return 0;
}
}
void inc_uint_prop(name key)
{
props p(_self, 0);
auto itr = p.find(key.value);
if( itr != p.end() ) {
p.modify( *itr, same_payer, [&]( auto& row ) {
row.val_uint++;
});
}
else {
p.emplace(_self, [&]( auto& row ) {
row.key = key;
row.val_uint = 1;
});
}
}
inline void inc_revision() {
inc_uint_prop(name("revision"));
}
// table recipients approval
struct [[eosio::table("approvals")]] approval {
name account;
uint8_t approved;
auto primary_key()const { return account.value; }
uint64_t by_approved()const { return approved ? account.value:0; }
uint64_t by_unapproved()const { return (!approved) ? account.value:0; }
};
typedef eosio::multi_index<
name("approvals"), approval,
indexed_by<name("approved"), const_mem_fun<approval, uint64_t, &approval::by_approved>>,
indexed_by<name("unapproved"), const_mem_fun<approval, uint64_t, &approval::by_unapproved>>
> approvals;
// all registered schedules
struct [[eosio::table("schedules")]] schedule {
name schedule_name;
name payer;
name tkcontract;
asset currency;
string memo;
asset dues; // how much we need to send to recipients
name last_processed; // last paid recipient
auto primary_key()const { return schedule_name.value; }
// index for iterating through active schedules
uint64_t by_dues()const { return (dues.amount > 0) ? schedule_name.value:0; }
};
typedef eosio::multi_index<
name("schedules"), schedule,
indexed_by<name("dues"), const_mem_fun<schedule, uint64_t, &schedule::by_dues>>
> schedules;
static inline uint128_t token_index_val(name tkcontract, asset currency)
{
return ((uint128_t)tkcontract.value << 64)|(uint128_t)currency.symbol.raw();
}
// assets belonging to the payer. scope=payer
struct [[eosio::table("funds")]] fundsrow {
uint64_t id;
name tkcontract;
asset currency;
asset dues; // how much we need to send to recipients
asset deposited; // how much we can spend
auto primary_key()const { return id; }
uint128_t by_token()const { return token_index_val(tkcontract, currency); }
};
typedef eosio::multi_index<
name("funds"), fundsrow,
indexed_by<name("token"), const_mem_fun<fundsrow, uint128_t, &fundsrow::by_token>>
> funds;
// payment recipients, scope=scheme_name
struct [[eosio::table("recipients")]] recipient {
name account;
uint64_t booked_total; // asset amount
uint64_t paid_total;
auto primary_key()const { return account.value; }
// index for iterating through open dues
uint64_t by_dues()const { return (booked_total > paid_total) ? account.value:0; }
};
typedef eosio::multi_index<
name("recipients"), recipient,
indexed_by<name("dues"), const_mem_fun<recipient, uint64_t, &recipient::by_dues>>
> recipients;
// optional transfer memos for recipients. scope=schedule
struct [[eosio::table("memos")]] memo {
name account;
string memo;
auto primary_key()const { return account.value; }
};
typedef eosio::multi_index<name("memos"), memo> memos;
void req_admin()
{
name admin = get_name_prop(name("adminacc"));
if( admin == name("") ) {
require_auth(_self);
}
else {
require_auth(admin);
}
}
struct transfer_args
{
name from;
name to;
asset quantity;
string memo;
};
void send_payment(name recipient, const extended_asset& x, const string memo)
{
action
{
permission_level{_self, name("active")},
x.contract,
name("transfer"),
transfer_args {
.from=_self, .to=recipient,
.quantity=x.quantity, .memo=memo
}
}.send();
}
// does not check any validity, just performs a transfer and bookeeping
void _pay_due(name schedule_name, name recipient) {
schedules sched(_self, 0);
auto scitr = sched.find(schedule_name.value);
check(scitr != sched.end(), "This must never happen 3");
funds fnd(_self, scitr->payer.value);
auto fndidx = fnd.get_index<name("token")>();
auto fnditr = fndidx.find(token_index_val(scitr->tkcontract, scitr->currency));
check(fnditr != fndidx.end(), "This must never happen 4");
recipients rcpts(_self, schedule_name.value);
auto rcitr = rcpts.find(recipient.value);
string memo;
memos memtbl(_self, schedule_name.value);
auto memitr = memtbl.find(recipient.value);
if( memitr == memtbl.end() ) {
memo = scitr->memo;
}
else {
memo = memitr->memo;
memtbl.erase(memitr);
}
asset due(rcitr->booked_total - rcitr->paid_total, scitr->currency.symbol);
extended_asset pay(due, scitr->tkcontract);
send_payment(recipient, pay, memo);
rcpts.modify( *rcitr, same_payer, [&]( auto& row ) {
row.paid_total = row.booked_total;
});
sched.modify( *scitr, same_payer, [&]( auto& row ) {
row.dues -= due;
});
fnd.modify( *fnditr, same_payer, [&]( auto& row ) {
row.dues -= due;
row.deposited -= due;
});
inc_revision();
}
// eosio.token structure
struct currency_stats {
asset supply;
asset max_supply;
name issuer;
uint64_t primary_key()const { return supply.symbol.code().raw(); }
};
typedef eosio::multi_index<"stat"_n, currency_stats> stats_table;
};
| 30.808123 | 108 | 0.559304 | [
"vector"
] |
a89304bbde8a4b7a290842f83e39c1e361a5ce47 | 36,993 | cxx | C++ | IO/vtkNetCDFCFReader.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | 2 | 2015-07-11T13:30:23.000Z | 2017-12-19T05:23:38.000Z | IO/vtkNetCDFCFReader.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | null | null | null | IO/vtkNetCDFCFReader.cxx | SCS-B3C/VTK5.6 | d4afb224f638c1f7e847b0cd3195ea8a977bb602 | [
"BSD-3-Clause"
] | null | null | null | // -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: vtkNetCDFCFReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkNetCDFCFReader.h"
#include "vtkDataArraySelection.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkRectilinearGrid.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkStructuredGrid.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
#include <vtkstd/set>
#include <vtksys/RegularExpression.hxx>
#include <vtksys/SystemTools.hxx>
#include <string.h>
#include <netcdf.h>
#define CALL_NETCDF_GENERIC(call, on_error) \
{ \
int errorcode = call; \
if (errorcode != NC_NOERR) \
{ \
const char * errorstring = nc_strerror(errorcode); \
on_error; \
} \
}
#define CALL_NETCDF(call) \
CALL_NETCDF_GENERIC(call, vtkErrorMacro(<< "netCDF Error: " << errorstring); return 0;)
#define CALL_NETCDF_GW(call) \
CALL_NETCDF_GENERIC(call, vtkGenericWarningMacro(<< "netCDF Error: " << errorstring); return 0;)
#include <vtkstd/algorithm>
#include <math.h>
//=============================================================================
// Convenience function for getting the text attribute on a variable. Returns
// true if the attribute exists, false otherwise.
static bool ReadTextAttribute(int ncFD, int varId, const char *name,
vtkStdString &result)
{
size_t length;
if (nc_inq_attlen(ncFD, varId, name, &length) != NC_NOERR) return false;
result.resize(length);
if (nc_get_att_text(ncFD,varId,name,&result.at(0)) != NC_NOERR) return false;
// The line below seems weird, but it is here for a good reason. In general,
// text attributes are not null terminated, so you have to add your own (which
// the vtkStdString will do for us). However, sometimes a null terminating
// character is written in the attribute anyway. In a C string this is no big
// deal. But it means that the vtkStdString has a null character in it and it
// is technically different than its own C string. This line corrects that
// regardless of whether the null string was written we will get the right
// string.
result = result.c_str();
return true;
}
//=============================================================================
vtkNetCDFCFReader::vtkDimensionInfo::vtkDimensionInfo(int ncFD, int id)
{
this->DimId = id;
this->LoadMetaData(ncFD);
}
int vtkNetCDFCFReader::vtkDimensionInfo::LoadMetaData(int ncFD)
{
this->Units = UNDEFINED_UNITS;
char name[NC_MAX_NAME+1];
CALL_NETCDF_GW(nc_inq_dimname(ncFD, this->DimId, name));
this->Name = name;
size_t dimLen;
CALL_NETCDF_GW(nc_inq_dimlen(ncFD, this->DimId, &dimLen));
this->Coordinates = vtkSmartPointer<vtkDoubleArray>::New();
this->Coordinates->SetName((this->Name + "_Coordinates").c_str());
this->Coordinates->SetNumberOfComponents(1);
this->Coordinates->SetNumberOfTuples(dimLen);
this->Bounds = vtkSmartPointer<vtkDoubleArray>::New();
this->Bounds->SetName((this->Name + "_Bounds").c_str());
this->Bounds->SetNumberOfComponents(1);
this->Bounds->SetNumberOfTuples(dimLen+1);
this->SpecialVariables = vtkSmartPointer<vtkStringArray>::New();
int varId;
int varNumDims;
int varDim;
// By convention if there is a single dimension variable with the same name as
// its dimension, then the data contains the coordinates for the dimension.
if ( (nc_inq_varid(ncFD, name, &varId) == NC_NOERR)
&& (nc_inq_varndims(ncFD, varId, &varNumDims) == NC_NOERR)
&& (varNumDims == 1)
&& (nc_inq_vardimid(ncFD, varId, &varDim) == NC_NOERR)
&& (varDim == this->DimId) )
{
this->SpecialVariables->InsertNextValue(name);
// Read coordinates
CALL_NETCDF_GW(nc_get_var_double(ncFD, varId,
this->Coordinates->GetPointer(0)));
// Check to see if the spacing is regular.
this->Origin = this->Coordinates->GetValue(0);
this->Spacing
= (this->Coordinates->GetValue(dimLen-1) - this->Origin)/(dimLen-1);
this->HasRegularSpacing = true; // Then check to see if it is false.
double tolerance = 0.01*this->Spacing;
for (size_t i = 1; i < dimLen; i++)
{
double expectedValue = this->Origin + i*this->Spacing;
double actualValue = this->Coordinates->GetValue(i);
if ( (actualValue < expectedValue-tolerance)
|| (actualValue > expectedValue+tolerance) )
{
this->HasRegularSpacing = false;
break;
}
}
// Check units.
vtkStdString units;
if (ReadTextAttribute(ncFD, varId, "units", units))
{
units = vtksys::SystemTools::LowerCase(units);
// Time, latitude, and longitude dimensions are those with units that
// correspond to strings formatted with the Unidata udunits package. I'm
// not sure if these checks are complete, but they matches all of the
// examples I have seen.
if (units.find(" since ") != vtkStdString::npos)
{
this->Units = TIME_UNITS;
}
else if (vtksys::RegularExpression("degrees?_?n").find(units))
{
this->Units = LATITUDE_UNITS;
}
else if (vtksys::RegularExpression("degrees?_?e").find(units))
{
this->Units = LONGITUDE_UNITS;
}
}
// Check axis.
vtkStdString axis;
if (ReadTextAttribute(ncFD, varId, "axis", axis))
{
// The axis attribute is an alternate way of defining the coordinate type.
// The string can be "X", "Y", "Z", or "T" which mean longitude, latitude,
// vertical, and time, respectively.
if (axis == "X")
{
this->Units = LONGITUDE_UNITS;
}
else if (axis == "Y")
{
this->Units = LATITUDE_UNITS;
}
else if (axis == "Z")
{
this->Units = VERTICAL_UNITS;
}
else if (axis == "T")
{
this->Units = TIME_UNITS;
}
}
// Check positive.
vtkStdString positive;
if (ReadTextAttribute(ncFD, varId, "positive", positive))
{
positive = vtksys::SystemTools::LowerCase(positive);
if (positive.find("down") != vtkStdString::npos)
{
// Flip the values of the coordinates.
for (vtkIdType i = 0; i < this->Coordinates->GetNumberOfTuples(); i++)
{
this->Coordinates->SetValue(i, -(this->Coordinates->GetValue(i)));
}
this->Spacing = -this->Spacing;
}
}
// Create the bounds array, which is used in place of the coordinates when
// loading as cell data. We will look for the bounds attribute on the
// description variable to see if cell bounds have been written out. This
// code assumes that if such an attribute exists, it is the name of another
// variable that is of dimensions of size dimLen X 2. There are no checks
// for this (other than the existence of the attribute), so if this is not
// the case then the code could fail.
vtkStdString boundsName;
if (ReadTextAttribute(ncFD, varId, "bounds", boundsName))
{
this->SpecialVariables->InsertNextValue(boundsName);
int boundsVarId;
CALL_NETCDF_GW(nc_inq_varid(ncFD, boundsName.c_str(), &boundsVarId));
// Read in the first bound value for each entry as a point bound. If the
// cells are connected, the second bound value should equal the first
// bound value of the next entry anyway.
size_t start[2]; start[0] = start[1] = 0;
size_t count[2]; count[0] = dimLen; count[1] = 1;
CALL_NETCDF_GW(nc_get_vars_double(ncFD, boundsVarId, start, count, NULL,
this->Bounds->GetPointer(0)));
// Read in the last value for the bounds array. It will be the second
// bound in the last entry. This will not be replicated unless the
// dimension is a longitudinal one that wraps all the way around.
start[0] = dimLen-1; start[1] = 1;
count[0] = 1; count[1] = 1;
CALL_NETCDF_GW(nc_get_vars_double(ncFD, boundsVarId, start, count, NULL,
this->Bounds->GetPointer(dimLen)));
}
else
{
// Bounds not given. Set them based on the coordinates.
this->Bounds->SetValue(
0, this->Coordinates->GetValue(0) - 0.5*this->Spacing);
for (vtkIdType i = 1; i < static_cast<vtkIdType>(dimLen); i++)
{
double v0 = this->Coordinates->GetValue(i-1);
double v1 = this->Coordinates->GetValue(i);
this->Bounds->SetValue(i, 0.5*(v0+v1));
}
this->Bounds->SetValue(dimLen,
this->Coordinates->GetValue(dimLen-1)+0.5*this->Spacing);
}
}
else
{
// Fake coordinates
for (size_t i = 0; i < dimLen; i++)
{
this->Coordinates->SetValue(i, static_cast<double>(i));
this->Bounds->SetValue(i, static_cast<double>(i) - 0.5);
}
this->Bounds->SetValue(dimLen, static_cast<double>(dimLen) - 0.5);
this->HasRegularSpacing = true;
this->Origin = 0.0;
this->Spacing = 1.0;
}
return 1;
}
//-----------------------------------------------------------------------------
class vtkNetCDFCFReader::vtkDimensionInfoVector
{
public:
vtkstd::vector<vtkDimensionInfo> v;
};
//=============================================================================
vtkNetCDFCFReader::vtkDependentDimensionInfo::vtkDependentDimensionInfo(
int ncFD, int varId,
vtkNetCDFCFReader *parent)
{
if (this->LoadMetaData(ncFD, varId, parent))
{
this->Valid = true;
}
else
{
this->Valid = false;
}
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::vtkDependentDimensionInfo::LoadMetaData(
int ncFD, int varId,
vtkNetCDFCFReader *parent)
{
int longitudeCoordVarId, latitudeCoordVarId;
int longitudeBoundsVarId, latitudeBoundsVarId;
longitudeCoordVarId = latitudeCoordVarId = -1;
longitudeBoundsVarId = latitudeBoundsVarId = -1;
this->GridDimensions = vtkSmartPointer<vtkIntArray>::New();
this->SpecialVariables = vtkSmartPointer<vtkStringArray>::New();
// The grid dimensions are the dimensions on the variable. Since multiple
// variables can be put on the same grid and this class identifies grids by
// their variables, I group all of the dimension combinations together for 2D
// coordinate lookup. Technically, the CF specification allows you to have
// specify different coordinate variables, but we do not support that because
// there is no easy way to differentiate grids with the same dimensions. If
// different coordinates are needed, then duplicate dimensions should be
// created. Anyone who disagrees should write their own class.
int numGridDimensions;
CALL_NETCDF_GW(nc_inq_varndims(ncFD, varId, &numGridDimensions));
if (numGridDimensions < 2) return 0;
this->GridDimensions->SetNumberOfTuples(numGridDimensions);
CALL_NETCDF_GW(nc_inq_vardimid(ncFD, varId,
this->GridDimensions->GetPointer(0)));
// Remove initial time dimension, which has no effect on data type.
if (parent->IsTimeDimension(ncFD, this->GridDimensions->GetValue(0)))
{
this->GridDimensions->RemoveTuple(0);
numGridDimensions--;
if (numGridDimensions < 2) return 0;
}
vtkStdString coordinates;
if (!ReadTextAttribute(ncFD, varId, "coordinates", coordinates)) return 0;
vtkstd::vector<vtkstd::string> coordName;
vtksys::SystemTools::Split(coordinates, coordName, ' ');
for (vtkstd::vector<vtkstd::string>::iterator iter = coordName.begin();
iter != coordName.end(); iter++)
{
int auxCoordVarId;
if (nc_inq_varid(ncFD, iter->c_str(), &auxCoordVarId) != NC_NOERR) continue;
// I am only interested in 2D variables.
int numDims;
CALL_NETCDF_GW(nc_inq_varndims(ncFD, auxCoordVarId, &numDims));
if (numDims != 2) continue;
// Make sure that the coordinate variables have the same dimensions and that
// those dimensions are the same as the last two dimensions on the grid.
// Not sure if that is enforced by the specification, but I am going to make
// that assumption.
int auxCoordDims[2];
CALL_NETCDF_GW(nc_inq_vardimid(ncFD, auxCoordVarId, auxCoordDims));
int *gridDims = this->GridDimensions->GetPointer(numGridDimensions - 2);
if ((auxCoordDims[0] != gridDims[0]) || (auxCoordDims[1] != gridDims[1]))
{
continue;
}
// The variable is no use to me unless it is identified as either longitude
// or latitude.
vtkStdString units;
if (!ReadTextAttribute(ncFD, auxCoordVarId, "units", units)) continue;
units = vtksys::SystemTools::LowerCase(units);
if (vtksys::RegularExpression("degrees?_?n").find(units))
{
latitudeCoordVarId = auxCoordVarId;
}
else if (vtksys::RegularExpression("degrees?_?e").find(units))
{
longitudeCoordVarId = auxCoordVarId;
}
else
{
continue;
}
this->SpecialVariables->InsertNextValue(*iter);
}
if ((longitudeCoordVarId == -1) || (latitudeCoordVarId == -1))
{
// Did not find coordinate variables.
return 0;
}
vtkStdString bounds;
if (ReadTextAttribute(ncFD, longitudeCoordVarId, "bounds", bounds))
{
// The bounds is supposed to point to an array with 3 dimensions. The first
// two should be the same as the coord array, the third with 4 entries.
// Maybe I should check this, but I'm not.
CALL_NETCDF_GW(nc_inq_varid(ncFD, bounds.c_str(), &longitudeBoundsVarId));
this->SpecialVariables->InsertNextValue(bounds);
}
if (ReadTextAttribute(ncFD, latitudeCoordVarId, "bounds", bounds))
{
// The bounds is supposed to point to an array with 3 dimensions. The first
// two should be the same as the coord array, the third with 4 entries.
// Maybe I should check this, but I'm not.
CALL_NETCDF_GW(nc_inq_varid(ncFD, bounds.c_str(), &latitudeBoundsVarId));
this->SpecialVariables->InsertNextValue(bounds);
}
this->HasBounds = ((longitudeBoundsVarId != -1)&&(latitudeBoundsVarId != -1));
// Load in all the longitude and latitude coordinates. Maybe not the most
// efficient thing to do for large data, but it is just a 2D plane, so it
// should be OK for most things.
this->LongitudeCoordinates = vtkSmartPointer<vtkDoubleArray>::New();
this->LatitudeCoordinates = vtkSmartPointer<vtkDoubleArray>::New();
if (this->HasBounds)
{
if (!this->LoadBoundsVariable(ncFD, longitudeBoundsVarId,
this->LongitudeCoordinates)) return 0;
if (!this->LoadBoundsVariable(ncFD, latitudeBoundsVarId,
this->LatitudeCoordinates)) return 0;
}
else
{
if (!this->LoadCoordinateVariable(ncFD, longitudeCoordVarId,
this->LongitudeCoordinates)) return 0;
if (!this->LoadCoordinateVariable(ncFD, latitudeCoordVarId,
this->LatitudeCoordinates)) return 0;
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::vtkDependentDimensionInfo::LoadCoordinateVariable(
int ncFD, int varId,
vtkDoubleArray *coords)
{
int dimIds[2];
CALL_NETCDF_GW(nc_inq_vardimid(ncFD, varId, dimIds));
size_t dimSizes[2];
for (int i = 0; i < 2; i++)
{
CALL_NETCDF_GW(nc_inq_dimlen(ncFD, dimIds[i], &dimSizes[i]));
}
coords->SetNumberOfComponents(static_cast<int>(dimSizes[1]));
coords->SetNumberOfTuples(static_cast<vtkIdType>(dimSizes[0]));
CALL_NETCDF_GW(nc_get_var_double(ncFD, varId, coords->GetPointer(0)));
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::vtkDependentDimensionInfo::LoadBoundsVariable(
int ncFD, int varId,
vtkDoubleArray *coords)
{
int dimIds[3];
CALL_NETCDF_GW(nc_inq_vardimid(ncFD, varId, dimIds));
size_t dimSizes[3];
for (int i = 0; i < 3; i++)
{
CALL_NETCDF_GW(nc_inq_dimlen(ncFD, dimIds[i], &dimSizes[i]));
}
if (dimSizes[2] != 4)
{
vtkGenericWarningMacro(<< "Expected 2D dependent coordinate bounds to have"
<< " 4 entries in final dimension. Instead has "
<< dimSizes[2]);
return 0;
}
// Bounds are stored as 4-tuples for every cell. Tuple entries 0 and 1
// connect to the cell in the -i topological direction. Tuple entries 0 and 3
// connect to the cell in the -j topological direction.
vtkstd::vector<double> boundsData(dimSizes[0]*dimSizes[1]*4);
CALL_NETCDF_GW(nc_get_var_double(ncFD, varId, &boundsData.at(0)));
// The coords array are the coords at the points. There is one more point
// than cell in each topological direction.
int numComponents = static_cast<int>(dimSizes[1]);
vtkIdType numTuples = static_cast<vtkIdType>(dimSizes[0]);
coords->SetNumberOfComponents(numComponents+1);
coords->SetNumberOfTuples(numTuples+1);
// Copy from the bounds data to the coordinates data. Most values will
// be copied from the bound's 0'th tuple entry. Values at the extremes
// will be copied from other entries.
for (vtkIdType j = 0; j < numTuples; j++)
{
for (int i = 0; i < numComponents; i++)
{
coords->SetComponent(j, i, boundsData[(j*numComponents + i)*4 + 0]);
}
coords->SetComponent(j, numComponents,
boundsData[((j+1)*numComponents-1)*4 + 1]);
}
for (int i = 0; i < numComponents; i++)
{
coords->SetComponent(numTuples, i,
boundsData[((numTuples-1)*numComponents)*4 + 2]);
}
coords->SetComponent(numTuples, numComponents,
boundsData[(numTuples*numComponents-1)*4 + 3]);
return 1;
}
//-----------------------------------------------------------------------------
class vtkNetCDFCFReader::vtkDependentDimensionInfoVector
{
public:
vtkstd::vector<vtkNetCDFCFReader::vtkDependentDimensionInfo> v;
};
//=============================================================================
vtkStandardNewMacro(vtkNetCDFCFReader);
//-----------------------------------------------------------------------------
vtkNetCDFCFReader::vtkNetCDFCFReader()
{
this->SphericalCoordinates = 1;
this->VerticalScale = 1.0;
this->VerticalBias = 0.0;
this->DimensionInfo = new vtkDimensionInfoVector;
this->DependentDimensionInfo = new vtkDependentDimensionInfoVector;
}
vtkNetCDFCFReader::~vtkNetCDFCFReader()
{
delete this->DimensionInfo;
delete this->DependentDimensionInfo;
}
void vtkNetCDFCFReader::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "SphericalCoordinates: " << this->SphericalCoordinates <<endl;
os << indent << "VerticalScale: " << this->VerticalScale <<endl;
os << indent << "VerticalBias: " << this->VerticalBias <<endl;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::CanReadFile(const char *filename)
{
// We really just read basic arrays from netCDF files. If the netCDF library
// says we can read it, then we can read it.
int ncFD;
int errorcode = nc_open(filename, NC_NOWRITE, &ncFD);
if (errorcode == NC_NOERR)
{
nc_close(ncFD);
return 1;
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::RequestDataObject(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject *output = vtkDataObject::GetData(outInfo);
// This is really too early to know the appropriate data type. We need to
// have meta data and let the user select arrays. We have to do part
// of the RequestInformation to get the appropriate meta data.
if (!this->UpdateMetaData()) return 0;
int dataType = VTK_IMAGE_DATA;
int ncFD;
CALL_NETCDF(nc_open(this->FileName, NC_NOWRITE, &ncFD));
int numArrays = this->VariableArraySelection->GetNumberOfArrays();
for (int arrayIndex = 0; arrayIndex < numArrays; arrayIndex++)
{
if (!this->VariableArraySelection->GetArraySetting(arrayIndex)) continue;
const char *name = this->VariableArraySelection->GetArrayName(arrayIndex);
int varId;
CALL_NETCDF(nc_inq_varid(ncFD, name, &varId));
int currentNumDims;
CALL_NETCDF(nc_inq_varndims(ncFD, varId, ¤tNumDims));
if (currentNumDims < 1) continue;
VTK_CREATE(vtkIntArray, currentDimensions);
currentDimensions->SetNumberOfComponents(1);
currentDimensions->SetNumberOfTuples(currentNumDims);
CALL_NETCDF(nc_inq_vardimid(ncFD, varId,
currentDimensions->GetPointer(0)));
// Remove initial time dimension, which has no effect on data type.
if (this->IsTimeDimension(ncFD, currentDimensions->GetValue(0)))
{
currentDimensions->RemoveTuple(0);
currentNumDims--;
if (currentNumDims < 1) continue;
}
// Check to see if the dimensions fit spherical coordinates.
if (this->SphericalCoordinates)
{
if (this->CoordinatesAreSpherical(currentDimensions->GetPointer(0),
currentNumDims))
{
dataType = VTK_STRUCTURED_GRID;
break;
}
}
// Check to see if any dimension has irregular spacing.
for (int i = 0; i < currentNumDims; i++)
{
int dimId = currentDimensions->GetValue(i);
if (!this->GetDimensionInfo(dimId)->GetHasRegularSpacing())
{
dataType = VTK_RECTILINEAR_GRID;
break;
}
}
break;
}
if (dataType == VTK_IMAGE_DATA)
{
if (!output || !output->IsA("vtkImageData"))
{
output = vtkImageData::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else if (dataType == VTK_RECTILINEAR_GRID)
{
if (!output || !output->IsA("vtkRectilinearGrid"))
{
output = vtkRectilinearGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
else // dataType == VTK_STRUCTURED_GRID
{
if (!output || !output->IsA("vtkStructuredGrid"))
{
output = vtkStructuredGrid::New();
output->SetPipelineInformation(outInfo);
output->Delete(); // Not really deleted.
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// Let the superclass do the heavy lifting.
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
// Add spacing information defined by the COARDS conventions.
vtkImageData *imageOutput = vtkImageData::GetData(outputVector);
if (imageOutput)
{
double origin[3];
origin[0] = origin[1] = origin[2] = 0.0;
double spacing[3];
spacing[0] = spacing[1] = spacing[2] = 1.0;
int numDim = this->LoadingDimensions->GetNumberOfTuples();
if (numDim >= 3) numDim = 3;
for (int i = 0; i < numDim; i++)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
origin[i] = this->GetDimensionInfo(dim)->GetOrigin();
spacing[i] = this->GetDimensionInfo(dim)->GetSpacing();
}
}
vtkRectilinearGrid *rectOutput = vtkRectilinearGrid::GetData(outputVector);
if (rectOutput)
{
int extent[6];
rectOutput->GetExtent(extent);
int numDim = this->LoadingDimensions->GetNumberOfTuples();
for (int i = 0; i < 3; i++)
{
vtkSmartPointer<vtkDoubleArray> coords;
if (i < numDim)
{
// Remember that netCDF dimension ordering is backward from VTK.
int dim = this->LoadingDimensions->GetValue(numDim-i-1);
coords = this->GetDimensionInfo(dim)->GetCoordinates();
int extLow = extent[2*i];
int extHi = extent[2*i+1];
if ((extLow != 0) || (extHi != coords->GetNumberOfTuples()-1))
{
// Getting a subset of this dimension.
VTK_CREATE(vtkDoubleArray, newcoords);
newcoords->SetNumberOfComponents(1);
newcoords->SetNumberOfTuples(extHi-extLow+1);
memcpy(newcoords->GetPointer(0), coords->GetPointer(extLow),
(extHi-extLow+1)*sizeof(double));
coords = newcoords;
}
}
else
{
coords = vtkSmartPointer<vtkDoubleArray>::New();
coords->SetNumberOfTuples(1);
coords->SetComponent(0, 0, 0.0);
}
switch (i)
{
case 0: rectOutput->SetXCoordinates(coords); break;
case 1: rectOutput->SetYCoordinates(coords); break;
case 2: rectOutput->SetZCoordinates(coords); break;
}
}
}
vtkStructuredGrid *structOutput = vtkStructuredGrid::GetData(outputVector);
if (structOutput)
{
if (this->FindDependentDimensionInfo(this->LoadingDimensions))
{
this->Add2DSphericalCoordinates(structOutput);
}
else
{
this->Add1DSphericalCoordinates(structOutput);
}
}
return 1;
}
//-----------------------------------------------------------------------------
void vtkNetCDFCFReader::Add1DSphericalCoordinates(
vtkStructuredGrid *structOutput)
{
int extent[6];
structOutput->GetExtent(extent);
vtkDoubleArray *coordArrays[3];
for (vtkIdType i = 0; i < this->LoadingDimensions->GetNumberOfTuples(); i++)
{
int dim = this->LoadingDimensions->GetValue(i);
coordArrays[i] = this->GetDimensionInfo(dim)->GetBounds();
}
int longitudeDim, latitudeDim, verticalDim;
this->IdentifySphericalCoordinates(
this->LoadingDimensions->GetPointer(0),
this->LoadingDimensions->GetNumberOfTuples(),
longitudeDim, latitudeDim, verticalDim);
VTK_CREATE(vtkPoints, points);
points->SetDataTypeToDouble();
points->Allocate( (extent[1]-extent[0]+1)
* (extent[3]-extent[2]+1)
* (extent[5]-extent[4]+1) );
// Check the height scale and bias.
double vertScale = this->VerticalScale;
double vertBias = this->VerticalBias;
if (verticalDim >= 0)
{
double *verticalRange = coordArrays[verticalDim]->GetRange();
if ( (verticalRange[0]*vertScale + vertBias < 0)
|| (verticalRange[1]*vertScale + vertBias < 0) )
{
vertBias = -vtkstd::min(verticalRange[0], verticalRange[1])*vertScale;
}
}
else
{
if (vertScale + vertBias <= 0)
{
vertScale = 1.0;
vertBias = 0.0;
}
}
int ijk[3];
for (ijk[0] = extent[4]; ijk[0] <= extent[5]; ijk[0]++)
{
for (ijk[1] = extent[2]; ijk[1] <= extent[3]; ijk[1]++)
{
for (ijk[2] = extent[0]; ijk[2] <= extent[1]; ijk[2]++)
{
double lon, lat, h;
if (verticalDim >= 0)
{
lon = coordArrays[longitudeDim]->GetValue(ijk[longitudeDim]);
lat = coordArrays[latitudeDim]->GetValue(ijk[latitudeDim]);
h = coordArrays[verticalDim]->GetValue(ijk[verticalDim]);
}
else
{
lon = coordArrays[longitudeDim]->GetValue(ijk[longitudeDim+1]);
lat = coordArrays[latitudeDim]->GetValue(ijk[latitudeDim+1]);
h = 1.0;
}
lon = vtkMath::RadiansFromDegrees(lon);
lat = vtkMath::RadiansFromDegrees(lat);
h = h*vertScale + vertBias;
double cartesianCoord[3];
cartesianCoord[0] = h*cos(lon)*cos(lat);
cartesianCoord[1] = h*sin(lon)*cos(lat);
cartesianCoord[2] = h*sin(lat);
points->InsertNextPoint(cartesianCoord);
}
}
}
structOutput->SetPoints(points);
}
//-----------------------------------------------------------------------------
void vtkNetCDFCFReader::Add2DSphericalCoordinates(
vtkStructuredGrid *structOutput)
{
vtkDependentDimensionInfo *info
= this->FindDependentDimensionInfo(this->LoadingDimensions);
int extent[6];
structOutput->GetExtent(extent);
VTK_CREATE(vtkPoints, points);
points->SetDataTypeToDouble();
points->Allocate( (extent[1]-extent[0]+1)
* (extent[3]-extent[2]+1)
* (extent[5]-extent[4]+1) );
vtkDoubleArray *longitudeCoordinates = info->GetLongitudeCoordinates();
vtkDoubleArray *latitudeCoordinates = info->GetLatitudeCoordinates();
vtkDoubleArray *verticalCoordinates = NULL;
if (this->LoadingDimensions->GetNumberOfTuples() == 3)
{
int vertDim = this->LoadingDimensions->GetValue(0);
if (info->GetHasBounds())
{
verticalCoordinates = this->GetDimensionInfo(vertDim)->GetBounds();
}
else
{
verticalCoordinates = this->GetDimensionInfo(vertDim)->GetCoordinates();
}
}
// Check the height scale and bias.
double vertScale = this->VerticalScale;
double vertBias = this->VerticalBias;
if (verticalCoordinates)
{
double *verticalRange = verticalCoordinates->GetRange();
if ( (verticalRange[0]*vertScale + vertBias < 0)
|| (verticalRange[1]*vertScale + vertBias < 0) )
{
vertBias = -vtkstd::min(verticalRange[0], verticalRange[1])*vertScale;
}
}
else
{
if (vertScale + vertBias <= 0)
{
vertScale = 1.0;
vertBias = 0.0;
}
}
for (int k = extent[4]; k <= extent[5]; k++)
{
double h;
if (verticalCoordinates)
{
h = verticalCoordinates->GetValue(k)*vertScale + vertBias;
}
else
{
h = vertScale + vertBias;
}
for (int j = extent[2]; j <= extent[3]; j++)
{
for (int i = extent[0]; i <= extent[1]; i++)
{
double lon = longitudeCoordinates->GetComponent(j, i);
double lat = latitudeCoordinates->GetComponent(j, i);
lon = vtkMath::RadiansFromDegrees(lon);
lat = vtkMath::RadiansFromDegrees(lat);
double cartesianCoord[3];
cartesianCoord[0] = h*cos(lon)*cos(lat);
cartesianCoord[1] = h*sin(lon)*cos(lat);
cartesianCoord[2] = h*sin(lat);
points->InsertNextPoint(cartesianCoord);
}
}
}
structOutput->SetPoints(points);
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::ReadMetaData(int ncFD)
{
int i;
vtkDebugMacro("ReadMetaData");
int numDimensions;
CALL_NETCDF(nc_inq_ndims(ncFD, &numDimensions));
this->DimensionInfo->v.resize(numDimensions);
vtkstd::set<vtkStdString> specialVariables;
for (i = 0; i < numDimensions; i++)
{
this->DimensionInfo->v[i] = vtkDimensionInfo(ncFD, i);
// Record any special variables for this dimension.
vtkStringArray* dimensionVariables
= this->DimensionInfo->v[i].GetSpecialVariables();
for (vtkIdType j = 0; j < dimensionVariables->GetNumberOfValues(); j++)
{
specialVariables.insert(dimensionVariables->GetValue(j));
}
}
int numVariables;
CALL_NETCDF(nc_inq_nvars(ncFD, &numVariables));
// Check all variables for special 2D coordinates.
for (i = 0; i < numVariables; i++)
{
vtkDependentDimensionInfo info(ncFD, i, this);
if (!info.GetValid()) continue;
if (this->FindDependentDimensionInfo(info.GetGridDimensions()) != NULL)
{
continue;
}
this->DependentDimensionInfo->v.push_back(info);
// Record any special variables.
vtkStringArray* dimensionVariables = info.GetSpecialVariables();
for (vtkIdType j = 0; j < dimensionVariables->GetNumberOfValues(); j++)
{
specialVariables.insert(dimensionVariables->GetValue(j));
}
}
// Look at all variables and record them so that the user can select
// which ones he wants.
this->VariableArraySelection->RemoveAllArrays();
for (i = 0; i < numVariables; i++)
{
char name[NC_MAX_NAME+1];
CALL_NETCDF(nc_inq_varname(ncFD, i, name));
// Make sure this is not a special variable that describes a dimension
// before exposing it.
if (specialVariables.find(name) == specialVariables.end())
{
this->VariableArraySelection->AddArray(name);
}
}
return 1;
}
//-----------------------------------------------------------------------------
int vtkNetCDFCFReader::IsTimeDimension(int vtkNotUsed(ncFD), int dimId)
{
return ( this->GetDimensionInfo(dimId)->GetUnits()
== vtkDimensionInfo::TIME_UNITS );
}
//-----------------------------------------------------------------------------
vtkSmartPointer<vtkDoubleArray> vtkNetCDFCFReader::GetTimeValues(
int vtkNotUsed(ncFD), int dimId)
{
return this->GetDimensionInfo(dimId)->GetCoordinates();
}
//-----------------------------------------------------------------------------
inline vtkNetCDFCFReader::vtkDimensionInfo *
vtkNetCDFCFReader::GetDimensionInfo(int dimension)
{
return &(this->DimensionInfo->v.at(dimension));
}
//-----------------------------------------------------------------------------
vtkNetCDFCFReader::vtkDependentDimensionInfo *
vtkNetCDFCFReader::FindDependentDimensionInfo(vtkIntArray *dims)
{
return this->FindDependentDimensionInfo(dims->GetPointer(0),
dims->GetNumberOfTuples());
}
vtkNetCDFCFReader::vtkDependentDimensionInfo *
vtkNetCDFCFReader::FindDependentDimensionInfo(const int *dims, int numDims)
{
for (size_t i = 0; i < this->DependentDimensionInfo->v.size(); i++)
{
vtkIntArray *dependentDims
= this->DependentDimensionInfo->v[i].GetGridDimensions();
if (numDims == dependentDims->GetNumberOfTuples())
{
bool same = true;
for (vtkIdType j = 0; j < numDims; j++)
{
if (dims[j] != dependentDims->GetValue(j))
{
same = false;
break;
}
}
if (same) return &(this->DependentDimensionInfo->v[i]);
}
}
return NULL;
}
//-----------------------------------------------------------------------------
void vtkNetCDFCFReader::IdentifySphericalCoordinates(const int *dimensions,
int numDimensions,
int &longitudeDim,
int &latitudeDim,
int &verticalDim)
{
longitudeDim = latitudeDim = verticalDim = -1;
for (int i = 0; i < numDimensions; i++)
{
switch (this->GetDimensionInfo(dimensions[i])->GetUnits())
{
case vtkDimensionInfo::LONGITUDE_UNITS:
longitudeDim = i;
break;
case vtkDimensionInfo::LATITUDE_UNITS:
latitudeDim = i;
break;
default:
verticalDim = i;
break;
}
}
}
| 34.157895 | 98 | 0.598735 | [
"vector"
] |
a8981dbc6191e0ff17f1385b4a4bd17922cbbd5f | 2,585 | hpp | C++ | src/recipe.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | src/recipe.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | src/recipe.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <cstddef>
#include <memory>
#include <unordered_map>
#include <stdexcept>
#include <cell.hpp>
#include <common_types.hpp>
#include <event_generator.hpp>
#include <util/unique_any.hpp>
namespace arb {
struct probe_info {
cell_member_type id;
probe_tag tag;
// Address type will be specific to cell kind of cell `id.gid`.
util::any address;
};
class invalid_recipe_error: public std::runtime_error {
public:
invalid_recipe_error(std::string whatstr): std::runtime_error(std::move(whatstr)) {}
};
/* Recipe descriptions are cell-oriented: in order that the building
* phase can be done distributedly and in order that the recipe
* description can be built indepdently of any runtime execution
* environment, connection end-points are represented by pairs
* (cell index, source/target index on cell).
*/
using cell_connection_endpoint = cell_member_type;
// Note: `cell_connection` and `connection` have essentially the same data
// and represent the same thing conceptually. `cell_connection` objects
// are notionally described in terms of external cell identifiers instead
// of internal gids, but we are not making the distinction between the
// two in the current code. These two types could well be merged.
struct cell_connection {
cell_connection_endpoint source;
cell_connection_endpoint dest;
float weight;
float delay;
cell_connection(cell_connection_endpoint src, cell_connection_endpoint dst, float w, float d):
source(src), dest(dst), weight(w), delay(d)
{}
};
class recipe {
public:
virtual cell_size_type num_cells() const = 0;
// Cell description type will be specific to cell kind of cell with given gid.
virtual util::unique_any get_cell_description(cell_gid_type gid) const = 0;
virtual cell_kind get_cell_kind(cell_gid_type) const = 0;
virtual cell_size_type num_sources(cell_gid_type) const { return 0; }
virtual cell_size_type num_targets(cell_gid_type) const { return 0; }
virtual cell_size_type num_probes(cell_gid_type) const { return 0; }
virtual std::vector<event_generator_ptr> event_generators(cell_gid_type) const {
return {};
}
virtual std::vector<cell_connection> connections_on(cell_gid_type) const {
return {};
}
virtual probe_info get_probe(cell_member_type) const {
throw std::logic_error("no probes");
}
// Global property type will be specific to given cell kind.
virtual util::any get_global_properties(cell_kind) const { return util::any{}; };
};
} // namespace arb
| 31.144578 | 98 | 0.737331 | [
"vector"
] |
a89e7d32cc534d420460dc924fae33f3c87c8803 | 9,217 | cpp | C++ | src/ai/final_battle/doctor.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 8 | 2018-04-03T23:06:33.000Z | 2021-12-28T18:04:19.000Z | src/ai/final_battle/doctor.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | null | null | null | src/ai/final_battle/doctor.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 1 | 2020-07-31T00:23:27.000Z | 2020-07-31T00:23:27.000Z | #include "doctor.h"
#include "doctor_common.h"
#include "../stdai.h"
#include "../ai.h"
#include "../../ObjManager.h"
#include "../../trig.h"
#include "../../game.h"
#include "../../player.h"
#include "../../map.h"
#include "../../sound/sound.h"
#include "../../common/misc.h"
#include "../../graphics/sprites.h"
#include "../../graphics/tileset.h"
#include "../../autogen/sprites.h"
/*
From King's Table, here's the Doctor's first form.
He teleports around the room firing red wave shots at you with
the Red Crystal following him. After every fourth teleport, he
substitutes the wave attack for a aerial "explosion" of bouncy
red shots (OBJ_DOCTOR_BLAST).
*/
INITFUNC(AIRoutines)
{
ONTICK(OBJ_BOSS_DOCTOR, ai_boss_doctor);
AFTERMOVE(OBJ_RED_CRYSTAL, aftermove_red_crystal);
ONTICK(OBJ_DOCTOR_SHOT, ai_doctor_shot);
ONTICK(OBJ_DOCTOR_SHOT_TRAIL, ai_doctor_shot_trail);
ONTICK(OBJ_DOCTOR_BLAST, ai_doctor_blast);
ONTICK(OBJ_DOCTOR_CROWNED, ai_doctor_crowned);
}
/*
void c------------------------------() {}
*/
void ai_boss_doctor(Object *o)
{
//AIDEBUG;
/*if (o->state > 2 && o->state < 500)
{
o->state = 937;
game.tsc->StartScript(410);
return;
}*/
switch(o->state)
{
case 0:
{
o->y += (8 * CSFI);
o->frame = 3;
o->state = 1;
o->BringToFront(); // make sure in front of doctor_crowned
crystal_tofront = true; // make sure front crystal is in front of us
}
break;
case 2: // transforming (script)
{
o->timer++;
o->frame = (o->timer & 2) ? 0 : 3;
if (o->timer > 50)
o->state = 10;
}
break;
case 10: // base state/falling (script)
{
o->yinertia += 0x80;
o->flags |= FLAG_SHOOTABLE;
o->damage = 3;
if (o->blockd)
{
o->state = 20;
o->timer = 0;
o->frame = 0;
o->savedhp = o->hp;
FACEPLAYER;
}
}
break;
// fire wave shot
case 20:
{
o->timer++;
if (o->timer < 50)
{
if ((o->hp - o->savedhp) > 20)
o->timer = 50;
}
if (o->timer == 50)
{ // arm across chest
FACEPLAYER;
o->frame = 4;
}
if (o->timer == 80)
{
Object *shot;
o->frame = 5; // arm cast out
shot = SpawnObjectAtActionPoint(o, OBJ_DOCTOR_SHOT);
shot->dir = o->dir;
shot->angle = 0;
shot = SpawnObjectAtActionPoint(o, OBJ_DOCTOR_SHOT);
shot->dir = o->dir;
shot->angle = 0x80;
sound(SND_FUNNY_EXPLODE);
}
if (o->timer == 120)
o->frame = 0; // arm down
if (o->timer > 130)
{
if ((o->hp - o->savedhp) > 50)
{
o->state = 100;
o->timer = 0;
}
if (o->timer > 160)
{
o->state = 100;
o->timer = 0;
}
}
}
break;
// big "explosion" blast
case 30:
{
o->state = 31;
o->timer = 0;
o->frame = 6;
o->xmark = o->x;
o->flags |= FLAG_SHOOTABLE;
}
case 31:
{
o->x = o->xmark;
if (++o->timer & 2) o->x += (1 * CSFI);
if (o->timer > 50)
{
o->state = 32;
o->timer = 0;
o->frame = 7;
sound(SND_LIGHTNING_STRIKE);
for(int angle=8;angle<256;angle+=16)
{
Object *shot = SpawnObjectAtActionPoint(o, OBJ_DOCTOR_BLAST);
ThrowObjectAtAngle(shot, angle, 0x400);
}
}
}
break;
case 32: // after blast
{
if (++o->timer > 50)
o->state = 100;
}
break;
// teleport away
case 100:
{
o->state = 101;
o->flags &= ~FLAG_SHOOTABLE;
o->damage = 0;
dr_tp_out_init(o);
}
case 101:
{
if (dr_tp_out(o))
{
o->state = 102;
o->timer = 0;
o->invisible = true;
// decide where we're going to go now, so the red crystal
// can start moving towards it. But, it's important not to
// actually move until the last possible second, or we could
// drag our floattext along with us (and give away our position).
o->xmark = (random(5, 35) * TILE_W) * CSFI;
o->ymark = (random(5, 7) * TILE_H) * CSFI;
}
}
break;
case 102: // invisible: waiting to reappear
{
if (++o->timer > 40)
{
o->state = 103;
o->timer = 16;
o->frame = 2;
o->yinertia = 0;
o->x = o->xmark;
o->y = o->ymark;
FACEPLAYER;
}
}
break;
// tp back in
case 103:
{
o->state++;
dr_tp_in_init(o);
}
case 104:
{
if (dr_tp_in(o))
{
o->flags |= FLAG_SHOOTABLE;
o->damage = 3;
if (++o->timer2 >= 4)
{ // big explode
o->timer2 = 0;
o->state = 30;
}
else
{ // another wave shot
o->state = 10;
}
}
}
break;
// defeated!
case 500:
{
o->flags &= ~FLAG_SHOOTABLE;
o->frame = 6;
// fall to earth
o->yinertia += 0x10;
if (o->blockd && o->yinertia >= 0)
{
o->state = 501;
o->timer = 0;
o->xmark = o->x;
FACEPLAYER;
}
}
break;
case 501: // flashing (transforming into Doctor 2)
{
FACEPLAYER;
o->frame = 8;
o->x = o->xmark;
if (!(++o->timer & 2))
o->x += (1 * CSFI);
}
break;
}
// enable per-frame bbox
COPY_PFBOX;
// set crystal follow position
if (o->state >= 10)
{
if (o->invisible) // teleporting
{
crystal_xmark = o->xmark;
crystal_ymark = o->ymark;
}
else
{
crystal_xmark = o->x;
crystal_ymark = o->y;
}
}
LIMITY(0x5ff);
}
/*
void c------------------------------() {}
*/
// wave shot
void ai_doctor_shot(Object *o)
{
if (o->x < 0 || o->x > ((map.xsize * TILE_W) * CSFI))
{
o->Delete();
return;
}
switch(o->state)
{
case 0:
{
o->state = 1;
o->xmark = o->x;
o->ymark = o->y;
}
case 1:
{
// distance apart from each other
if (o->timer2 < 128)
o->timer2++;
// spin
o->angle += 6;
// travel
o->speed += (o->dir == LEFT) ? -0x15 : 0x15;
o->xmark += o->speed;
o->x = o->xmark + (xinertia_from_angle(o->angle, o->timer2 * CSFI) / 8);
o->y = o->ymark + (yinertia_from_angle(o->angle, o->timer2 * CSFI) / 2);
Object *trail = CreateObject(o->x, o->y, OBJ_DOCTOR_SHOT_TRAIL);
trail->sprite = SPR_DOCTOR_SHOT;
trail->frame = 1;
trail->PushBehind(o);
}
break;
}
}
void ai_doctor_shot_trail(Object *o)
{
ANIMATE_FWD(3);
if (o->frame > 3)
o->Delete();
}
// from his "explosion" attack
void ai_doctor_blast(Object *o)
{
// they're bouncy
if ((o->blockl && o->xinertia < 0) || \
(o->blockr && o->xinertia > 0))
{
o->xinertia = -o->xinertia;
}
if (o->blockd && o->yinertia > 0)
o->yinertia = -0x200;
if (o->blocku && o->yinertia < 0)
o->yinertia = 0x200;
ANIMATE(0, 0, 1);
if ((++o->timer % 4) == 1)
CreateObject(o->x, o->y, OBJ_DOCTOR_SHOT_TRAIL)->PushBehind(o);
if (o->timer > 250)
o->Delete();
}
/*
void c------------------------------() {}
*/
// The Doctor's red crystal.
// There are actually two, one is behind him and one is in front
// and they alternate visibility as they spin around him so it looks 3D.
//
// This function has to be an aftermove, otherwise, because one is in front
// and the other behind, one will be checking crystal_xmark before the Doctor
// updates it, and the other afterwards, and they will get out of sync.
void aftermove_red_crystal(Object *o)
{
ANIMATE(3, 0, 1);
switch(o->state)
{
case 0:
{
if (crystal_xmark != 0)
{
o->state = 1;
crystal_tofront = true;
}
}
break;
case 1:
{
o->xinertia += (o->x < crystal_xmark) ? 0x55 : -0x55;
o->yinertia += (o->y < crystal_ymark) ? 0x55 : -0x55;
LIMITX(0x400);
LIMITY(0x400);
if ((o->dir == LEFT && o->xinertia > 0) || \
(o->dir == RIGHT && o->xinertia < 0))
{
o->invisible = true;
}
else
{
o->invisible = false;
}
}
break;
}
if (crystal_tofront && o->dir == LEFT)
{
o->BringToFront();
crystal_tofront = false;
}
}
/*
void c------------------------------() {}
*/
// doctor as npc before fight
void ai_doctor_crowned(Object *o)
{
switch(o->state)
{
case 0:
{
// do this manually instead of a spawn point,
// cause he's going to transform.
o->x -= (8 * CSFI);
o->y -= (16 * CSFI);
o->state = 1;
crystal_xmark = crystal_ymark = 0;
crystal_tofront = true;
}
case 1: // faces away
{
o->frame = 0;
}
break;
case 10: // goes "ho ho ho" (while still facing away)
{
o->frame = 0;
o->animtimer = 0;
o->timer = 0;
o->state = 11;
}
case 11:
{
ANIMATE(5, 0, 1);
// he has to show shrug frame exactly 6 times.
// ANIMATE(5) changes frame on every 6th tick
// so this is 6*6*nframes(2) = 72
if (++o->timer >= 72)
o->state = 1;
}
break;
case 20: // turns around (faces screen instead of away)
{
o->state = 21;
o->frame = 2;
}
break;
case 40: // arm up--presents red crystal
{
o->state = 41;
// spawn the red crystal
// one is for when it's behind him, the other is in front.
int x = o->x - (6 * CSFI);
int y = o->y - (8 * CSFI);
dr_create_red_crystal(x, y);
}
case 41:
{
o->frame = 4;
}
break;
case 50: // "ho ho ho" (while facing player)
{
o->frame = 4;
o->animtimer = 0;
o->timer = 0;
o->state = 51;
}
case 51:
{
ANIMATE(5, 4, 5);
if (++o->timer >= 72)
o->state = 41;
}
break;
}
}
| 17.522814 | 77 | 0.534773 | [
"object",
"transform",
"3d"
] |
a8a478d5f578453ce6e46b424b19580d80b87cc3 | 9,443 | cpp | C++ | thirdparty/physx/PhysXSDK/Source/PhysX/src/gpu/NpPhysicsGpu.cpp | johndpope/echo | e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7 | [
"MIT"
] | null | null | null | thirdparty/physx/PhysXSDK/Source/PhysX/src/gpu/NpPhysicsGpu.cpp | johndpope/echo | e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7 | [
"MIT"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | thirdparty/physx/PhysXSDK/Source/PhysX/src/gpu/NpPhysicsGpu.cpp | johndpope/echo | e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "NpPhysicsGpu.h"
#if PX_SUPPORT_GPU_PHYSX
#include "NpPhysics.h"
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
#include "PxParticleGpu.h"
#include "NpScene.h"
using namespace physx;
//-------------------------------------------------------------------------------------------------------------------//
Ps::Array<NpPhysicsGpu::MeshMirror>::Iterator NpPhysicsGpu::findMeshMirror(const void* meshAddress)
{
Ps::Array<MeshMirror>::Iterator i = mMeshMirrors.begin();
while (i != mMeshMirrors.end() && i->meshAddress != meshAddress)
i++;
return i;
}
Ps::Array<NpPhysicsGpu::MeshMirror>::Iterator NpPhysicsGpu::findMeshMirror(const void* meshAddress, PxCudaContextManager& ctx)
{
Ps::Array<MeshMirror>::Iterator i = mMeshMirrors.begin();
while (i != mMeshMirrors.end() && (i->meshAddress != meshAddress || i->ctx != &ctx))
i++;
return i;
}
PxPhysXGpu* NpPhysicsGpu::getPhysXGpu(bool createIfNeeded, const char* functionName, bool doWarn)
{
PxPhysXGpu* physXGpu = PxvGetPhysXGpu(createIfNeeded);
if (!physXGpu && doWarn)
getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "%s, GPU implementation not available.", functionName);
return physXGpu;
}
bool NpPhysicsGpu::checkNewMirror(const void* meshPtr, PxCudaContextManager& ctx, const char* functionName)
{
Ps::Array<MeshMirror>::Iterator it = findMeshMirror(meshPtr, ctx);
if (it == mMeshMirrors.end())
return true;
getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "%s has no effect. Mirror already exists.", functionName);
return false;
}
bool NpPhysicsGpu::checkMirrorExists(Ps::Array<MeshMirror>::Iterator it, const char* functionName)
{
if (it != mMeshMirrors.end())
return true;
getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "%s has no effect. Mirror doesn't exist.", functionName);
return false;
}
bool NpPhysicsGpu::checkMirrorHandle(PxU32 mirrorHandle, const char* functionName)
{
if (mirrorHandle != PX_INVALID_U32)
return true;
getFoundation().error(PxErrorCode::eOUT_OF_MEMORY, __FILE__, __LINE__, "%s failed.", functionName);
return false;
}
void NpPhysicsGpu::addMeshMirror(const void* meshPtr, PxU32 mirrorHandle, PxCudaContextManager& ctx)
{
MeshMirror& meshMirror = mMeshMirrors.insert();
meshMirror.meshAddress = meshPtr;
meshMirror.ctx = &ctx;
meshMirror.mirrorHandle = mirrorHandle;
}
void NpPhysicsGpu::releaseMeshMirror(const void* meshPtr, const char* functionName, PxCudaContextManager* ctx)
{
PxPhysXGpu* physXGpu = getPhysXGpu(false, functionName, ctx != NULL);
if (!physXGpu)
return;
if (ctx)
{
Ps::Array<MeshMirror>::Iterator mirrorIt = findMeshMirror(meshPtr, *ctx);
if (!checkMirrorExists(mirrorIt, functionName))
return;
physXGpu->releaseMirror(mirrorIt->mirrorHandle);
mMeshMirrors.replaceWithLast(mirrorIt);
}
else
{
//remove all mesh mirrors for all contexts.
Ps::Array<MeshMirror>::Iterator mirrorIt;
while ((mirrorIt = findMeshMirror(meshPtr)) != mMeshMirrors.end())
{
physXGpu->releaseMirror(mirrorIt->mirrorHandle);
mMeshMirrors.replaceWithLast(mirrorIt);
}
}
}
//-------------------------------------------------------------------------------------------------------------------//
bool NpPhysicsGpu::createTriangleMeshMirror(const PxTriangleMesh& triangleMesh, PxCudaContextManager& contextManager)
{
const char* functionName = "PxParticleGpu::createTriangleMeshMirror()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (!physXGpu)
return false;
const void* meshPtr = (const void*)&triangleMesh;
if (!checkNewMirror(meshPtr, contextManager, functionName))
return true;
PxU32 mirrorHandle = physXGpu->createTriangleMeshMirror(triangleMesh, contextManager);
if (!checkMirrorHandle(mirrorHandle, functionName))
return false;
addMeshMirror(meshPtr, mirrorHandle, contextManager);
return true;
}
//-------------------------------------------------------------------------------------------------------------------//
void NpPhysicsGpu::releaseTriangleMeshMirror(const PxTriangleMesh& triangleMesh, PxCudaContextManager* contextManager)
{
releaseMeshMirror((const void*)&triangleMesh, "PxParticleGpu::releaseTriangleMeshMirror()", contextManager);
}
//-------------------------------------------------------------------------------------------------------------------//
bool NpPhysicsGpu::createHeightFieldMirror(const PxHeightField& heightField, PxCudaContextManager& contextManager)
{
const char* functionName = "PxParticleGpu::createHeightFieldMirror()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (!physXGpu)
return false;
const void* meshPtr = (const void*)&heightField;
if (!checkNewMirror(meshPtr, contextManager, functionName))
return true;
PxU32 mirrorHandle = physXGpu->createHeightFieldMirror(heightField, contextManager);
if (!checkMirrorHandle(mirrorHandle, functionName))
return false;
addMeshMirror(meshPtr, mirrorHandle, contextManager);
return true;
}
//-------------------------------------------------------------------------------------------------------------------//
void NpPhysicsGpu::releaseHeightFieldMirror(const PxHeightField& heightField, PxCudaContextManager* contextManager)
{
releaseMeshMirror((const void*)&heightField, "PxParticleGpu::releaseHeightFieldMirror()", contextManager);
}
//-------------------------------------------------------------------------------------------------------------------//
bool NpPhysicsGpu::createConvexMeshMirror(const PxConvexMesh& convexMesh, PxCudaContextManager& contextManager)
{
const char* functionName = "PxParticleGpu::createConvexMeshMirror()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (!physXGpu)
return false;
const void* meshPtr = (const void*)&convexMesh;
if (!checkNewMirror(meshPtr, contextManager, functionName))
return true;
PxU32 mirrorHandle = physXGpu->createConvexMeshMirror(convexMesh, contextManager);
if (!checkMirrorHandle(mirrorHandle, functionName))
return false;
addMeshMirror(meshPtr, mirrorHandle, contextManager);
return true;
}
//-------------------------------------------------------------------------------------------------------------------//
void NpPhysicsGpu::releaseConvexMeshMirror(const PxConvexMesh& convexMesh, PxCudaContextManager* contextManager)
{
releaseMeshMirror((const void*)&convexMesh, "PxParticleGpu::releaseConvexMeshMirror()", contextManager);
}
//-------------------------------------------------------------------------------------------------------------------//
namespace
{
PxSceneGpu* getSceneGpu(const PxScene& scene)
{
#if PX_SUPPORT_GPU_PHYSX
return ((NpScene*)&scene)->mScene.getScScene().getSceneGpu(true);
#else
return NULL;
#endif
}
}
void NpPhysicsGpu::setExplicitCudaFlushCountHint(const class PxScene& scene, PxU32 cudaFlushCount)
{
const char* functionName = "PxParticleGpu::setExplicitCudaFlushCountHint()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (physXGpu)
{
PxSceneGpu* gpuScene = getSceneGpu(scene);
PX_ASSERT(gpuScene);
physXGpu->setExplicitCudaFlushCountHint((PxgSceneGpu&)(*gpuScene), cudaFlushCount);
}
}
//-------------------------------------------------------------------------------------------------------------------//
bool NpPhysicsGpu::setTriangleMeshCacheSizeHint(const class PxScene& scene, PxU32 size)
{
const char* functionName = "PxParticleGpu::setTriangleMeshCacheSizeHint()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (physXGpu)
{
PxSceneGpu* gpuScene = getSceneGpu(scene);
PX_ASSERT(gpuScene);
return physXGpu->setTriangleMeshCacheSizeHint((PxgSceneGpu&)(*gpuScene), size);
}
return false;
}
//-------------------------------------------------------------------------------------------------------------------//
PxTriangleMeshCacheStatistics NpPhysicsGpu::getTriangleMeshCacheStatistics(const class PxScene& scene)
{
PxTriangleMeshCacheStatistics stats;
const char* functionName = "PxParticleGpu::getTriangleMeshCacheStatistics()";
PxPhysXGpu* physXGpu = getPhysXGpu(true, functionName);
if (physXGpu)
{
PxSceneGpu* gpuScene = getSceneGpu(scene);
PX_ASSERT(gpuScene);
stats = physXGpu->getTriangleMeshCacheStatistics((PxgSceneGpu&)(*gpuScene));
}
return stats;
}
//-------------------------------------------------------------------------------------------------------------------//
NpPhysicsGpu::NpPhysicsGpu(NpPhysics& npPhysics) : mMeshMirrors(PX_DEBUG_EXP("NpPhysicsGpu:mMeshMirrors")), mNpPhysics(npPhysics)
{}
//-------------------------------------------------------------------------------------------------------------------//
NpPhysicsGpu::~NpPhysicsGpu()
{}
//-------------------------------------------------------------------------------------------------------------------//
#endif // PX_SUPPORT_GPU_PHYSX
| 34.338182 | 134 | 0.645028 | [
"mesh"
] |
a8a905542bc9e3e5e81b83c46ed73c78a43b37ab | 6,772 | cpp | C++ | bmlb/src/v20180625/model/SetTrafficMirrorHealthSwitchRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | bmlb/src/v20180625/model/SetTrafficMirrorHealthSwitchRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | bmlb/src/v20180625/model/SetTrafficMirrorHealthSwitchRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/bmlb/v20180625/model/SetTrafficMirrorHealthSwitchRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Bmlb::V20180625::Model;
using namespace rapidjson;
using namespace std;
SetTrafficMirrorHealthSwitchRequest::SetTrafficMirrorHealthSwitchRequest() :
m_trafficMirrorIdHasBeenSet(false),
m_healthSwitchHasBeenSet(false),
m_healthNumHasBeenSet(false),
m_unhealthNumHasBeenSet(false),
m_intervalTimeHasBeenSet(false),
m_httpCheckDomainHasBeenSet(false),
m_httpCheckPathHasBeenSet(false),
m_httpCodesHasBeenSet(false)
{
}
string SetTrafficMirrorHealthSwitchRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_trafficMirrorIdHasBeenSet)
{
Value iKey(kStringType);
string key = "TrafficMirrorId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_trafficMirrorId.c_str(), allocator).Move(), allocator);
}
if (m_healthSwitchHasBeenSet)
{
Value iKey(kStringType);
string key = "HealthSwitch";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_healthSwitch, allocator);
}
if (m_healthNumHasBeenSet)
{
Value iKey(kStringType);
string key = "HealthNum";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_healthNum, allocator);
}
if (m_unhealthNumHasBeenSet)
{
Value iKey(kStringType);
string key = "UnhealthNum";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_unhealthNum, allocator);
}
if (m_intervalTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "IntervalTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_intervalTime, allocator);
}
if (m_httpCheckDomainHasBeenSet)
{
Value iKey(kStringType);
string key = "HttpCheckDomain";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_httpCheckDomain.c_str(), allocator).Move(), allocator);
}
if (m_httpCheckPathHasBeenSet)
{
Value iKey(kStringType);
string key = "HttpCheckPath";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_httpCheckPath.c_str(), allocator).Move(), allocator);
}
if (m_httpCodesHasBeenSet)
{
Value iKey(kStringType);
string key = "HttpCodes";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(kArrayType).Move(), allocator);
for (auto itr = m_httpCodes.begin(); itr != m_httpCodes.end(); ++itr)
{
d[key.c_str()].PushBack(Value().SetInt64(*itr), allocator);
}
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string SetTrafficMirrorHealthSwitchRequest::GetTrafficMirrorId() const
{
return m_trafficMirrorId;
}
void SetTrafficMirrorHealthSwitchRequest::SetTrafficMirrorId(const string& _trafficMirrorId)
{
m_trafficMirrorId = _trafficMirrorId;
m_trafficMirrorIdHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::TrafficMirrorIdHasBeenSet() const
{
return m_trafficMirrorIdHasBeenSet;
}
int64_t SetTrafficMirrorHealthSwitchRequest::GetHealthSwitch() const
{
return m_healthSwitch;
}
void SetTrafficMirrorHealthSwitchRequest::SetHealthSwitch(const int64_t& _healthSwitch)
{
m_healthSwitch = _healthSwitch;
m_healthSwitchHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::HealthSwitchHasBeenSet() const
{
return m_healthSwitchHasBeenSet;
}
int64_t SetTrafficMirrorHealthSwitchRequest::GetHealthNum() const
{
return m_healthNum;
}
void SetTrafficMirrorHealthSwitchRequest::SetHealthNum(const int64_t& _healthNum)
{
m_healthNum = _healthNum;
m_healthNumHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::HealthNumHasBeenSet() const
{
return m_healthNumHasBeenSet;
}
int64_t SetTrafficMirrorHealthSwitchRequest::GetUnhealthNum() const
{
return m_unhealthNum;
}
void SetTrafficMirrorHealthSwitchRequest::SetUnhealthNum(const int64_t& _unhealthNum)
{
m_unhealthNum = _unhealthNum;
m_unhealthNumHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::UnhealthNumHasBeenSet() const
{
return m_unhealthNumHasBeenSet;
}
int64_t SetTrafficMirrorHealthSwitchRequest::GetIntervalTime() const
{
return m_intervalTime;
}
void SetTrafficMirrorHealthSwitchRequest::SetIntervalTime(const int64_t& _intervalTime)
{
m_intervalTime = _intervalTime;
m_intervalTimeHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::IntervalTimeHasBeenSet() const
{
return m_intervalTimeHasBeenSet;
}
string SetTrafficMirrorHealthSwitchRequest::GetHttpCheckDomain() const
{
return m_httpCheckDomain;
}
void SetTrafficMirrorHealthSwitchRequest::SetHttpCheckDomain(const string& _httpCheckDomain)
{
m_httpCheckDomain = _httpCheckDomain;
m_httpCheckDomainHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::HttpCheckDomainHasBeenSet() const
{
return m_httpCheckDomainHasBeenSet;
}
string SetTrafficMirrorHealthSwitchRequest::GetHttpCheckPath() const
{
return m_httpCheckPath;
}
void SetTrafficMirrorHealthSwitchRequest::SetHttpCheckPath(const string& _httpCheckPath)
{
m_httpCheckPath = _httpCheckPath;
m_httpCheckPathHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::HttpCheckPathHasBeenSet() const
{
return m_httpCheckPathHasBeenSet;
}
vector<int64_t> SetTrafficMirrorHealthSwitchRequest::GetHttpCodes() const
{
return m_httpCodes;
}
void SetTrafficMirrorHealthSwitchRequest::SetHttpCodes(const vector<int64_t>& _httpCodes)
{
m_httpCodes = _httpCodes;
m_httpCodesHasBeenSet = true;
}
bool SetTrafficMirrorHealthSwitchRequest::HttpCodesHasBeenSet() const
{
return m_httpCodesHasBeenSet;
}
| 26.98008 | 92 | 0.74114 | [
"vector",
"model"
] |
a8abe4ff9439daab82101e0d577268224c0aeb13 | 793 | cpp | C++ | LeetCode/Solutions/LC0015.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | LeetCode/Solutions/LC0015.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | LeetCode/Solutions/LC0015.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | /*
Problem Statement: https://leetcode.com/problems/3sum/
Time: O(n²)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int> nums) {
int l, r, sum, n = nums.size();
vector<vector<int>> triplets;
sort(nums.begin(), nums.end());
for (int i = 0; i < n && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
l = i + 1;
r = n - 1;
while (l < r) {
sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
triplets.push_back({nums[i], nums[l], nums[r]});
while (l < r && nums[l] == nums[l + 1])
l++;
while (l < r && nums[r] == nums[r - 1])
r--;
l++;
}
else if (sum < 0)
l++;
else
r--;
}
}
return triplets;
}
}; | 20.333333 | 54 | 0.496847 | [
"vector"
] |
a8b263653ed340126460d26efb8ce04ef92ff417 | 10,317 | cpp | C++ | src/API/Wallet/Owner/OwnerServer.cpp | 1div0/GrinPlusPlus | 44ba6474b971cd39a96b7ad9742b23d3cb5334c9 | [
"MIT"
] | null | null | null | src/API/Wallet/Owner/OwnerServer.cpp | 1div0/GrinPlusPlus | 44ba6474b971cd39a96b7ad9742b23d3cb5334c9 | [
"MIT"
] | null | null | null | src/API/Wallet/Owner/OwnerServer.cpp | 1div0/GrinPlusPlus | 44ba6474b971cd39a96b7ad9742b23d3cb5334c9 | [
"MIT"
] | null | null | null | #include <API/Wallet/Owner/OwnerServer.h>
#include <Wallet/WalletManager.h>
#include <Net/Tor/TorProcess.h>
// APIs
#include <API/Wallet/Owner/Handlers/CreateWalletHandler.h>
#include <API/Wallet/Owner/Handlers/RestoreWalletHandler.h>
#include <API/Wallet/Owner/Handlers/LoginHandler.h>
#include <API/Wallet/Owner/Handlers/LogoutHandler.h>
#include <API/Wallet/Owner/Handlers/SendHandler.h>
#include <API/Wallet/Owner/Handlers/ReceiveHandler.h>
#include <API/Wallet/Owner/Handlers/FinalizeHandler.h>
#include <API/Wallet/Owner/Handlers/RetryTorHandler.h>
#include <API/Wallet/Owner/Handlers/DeleteWalletHandler.h>
#include <API/Wallet/Owner/Handlers/GetWalletSeedHandler.h>
#include <API/Wallet/Owner/Handlers/CancelTxHandler.h>
#include <API/Wallet/Owner/Handlers/GetBalanceHandler.h>
#include <API/Wallet/Owner/Handlers/ListTxsHandler.h>
#include <API/Wallet/Owner/Handlers/RepostTxHandler.h>
#include <API/Wallet/Owner/Handlers/EstimateFeeHandler.h>
OwnerServer::UPtr OwnerServer::Create(const TorProcess::Ptr& pTorProcess, const IWalletManagerPtr& pWalletManager)
{
RPCServerPtr pServer = RPCServer::Create(
EServerType::LOCAL,
std::make_optional<uint16_t>((uint16_t)3421), // TODO: Read port from config (Use same port as v1 owner)
"/v2",
LoggerAPI::LogFile::WALLET
);
/*
Request:
{
"jsonrpc": "2.0",
"method": "create_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!",
"num_seed_words": 24
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("create_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new CreateWalletHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "restore_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!",
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("restore_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new RestoreWalletHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "login",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"listener_port": 1100,
"tor_address": ""
}
}
*/
pServer->AddMethod("login", std::shared_ptr<RPCMethod>((RPCMethod*)new LoginHandler(pWalletManager, pTorProcess)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "logout",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk="
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {}
}
*/
pServer->AddMethod("logout", std::shared_ptr<RPCMethod>((RPCMethod*)new LogoutHandler(pWalletManager)));
pServer->AddMethod("send", std::shared_ptr<RPCMethod>((RPCMethod*)new SendHandler(pTorProcess, pWalletManager)));
pServer->AddMethod("receive", std::shared_ptr<RPCMethod>((RPCMethod*)new ReceiveHandler(pWalletManager)));
pServer->AddMethod("finalize", std::shared_ptr<RPCMethod>((RPCMethod*)new FinalizeHandler(pTorProcess, pWalletManager)));
pServer->AddMethod("retry_tor", std::shared_ptr<RPCMethod>((RPCMethod*)new RetryTorHandler(pTorProcess, pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "delete_wallet",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("delete_wallet", std::shared_ptr<RPCMethod>((RPCMethod*)new DeleteWalletHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "get_wallet_seed",
"id": 1,
"params": {
"username": "David",
"password": "P@ssw0rd123!"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"wallet_seed": "agree muscle erase plunge grit effort provide electric social decide include whisper tunnel dizzy bean tumble play robot fire verify program solid weasel nuclear"
}
}
*/
pServer->AddMethod("get_wallet_seed", std::shared_ptr<RPCMethod>((RPCMethod*)new GetWalletSeedHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "cancel_tx",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"tx_id": 123
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("cancel_tx", std::shared_ptr<RPCMethod>((RPCMethod*)new CancelTxHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "get_balance",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk="
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"total": 20482100000,
"unconfirmed": 6282100000,
"immature": 10200000000,
"locked": 5700000000,
"spendable": 4000000000
}
}
*/
pServer->AddMethod("get_balance", std::shared_ptr<RPCMethod>((RPCMethod*)new GetBalanceHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "list_txs",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"start_range_ms": 1567361400000,
"end_range_ms": 1575227400000,
"statuses": ["COINBASE","SENT","RECEIVED","SENT_CANCELED","RECEIVED_CANCELED","SENDING_NOT_FINALIZED","RECEIVING_IN_PROGRESS", "SENDING_FINALIZED"]
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"txs": []
}
}
*/
pServer->AddMethod("list_txs", std::shared_ptr<RPCMethod>((RPCMethod*)new ListTxsHandler(pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "repost_tx",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"tx_id": 123,
"method": "STEM"
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": "SUCCESS"
}
}
*/
pServer->AddMethod("repost_tx", std::shared_ptr<RPCMethod>((RPCMethod*)new RepostTxHandler(pTorProcess, pWalletManager)));
/*
Request:
{
"jsonrpc": "2.0",
"method": "estimate_fee",
"id": 1,
"params": {
"session_token": "mFHve+/CFsPuQf1+Anp24+R1rLZCVBIyKF+fJEuxAappgT2WKMfpOiNwvRk=",
"amount": 12345678,
"fee_base": "1000000",
"change_outputs": 1,
"selection_strategy": {
"strategy": "SMALLEST"
}
}
}
Reply:
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"fee": "7000000",
"inputs": [
{
"keychain_path": "m/1/0/1000",
"commitment": "0808657d5346f4061e5484b6f57ed036ce2cb4430599cec5dcb999d07755772010",
"amount": 30000000,
"status": "Spendable"
}
]
}
}
*/
pServer->AddMethod("estimate_fee", std::shared_ptr<RPCMethod>((RPCMethod*)new EstimateFeeHandler(pWalletManager)));
// TODO: Add the following APIs:
// authenticate - Simply validates the password - useful for confirming password before sending funds
// tx_info - Detailed info about a specific transaction (status, kernels, inputs, outputs, payment proofs, labels, etc)
// update_labels - Add or remove labels - useful for coin control
// verify_payment_proof - Takes in an existing payment proof and validates it
return std::make_unique<OwnerServer>(pServer);
} | 32.140187 | 195 | 0.518659 | [
"solid"
] |
a8b88eb3574bf8fde6b6fdaa9c0f1dd5fa974e49 | 22,690 | cpp | C++ | Programs/Launcher/Classes/Data/Private/ConfigParser.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Programs/Launcher/Classes/Data/Private/ConfigParser.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Programs/Launcher/Classes/Data/Private/ConfigParser.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #include "Data/ConfigParser.h"
#include "Core/CommonTasks/BaseTask.h"
#include "Utils/ErrorMessenger.h"
#include "defines.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonObject>
#include <QDebug>
#include <QJsonParseError>
#include <QRegularExpression>
#include <functional>
namespace ConfigParserDetails
{
QString ProcessID(const QString& id)
{
QRegularExpressionMatch match;
QRegularExpression regex("\\[\\d+\\_\\d+\\_\\d+\\]");
int index = id.indexOf(regex, 0, &match);
if (index == -1)
{
int digitIndex = id.indexOf(QRegularExpression("\\d+"));
if (digitIndex == -1)
{
return id;
}
return id.right(id.length() - digitIndex);
}
QString version = match.captured();
int versionLength = version.length();
QStringList digits = version.split(QRegularExpression("\\D+"), QString::SkipEmptyParts);
version = digits.join(".");
QString dateTime = id.right(id.length() - versionLength - index);
QString extension(".txt");
if (dateTime.endsWith(extension))
{
dateTime.chop(extension.length());
}
QRegularExpression timeRegex("\\_\\d+\\_\\d+\\_\\d+");
if (dateTime.indexOf(timeRegex, 0, &match) != -1)
{
QString time = match.captured();
time = time.split(QRegularExpression("\\D+"), QString::SkipEmptyParts).join(".");
dateTime.replace(timeRegex, "_" + time);
}
QString result = version + dateTime;
return result;
}
bool ExtractApp(const QString& appName, const QJsonObject& entry, Branch* branch, bool toolset)
{
if (appName.isEmpty())
{
return false;
}
Application* app = branch->GetApplication(appName);
if (app == nullptr)
{
branch->applications.append(Application(appName));
app = &branch->applications.last();
}
QString buildNum = entry["build_num"].toString();
AppVersion* appVer = nullptr;
if (buildNum.isEmpty() == false)
{
appVer = app->GetVersionByNum(buildNum);
}
if (appVer == nullptr)
{
QString buildType = entry["build_type"].toString();
if (buildType.isEmpty())
{
return false;
}
appVer = app->GetVersion(buildType);
}
if (appVer == nullptr)
{
app->versions.append(AppVersion());
appVer = &app->versions.last();
}
return FillAppFields(appVer, entry, toolset);
}
}
bool LessThan(const AppVersion& leftVer, const AppVersion& rightVer);
bool ConfigParser::ExtractLauncherVersionAndURL(const QJsonValue& value)
{
QJsonObject launcherObject = value.toObject();
QJsonObject platformObject = launcherObject[platformString].toObject();
QJsonValue versionValue = platformObject["version"];
if (versionValue.isString())
{
launcherVersion = versionValue.toString();
}
QJsonValue urlValue = platformObject["url"];
if (urlValue.isString())
{
launcherURL = urlValue.toString();
}
QJsonValue newsValue = launcherObject["news"];
if (newsValue.isString())
{
webPageURL = newsValue.toString();
}
return !launcherObject.isEmpty();
}
bool ConfigParser::ExtractLauncherStrings(const QJsonValue& value)
{
QJsonArray array = value.toArray();
bool isValid = !array.isEmpty();
for (const QJsonValueRef& ref : array)
{
QJsonObject entry = ref.toObject();
if (entry["os"].toString() != platformString)
{
continue;
}
QString key = entry["build_tag"].toString();
QString stringValue = entry["build_name"].toString();
isValid &= !key.isEmpty() && !stringValue.isEmpty();
strings[key] = stringValue;
}
return isValid;
}
bool ConfigParser::ExtractFavorites(const QJsonValue& value)
{
QJsonArray array = value.toArray();
bool isValid = !array.isEmpty();
for (const QJsonValueRef& ref : array)
{
QJsonObject entry = ref.toObject();
if (entry["favourite"].toString() != "1")
{
continue;
}
QString fave = entry["branch_name"].toString();
isValid &= !fave.isEmpty();
//favorites list can not be large
if (!favorites.contains(fave))
{
favorites.append(fave);
}
}
return isValid;
}
bool ConfigParser::ExtractBranches(const QJsonValue& value)
{
QJsonArray array = value.toArray();
//this array can be empty
bool isValid = true;
for (const QJsonValueRef& ref : array)
{
QJsonObject entry = ref.toObject();
QString branchNameID = "branchName";
//now ASK builds without branch name
if (!entry[branchNameID].isString())
{
isValid = false;
continue;
}
QString branchName = entry[branchNameID].toString();
Branch* branch = nullptr;
//foreach will cause deep copy in this case
int branchCount = branches.size();
for (int i = 0; i < branchCount; ++i)
{
if (branches[i].id == branchName)
{
branch = &branches[i];
}
}
if (branch == nullptr)
{
branches.append(Branch(branchName));
branch = &branches.last();
}
QString appName = entry["build_name"].toString();
if (IsToolset(appName))
{
for (const QString& toolsetApp : ConfigParser::GetToolsetApplications())
{
isValid &= ConfigParserDetails::ExtractApp(toolsetApp, entry, branch, true);
}
}
else
{
isValid &= ConfigParserDetails::ExtractApp(appName, entry, branch, false);
}
}
//hot fix to sort downloaded items without rewriting mainWindow
for (auto branchIter = branches.begin(); branchIter != branches.end(); ++branchIter)
{
QList<Application>& apps = branchIter->applications;
qSort(apps.begin(), apps.end(), [](const Application& appLeft, const Application& appRight)
{
return appLeft.id < appRight.id;
});
}
return isValid;
}
bool IsToolset(const QString& appName)
{
return appName.startsWith("toolset", Qt::CaseInsensitive);
}
bool IsBuildSupported(const QString& url)
{
static QStringList supportedExtensions = {
".zip", ".ipa"
};
for (const QString& ext : supportedExtensions)
{
if (url.endsWith(ext))
{
return true;
}
}
return false;
}
bool FillAppFields(AppVersion* appVer, const QJsonObject& entry, bool toolset)
{
QString url = entry["artifacts"].toString();
QString buildType = entry["build_type"].toString();
//remember num to fill it later
appVer->buildNum = entry["build_num"].toString();
if (appVer->id.isEmpty() || url.endsWith(".zip") || buildType.startsWith("Desc"))
{
appVer->id = ConfigParserDetails::ProcessID(buildType);
}
if (IsBuildSupported(url) == false)
{
//this is valid situation
return true;
}
appVer->url = url;
appVer->runPath = toolset ? "" : entry["exe_location"].toString();
appVer->isToolSet = toolset;
return !appVer->url.isEmpty();
}
AppVersion* Application::GetVersion(const QString& versionID)
{
int versCount = versions.size();
for (int i = 0; i < versCount; ++i)
if (versions[i].id == versionID)
return &versions[i];
return 0;
}
AppVersion* Application::GetVersionByNum(const QString& num)
{
auto iter = std::find_if(versions.begin(), versions.end(), [num](const AppVersion& ver) {
return ver.buildNum == num;
});
if (iter == versions.end())
{
return nullptr;
}
return &(*iter);
}
void Application::RemoveVersion(const QString& versionID)
{
int index = -1;
int versCount = versions.size();
for (int i = 0; i < versCount; ++i)
{
if (versions[i].id == versionID)
{
index = i;
break;
}
}
if (index != -1)
versions.removeAt(index);
}
Application* Branch::GetApplication(const QString& appID)
{
int appCount = applications.size();
for (int i = 0; i < appCount; ++i)
if (applications[i].id == appID)
return &applications[i];
return 0;
}
void Branch::RemoveApplication(const QString& appID)
{
int index = -1;
int appCount = applications.size();
for (int i = 0; i < appCount; ++i)
{
if (applications[i].id == appID)
{
index = i;
break;
}
}
if (index != -1)
applications.removeAt(index);
}
ConfigParser::ConfigParser()
: launcherVersion(LAUNCHER_VER)
, webPageURL("")
, remoteConfigURL("")
{
}
void ConfigParser::Clear()
{
launcherVersion = LAUNCHER_VER;
launcherURL.clear();
webPageURL.clear();
remoteConfigURL.clear();
favorites.clear();
branches.clear();
strings.clear();
}
bool ConfigParser::ParseJSON(const QByteArray& configData, BaseTask* task)
{
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(configData, &parseError);
if (parseError.error != QJsonParseError::NoError)
{
//this is not JSON
return false;
}
QJsonObject rootObj = document.object();
if (rootObj.keys().isEmpty())
{
task->SetError(QObject::tr("Config parser: Got an empty config from server "));
}
using namespace std::placeholders;
using ParserFn = std::function<bool(const QJsonValue&)>;
QMap<QString, ParserFn> parsers = {
{ "launcher", std::bind(&ConfigParser::ExtractLauncherVersionAndURL, this, _1) },
{ "seo_list", std::bind(&ConfigParser::ExtractLauncherStrings, this, _1) },
{ "branches", std::bind(&ConfigParser::ExtractFavorites, this, _1) },
{ "builds", std::bind(&ConfigParser::ExtractBranches, this, _1) }
};
bool haveUsefulInformation = false;
for (const QString& key : rootObj.keys())
{
if (parsers.contains(key))
{
QJsonValue value = rootObj.value(key);
ParserFn parser = parsers[key];
if (parser(value))
{
haveUsefulInformation = true;
}
else
{
task->SetError(QObject::tr("Got wrong config page: %1").arg(key));
}
}
}
if (haveUsefulInformation)
{
for (Branch& branch : branches)
{
for (Application& application : branch.applications)
{
qSort(application.versions.begin(), application.versions.end(), LessThan);
}
}
}
return haveUsefulInformation;
}
const QList<Branch>& ConfigParser::GetBranches() const
{
return branches;
}
QList<Branch>& ConfigParser::GetBranches()
{
return branches;
}
void ConfigParser::CopyStringsAndFavsFromConfig(ConfigParser* parser)
{
QMap<QString, QString>::ConstIterator it = parser->strings.begin();
QMap<QString, QString>::ConstIterator itEnd = parser->strings.end();
for (; it != itEnd; ++it)
strings[it.key()] = it.value();
if (!parser->favorites.isEmpty())
{
favorites = parser->favorites;
}
}
void ConfigParser::UpdateApplicationsNames()
{
for (auto branchIter = branches.begin(); branchIter != branches.end(); ++branchIter)
{
for (auto appIter = branchIter->applications.begin(); appIter != branchIter->applications.end(); ++appIter)
{
auto stringsIter = strings.find(appIter->id);
if (stringsIter != strings.end())
{
appIter->id = *stringsIter;
}
}
}
}
QByteArray ConfigParser::Serialize() const
{
QJsonObject rootObject;
QJsonObject launcherObject;
launcherObject["url"] = webPageURL;
rootObject["launcher"] = launcherObject;
QJsonArray favoritesArray;
for (const QString& favoriteBranch : favorites)
{
QJsonObject favObject = {
{ "branch_name", favoriteBranch },
{ "favourite", "1" }
};
favoritesArray.append(favObject);
}
rootObject["branches"] = favoritesArray;
QJsonArray stringsArray;
QMap<QString, QString>::ConstIterator it = strings.constBegin();
QMap<QString, QString>::ConstIterator itEnd = strings.constEnd();
for (; it != itEnd; ++it)
{
QJsonObject stringsObj = {
{ "build_tag", it.key() },
{ "build_name", it.value() },
{ "os", platformString }
};
stringsArray.append(stringsObj);
}
rootObject["seo_list"] = stringsArray;
QJsonArray buildsArray;
for (int i = 0; i < branches.size(); ++i)
{
const Branch* branch = GetBranch(i);
for (int j = 0; j < branch->GetAppCount(); ++j)
{
const Application* app = branch->GetApplication(j);
for (int k = 0; k < app->GetVerionsCount(); ++k)
{
const AppVersion* ver = app->GetVersion(k);
QString appName = ver->isToolSet ? "ToolSet" : app->id;
QJsonObject buildObj = {
{ "build_num", ver->buildNum },
{ "build_type", ver->id },
{ "build_name", appName },
{ "branchName", branch->id },
{ "artifacts", ver->url },
{ "exe_location", ver->runPath }
};
buildsArray.append(buildObj);
}
}
}
rootObject["builds"] = buildsArray;
QJsonDocument document(rootObject);
return document.toJson();
}
void ConfigParser::SaveToFile(const QString& filePath) const
{
QFile file(filePath);
if (file.open(QFile::WriteOnly | QFile::Truncate))
{
QByteArray data = Serialize();
file.write(data);
}
file.close();
}
void ConfigParser::RemoveBranch(const QString& branchID)
{
int index = -1;
int branchesCount = branches.size();
for (int i = 0; i < branchesCount; ++i)
{
if (branches[i].id == branchID)
{
index = i;
break;
}
}
if (index != -1)
{
branches.removeAt(index);
}
}
void ConfigParser::InsertApplication(const QString& branchID, const QString& appID, const AppVersion& version)
{
if (version.isToolSet)
{
for (const QString& fakeAppID : GetTranslatedToolsetApplications())
{
InsertApplicationImpl(branchID, fakeAppID, version);
}
}
else
{
InsertApplicationImpl(branchID, appID, version);
}
}
void ConfigParser::InsertApplicationImpl(const QString& branchID, const QString& appID, const AppVersion& version)
{
Branch* branch = GetBranch(branchID);
if (!branch)
{
branches.push_back(Branch(branchID));
branch = GetBranch(branchID);
}
Application* app = branch->GetApplication(appID);
if (!app)
{
branch->applications.push_back(Application(appID));
app = branch->GetApplication(appID);
}
app->versions.clear();
app->versions.push_back(version);
qSort(app->versions.begin(), app->versions.end(), LessThan);
}
void ConfigParser::RemoveApplication(const QString& branchID, const QString& appID, const QString& versionID)
{
Branch* branch = GetBranch(branchID);
if (!branch)
return;
Application* app = branch->GetApplication(appID);
if (!app)
return;
AppVersion* appVersion = app->GetVersion(versionID);
if (!appVersion)
return;
app->RemoveVersion(versionID);
if (!app->GetVerionsCount())
branch->RemoveApplication(appID);
if (!branch->GetAppCount())
RemoveBranch(branchID);
}
QStringList ConfigParser::GetToolsetApplications()
{
static QStringList applications;
if (applications.isEmpty())
{
applications << "AssetCacheServer"
<< "ResourceEditor"
<< "QuickEd";
//try to get project name as it stored in ba-manager
QString prefix =
#ifdef Q_OS_WIN
"_win";
#elif defined(Q_OS_MAC)
"_mac";
#else
#error "unsupported platform"
#endif //platform
for (auto iter = applications.begin(); iter != applications.end(); ++iter)
{
*iter += prefix;
}
}
return applications;
}
QStringList ConfigParser::GetTranslatedToolsetApplications() const
{
QStringList applications = GetToolsetApplications();
for (auto iter = applications.begin(); iter != applications.end(); ++iter)
{
*iter = GetString(*iter);
}
return applications;
}
int ConfigParser::GetBranchCount()
{
return branches.size();
}
QString ConfigParser::GetBranchID(int branchIndex)
{
if (branchIndex >= 0 && branchIndex < branches.size())
return branches[branchIndex].id;
return QString();
}
Branch* ConfigParser::GetBranch(int branchIndex)
{
if (branchIndex >= 0 && branchIndex < branches.size())
return &branches[branchIndex];
return nullptr;
}
Branch* ConfigParser::GetBranch(const QString& branch)
{
int branchCount = branches.size();
for (int i = 0; i < branchCount; ++i)
if (branches[i].id == branch)
return &branches[i];
return nullptr;
}
const Branch* ConfigParser::GetBranch(int branchIndex) const
{
return const_cast<ConfigParser*>(this)->GetBranch(branchIndex);
}
const Branch* ConfigParser::GetBranch(const QString& branch) const
{
return const_cast<ConfigParser*>(this)->GetBranch(branch);
}
Application* ConfigParser::GetApplication(const QString& branchID, const QString& appID)
{
Branch* branch = GetBranch(branchID);
if (branch)
{
int appCount = branch->applications.size();
for (int i = 0; i < appCount; ++i)
if (branch->applications[i].id == appID)
{
return &branch->applications[i];
}
}
return nullptr;
}
const Application* ConfigParser::GetApplication(const QString& branchID, const QString& appID) const
{
const Branch* branch = GetBranch(branchID);
if (branch != nullptr)
{
int appCount = branch->applications.size();
for (int i = 0; i < appCount; ++i)
if (branch->applications[i].id == appID)
{
return &branch->applications[i];
}
}
return nullptr;
}
AppVersion* ConfigParser::GetAppVersion(const QString& branchID, const QString& appID, const QString& ver)
{
Application* app = GetApplication(branchID, appID);
if (app != nullptr)
{
int versCount = app->versions.size();
for (int i = 0; i < versCount; ++i)
if (app->versions[i].id == ver)
return &app->versions[i];
}
return nullptr;
}
AppVersion* ConfigParser::GetAppVersion(const QString& branchID, const QString& appID)
{
Application* app = GetApplication(branchID, appID);
if (app != nullptr)
{
if (app->versions.isEmpty() == false)
{
return &app->versions.first();
}
}
return nullptr;
}
QString ConfigParser::GetString(const QString& stringID) const
{
if (strings.contains(stringID))
return strings[stringID];
return stringID;
}
const QMap<QString, QString>& ConfigParser::GetStrings() const
{
return strings;
}
const QString& ConfigParser::GetLauncherVersion() const
{
return launcherVersion;
}
const QString& ConfigParser::GetLauncherURL() const
{
return launcherURL;
}
const QString& ConfigParser::GetWebpageURL() const
{
return webPageURL;
}
void ConfigParser::SetLauncherURL(const QString& url)
{
launcherURL = url;
}
void ConfigParser::SetWebpageURL(const QString& url)
{
webPageURL = url;
}
void ConfigParser::SetRemoteConfigURL(const QString& url)
{
remoteConfigURL = url;
}
void ConfigParser::MergeBranchesIDs(QSet<QString>& branchIDs)
{
int branchCount = branches.size();
for (int i = 0; i < branchCount; ++i)
branchIDs.insert(branches[i].id);
}
const QStringList& ConfigParser::GetFavorites()
{
return favorites;
}
//expected format of input string: 0.8_2015-02-14_11.20.12_0000,
//where 0.8 - DAVA version, 2015-02-14 - build date, 11.20.12 - build time and 0000 - build version
//all blocks can be modified or empty
bool LessThan(const AppVersion& leftVer, const AppVersion& rightVer)
{
//ignore non-toolset builds
if (leftVer.isToolSet != rightVer.isToolSet)
{
return leftVer.isToolSet == false;
}
const QString& leftBuildNum = leftVer.buildNum;
const QString& rightBuildNum = rightVer.buildNum;
if (leftBuildNum != rightBuildNum)
{
return leftBuildNum < rightBuildNum;
}
const QString& left = leftVer.id;
const QString& right = rightVer.id;
QStringList leftList = left.split('_', QString::SkipEmptyParts);
QStringList rightList = right.split('_', QString::SkipEmptyParts);
int minSize = qMin(leftList.size(), rightList.size());
for (int i = 0; i < minSize; ++i)
{
const QString& leftSubStr = leftList.at(i);
const QString& rightSubStr = rightList.at(i);
QStringList leftSubList = leftSubStr.split('.', QString::SkipEmptyParts);
QStringList rightSubList = rightSubStr.split('.', QString::SkipEmptyParts);
int subMinSize = qMin(leftSubList.size(), rightSubList.size());
for (int subStrIndex = 0; subStrIndex < subMinSize; ++subStrIndex)
{
bool leftOk;
bool rightOk;
const QString& leftSubSubStr = leftSubList.at(subStrIndex);
const QString& rightSubSubStr = rightSubList.at(subStrIndex);
qlonglong leftVal = leftSubSubStr.toLongLong(&leftOk);
qlonglong rightVal = rightSubSubStr.toLongLong(&rightOk);
if (leftOk && rightOk)
{
if (leftVal != rightVal)
{
return leftVal < rightVal;
}
}
else //date format or other
{
if (leftSubSubStr != rightSubSubStr)
{
return leftSubSubStr < rightSubSubStr;
}
}
}
//if version lists are equal - checking for extra subversion
if (leftSubList.size() != rightSubList.size())
{
return leftSubList.size() < rightSubList.size();
}
}
return false; // string are equal
};
| 26.947743 | 115 | 0.600044 | [
"object"
] |
a8bb576af07bbec24fdb3837f21b8183e8e6e803 | 559 | cpp | C++ | native/cocos/core/utils/MutableForwardIterator.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/utils/MutableForwardIterator.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/cocos/core/utils/MutableForwardIterator.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "core/utils/MutableForwardIterator.h"
namespace cc {
}
#if UNIT_TEST
void MutableForwardIteratorTest() {
using namespace cc;
ccstd::vector<int> myarr{1, 2, 3, 43, 4, 5};
MutableForwardIterator<int> iter{myarr};
iter.fastRemoveAt(2);
iter.fastRemove(43);
iter.push(123);
iter.push(100);
iter.fastRemove(123);
for (iter.i = 0; iter.i < static_cast<int32_t>(myarr.size()); ++iter.i) {
auto &&item = myarr[iter.i];
printf("item[%d]=%d\n", iter.i, item);
}
int a = 0;
}
#endif
| 18.633333 | 77 | 0.599284 | [
"vector"
] |
a8c58eec3c0e0c7703684862b9f6251dd0bf94e1 | 3,143 | cpp | C++ | src/main.cpp | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | src/main.cpp | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | src/main.cpp | Lavesson/api-mock | 07f0c3d2213df7be7699258d4273c58f13958763 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <algorithm>
#include "api-mock.h"
typedef std::unordered_map<std::string, std::string> Flags;
typedef std::pair<std::string, std::string> FlagEntry;
static const std::string ADDRESS = "127.0.0.1";
static const int FLAG_SIGN_LENGTH = 2;
static const std::string FLAG_SIGN = "--";
static const Flags DEFAULT_OPTIONS = {
{ "port", "8888" },
{ "buffer", "8192" },
};
static const std::vector<std::string> SUPPORTED_FLAGS = {
"port", "buffer", "help", "verbose"
};
bool supportedFlag(const std::string& flag) {
return std::find(SUPPORTED_FLAGS.begin(), SUPPORTED_FLAGS.end(), flag) != SUPPORTED_FLAGS.end();
}
void makeSureFlagIsSupported(const std::string& entry) {
if (!supportedFlag(entry))
throw ApiMock::UnknownFlagException(entry);
}
FlagEntry extractFlagEntry(const std::string& entry) {
const std::string DELIMITER = "=";
auto delimiterIndex = entry.find(DELIMITER);
FlagEntry flag = (delimiterIndex == std::string::npos)
? std::make_pair(entry.substr(FLAG_SIGN_LENGTH, delimiterIndex - FLAG_SIGN_LENGTH), "")
: std::make_pair(entry.substr(FLAG_SIGN_LENGTH, delimiterIndex-FLAG_SIGN_LENGTH),
entry.substr(delimiterIndex + 1));
makeSureFlagIsSupported(flag.first);
return flag;
}
bool isValidFlagFormat(const std::string &next) {
return next.length() > FLAG_SIGN_LENGTH && next.substr(0, FLAG_SIGN_LENGTH) == FLAG_SIGN;
}
Flags parseFlags(int argc, char** argv) {
Flags f;
for (int i = 1; i < argc; ++i) {
auto next = std::string(argv[i]);
if (isValidFlagFormat(next))
f.insert(extractFlagEntry(argv[i]));
}
return f;
}
Flags getMergedFlags(int argc, char** argv) {
auto flagsFromCmdLine = parseFlags(argc, argv);
flagsFromCmdLine.insert(DEFAULT_OPTIONS.begin(), DEFAULT_OPTIONS.end());
return flagsFromCmdLine;
}
bool flagIsPresent(std::string flag, Flags flags) {
return flags.find(flag) != flags.end();
}
void startServer(Flags flags) {
try {
ApiMock::HttpServer s(flagIsPresent("verbose", flags));
ApiMock::RoutedResourceStrategy routes;
ApiMock::ConfigureDependencies();
ApiMock::ConfigureRoutes(&routes);
s.startServer(
ADDRESS, std::stoi(flags["port"]), std::stoi(flags["buffer"]), &routes);
}
catch (ApiMock::SocketException e) {
printf("%s\n", e.what());
}
}
void showUsage() {
printf(
"Usage: api-mock [options]\n"
"\n"
"Options:\n"
" --port=PORT Set the port to use when starting the server.\n"
" Default port value is 8888.\n"
" --buffer=BYTES Set the size in bytes of the buffer used for\n"
" HTTP requests. Default size is 8192 bytes\n"
" --help Print this screen.\n"
" --verbose Log all output to the terminal.\n"
"\n");
}
int main(int argc, char** argv) {
try {
auto flags = getMergedFlags(argc, argv);
if (flagIsPresent("help", flags)) {
showUsage();
return 0;
}
printf("Starting server at %s:%s\n", ADDRESS.c_str(), flags["port"].c_str());
startServer(flags);
return 0;
} catch (ApiMock::UnknownFlagException e) {
printf("%s\n", e.what());
}
} | 27.570175 | 97 | 0.670697 | [
"vector"
] |
a8c9c4642c80f812192d53f37a4801092dfe3908 | 7,444 | cpp | C++ | cxxp1/src/smalls/parser/SyntaxReader.cpp | tmikov/smalls | 399db35e9c96a6ab29ac8545afeb59e4737aebe4 | [
"Apache-2.0"
] | 4 | 2015-03-26T19:35:07.000Z | 2020-03-11T06:45:32.000Z | cxxp1/src/smalls/parser/SyntaxReader.cpp | tmikov/smalls | 399db35e9c96a6ab29ac8545afeb59e4737aebe4 | [
"Apache-2.0"
] | null | null | null | cxxp1/src/smalls/parser/SyntaxReader.cpp | tmikov/smalls | 399db35e9c96a6ab29ac8545afeb59e4737aebe4 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2012 Tzvetan Mikov <tmikov@gmail.com>
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "SyntaxReader.hpp"
#include "SymbolTable.hpp"
#include "ListBuilder.hpp"
#include "p1/util/format-str.hpp"
#include "Keywords.hpp"
using namespace p1;
using namespace p1::smalls;
using namespace p1::smalls::detail;
static inline bool setContains ( unsigned set, TokenKind::Enum tok )
{
return (set & (1 << tok)) != 0;
}
static inline unsigned setAdd ( unsigned set, TokenKind::Enum tok )
{
return set | (1 << tok);
}
SyntaxReader::SyntaxReader ( Lexer & lex, const Keywords & kw )
: DAT_EOF( new Syntax(SyntaxKind::DEOF, SourceCoords(NULL,0,0)) ),
DAT_COM( new Syntax(SyntaxKind::COMMENT, SourceCoords(NULL,0,0)) ),
m_lex( lex ),
m_kw( kw )
{
assert( &m_kw.symbolTable == &m_lex.symbolTable() );
next();
}
void SyntaxReader::error ( const gc_char * msg, ... )
{
std::va_list ap;
va_start( ap, msg );
m_lex.errorReporter().error( m_tok.coords(), vformatGCStr( msg, ap ) );
va_end( ap );
}
Syntax * SyntaxReader::parseDatum ()
{
return readSkipDatCom( setAdd(0, TokenKind::EOFTOK) );
}
Syntax * SyntaxReader::readSkipDatCom ( unsigned termSet )
{
// Ignore DATUM_COMMENT-s
Syntax * res;
while ( (res = read(termSet)) == DAT_COM)
{}
return res;
}
Syntax * SyntaxReader::read ( unsigned termSet )
{
bool inError = false;
for(;;)
{
Syntax * res;
switch (m_tok.kind())
{
case TokenKind::EOFTOK: return DAT_EOF;
case TokenKind::BOOL: res = new SyntaxValue( SyntaxKind::BOOL, m_tok.coords(), m_tok.vbool() ); next(); return res;
case TokenKind::INTEGER: res = new SyntaxValue( SyntaxKind::INTEGER, m_tok.coords(), m_tok.integer() ); next(); return res;
case TokenKind::REAL: res = new SyntaxValue( SyntaxKind::REAL, m_tok.coords(), m_tok.real() ); next(); return res;
case TokenKind::STR: res = new SyntaxValue( SyntaxKind::STR, m_tok.coords(), m_tok.string() ); next(); return res;
case TokenKind::SYMBOL: res = new SyntaxSymbol( m_tok.coords(), m_tok.symbol() ); next(); return res;
case TokenKind::LPAR:
{ SourceCoords coords=m_tok.coords(); next(); return list( coords, TokenKind::RPAR, termSet ); }
case TokenKind::LSQUARE:
{ SourceCoords coords=m_tok.coords(); next(); return list( coords, TokenKind::RSQUARE, termSet ); }
case TokenKind::HASH_LPAR:
{ SourceCoords coords=m_tok.coords(); next(); return vector( coords, TokenKind::RPAR, termSet ); }
case TokenKind::APOSTR: return abbrev( m_kw.sym_quote, termSet );
case TokenKind::ACCENT: return abbrev( m_kw.sym_quasiquote, termSet );
case TokenKind::COMMA: return abbrev( m_kw.sym_unquote, termSet );
case TokenKind::COMMA_AT: return abbrev( m_kw.sym_unquote_splicing, termSet );
case TokenKind::HASH_APOSTR: return abbrev( m_kw.sym_syntax, termSet );
case TokenKind::HASH_ACCENT: return abbrev( m_kw.sym_quasisyntax, termSet );
case TokenKind::HASH_COMMA: return abbrev( m_kw.sym_unsyntax, termSet );
case TokenKind::HASH_COMMA_AT: return abbrev( m_kw.sym_unsyntax_splicing, termSet );
case TokenKind::DATUM_COMMENT:
next();
read( termSet ); // Ignore the next datum
return DAT_COM;
case TokenKind::NESTED_COMMENT_END:
case TokenKind::NESTED_COMMENT_START:
assert(false);
case TokenKind::DOT:
case TokenKind::RPAR:
case TokenKind::RSQUARE:
case TokenKind::NONE:
// Skip invalid tokens, reporting only the first one
if (!inError)
{
error( "'%s' isn't allowed here", TokenKind::repr(m_tok.kind()) );
inError = true;
}
if (setContains(termSet,m_tok.kind()))
return new SyntaxNil(m_tok.coords());
next();
break;
}
}
}
SyntaxPair * SyntaxReader::list ( const SourceCoords & coords, TokenKind::Enum terminator, unsigned termSet )
{
ListBuilder lb;
termSet = setAdd(termSet,terminator);
unsigned carTermSet = setAdd(termSet, TokenKind::DOT);
lb << coords;
for(;;)
{
Syntax * car;
// Check for end of list. It is complicated by having to skip DATUM_COMMENT-s
do
{
if (m_tok.kind() == terminator)
{
lb << m_tok.coords();
next();
return lb.toList();
}
}
while ( (car = read( carTermSet )) == DAT_COM);
if (car == DAT_EOF)
{
error( "Unterminated list" );
return lb.toList();
}
lb << car;
if (m_tok.kind() == TokenKind::DOT)
{
Syntax * cdr;
next();
if ( (cdr = readSkipDatCom(termSet)) == DAT_EOF)
{
error( "Unterminated list" );
return lb.toList();
}
if (m_tok.kind() == terminator)
next();
else
{
error( "Expected %s", TokenKind::repr(terminator) );
// skip until terminator
assert( setContains(termSet, TokenKind::EOFTOK) ); // all sets should include EOF
for(;;)
{
if (m_tok.kind() == terminator)
{
next();
break;
}
if (setContains(termSet, m_tok.kind()))
break;
next();
}
}
return lb.toList( cdr );
}
}
}
SyntaxVector * SyntaxReader::vector ( const SourceCoords & coords, TokenKind::Enum terminator, unsigned termSet )
{
Syntax ** vec = NULL;
unsigned count = 0, size = 0;
termSet = setAdd(termSet,terminator);
while (m_tok.kind() != terminator)
{
Syntax * elem;
if ( (elem = read( termSet )) == DAT_COM) // skip DATUM_COMMENT-s
continue;
if (elem == DAT_EOF)
{
error( "Unterminated vector" );
return new SyntaxVector( coords, NULL, 0 ); // Return an empty vector just for error recovery
}
if (!vec)
{
vec = new (GC) Syntax*[4];
size = 4;
}
else if (count == size)
{
Syntax ** newVec = new (GC) Syntax*[size*2];
std::memcpy( newVec, vec, sizeof(vec[0])*size );
vec = newVec;
size *= 2;
}
vec[count++] = elem;
}
next(); // skip the closing parren
if (!vec)
return new SyntaxVector( coords, NULL, 0 );
else if (count*4 >= size*3) // If at least 75% full
return new SyntaxVector( coords, vec, count );
else
{
// Allocate an exact-sized vector
Syntax ** newVec = new (GC) Syntax*[count];
std::memcpy( newVec, vec, sizeof(vec[0])*count );
return new SyntaxVector( coords, newVec, count );
}
}
SyntaxPair * SyntaxReader::abbrev ( Symbol * sym, unsigned termSet )
{
SyntaxValue * symdat = new SyntaxValue( SyntaxKind::SYMBOL, m_tok.coords(), sym );
next();
Syntax * datum;
if ( (datum = readSkipDatCom( termSet )) == DAT_EOF)
error( "Unterminated abbreviation" );
return
new SyntaxPair( symdat->coords, symdat, new SyntaxPair( datum->coords, datum, new SyntaxNil( datum->coords ) ) );
}
| 29.192157 | 127 | 0.626411 | [
"vector"
] |
a8cbd49e35e43926aa1737564e44eccb326d8d83 | 1,401 | cpp | C++ | 42.Trapping_Rain_Water.cpp | arpit456jain/LeetCode-Solutions-Cpp | 080a5a7aa2bbc53e422d000e42c501f74ddd47e7 | [
"MIT"
] | 1 | 2021-08-01T05:08:29.000Z | 2021-08-01T05:08:29.000Z | 42.Trapping_Rain_Water.cpp | arpit456jain/LeetCode-Solutions | 080a5a7aa2bbc53e422d000e42c501f74ddd47e7 | [
"MIT"
] | null | null | null | 42.Trapping_Rain_Water.cpp | arpit456jain/LeetCode-Solutions | 080a5a7aa2bbc53e422d000e42c501f74ddd47e7 | [
"MIT"
] | null | null | null | class Solution {
public:
int optimizeApproch(vector<int>& arr, int n)
{
// Create two arrays left and right of size n. create a variable max_ = INT_MIN.
int max1 = arr[0];
int prefixMax[n];
int prefixMin[n];
// Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_
for (int i = 0; i < n; i++)
{
// O(n)
max1 = max(max1, arr[i]);
prefixMax[i] = max1;
}
max1 = arr[n - 1];
// Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_
for (int i = n - 1; i >= 0; i--)
{
// O(n)
max1 = max(max1, arr[i]);
prefixMin[i] = max1;
}
int total_water = 0;
// The amount of water that will be stored in this column is min(a,b) – array[i],(where a = left[i] and b = right[i]) add this value to total amount of water stored
for (int i = 0; i < n; i++)
{
total_water += min(prefixMax[i],prefixMin[i]) - arr[i];
}
// return the total amount of water stored.
return total_water;
}
int trap(vector<int>& arr) {
int n = arr.size();
int ans = optimizeApproch(arr, n); // T.C : O(n)
return ans;
}
}; | 36.868421 | 172 | 0.51606 | [
"vector"
] |
a8cca3b960bf6ee6f791c4f8553f43a9eda12802 | 5,212 | cpp | C++ | src/tests/class_tests/openms/source/BasicProteinInferenceAlgorithm_test.cpp | Arraxx/OpenMS | ce6c8d6427ca89360523ee97f1110bb80d8b4a89 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | src/tests/class_tests/openms/source/BasicProteinInferenceAlgorithm_test.cpp | Arraxx/OpenMS | ce6c8d6427ca89360523ee97f1110bb80d8b4a89 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | 1 | 2021-09-24T20:05:16.000Z | 2021-09-24T20:05:16.000Z | src/tests/class_tests/openms/source/BasicProteinInferenceAlgorithm_test.cpp | Arraxx/OpenMS | ce6c8d6427ca89360523ee97f1110bb80d8b4a89 | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | 1 | 2021-09-18T07:00:02.000Z | 2021-09-18T07:00:02.000Z | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/ANALYSIS/ID/BasicProteinInferenceAlgorithm.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/test_config.h>
using namespace OpenMS;
using namespace std;
START_TEST(BasicProteinInferenceAlgorithm, "$Id$")
START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID)
{
vector<ProteinIdentification> prots;
vector<PeptideIdentification> peps;
IdXMLFile idf;
idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps);
BasicProteinInferenceAlgorithm bpia;
Param p = bpia.getParameters();
p.setValue("min_peptides_per_protein", 0);
bpia.setParameters(p);
bpia.run(peps, prots);
TEST_EQUAL(prots[0].getHits()[0].getScore(), 0.6)
TEST_EQUAL(prots[0].getHits()[1].getScore(), 0.6)
TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity())
TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.8)
TEST_EQUAL(prots[0].getHits()[4].getScore(), 0.6)
TEST_EQUAL(prots[0].getHits()[5].getScore(), 0.9)
TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 1)
TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 1)
TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0)
TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 2)
TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 1)
TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1)
}
END_SECTION
START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID without shared peps)
{
vector<ProteinIdentification> prots;
vector<PeptideIdentification> peps;
IdXMLFile idf;
idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps);
BasicProteinInferenceAlgorithm bpia;
Param p = bpia.getParameters();
p.setValue("use_shared_peptides","false");
p.setValue("min_peptides_per_protein", 0);
bpia.setParameters(p);
bpia.run(peps, prots);
TEST_EQUAL(prots[0].getHits()[0].getScore(), -std::numeric_limits<double>::infinity())
TEST_EQUAL(prots[0].getHits()[1].getScore(), -std::numeric_limits<double>::infinity())
TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity())
TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.8)
TEST_EQUAL(prots[0].getHits()[4].getScore(), -std::numeric_limits<double>::infinity())
TEST_EQUAL(prots[0].getHits()[5].getScore(), 0.9)
TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 0)
TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 0)
TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0)
TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 1)
TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 0)
TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1)
}
END_SECTION
END_TEST
| 51.60396 | 92 | 0.665196 | [
"vector"
] |
a8cedc977a0d063a3b23c7ba001df8ce5423913b | 3,233 | cpp | C++ | catboost/app/main.cpp | PallHaraldsson/catboost | f4b86aae0acb853f0216081518d490e52722ad88 | [
"Apache-2.0"
] | null | null | null | catboost/app/main.cpp | PallHaraldsson/catboost | f4b86aae0acb853f0216081518d490e52722ad88 | [
"Apache-2.0"
] | null | null | null | catboost/app/main.cpp | PallHaraldsson/catboost | f4b86aae0acb853f0216081518d490e52722ad88 | [
"Apache-2.0"
] | null | null | null | #include "modes.h"
#include <catboost/private/libs/app_helpers/mode_calc_helpers.h>
#include <catboost/private/libs/app_helpers/mode_fstr_helpers.h>
#include <catboost/libs/helpers/exception.h>
#include <catboost/private/libs/init/init_reg.h>
#include <catboost/libs/logging/logging.h>
#include <library/getopt/small/modchooser.h>
#include <library/svnversion/svnversion.h>
#include <util/generic/ptr.h>
#include <util/stream/output.h>
#include <cstdlib>
static int mode_calc(int argc, const char** argv) {
THolder<NCB::IModeCalcImplementation> modeCalcImplementaion;
if (NCB::TModeCalcImplementationFactory::Has(NCB::EImplementationType::YandexSpecific)) {
modeCalcImplementaion = NCB::TModeCalcImplementationFactory::Construct(NCB::EImplementationType::YandexSpecific);
} else {
CB_ENSURE(NCB::TModeCalcImplementationFactory::Has(NCB::EImplementationType::OpenSource),
"Mode calc implementation factory should have open source implementation");
modeCalcImplementaion = NCB::TModeCalcImplementationFactory::Construct(NCB::EImplementationType::OpenSource);
}
return modeCalcImplementaion->mode_calc(argc, argv);
}
static int mode_fstr(int argc, const char** argv) {
THolder<NCB::IModeFstrImplementation> modeFstrImplementaion;
if (NCB::TModeFstrImplementationFactory::Has(NCB::EImplementationType::YandexSpecific)) {
modeFstrImplementaion = NCB::TModeFstrImplementationFactory::Construct(NCB::EImplementationType::YandexSpecific);
} else {
CB_ENSURE(NCB::TModeFstrImplementationFactory::Has(NCB::EImplementationType::OpenSource),
"Mode fstr implementation factory should have open source implementation");
modeFstrImplementaion = NCB::TModeFstrImplementationFactory::Construct(NCB::EImplementationType::OpenSource);
}
return modeFstrImplementaion->mode_fstr(argc, argv);
}
int main(int argc, const char* argv[]) {
try {
NCB::TCmdLineInit::Do(argc, argv);
TSetLoggingVerbose inThisScope;
TModChooser modChooser;
modChooser.AddMode("fit", mode_fit, "train model");
modChooser.AddMode("calc", mode_calc, "evaluate model predictions");
modChooser.AddMode("fstr", mode_fstr, "evaluate feature importances");
modChooser.AddMode("ostr", mode_ostr, "evaluate object importances");
modChooser.AddMode("eval-metrics", mode_eval_metrics, "evaluate metrics for model");
modChooser.AddMode("eval-feature", mode_eval_feature, "evaluate features");
modChooser.AddMode("metadata", mode_metadata, "get/set/dump metainfo fields from model");
modChooser.AddMode("model-sum", mode_model_sum, "sum model files");
modChooser.AddMode("run-worker", mode_run_worker, "run worker");
modChooser.AddMode("roc", mode_roc, "evaluate data for roc curve");
modChooser.AddMode("model-based-eval", mode_model_based_eval, "model-based eval");
modChooser.DisableSvnRevisionOption();
modChooser.SetVersionHandler(PrintProgramSvnVersion);
return modChooser.Run(argc, argv);
} catch (...) {
Cerr << "AN EXCEPTION OCCURRED. " << CurrentExceptionMessage() << Endl;
return EXIT_FAILURE;
}
}
| 48.984848 | 121 | 0.732756 | [
"object",
"model"
] |
a8d33ec59fb1344abb327b96f1e8b2906aa39c39 | 423 | cpp | C++ | solutions/1491. Average Salary Excluding the Minimum and Maximum Salary.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | 1 | 2020-09-27T17:36:58.000Z | 2020-09-27T17:36:58.000Z | solutions/1491. Average Salary Excluding the Minimum and Maximum Salary.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | null | null | null | solutions/1491. Average Salary Excluding the Minimum and Maximum Salary.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | 1 | 2020-09-21T15:16:24.000Z | 2020-09-21T15:16:24.000Z | class Solution {
public:
double average(vector<int>& salary) {
int least = INT_MAX;
int most = INT_MIN;
double total = 0;
for(int i=0;i<salary.size();i++){
if(salary[i]<least) least = salary[i];
if(salary[i]>most) most = salary[i];
total+=salary[i];
}
return (total-(most+least))/(salary.size()-2);
}
};
| 23.5 | 54 | 0.475177 | [
"vector"
] |
a8d7ee6cb8b3ab8521a4ffbe07b64cd822959c60 | 18,019 | cpp | C++ | src/crypto/hash/sigma/shavite3_256/shavite3_256_opt.cpp | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | 158 | 2016-01-08T10:38:37.000Z | 2022-02-01T06:28:05.000Z | src/crypto/hash/sigma/shavite3_256/shavite3_256_opt.cpp | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | 196 | 2015-11-19T10:59:24.000Z | 2021-10-07T14:52:13.000Z | src/crypto/hash/sigma/shavite3_256/shavite3_256_opt.cpp | Gulden-Coin/gulden-official | fd9b07bb17a87bfbaab7b9c9a3415279fcb3c508 | [
"MIT"
] | 71 | 2016-06-25T23:29:04.000Z | 2022-03-14T10:57:19.000Z | // File originates from the supercop project
// Authors: Eli Biham and Orr Dunkelman
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2019 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#include "shavite3_256_opt.h"
#ifndef USE_HARDWARE_AES
#define _mm_aesenc_si128 _mm_aesenc_si128_sw
#endif
#ifdef SHAVITE3_256_OPT_IMPL
#include "compat.h"
#include "assert.h"
#include <memory.h>
#define T8(x) ((x) & 0xff)
/// Encrypts the plaintext pt[] using the key message[], and counter[], to produce the ciphertext ct[]
#define SHAVITE_MIXING_256_OPT \
x11 = x15; \
x10 = x14; \
x9 = x13; \
x8 = x12; \
\
x6 = x11; \
x6 = _mm_srli_si128(x6, 4); \
x8 = _mm_xor_si128(x8, x6); \
x6 = x8; \
x6 = _mm_slli_si128(x6, 12);\
x8 = _mm_xor_si128(x8, x6); \
\
x7 = x8; \
x7 = _mm_srli_si128(x7, 4);\
x9 = _mm_xor_si128(x9, x7); \
x7 = x9; \
x7 = _mm_slli_si128(x7, 12); \
x9 = _mm_xor_si128(x9, x7); \
\
x6 = x9; \
x6 = _mm_srli_si128(x6, 4); \
x10 = _mm_xor_si128(x10, x6);\
x6 = x10; \
x6 = _mm_slli_si128(x6, 12);\
x10 = _mm_xor_si128(x10, x6);\
\
x7 = x10; \
x7 = _mm_srli_si128(x7, 4); \
x11 = _mm_xor_si128(x11, x7);\
x7 = x11; \
x7 = _mm_slli_si128(x7, 12);\
x11 = _mm_xor_si128(x11, x7);
// encryption + Davies-Meyer transform
void shavite3_256_opt_Compress256(const unsigned char* message_block, unsigned char* chaining_value, uint64_t counter)
{
__attribute__ ((aligned (16))) static const unsigned int SHAVITE_REVERSE[4] = {0x07060504, 0x0b0a0908, 0x0f0e0d0c, 0x03020100 };
__attribute__ ((aligned (16))) static const unsigned int SHAVITE256_XOR2[4] = {0x0, 0xFFFFFFFF, 0x0, 0x0};
__attribute__ ((aligned (16))) static const unsigned int SHAVITE256_XOR3[4] = {0x0, 0x0, 0xFFFFFFFF, 0x0};
__attribute__ ((aligned (16))) static const unsigned int SHAVITE256_XOR4[4] = {0x0, 0x0, 0x0, 0xFFFFFFFF};
__attribute__ ((aligned (16))) const unsigned int SHAVITE_CNTS[4] = {(unsigned int)(counter & 0xFFFFFFFFULL),(unsigned int)(counter>>32),0,0};
__m128i x0;
__m128i x1;
__m128i x2;
__m128i x3;
__m128i x4;
__m128i x6;
__m128i x7;
__m128i x8;
__m128i x9;
__m128i x10;
__m128i x11;
__m128i x12;
__m128i x13;
__m128i x14;
__m128i x15;
// (L,R) = (xmm0,xmm1)
const __m128i ptxt1 = _mm_loadu_si128((const __m128i*)chaining_value);
const __m128i ptxt2 = _mm_loadu_si128((const __m128i*)(chaining_value+16));
x0 = ptxt1;
x1 = ptxt2;
x3 = _mm_loadu_si128((__m128i*)SHAVITE_CNTS);
x4 = _mm_loadu_si128((__m128i*)SHAVITE256_XOR2);
x2 = _mm_setzero_si128();
// init key schedule
x8 = _mm_loadu_si128((__m128i*)message_block);
x9 = _mm_loadu_si128((__m128i*)(((unsigned int*)message_block)+4));
x10 = _mm_loadu_si128((__m128i*)(((unsigned int*)message_block)+8));
x11 = _mm_loadu_si128((__m128i*)(((unsigned int*)message_block)+12));
// xmm8..xmm11 = rk[0..15]
// start key schedule
x12 = x8;
x13 = x9;
x14 = x10;
x15 = x11;
const __m128i xtemp = _mm_loadu_si128((__m128i*)SHAVITE_REVERSE);
x12 = _mm_shuffle_epi8(x12, xtemp);
x13 = _mm_shuffle_epi8(x13, xtemp);
x14 = _mm_shuffle_epi8(x14, xtemp);
x15 = _mm_shuffle_epi8(x15, xtemp);
x12 = _mm_aesenc_si128(x12, x2);
x13 = _mm_aesenc_si128(x13, x2);
x14 = _mm_aesenc_si128(x14, x2);
x15 = _mm_aesenc_si128(x15, x2);
x12 = _mm_xor_si128(x12, x3);
x12 = _mm_xor_si128(x12, x4);
x4 = _mm_loadu_si128((__m128i*)SHAVITE256_XOR3);
x12 = _mm_xor_si128(x12, x11);
x13 = _mm_xor_si128(x13, x12);
x14 = _mm_xor_si128(x14, x13);
x15 = _mm_xor_si128(x15, x14);
// xmm12..xmm15 = rk[16..31]
// F3 - first round
x6 = x8;
x8 = _mm_xor_si128(x8, x1);
x8 = _mm_aesenc_si128(x8, x9);
x8 = _mm_aesenc_si128(x8, x10);
x8 = _mm_aesenc_si128(x8, x2);
x0 = _mm_xor_si128(x0, x8);
x8 = x6;
// F3 - second round
x6 = x11;
x11 = _mm_xor_si128(x11, x0);
x11 = _mm_aesenc_si128(x11, x12);
x11 = _mm_aesenc_si128(x11, x13);
x11 = _mm_aesenc_si128(x11, x2);
x1 = _mm_xor_si128(x1, x11);
x11 = x6;
// key schedule
SHAVITE_MIXING_256_OPT
// xmm8..xmm11 - rk[32..47]
// F3 - third round
x6 = x14;
x14 = _mm_xor_si128(x14, x1);
x14 = _mm_aesenc_si128(x14, x15);
x14 = _mm_aesenc_si128(x14, x8);
x14 = _mm_aesenc_si128(x14, x2);
x0 = _mm_xor_si128(x0, x14);
x14 = x6;
// key schedule
x3 = _mm_shuffle_epi32(x3, 135);
x12 = x8;
x13 = x9;
x14 = x10;
x15 = x11;
x12 = _mm_shuffle_epi8(x12, xtemp);
x13 = _mm_shuffle_epi8(x13, xtemp);
x14 = _mm_shuffle_epi8(x14, xtemp);
x15 = _mm_shuffle_epi8(x15, xtemp);
x12 = _mm_aesenc_si128(x12, x2);
x13 = _mm_aesenc_si128(x13, x2);
x14 = _mm_aesenc_si128(x14, x2);
x15 = _mm_aesenc_si128(x15, x2);
x12 = _mm_xor_si128(x12, x11);
x14 = _mm_xor_si128(x14, x3);
x14 = _mm_xor_si128(x14, x4);
x4 = _mm_loadu_si128((__m128i*)SHAVITE256_XOR4);
x13 = _mm_xor_si128(x13, x12);
x14 = _mm_xor_si128(x14, x13);
x15 = _mm_xor_si128(x15, x14);
// xmm12..xmm15 - rk[48..63]
// F3 - fourth round
x6 = x9;
x9 = _mm_xor_si128(x9, x0);
x9 = _mm_aesenc_si128(x9, x10);
x9 = _mm_aesenc_si128(x9, x11);
x9 = _mm_aesenc_si128(x9, x2);
x1 = _mm_xor_si128(x1, x9);
x9 = x6;
// key schedule
SHAVITE_MIXING_256_OPT
// xmm8..xmm11 = rk[64..79]
// F3 - fifth round
x6 = x12;
x12 = _mm_xor_si128(x12, x1);
x12 = _mm_aesenc_si128(x12, x13);
x12 = _mm_aesenc_si128(x12, x14);
x12 = _mm_aesenc_si128(x12, x2);
x0 = _mm_xor_si128(x0, x12);
x12 = x6;
// F3 - sixth round
x6 = x15;
x15 = _mm_xor_si128(x15, x0);
x15 = _mm_aesenc_si128(x15, x8);
x15 = _mm_aesenc_si128(x15, x9);
x15 = _mm_aesenc_si128(x15, x2);
x1 = _mm_xor_si128(x1, x15);
x15 = x6;
// key schedule
x3 = _mm_shuffle_epi32(x3, 147);
x12 = x8;
x13 = x9;
x14 = x10;
x15 = x11;
x12 = _mm_shuffle_epi8(x12, xtemp);
x13 = _mm_shuffle_epi8(x13, xtemp);
x14 = _mm_shuffle_epi8(x14, xtemp);
x15 = _mm_shuffle_epi8(x15, xtemp);
x12 = _mm_aesenc_si128(x12, x2);
x13 = _mm_aesenc_si128(x13, x2);
x14 = _mm_aesenc_si128(x14, x2);
x15 = _mm_aesenc_si128(x15, x2);
x12 = _mm_xor_si128(x12, x11);
x13 = _mm_xor_si128(x13, x3);
x13 = _mm_xor_si128(x13, x4);
x13 = _mm_xor_si128(x13, x12);
x14 = _mm_xor_si128(x14, x13);
x15 = _mm_xor_si128(x15, x14);
// xmm12..xmm15 = rk[80..95]
// F3 - seventh round
x6 = x10;
x10 = _mm_xor_si128(x10, x1);
x10 = _mm_aesenc_si128(x10, x11);
x10 = _mm_aesenc_si128(x10, x12);
x10 = _mm_aesenc_si128(x10, x2);
x0 = _mm_xor_si128(x0, x10);
x10 = x6;
// key schedule
SHAVITE_MIXING_256_OPT
// xmm8..xmm11 = rk[96..111]
// F3 - eigth round
x6 = x13;
x13 = _mm_xor_si128(x13, x0);
x13 = _mm_aesenc_si128(x13, x14);
x13 = _mm_aesenc_si128(x13, x15);
x13 = _mm_aesenc_si128(x13, x2);
x1 = _mm_xor_si128(x1, x13);
x13 = x6;
// key schedule
x3 = _mm_shuffle_epi32(x3, 135);
x12 = x8;
x13 = x9;
x14 = x10;
x15 = x11;
x12 = _mm_shuffle_epi8(x12, xtemp);
x13 = _mm_shuffle_epi8(x13, xtemp);
x14 = _mm_shuffle_epi8(x14, xtemp);
x15 = _mm_shuffle_epi8(x15, xtemp);
x12 = _mm_aesenc_si128(x12, x2);
x13 = _mm_aesenc_si128(x13, x2);
x14 = _mm_aesenc_si128(x14, x2);
x15 = _mm_aesenc_si128(x15, x2);
x12 = _mm_xor_si128(x12, x11);
x15 = _mm_xor_si128(x15, x3);
x15 = _mm_xor_si128(x15, x4);
x13 = _mm_xor_si128(x13, x12);
x14 = _mm_xor_si128(x14, x13);
x15 = _mm_xor_si128(x15, x14);
// xmm12..xmm15 = rk[112..127]
// F3 - ninth round
x6 = x8;
x8 = _mm_xor_si128(x8, x1);
x8 = _mm_aesenc_si128(x8, x9);
x8 = _mm_aesenc_si128(x8, x10);
x8 = _mm_aesenc_si128(x8, x2);
x0 = _mm_xor_si128(x0, x8);
x8 = x6;
// F3 - tenth round
x6 = x11;
x11 = _mm_xor_si128(x11, x0);
x11 = _mm_aesenc_si128(x11, x12);
x11 = _mm_aesenc_si128(x11, x13);
x11 = _mm_aesenc_si128(x11, x2);
x1 = _mm_xor_si128(x1, x11);
x11 = x6;
// key schedule
SHAVITE_MIXING_256_OPT
// xmm8..xmm11 = rk[128..143]
// F3 - eleventh round
x6 = x14;
x14 = _mm_xor_si128(x14, x1);
x14 = _mm_aesenc_si128(x14, x15);
x14 = _mm_aesenc_si128(x14, x8);
x14 = _mm_aesenc_si128(x14, x2);
x0 = _mm_xor_si128(x0, x14);
x14 = x6;
// F3 - twelfth round
x6 = x9;
x9 = _mm_xor_si128(x9, x0);
x9 = _mm_aesenc_si128(x9, x10);
x9 = _mm_aesenc_si128(x9, x11);
x9 = _mm_aesenc_si128(x9, x2);
x1 = _mm_xor_si128(x1, x9);
x9 = x6;
// feedforward
x0 = _mm_xor_si128(x0, ptxt1);
x1 = _mm_xor_si128(x1, ptxt2);
_mm_storeu_si128((__m128i *)chaining_value, x0);
_mm_storeu_si128((__m128i *)(chaining_value + 16), x1);
return;
}
#define U8TO16_LITTLE(c) (((uint16_t)T8(*((uint8_t*)(c)))) | ((uint16_t)T8(*(((uint8_t*)(c)) + 1)) << 8))
// Make sure that the local variable names do not collide with variables of the calling code (i.e., those used in c, v)
#define U16TO8_LITTLE(c, v) do { \
uint16_t tmp_portable_h_x = (v); \
uint8_t *tmp_portable_h_d = (c); \
tmp_portable_h_d[0] = T8(tmp_portable_h_x); \
tmp_portable_h_d[1] = T8(tmp_portable_h_x >> 8); \
} while (0)
#define U8TO32_LITTLE(c) (((uint32_t)T8(*((uint8_t*)(c)))) | ((uint32_t)T8(*(((uint8_t*)(c)) + 1)) << 8) | ((uint32_t)T8(*(((uint8_t*)(c)) + 2)) << 16) | ((uint32_t)T8(*(((uint8_t*)(c)) + 3)) << 24))
// Make sure that the local variable names do not collide with variables of the calling code (i.e., those used in c, v)
#define U32TO8_LITTLE(c, v) do { \
uint32_t tmp_portable_h_x = (v); \
uint8_t *tmp_portable_h_d = (c); \
tmp_portable_h_d[0] = T8(tmp_portable_h_x); \
tmp_portable_h_d[1] = T8(tmp_portable_h_x >> 8); \
tmp_portable_h_d[2] = T8(tmp_portable_h_x >> 16); \
tmp_portable_h_d[3] = T8(tmp_portable_h_x >> 24); \
} while (0)
// Make sure that the local variable names do not collide with variables of the calling code (i.e., those used in c, v)
#define U64TO8_LITTLE(c, v) do { \
uint64_t tmp_portable_h_x = (v); \
uint8_t *tmp_portable_h_d = (c); \
tmp_portable_h_d[0] = T8(tmp_portable_h_x); \
tmp_portable_h_d[1] = T8(tmp_portable_h_x >> 8); \
tmp_portable_h_d[2] = T8(tmp_portable_h_x >> 16); \
tmp_portable_h_d[3] = T8(tmp_portable_h_x >> 24); \
tmp_portable_h_d[4] = T8(tmp_portable_h_x >> 32); \
tmp_portable_h_d[5] = T8(tmp_portable_h_x >> 40); \
tmp_portable_h_d[6] = T8(tmp_portable_h_x >> 48); \
tmp_portable_h_d[7] = T8(tmp_portable_h_x >> 56); \
} while (0)
// Initialization of the internal state of the hash function
bool shavite3_256_opt_Init ( shavite3_256_opt_hashState* state)
{
// Initialization of the counter of number of bits that were hashed so far
state->bitcount = 0;
// Store the requested digest size
state->DigestSize = 256;
// Initialize the message block to empty
memset(state->buffer,0,64);
// Set the input to the compression function to all zero
memset(state->chaining_value,0,32);
// Compute MIV_{256}
shavite3_256_opt_Compress256(state->buffer,state->chaining_value,0x0ULL);
// Set the message block to the size of the requested digest size
U16TO8_LITTLE(state->buffer,256);
// Compute IV_m
shavite3_256_opt_Compress256(state->buffer,state->chaining_value,0x0ULL);
// Set the block size to be 512 bits (as required for C_{256})
state->BlockSize=512;
// Set the message block to zero
memset(state->buffer,0,64);
return true;
}
// Compressing the input data, and updating the internal state
bool shavite3_256_opt_Update ( shavite3_256_opt_hashState* state, const unsigned char* data, uint64_t dataLenBytes)
{
// p is a pointer to the current location inside data that we need to process (i.e., the first byte of the data which was not used as an input to the compression function
uint8_t* p = (uint8_t*)data;
// len is the size of the data that was not process yet in bytes
int len = dataLenBytes;
// BlockSizeB is the size of the message block of the compression function
int BlockSizeB = (state->BlockSize/8);
// bufcnt stores the number of bytes that are were "sent" to the compression function, but were not yet processed, as a full block has not been obtained
int bufcnt= (state->bitcount>>3)%BlockSizeB;
// local_bitcount contains the number of bits actually hashed so far
uint64_t SHAVITE_CNT;
// load the number of bits hashed so far into SHAVITE_CNT
SHAVITE_CNT=state->bitcount;
// mark that we processed more bits
state->bitcount += dataLenBytes*8;
// Check if we have enough data to call the compression function
// If not, just copy the input to the buffer of the message block
if (bufcnt + len < BlockSizeB)
{
memcpy(&state->buffer[bufcnt], p, len);
return true;
}
// There is enough data to start calling the compression function.
// We first check whether there is data remaining from previous calls
if (bufcnt>0)
{
// Copy from the input the required number of bytes to fill a block
memcpy(&state->buffer[bufcnt], p, BlockSizeB-bufcnt);
// Update the location of the first byte that was not processed
p += BlockSizeB-bufcnt;
// Update the remaining number of bytes to process
len -= BlockSizeB-bufcnt;
// Update the number of bits hashed so far (locally)
SHAVITE_CNT+=8*(BlockSizeB-bufcnt);
// Call the compression function to process the current block
shavite3_256_opt_Compress256(state->buffer, state->chaining_value, SHAVITE_CNT);
}
// At this point, the only remaining data is from the message block call the compression function as many times as possible, and store the remaining bytes in the buffer
// Each step of the loop compresses BlockSizeB bytes
for( ; len>=BlockSizeB; len-=BlockSizeB, p+=BlockSizeB)
{
// Update the number of bits hashed so far (locally)
SHAVITE_CNT+=8*BlockSizeB;
// Call the compression function to process the current block
shavite3_256_opt_Compress256(p, state->chaining_value, SHAVITE_CNT);
}
// If there are still unprocessed bytes, store them locally and wait for more
if (len>0)
{
memcpy(state->buffer, p, len);
}
return true;
}
// Performing the padding scheme, and dealing with any remaining bits
bool shavite3_256_opt_Final ( shavite3_256_opt_hashState *state, unsigned char *hashval)
{
// Stores inputs (message blocks) to the compression function
uint8_t block[64];
// Stores results (chaining value) of the compression function
uint8_t result[32];
// BlockSizeB is the size of the message block of the compression function
int BlockSizeB = (state->BlockSize/8);
// bufcnt stores the number of bytes that are were "sent" to the compression function, but were not yet processed, as a full block has not been obtained
int bufcnt= ((uint32_t)state->bitcount>>3)%BlockSizeB;
int i;
// Copy the current chaining value into result (as a temporary step)
memcpy(result, state->chaining_value, 32);
// Initialize block as the message block to compress with the bytes that were not processed yet
memset(block, 0, BlockSizeB);
memcpy(block, state->buffer, bufcnt);
// Pad the buffer with the byte which contains the fraction of bytes from and a bit equal to 1
block[bufcnt] = (state->partial_byte & ~((0x80 >> (state->bitcount&7))-1)) | (0x80 >> (state->bitcount&7));
// Compress the last block (according to the digest size)
// An additional message block is required if there are less than 10 more bytes for message length and digest length encoding
if (bufcnt>=BlockSizeB-10)
{
// Compress the current block
shavite3_256_opt_Compress256(block,result,state->bitcount);
// Generate the full padding block
memset(block, 0, BlockSizeB);
U64TO8_LITTLE(block+BlockSizeB-10, state->bitcount);
U16TO8_LITTLE(block+BlockSizeB-2, state->DigestSize);
// Compress the full padding block
shavite3_256_opt_Compress256(block,result,0x0UL);
}
else
{
// Pad the number of bits hashed so far and the digest size to the last message block and compress it
U64TO8_LITTLE(block+BlockSizeB-10, state->bitcount);
U16TO8_LITTLE(block+BlockSizeB-2, state->DigestSize);
if ((state->bitcount&(state->BlockSize-1))==0)
{
shavite3_256_opt_Compress256(block,result, 0ULL);
}
else
{
shavite3_256_opt_Compress256(block,result, state->bitcount);
}
}
// Copy the result into the supplied array of bytes.
for (i=0;i<(state->DigestSize+7)/8;i++)
{
hashval[i]=result[i];
}
// Treat cases where the digest size is not a multiple of a byte
if ((state->DigestSize)&7)
{
hashval[(state->DigestSize+7)/8] &= (0xFF<<(8-((state->DigestSize)%8)))&0xFF;
}
return true;
}
#endif
| 32.643116 | 200 | 0.633553 | [
"transform"
] |
a8d99b75a3cb50a5094033cf6548e9853b9a2a81 | 8,585 | hpp | C++ | dhcp6.hpp | niklata/ndhs | b63fe9456085257567a030eca32581af178e3af6 | [
"MIT"
] | 6 | 2015-02-16T15:40:28.000Z | 2019-08-11T01:31:18.000Z | dhcp6.hpp | niklata/ndhs | b63fe9456085257567a030eca32581af178e3af6 | [
"MIT"
] | 1 | 2015-12-25T18:14:02.000Z | 2015-12-26T03:52:54.000Z | dhcp6.hpp | niklata/ndhs | b63fe9456085257567a030eca32581af178e3af6 | [
"MIT"
] | null | null | null | // Copyright 2016-2022 Nicholas J. Kain <njkain at gmail dot com>
// SPDX-License-Identifier: MIT
#ifndef NK_NRAD6_DHCP6_HPP_
#define NK_NRAD6_DHCP6_HPP_
#include <string>
#include <stdint.h>
#include <iterator>
#include <nk/net/ip_address.hpp>
#include <nk/netbits.hpp>
#include <nk/sys/posix/handle.hpp>
#include "dhcp_state.hpp"
#include "radv6.hpp"
#include "sbufs.h"
enum class dhcp6_msgtype {
unknown = 0,
solicit = 1,
advertise = 2,
request = 3,
confirm = 4,
renew = 5,
rebind = 6,
reply = 7,
release = 8,
decline = 9,
reconfigure = 10,
information_request = 11,
relay_forward = 12,
relay_reply = 13,
};
// Packet header.
class dhcp6_header
{
public:
dhcp6_header() : type_(0), xid_{0, 0, 0} {}
dhcp6_header(const dhcp6_header &o) : type_(o.type_) {
memcpy(xid_, o.xid_, sizeof xid_);
}
dhcp6_header &operator=(const dhcp6_header &o) {
type_ = o.type_;
memcpy(xid_, o.xid_, sizeof xid_);
return *this;
}
dhcp6_msgtype msg_type() const {
if (type_ >= 1 && type_ <= 13)
return static_cast<dhcp6_msgtype>(type_);
return dhcp6_msgtype::unknown;
};
void msg_type(dhcp6_msgtype v) { type_ = static_cast<uint8_t>(v); }
static const std::size_t size = 4;
bool read(sbufs &rbuf)
{
if (rbuf.brem() < size) return false;
memcpy(&type_, rbuf.si, sizeof type_);
memcpy(&xid_, rbuf.si + 1, sizeof xid_);
rbuf.si += size;
return true;
}
bool write(sbufs &sbuf) const
{
if (sbuf.brem() < size) return false;
memcpy(sbuf.si, &type_, sizeof type_);
memcpy(sbuf.si + 1, &xid_, sizeof xid_);
sbuf.si += size;
return true;
}
private:
uint8_t type_;
char xid_[3];
};
// Option header.
class dhcp6_opt
{
public:
dhcp6_opt() { std::fill(data_, data_ + sizeof data_, 0); }
uint16_t type() const { return decode16be(data_); }
uint16_t length() const { return decode16be(data_ + 2); }
void type(uint16_t v) { encode16be(v, data_); }
void length(uint16_t v) { encode16be(v, data_ + 2); }
static const std::size_t size = 4;
bool read(sbufs &rbuf)
{
if (rbuf.brem() < size) return false;
memcpy(&data_, rbuf.si, sizeof data_);
rbuf.si += size;
return true;
}
bool write(sbufs &sbuf) const
{
if (sbuf.brem() < size) return false;
memcpy(sbuf.si, &data_, sizeof data_);
sbuf.si += size;
return true;
}
private:
uint8_t data_[4];
};
// Server Identifier Option
struct dhcp6_opt_serverid
{
dhcp6_opt_serverid(const char *s, size_t slen) : duid_string_(s), duid_len_(slen) {}
const char *duid_string_;
size_t duid_len_;
bool write(sbufs &sbuf) const
{
const auto size = dhcp6_opt::size + duid_len_;
if (sbuf.brem() < size) return false;
dhcp6_opt header;
header.type(2);
header.length(duid_len_);
if (!header.write(sbuf)) return false;
memcpy(sbuf.si, duid_string_, duid_len_);
sbuf.si += duid_len_;
return true;
}
};
struct d6_ia_addr {
nk::ip_address addr;
uint32_t prefer_lifetime;
uint32_t valid_lifetime;
static const std::size_t size = 24;
bool read(sbufs &rbuf)
{
if (rbuf.brem() < size) return false;
addr.from_v6bytes(rbuf.si);
prefer_lifetime = decode32be(rbuf.si + 16);
valid_lifetime = decode32be(rbuf.si + 20);
rbuf.si += size;
return true;
}
bool write(sbufs &sbuf) const
{
if (sbuf.brem() < size) return false;
addr.raw_v6bytes(sbuf.si);
encode32be(prefer_lifetime, sbuf.si + 16);
encode32be(valid_lifetime, sbuf.si + 20);
sbuf.si += size;
return true;
}
};
struct d6_ia {
uint32_t iaid;
uint32_t t1_seconds;
uint32_t t2_seconds;
std::vector<d6_ia_addr> ia_na_addrs;
static const std::size_t size = 12;
bool read(sbufs &rbuf)
{
if (rbuf.brem() < size) return false;
iaid = decode32be(rbuf.si);
t1_seconds = decode32be(rbuf.si + 4);
t2_seconds = decode32be(rbuf.si + 8);
rbuf.si += size;
return true;
}
bool write(sbufs &sbuf) const
{
if (sbuf.brem() < size) return false;
encode32be(iaid, sbuf.si);
encode32be(t1_seconds, sbuf.si + 4);
encode32be(t2_seconds, sbuf.si + 8);
sbuf.si += size;
return true;
}
};
struct d6_statuscode
{
enum class code {
success = 0,
unspecfail = 1,
noaddrsavail = 2,
nobinding = 3,
notonlink = 4,
usemulticast = 5,
};
d6_statuscode() : status_code(code::success) {}
explicit d6_statuscode(code c) : status_code(c) {}
code status_code;
static const std::size_t size = 2;
bool write(sbufs &sbuf) const
{
if (sbuf.brem() < size) return false;
encode16be(static_cast<uint16_t>(status_code), sbuf.si);
sbuf.si += size;
return true;
}
};
class D6Listener
{
public:
D6Listener() {}
D6Listener(const D6Listener &) = delete;
D6Listener &operator=(const D6Listener &) = delete;
[[nodiscard]] bool init(const std::string &ifname, uint8_t preference);
void process_input();
auto fd() const { return fd_(); }
auto& ifname() const { return ifname_; }
private:
using prev_opt_state = std::pair<int8_t, uint16_t>; // Type of parent opt and length left
struct d6msg_state
{
d6msg_state() : optreq_exists(false), optreq_dns(false), optreq_dns_search(false),
optreq_sntp(false), optreq_info_refresh_time(false), optreq_ntp(false),
use_rapid_commit(false) {}
dhcp6_header header;
std::string fqdn_;
std::string client_duid;
std::vector<uint8_t> client_duid_blob;
std::vector<uint8_t> server_duid_blob;
std::vector<d6_ia> ias;
std::vector<prev_opt_state> prev_opt;
uint16_t elapsed_time;
bool optreq_exists:1;
bool optreq_dns:1;
bool optreq_dns_search:1;
bool optreq_sntp:1;
bool optreq_info_refresh_time:1;
bool optreq_ntp:1;
bool use_rapid_commit:1;
};
bool create_dhcp6_socket();
[[nodiscard]] bool allot_dynamic_ip(const d6msg_state &d6s, sbufs &ss, uint32_t iaid,
d6_statuscode::code failcode, bool &use_dynamic);
[[nodiscard]] bool emit_IA_addr(const d6msg_state &d6s, sbufs &ss, const dhcpv6_entry *v);
[[nodiscard]] bool emit_IA_code(const d6msg_state &d6s, sbufs &ss, uint32_t iaid,
d6_statuscode::code scode);
[[nodiscard]] bool attach_address_info(const d6msg_state &d6s, sbufs &ss,
d6_statuscode::code failcode, bool *has_addrs = nullptr);
[[nodiscard]] bool attach_dns_ntp_info(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool attach_status_code(const d6msg_state &d6s, sbufs &ss, d6_statuscode::code scode);
[[nodiscard]] bool write_response_header(const d6msg_state &d6s, sbufs &ss, dhcp6_msgtype mtype);
[[nodiscard]] bool handle_solicit_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_request_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool confirm_match(const d6msg_state &d6s, bool &confirmed);
[[nodiscard]] bool mark_addr_unused(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_confirm_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_renew_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_rebind_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_information_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_release_msg(const d6msg_state &d6s, sbufs &ss);
[[nodiscard]] bool handle_decline_msg(const d6msg_state &d6s, sbufs &ss);
bool serverid_incorrect(const d6msg_state &d6s) const;
void attach_bpf(int fd);
void process_receive(char *buf, std::size_t buflen,
const sockaddr_storage &sai, socklen_t sailen);
nk::ip_address local_ip_;
nk::ip_address local_ip_prefix_;
nk::ip_address link_local_ip_;
std::string ifname_;
nk::sys::handle fd_;
bool using_bpf_:1;
unsigned char prefixlen_;
uint8_t preference_;
[[nodiscard]] bool options_consume(d6msg_state &d6s, size_t v);
};
#endif
| 31.105072 | 104 | 0.622365 | [
"vector"
] |
5ef5ff0038c3ebb070266e2e3da762d4a7674539 | 13,554 | cpp | C++ | isis/src/control/apps/findfeatures/findfeatures.cpp | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | null | null | null | isis/src/control/apps/findfeatures/findfeatures.cpp | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | null | null | null | isis/src/control/apps/findfeatures/findfeatures.cpp | kdl222/ISIS3 | aab0e63088046690e6c031881825596c1c2cc380 | [
"CC0-1.0"
] | 1 | 2021-04-16T03:00:44.000Z | 2021-04-16T03:00:44.000Z | /** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <cmath>
#include <ctime>
/*#define USE_GUI_QAPP 1*/
#include <QApplication>
#include <QScopedPointer>
#include <QSharedPointer>
#include <QFile>
#include <QTextStream>
// OpenCV stuff
#include "opencv2/core.hpp"
// boost library
#include <boost/foreach.hpp>
#define HAVE_ISNAN
#include "Camera.h"
#include "ControlMeasure.h"
#include "ControlMeasureLogData.h"
#include "ControlNet.h"
#include "ControlPoint.h"
#include "Cube.h"
#include "Distance.h"
#include "Environment.h"
#include "FastGeom.h"
#include "FeatureAlgorithmFactory.h"
#include "FileList.h"
#include "GenericTransform.h"
#include "ID.h"
#include "ImageSource.h"
#include "ImageTransform.h"
#include "ScalingTransform.h"
#include "IException.h"
#include "IString.h"
#include "iTime.h"
#include "Latitude.h"
#include "Longitude.h"
#include "MatcherSolution.h"
#include "MatchImage.h"
#include "MatchMaker.h"
#include "Process.h"
#include "Progress.h"
#include "PvlFlatMap.h"
#include "PvlGroup.h"
#include "QDebugLogger.h"
#include "RobustMatcher.h"
#include "SerialNumber.h"
#include "ScharrTransform.h"
#include "SobelTransform.h"
#include "Statistics.h"
#include "SurfacePoint.h"
#include "TextFile.h"
#include "UserInterface.h"
#include "Pvl.h"
using namespace std;
namespace Isis{
static void writeInfo(const QString &toname, Pvl &data, UserInterface &ui, Pvl *log) {
if ( !toname.isEmpty() ) {
FileName toinfo(toname);
QString fname = toinfo.expanded();
data.write(fname);
}
else {
if ( !ui.IsInteractive() ) {
std::cout << data << "\n";
}
else {
if (log){
PvlGroup results = data.findGroup("Results");
log->addGroup(results);
}
}
}
return;
}
void findfeatures(UserInterface &ui, Pvl *log) {
// Program constants
const QString findfeatures_program = "findfeatures";
const QString findfeatures_version = "1.0";
const QString findfeatures_revision = "$Revision$";
// Get time for findfeatures_runtime
time_t startTime = time(NULL);
struct tm *tmbuf = localtime(&startTime);
char timestr[80];
strftime(timestr, 80, "%Y-%m-%dT%H:%M:%S", tmbuf);
const QString findfeatures_runtime = (QString) timestr;
QString toinfo;
if ( ui.WasEntered("TOINFO")) {
toinfo = ui.GetAsString("TOINFO");
}
// Set up program debugging and logging
QDebugStream logger( QDebugLogger::null() );
bool p_debug( ui.GetBoolean("DEBUG") );
if ( p_debug ) {
// User specified a file by name
if ( ui.WasEntered("DEBUGLOG") ) {
logger = QDebugLogger::create( ui.GetAsString("DEBUGLOG") );
}
else {
// User wants debugging but entered no file so give'em std::cout.
logger = QDebugLogger::toStdOut();
}
}
// Write out program logger information
logger->dbugout() << "\n\n---------------------------------------------------\n";
logger->dbugout() << "Program: " << findfeatures_program << "\n";
logger->dbugout() << "Version " << findfeatures_version << "\n";
logger->dbugout() << "Revision: " << findfeatures_revision << "\n";
logger->dbugout() << "RunTime: " << findfeatures_runtime << "\n";
logger->dbugout() << "OpenCV_Version: " << CV_VERSION << "\n";
logger->flush();
// Set up for info requests
FeatureAlgorithmFactory *factory = FeatureAlgorithmFactory::getInstance();
if ( ui.GetBoolean("LISTALL") ) {
Pvl info;
QStringList algorithms = factory->getListAll();
// cout << algorithms.join("\n") << "\n";
info.addObject( factory->info(algorithms) );
writeInfo(toinfo, info, ui, log);
return;
}
// Get parameters from user
PvlFlatMap parameters;
// Check for parameters file provided by user
if ( ui.WasEntered("PARAMETERS") ) {
QString pfilename = ui.GetAsString("PARAMETERS");
Pvl pfile(pfilename);
parameters.merge( PvlFlatMap(pfile) );
parameters.add("ParameterFile", pfilename);
}
// Get individual parameters if provided
QStringList parmlist;
parmlist << "Ratio" << "EpiTolerance" << "EpiConfidence" << "HmgTolerance"
<< "MaxPoints" << "FastGeom" << "FastGeomPoints" << "GeomType"
<< "GeomSource" << "Filter";
BOOST_FOREACH (QString p, parmlist ) {
parameters.add(p, ui.GetAsString(p));
}
// Got all parameters. Add them now and they don't need to be considered
// from here on. Parameters specified in input algorithm specs take
// precedence (in MatchMaker)
factory->setGlobalParameters(parameters);
// Retrieve the ALGORITHM specification (if requested)
QString aspec;
if ( ui.WasEntered("ALGORITHM") ) {
aspec = ui.GetString("ALGORITHM");
}
// Now check for file containing algorithms
if ( ui.WasEntered("ALGOSPECFILE") ) {
QString specfile = ui.GetAsString("ALGOSPECFILE");
TextFile sFile(specfile);
sFile.OpenChk(true);
QString algorithm;
QStringList algos;
while ( sFile.GetLine(algorithm, true) ) {
algos.append(algorithm);
}
if ( !aspec.isEmpty() ) { aspec.append("|"); }
aspec.append( algos.join("|") );
}
// Create a list of algorithm specifications from user specs and log it
// if requested
RobustMatcherList algorithms = factory->create(aspec);
if ( ui.GetBoolean("LISTSPEC") ) {
Pvl info;
info.addObject(factory->info(algorithms));
writeInfo(toinfo, info, ui, log);
// If no input files are provided exit here
if ( ! ( ui.WasEntered("FROM") && ui.WasEntered("FROMLIST") ) ) {
return;
}
}
// First see what we can do about threads if your user is resource conscience
int nCPUs = cv::getNumberOfCPUs();
int nthreads = cv::getNumThreads();
logger->dbugout() << "\nSystem Environment...\n";
logger->dbugout() << "Number available CPUs: " << nCPUs << "\n";
logger->dbugout() << "Number default threads: " << nthreads << "\n";
// See if user wants to restrict the number of threads used
int uthreads = nthreads;
if ( ui.WasEntered("MAXTHREADS") ) {
uthreads = ui.GetInteger("MAXTHREADS");
if (uthreads < nthreads) cv::setNumThreads(uthreads);
logger->dbugout() << "User restricted threads: " << uthreads << "\n";
}
int total_threads = cv::getNumThreads();
logger->dbugout() << "Total threads: " << total_threads << "\n";
logger->flush();
//-------------Matching Business--------------------------
// Make the matcher class
MatchMaker matcher(ui.GetString("NETWORKID"));
matcher.setDebugLogger(logger, p_debug );
// Acquire query image
matcher.setQueryImage(MatchImage(ImageSource(ui.GetAsString("MATCH"))));
// Get the trainer images
if ( ui.WasEntered("FROM") ) {
matcher.addTrainImage(MatchImage(ImageSource(ui.GetAsString("FROM"))));
}
// If there is a list provided, get that too
if ( ui.WasEntered("FROMLIST") ) {
FileList trainers(ui.GetFileName("FROMLIST"));
BOOST_FOREACH ( FileName tfile, trainers ) {
matcher.addTrainImage(MatchImage(ImageSource(tfile.original())));
}
}
// Got to have both file names provided at this point
if ( matcher.size() <= 0 ) {
throw IException(IException::User,
"Must provide both a FROM/FROMLIST and MATCH cube or image filename",
_FILEINFO_);
}
// Define which geometry source we should use. None is the default
QString geomsource = ui.GetString("GEOMSOURCE").toLower();
if ( "match" == geomsource ) { matcher.setGeometrySourceFlag(MatchMaker::Query); }
if ( "from" == geomsource ) { matcher.setGeometrySourceFlag(MatchMaker::Train); }
// Check for FASTGEOM option
if ( ui.GetBoolean("FASTGEOM") ) {
FastGeom geom( factory->globalParameters() );
matcher.foreachPair( geom );
}
// Check for Sobel/Scharr filtering options for both Train and Images
QString filter = factory->globalParameters().get("FILTER", "").toLower();
// Apply the Sobel filter to all image
if ( "sobel" == filter ) {
matcher.query().addTransform(new SobelTransform("SobelTransform"));
for (int i = 0 ; i < matcher.size() ; i++) {
matcher.train(i).addTransform(new SobelTransform("SobelTransform"));
}
}
// Add the Scharr filter to all images
if ( "scharr" == filter ) {
matcher.query().addTransform(new ScharrTransform("ScharrTransform"));
for (int i = 0 ; i < matcher.size() ; i++) {
matcher.train(i).addTransform(new ScharrTransform("ScharrTransform"));
}
}
// Apply all matcher/transform permutations
logger->dbugout() << "\nTotal Algorithms to Run: " << algorithms.size() << "\n";
MatcherSolutionList matches = matcher.match(algorithms);
const MatcherSolution *best = MatcherSolution::best(matches);
logger->dbugout().flush();
// If all failed, we're done
if ( !best ) {
logger->dbugout() << "Bummer! No matches were found!\n";
QString mess = "NO MATCHES WERE FOUND!!!";
throw IException(IException::User, mess, _FILEINFO_);
}
// Not valid results
if ( best->size() <= 0 ) {
logger->dbugout() << "Shucks! Insufficient matches were found ("
<< best->size() << ")\n";
QString mess = "Shucks! Insufficient matches were found (" +
QString::number(best->size()) + ")";
throw IException(IException::User, mess, _FILEINFO_);
}
// Got some matches so lets process them
Statistics quality = best->qualityStatistics();
PvlGroup bestinfo("MatchSolution");
bestinfo += PvlKeyword("Matcher", best->matcher()->name());
bestinfo += PvlKeyword("MatchedPairs", toString(best->size()));
bestinfo += PvlKeyword("Efficiency", toString(quality.Average()));
if ( quality.ValidPixels() > 1 ) {
bestinfo += PvlKeyword("StdDevEfficiency",
toString(quality.StandardDeviation()));
}
if(log){
log->addGroup(bestinfo);
}
// If a cnet file was entered, write the ControlNet file of the specified
// type. Note that it was created as an image-to-image network. Must make
// adjustments if a ground network is requested.
if ( ui.WasEntered("ONET") ) {
ControlNet cnet;
cnet.SetNetworkId(ui.GetString("NETWORKID"));
cnet.SetUserName(Isis::Environment::userName());
cnet.SetDescription(best->matcher()->name());
cnet.SetCreatedDate(findfeatures_runtime);
QString target = ( ui.WasEntered("TARGET") ) ? ui.GetString("TARGET") :
best->target();
cnet.SetTarget( target );
ID pointId( ui.GetString("POINTID"), ui.GetInteger("POINTINDEX") );
matcher.setDebugOff();
PvlGroup cnetinfo = matcher.network(cnet, *best, pointId);
if ( cnet.GetNumPoints() <= 0 ) {
QString mess = "No control points found!!";
logger->dbugout() << mess << "\n";
throw IException(IException::User, mess, _FILEINFO_);
}
// Umm..have to check this. Probably only makes sense with two images
if ( ui.GetString("NETTYPE").toLower() == "ground" ) {
cnetinfo += PvlKeyword("SpecialNetType", "Ground");
for ( int i = 0 ; i < cnet.GetNumPoints() ; i++ ) {
ControlPoint *point = cnet.GetPoint(i);
point->SetType(ControlPoint::Fixed);
point->Delete(matcher.query().id());
point->SetRefMeasure(0);
}
}
// Write out control network
cnet.Write( ui.GetFileName("ONET") );
if(log){
log->addGroup(cnetinfo);
}
}
// If user wants a list of matched images, write the list to the TOLIST filename
if ( ui.WasEntered("TOLIST") ) {
QLogger fout( QDebugLogger::create( ui.GetAsString("TOLIST"),
(QIODevice::WriteOnly |
QIODevice::Truncate) ) );
fout.logger() << matcher.query().name() << "\n";
MatcherSolution::MatchPairConstIterator mpair = best->begin();
while ( mpair != best->end() ) {
if ( mpair->size() > 0 ) {
fout.logger() << mpair->train().source().name() << "\n";
}
++mpair;
}
}
// If user wants a list of failed matched images, write the list to the
// TONOTMATCHED file in append mode (assuming other runs will accumulate
// failed matches)
if ( ui.WasEntered("TONOTMATCHED") ) {
QLogger fout( QDebugLogger::create( ui.GetAsString("TONOTMATCHED"),
(QIODevice::WriteOnly |
QIODevice::Append) ) );
MatcherSolution::MatchPairConstIterator mpair = best->begin();
while ( mpair != best->end() ) {
if ( mpair->size() == 0 ) {
fout.logger() << mpair->train().source().name() << "\n";
}
++mpair;
}
}
return;
}
}
| 34.227273 | 92 | 0.608381 | [
"geometry",
"transform"
] |
5ef62eacbf7330ed83502d53d5157c179251f9b8 | 6,543 | hpp | C++ | include/mango/core/stream.hpp | diablodale/mango | 2efce1d8e7c97dd89ca1e19634fe2014bf289824 | [
"Zlib"
] | null | null | null | include/mango/core/stream.hpp | diablodale/mango | 2efce1d8e7c97dd89ca1e19634fe2014bf289824 | [
"Zlib"
] | null | null | null | include/mango/core/stream.hpp | diablodale/mango | 2efce1d8e7c97dd89ca1e19634fe2014bf289824 | [
"Zlib"
] | null | null | null | /*
MANGO Multimedia Development Platform
Copyright (C) 2012-2020 Twilight Finland 3D Oy Ltd. All rights reserved.
*/
#pragma once
#include "configure.hpp"
#include "object.hpp"
#include "endian.hpp"
#include "memory.hpp"
#include "half.hpp"
namespace mango
{
class Stream : protected NonCopyable
{
public:
enum OpenMode
{
READ,
WRITE
};
enum SeekMode
{
BEGIN,
CURRENT,
END
};
Stream() = default;
virtual ~Stream() = default;
virtual u64 size() const = 0;
virtual u64 offset() const = 0;
virtual void seek(u64 distance, SeekMode mode) = 0;
virtual void read(void* dest, size_t size) = 0;
virtual void write(const void* data, size_t size) = 0;
void write(ConstMemory memory)
{
write(memory.address, memory.size);
}
};
// --------------------------------------------------------------
// SameEndianStream
// --------------------------------------------------------------
class SameEndianStream
{
private:
Stream& s;
public:
SameEndianStream(Stream& stream)
: s(stream)
{
}
u64 size() const
{
return s.size();
}
u64 offset() const
{
return s.offset();
}
void seek(u64 distance, Stream::SeekMode mode)
{
s.seek(distance, mode);
}
// read functions
void read(void* dest, size_t size)
{
s.read(dest, size);
}
u8 read8()
{
u8 value;
s.read(&value, sizeof(u8));
return value;
}
u16 read16()
{
u16 value;
s.read(&value, sizeof(u16));
return value;
}
u32 read32()
{
u32 value;
s.read(&value, sizeof(u32));
return value;
}
u64 read64()
{
u64 value;
s.read(&value, sizeof(u64));
return value;
}
float16 read16f()
{
Half value;
value.u = read16();
return value;
}
float read32f()
{
Float value;
value.u = read32();
return value;
}
double read64f()
{
Double value;
value.u = read64();
return value;
}
// write functions
void write(const void* data, size_t size)
{
s.write(data, size);
}
void write(ConstMemory memory)
{
s.write(memory);
}
void write8(u8 value)
{
s.write(&value, sizeof(u8));
}
void write16(u16 value)
{
s.write(&value, sizeof(u16));
}
void write32(u32 value)
{
s.write(&value, sizeof(u32));
}
void write64(u64 value)
{
s.write(&value, sizeof(u64));
}
void write16f(Half value)
{
write16(value.u);
}
void write32f(Float value)
{
write32(value.u);
}
void write64f(Double value)
{
write64(value.u);
}
};
// --------------------------------------------------------------
// SwapEndianStream
// --------------------------------------------------------------
class SwapEndianStream
{
private:
Stream& s;
public:
SwapEndianStream(Stream& stream)
: s(stream)
{
}
u64 size() const
{
return s.size();
}
u64 offset() const
{
return s.offset();
}
void seek(u64 distance, Stream::SeekMode mode)
{
s.seek(distance, mode);
}
// read functions
void read(void* dest, size_t size)
{
s.read(dest, size);
}
u8 read8()
{
u8 value;
s.read(&value, sizeof(u8));
return value;
}
u16 read16()
{
u16 value;
s.read(&value, sizeof(u16));
value = byteswap(value);
return value;
}
u32 read32()
{
u32 value;
s.read(&value, sizeof(u32));
value = byteswap(value);
return value;
}
u64 read64()
{
u64 value;
s.read(&value, sizeof(u64));
value = byteswap(value);
return value;
}
float16 read16f()
{
Half value;
value.u = read16();
return value;
}
float read32f()
{
Float value;
value.u = read32();
return value;
}
double read64f()
{
Double value;
value.u = read64();
return value;
}
// write functions
void write(const void* data, size_t size)
{
s.write(data, size);
}
void write(ConstMemory memory)
{
s.write(memory);
}
void write8(u8 value)
{
s.write(&value, 1);
}
void write16(u16 value)
{
value = byteswap(value);
s.write(&value, 2);
}
void write32(u32 value)
{
value = byteswap(value);
s.write(&value, 4);
}
void write64(u64 value)
{
value = byteswap(value);
s.write(&value, 8);
}
void write16f(Half value)
{
write16(value.u);
}
void write32f(Float value)
{
write32(value.u);
}
void write64f(Double value)
{
write64(value.u);
}
};
// --------------------------------------------------------------
// Little/BigEndianStream
// --------------------------------------------------------------
#ifdef MANGO_LITTLE_ENDIAN
using LittleEndianStream = SameEndianStream;
using BigEndianStream = SwapEndianStream;
#else
using LittleEndianStream = SwapEndianStream;
using BigEndianStream = SameEndianStream;
#endif
} // namespace mango
| 19.300885 | 76 | 0.40807 | [
"object",
"3d"
] |
5ef72c881d91081d71922ad98f0377ec9c4c7db6 | 1,221 | cpp | C++ | geeksforgeeks/arrays/array-rotation/4c. maximum-sum-iarri-among-rotations-given-array.cpp | jatin69/Revision-cpp | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 4 | 2020-01-16T14:49:46.000Z | 2021-08-23T12:45:19.000Z | geeksforgeeks/arrays/array-rotation/4c. maximum-sum-iarri-among-rotations-given-array.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 2 | 2018-06-06T13:08:11.000Z | 2018-10-02T19:07:32.000Z | geeksforgeeks/arrays/array-rotation/4c. maximum-sum-iarri-among-rotations-given-array.cpp | jatin69/coding-practice | 52742ea76ee2440d92b116252399360fef46e0c7 | [
"MIT"
] | 5 | 2018-10-02T13:49:16.000Z | 2021-08-11T07:29:50.000Z | /*
* Author : Jatin Rohilla
* Date : 17/06/2018
*
* Editor : Dev c++ 5.11
* Compiler : g++ 5.1.0
* flags : -std=c++11
*
question - https://www.geeksforgeeks.org/maximum-sum-iarri-among-rotations-given-array/
time - O(n)
space - O(1)
*/
#include<bits/stdc++.h>
using namespace std;
int maxSum(vector<int>& A) {
int n = A.size();
int Asum = 0;
int currValue = 0;
for(int i=0;i<n;++i){
Asum += A[i];
// value at zero left rotations.
currValue += (i*A[i]);
}
int maxValue = 0;
// start by left rotating original array by 1
for(int i=1;i<n;++i){
/* One left rotation will decrease the multiplication factor by 1
so we gotta subtract ( 1*A[0] + 1*A[1] + ... 1*A[n-1] )
But if we look closely we see that A[0] had a multiplication factor 0 initially
so we are taking away from zero. Can't do that. So gotta give it back.
Asum - A[i-1] represents array sum except first element.
Also, first element now goes to last & now has n-1 multiplication factor.
*/
currValue = currValue - (Asum - A[i-1]) + (n-1)*A[i-1];
maxValue = max(maxValue, currValue);
}
return maxValue;
}
int main(){
vector<int> A = {
8, 3, 1, 2
};
cout << maxSum(A);
return 0;
}
| 19.078125 | 87 | 0.613432 | [
"vector"
] |
5efe1189fd4ea00535ec2a20f1f7c28458c8e63b | 1,598 | hpp | C++ | TeaGameLib/include/ResourceManager.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 11 | 2020-03-08T03:12:38.000Z | 2020-10-30T14:35:39.000Z | TeaGameLib/include/ResourceManager.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 3 | 2020-03-09T06:46:24.000Z | 2020-03-19T11:00:12.000Z | TeaGameLib/include/ResourceManager.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 1 | 2020-03-19T09:42:45.000Z | 2020-03-19T09:42:45.000Z | #pragma once
#include "Platform/Effect.hpp"
#include "Window/App/EffectMsgQueue.hpp"
#include "InternalGameLib/Resource/ResourceLoader.hpp"
namespace teaGameLib {
class ResourceManager {
static InternalGameLibHandlersPtr internalGameLibHandlersPtr;
static void Init(InternalGameLibHandlersPtr _internalGameLibHandlersPtr) {
ResourceManager::internalGameLibHandlersPtr = _internalGameLibHandlersPtr;
}
friend class App;
public:
template<typename Msg, typename MsgFunc>
static Cmd<Msg> GetTextureResource(const std::string& fileName, MsgFunc msgFunc) {
return { [fileName,msgFunc](EffectMsgQueue<Msg> effectMsgQueue) {
auto result = resource::ResourceLoader::LoadTexture(
fileName,
internalGameLibHandlersPtr);
effectMsgQueue.InQueueMsg(msgFunc(result));
} };
}
template<typename Msg, typename MsgFunc>
static Cmd<Msg> GetTextureResources(const std::vector<std::string>& fileNames, MsgFunc msgFunc) {
return { [fileNames = std::move(fileNames),msgFunc] (EffectMsgQueue<Msg> effectMsgQueue) {
std::vector<resource::TextureResource> textureResources;
for (const auto& fileName : fileNames) {
auto result = resource::ResourceLoader::LoadTexture(
fileName,
internalGameLibHandlersPtr);
if (result.has_value() == false) {
effectMsgQueue.InQueueMsg(msgFunc(std::optional<std::vector<resource::TextureResource>>{ }));
return;
}
textureResources.emplace_back(result.value());
}
effectMsgQueue.InQueueMsg(msgFunc(std::optional{ std::move(textureResources) }));
} };
}
};
} | 31.96 | 99 | 0.733417 | [
"vector"
] |
5eff2ed2b2d8a2b22538fb1b11e9a8411a7434af | 452 | cpp | C++ | Chapter06/6_3.cpp | GeertArien/c-accelerated | c0ae9f66b1733de04f3133db2e9d8af6d555fe6e | [
"MIT"
] | 27 | 2019-03-12T02:24:43.000Z | 2022-02-18T22:49:00.000Z | Chapter06/6_3.cpp | GeertArien/C-Accelerated | c0ae9f66b1733de04f3133db2e9d8af6d555fe6e | [
"MIT"
] | 1 | 2020-06-24T18:34:45.000Z | 2020-06-28T12:55:05.000Z | Chapter06/6_3.cpp | GeertArien/c-accelerated | c0ae9f66b1733de04f3133db2e9d8af6d555fe6e | [
"MIT"
] | 12 | 2019-04-22T03:49:19.000Z | 2021-08-31T17:39:35.000Z | /**
Accelerated C++, Exercise 6-3, 6_3.cpp
What does this program fragment do?
vector<int> u(10, 100);
vector<int> v;
copy(u.begin(), u.end(), v.begin());
Write a program that contains this fragment, and compile and execute it.
*/
#include "stdafx.h"
#include "6_3.h"
#include <vector>
using std::vector;
using std::copy;
int ex6_3()
{
vector<int> u(10, 100);
vector<int> v;
copy(u.begin(), u.end(), v.begin());
return 0;
} | 15.586207 | 72 | 0.630531 | [
"vector"
] |
6f056e89deea269fe7172480ad79197b15bcda76 | 7,435 | cc | C++ | chrome/browser/chromeos/usb_mount_observer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/chromeos/usb_mount_observer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/usb_mount_observer.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/usb_mount_observer.h"
#include "base/command_line.h"
#include "base/singleton.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
namespace chromeos {
const char* kFilebrowseURLHash = "chrome://filebrowse#";
const char* kFilebrowseScanning = "scanningdevice";
const int kPopupLeft = 0;
const int kPopupTop = 0;
const int kPopupWidth = 250;
const int kPopupHeight = 300;
// static
USBMountObserver* USBMountObserver::GetInstance() {
return Singleton<USBMountObserver>::get();
}
void USBMountObserver::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::BROWSER_CLOSED);
for (BrowserIterator i = browsers_.begin(); i != browsers_.end();
++i) {
if (Source<Browser>(source).ptr() == i->browser) {
i->browser = NULL;
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
source);
return;
}
}
}
void USBMountObserver::ScanForDevices(chromeos::MountLibrary* obj) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (!disk.is_parent && !disk.device_path.empty()) {
obj->MountPath(disk.device_path.c_str());
}
}
}
void USBMountObserver::OpenFileBrowse(const std::string& url,
const std::string& device_path,
bool small) {
Browser* browser;
Profile* profile;
browser = BrowserList::GetLastActive();
if (browser == NULL) {
return;
}
profile = browser->profile();
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableAdvancedFileSystem)) {
return;
}
if (small) {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kSmallPopupWidth,
FileBrowseUI::kSmallPopupHeight);
} else {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kPopupWidth,
FileBrowseUI::kPopupHeight);
}
registrar_.Add(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
BrowserIterator iter = FindBrowserForPath(device_path);
if (iter == browsers_.end()) {
BrowserWithPath new_browser;
new_browser.browser = browser;
new_browser.device_path = device_path;
browsers_.push_back(new_browser);
} else {
iter->browser = browser;
}
}
void USBMountObserver::MountChanged(chromeos::MountLibrary* obj,
chromeos::MountEventType evt,
const std::string& path) {
if (evt == chromeos::DISK_ADDED) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (disk.device_path == path) {
if (disk.is_parent) {
if (!disk.has_media) {
RemoveBrowserFromVector(disk.system_path);
}
} else if (!obj->MountPath(path.c_str())) {
RemoveBrowserFromVector(disk.system_path);
}
}
}
VLOG(1) << "Got added mount: " << path;
} else if (evt == chromeos::DISK_REMOVED ||
evt == chromeos::DEVICE_REMOVED) {
RemoveBrowserFromVector(path);
} else if (evt == chromeos::DISK_CHANGED) {
BrowserIterator iter = FindBrowserForPath(path);
VLOG(1) << "Got changed mount: " << path;
if (iter == browsers_.end()) {
// We don't currently have this one, so it must have been
// mounted
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
if (disks[i].device_path == path) {
if (!disks[i].mount_path.empty()) {
// Doing second search to see if the current disk has already
// been popped up due to its parent device being plugged in.
iter = FindBrowserForPath(disks[i].system_path);
if (iter != browsers_.end() && iter->browser) {
std::string url = kFilebrowseURLHash;
url += disks[i].mount_path;
TabContents* tab = iter->browser->GetSelectedTabContents();
iter->browser->window()->SetBounds(gfx::Rect(
0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight));
tab->OpenURL(GURL(url), GURL(), CURRENT_TAB,
PageTransition::LINK);
tab->NavigateToPendingEntry(NavigationController::RELOAD);
iter->device_path = path;
iter->mount_path = disks[i].mount_path;
} else {
OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false);
}
}
return;
}
}
}
} else if (evt == chromeos::DEVICE_ADDED) {
VLOG(1) << "Got device added: " << path;
OpenFileBrowse(kFilebrowseScanning, path, true);
} else if (evt == chromeos::DEVICE_SCANNED) {
VLOG(1) << "Got device scanned: " << path;
}
}
USBMountObserver::BrowserIterator USBMountObserver::FindBrowserForPath(
const std::string& path) {
for (BrowserIterator i = browsers_.begin();i != browsers_.end();
++i) {
// Doing a substring match so that we find if this new one is a subdevice
// of another already inserted device.
if (path.find(i->device_path) != std::string::npos) {
return i;
}
}
return browsers_.end();
}
void USBMountObserver::RemoveBrowserFromVector(const std::string& path) {
BrowserIterator i = FindBrowserForPath(path);
std::string mount_path;
if (i != browsers_.end()) {
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(i->browser));
mount_path = i->mount_path;
browsers_.erase(i);
}
std::vector<Browser*> close_these;
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
if (*it && (*it)->GetTabContentsAt((*it)->selected_index())) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIFileBrowseHost &&
url.ref().find(mount_path) != std::string::npos &&
!mount_path.empty()) {
close_these.push_back(*it);
}
}
}
}
for (size_t x = 0; x < close_these.size(); x++) {
if (close_these[x]->window()) {
close_these[x]->window()->Close();
}
}
}
} // namespace chromeos
| 36.268293 | 80 | 0.596503 | [
"vector"
] |
6f1381fab9e69a9febcff9c13294f132b7b6d424 | 23,520 | cpp | C++ | source/hints.cpp | ssroffe/OoT3D_Randomizer | 1371fa2d26d094c936d2664a578cfe8642558f83 | [
"MIT"
] | null | null | null | source/hints.cpp | ssroffe/OoT3D_Randomizer | 1371fa2d26d094c936d2664a578cfe8642558f83 | [
"MIT"
] | null | null | null | source/hints.cpp | ssroffe/OoT3D_Randomizer | 1371fa2d26d094c936d2664a578cfe8642558f83 | [
"MIT"
] | null | null | null | #include "hints.hpp"
#include "custom_messages.hpp"
#include "dungeon.hpp"
#include "item_location.hpp"
#include "item_pool.hpp"
#include "location_access.hpp"
#include "logic.hpp"
#include "random.hpp"
#include "spoiler_log.hpp"
#include "fill.hpp"
#include "hint_list.hpp"
#include "trial.hpp"
using namespace CustomMessages;
using namespace Logic;
using namespace Settings;
using namespace Trial;
constexpr std::array<HintSetting, 4> hintSettingTable{{
// Useless hints
{
.dungeonsWothLimit = 2,
.dungeonsBarrenLimit = 1,
.namedItemsRequired = false,
.distTable = {{
{.type = HintType::Trial, .order = 1, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Always, .order = 2, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Woth, .order = 3, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Barren, .order = 4, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Entrance, .order = 5, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Sometimes, .order = 6, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Random, .order = 7, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Item, .order = 8, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Song, .order = 9, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Overworld, .order = 10, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Dungeon, .order = 11, .weight = 0, .fixed = 0, .copies = 0},
{.type = HintType::Junk, .order = 12, .weight = 99, .fixed = 0, .copies = 0},
{.type = HintType::NamedItem, .order = 13, .weight = 0, .fixed = 0, .copies = 0},
}},
},
// Balanced hints
{
.dungeonsWothLimit = 2,
.dungeonsBarrenLimit = 1,
.namedItemsRequired = true,
.distTable = {{
{.type = HintType::Trial, .order = 1, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Always, .order = 2, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Woth, .order = 3, .weight = 7, .fixed = 0, .copies = 1},
{.type = HintType::Barren, .order = 4, .weight = 4, .fixed = 0, .copies = 1},
{.type = HintType::Entrance, .order = 5, .weight = 6, .fixed = 0, .copies = 1},
{.type = HintType::Sometimes, .order = 6, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Random, .order = 7, .weight = 12, .fixed = 0, .copies = 1},
{.type = HintType::Item, .order = 8, .weight = 10, .fixed = 0, .copies = 1},
{.type = HintType::Song, .order = 9, .weight = 2, .fixed = 0, .copies = 1},
{.type = HintType::Overworld, .order = 10, .weight = 4, .fixed = 0, .copies = 1},
{.type = HintType::Dungeon, .order = 11, .weight = 3, .fixed = 0, .copies = 1},
{.type = HintType::Junk, .order = 12, .weight = 6, .fixed = 0, .copies = 1},
{.type = HintType::NamedItem, .order = 13, .weight = 0, .fixed = 0, .copies = 1},
}},
},
// Strong hints
{
.dungeonsWothLimit = 2,
.dungeonsBarrenLimit = 1,
.namedItemsRequired = true,
.distTable = {{
{.type = HintType::Trial, .order = 1, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Always, .order = 2, .weight = 0, .fixed = 0, .copies = 2},
{.type = HintType::Woth, .order = 3, .weight = 12, .fixed = 0, .copies = 2},
{.type = HintType::Barren, .order = 4, .weight = 12, .fixed = 0, .copies = 1},
{.type = HintType::Entrance, .order = 5, .weight = 4, .fixed = 0, .copies = 1},
{.type = HintType::Sometimes, .order = 6, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Random, .order = 7, .weight = 8, .fixed = 0, .copies = 1},
{.type = HintType::Item, .order = 8, .weight = 8, .fixed = 0, .copies = 1},
{.type = HintType::Song, .order = 9, .weight = 4, .fixed = 0, .copies = 1},
{.type = HintType::Overworld, .order = 10, .weight = 6, .fixed = 0, .copies = 1},
{.type = HintType::Dungeon, .order = 11, .weight = 6, .fixed = 0, .copies = 1},
{.type = HintType::Junk, .order = 12, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::NamedItem, .order = 13, .weight = 0, .fixed = 0, .copies = 1},
}},
},
// Very strong hints
{
.dungeonsWothLimit = 40,
.dungeonsBarrenLimit = 40,
.namedItemsRequired = true,
.distTable = {{
{.type = HintType::Trial, .order = 1, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Always, .order = 2, .weight = 0, .fixed = 0, .copies = 2},
{.type = HintType::Woth, .order = 3, .weight = 15, .fixed = 0, .copies = 2},
{.type = HintType::Barren, .order = 4, .weight = 15, .fixed = 0, .copies = 1},
{.type = HintType::Entrance, .order = 5, .weight = 10, .fixed = 0, .copies = 1},
{.type = HintType::Sometimes, .order = 6, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Random, .order = 7, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::Item, .order = 8, .weight = 5, .fixed = 0, .copies = 1},
{.type = HintType::Song, .order = 9, .weight = 2, .fixed = 0, .copies = 1},
{.type = HintType::Overworld, .order = 10, .weight = 7, .fixed = 0, .copies = 1},
{.type = HintType::Dungeon, .order = 11, .weight = 7, .fixed = 0, .copies = 1},
{.type = HintType::Junk, .order = 12, .weight = 0, .fixed = 0, .copies = 1},
{.type = HintType::NamedItem, .order = 13, .weight = 0, .fixed = 0, .copies = 1},
}},
},
}};
static Exit* GetHintRegion(Exit* exit) {
std::vector<Exit*> alreadyChecked = {};
std::vector<Exit*> spotQueue = {exit};
while (!spotQueue.empty()) {
Exit* region = spotQueue.back();
alreadyChecked.push_back(region);
spotQueue.pop_back();
if (region->hintText != &Hints::NoHintText) {
return region;
}
//add unchecked exits to spot queue
bool checked = false;
for (auto exitPair : region->exits) {
Exit* e = exitPair.GetExit();
for (Exit* checkedExit : alreadyChecked) {
if (e == checkedExit) {
checked = true;
break;
}
}
if (!checked) {
spotQueue.insert(spotQueue.begin(), e);
}
}
}
return &Exits::NoExit;
}
static std::vector<ItemLocation*> GetAccessibleGossipStones(ItemLocation* hintedLocation = &Ganon) {
//temporarily remove the hinted location's item, and then perform a
//reachability search for gossip stone locations.
Item originalItem = hintedLocation->GetPlacedItem();
hintedLocation->SetPlacedItem(NoItem);
LogicReset();
auto accessibleGossipStones = GetAccessibleLocations(gossipStoneLocations);
//Give the item back to the location
hintedLocation->SetPlacedItem(originalItem);
return accessibleGossipStones;
}
static void AddHint(Text hint, ItemLocation* gossipStone, const std::vector<u8>& colors = {}) {
//save hints as dummy items to gossip stone locations for writing to the spoiler log
gossipStone->SetPlacedItem(Item{hint.GetEnglish(), ITEMTYPE_EVENT, GI_RUPEE_BLUE_LOSE, false, &noVariable, &Hints::NoHintText});
//create the in game message
u32 messageId = 0x400 + gossipStone->GetFlag();
CreateMessageFromTextObject(messageId, 0, 2, 3, AddColorsAndFormat(hint, colors));
}
static void CreateLocationHint(const std::vector<ItemLocation*>& possibleHintLocations) {
//return if there aren't any hintable locations or gossip stones available
if (possibleHintLocations.empty()) {
PlacementLog_Msg("\tNO LOCATIONS TO HINT\n\n");
return;
}
ItemLocation* hintedLocation = RandomElement(possibleHintLocations);
const std::vector<ItemLocation*> accessibleGossipStones = GetAccessibleGossipStones(hintedLocation);
PlacementLog_Msg("\tLocation: ");
PlacementLog_Msg(hintedLocation->GetName());
PlacementLog_Msg("\n");
PlacementLog_Msg("\tItem: ");
PlacementLog_Msg(hintedLocation->GetPlacedItemName());
PlacementLog_Msg("\n");
if (accessibleGossipStones.empty()) {
PlacementLog_Msg("\tNO GOSSIP STONES TO PLACE HINT\n\n");
return;
}
ItemLocation* gossipStone = RandomElement(accessibleGossipStones);
hintedLocation->SetAsHinted();
//make hint text
Text locationHintText = hintedLocation->GetHintText().GetText();
Text itemHintText = hintedLocation->GetPlacedItem().GetHintText().GetText();
Text prefix = Hints::Prefix.GetText();
Text finalHint = prefix + locationHintText + " #"+itemHintText+"#.";
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(finalHint.english);
PlacementLog_Msg("\n\n");
AddHint(finalHint, gossipStone, {QM_GREEN, QM_RED});
}
static void CreateWothHint(u8* remainingDungeonWothHints) {
//get locations that are in the current playthrough
std::vector<ItemLocation*> possibleHintLocations = {};
//iterate through playthrough locations by sphere
for (std::vector<ItemLocation*> sphere : playthroughLocations) {
std::vector<ItemLocation*> sphereHintLocations = FilterFromPool(sphere, [remainingDungeonWothHints](ItemLocation* loc){
return loc->IsHintable() && //only filter hintable locations
!loc->IsHintedAt() && //only filter locations that haven't been hinted at
(loc->IsOverworld() || (loc->IsDungeon() && (*remainingDungeonWothHints) > 0)); //make sure we haven't surpassed the woth dungeon limit
});
AddElementsToPool(possibleHintLocations, sphereHintLocations);
}
//If no more locations can be hinted at for woth, then just try to get another hint
if (possibleHintLocations.empty()) {
PlacementLog_Msg("\tNO LOCATIONS TO HINT\n\n");
return;
}
ItemLocation* hintedLocation = RandomElement(possibleHintLocations);
PlacementLog_Msg("\tLocation: ");
PlacementLog_Msg(hintedLocation->GetName());
PlacementLog_Msg("\n");
PlacementLog_Msg("\tItem: ");
PlacementLog_Msg(hintedLocation->GetPlacedItemName());
PlacementLog_Msg("\n");
//get an accessible gossip stone
const std::vector<ItemLocation*> gossipStoneLocations = GetAccessibleGossipStones(hintedLocation);
if (gossipStoneLocations.empty()) {
PlacementLog_Msg("\tNO GOSSIP STONES TO PLACE HINT\n\n");
return;
}
hintedLocation->SetAsHinted();
ItemLocation* gossipStone = RandomElement(gossipStoneLocations);
//form hint text
Text locationText;
if (hintedLocation->IsDungeon()) {
*remainingDungeonWothHints -= 1;
locationText = hintedLocation->GetParentRegion()->hintText->GetText();
} else {
locationText = GetHintRegion(hintedLocation->GetParentRegion())->hintText->GetText();
}
Text finalWothHint = Hints::Prefix.GetText()+"#"+locationText+"#"+Hints::WayOfTheHero.GetText();
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(finalWothHint.english);
PlacementLog_Msg("\n\n");
AddHint(finalWothHint, gossipStone, {QM_LBLUE});
}
static void CreateBarrenHint(u8* remainingDungeonBarrenHints, std::vector<ItemLocation*>& barrenLocations) {
//remove dungeon locations if necessary
if (*remainingDungeonBarrenHints < 1) {
barrenLocations = FilterFromPool(barrenLocations, [](ItemLocation* loc){return !loc->IsDungeon();});
}
if (barrenLocations.empty()) {
return;
}
ItemLocation* hintedLocation = RandomElement(barrenLocations, true);
PlacementLog_Msg("\tLocation: ");
PlacementLog_Msg(hintedLocation->GetName());
PlacementLog_Msg("\n");
PlacementLog_Msg("\tItem: ");
PlacementLog_Msg(hintedLocation->GetPlacedItemName());
PlacementLog_Msg("\n");
//get an accessible gossip stone
const std::vector<ItemLocation*> gossipStoneLocations = GetAccessibleGossipStones(hintedLocation);
if (gossipStoneLocations.empty()) {
PlacementLog_Msg("\tNO GOSSIP STONES TO PLACE HINT\n\n");
return;
}
hintedLocation->SetAsHinted();
ItemLocation* gossipStone = RandomElement(gossipStoneLocations);
//form hint text
Text locationText;
if (hintedLocation->IsDungeon()) {
*remainingDungeonBarrenHints -= 1;
locationText = hintedLocation->GetParentRegion()->hintText->GetText();
} else {
locationText = GetHintRegion(hintedLocation->GetParentRegion())->hintText->GetText();
}
Text finalBarrenHint = Hints::Prefix.GetText()+Hints::Plundering.GetText()+"#"+locationText+"#"+Hints::Foolish.GetText();
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(finalBarrenHint.english);
PlacementLog_Msg("\n\n");
AddHint(finalBarrenHint, gossipStone, {QM_PINK});
//get rid of all other locations in this same barren region
barrenLocations = FilterFromPool(barrenLocations, [hintedLocation](ItemLocation* loc){
return GetHintRegion(loc->GetParentRegion())->hintText != GetHintRegion(hintedLocation->GetParentRegion())->hintText;
});
}
static void CreateRandomLocationHint(bool goodItem = false) {
const std::vector<ItemLocation*> possibleHintLocations = FilterFromPool(allLocations, [goodItem](const ItemLocation* loc) {
return loc->IsHintable() && !loc->IsHintedAt() && (!goodItem || loc->GetPlacedItem().IsMajorItem());
});
//If no more locations can be hinted at, then just try to get another hint
if (possibleHintLocations.empty()) {
PlacementLog_Msg("\tNO LOCATIONS TO HINT\n\n");
return;
}
ItemLocation* hintedLocation = RandomElement(possibleHintLocations);
PlacementLog_Msg("\tLocation: ");
PlacementLog_Msg(hintedLocation->GetName());
PlacementLog_Msg("\n");
PlacementLog_Msg("\tItem: ");
PlacementLog_Msg(hintedLocation->GetPlacedItemName());
PlacementLog_Msg("\n");
//get an acessible gossip stone
const std::vector<ItemLocation*> gossipStoneLocations = GetAccessibleGossipStones(hintedLocation);
if (gossipStoneLocations.empty()) {
PlacementLog_Msg("\tNO GOSSIP STONES TO PLACE HINT\n\n");
return;
}
hintedLocation->SetAsHinted();
ItemLocation* gossipStone = RandomElement(gossipStoneLocations);
//form hint text
Text itemText = hintedLocation->GetPlacedItem().GetHintText().GetText();
if (hintedLocation->IsDungeon()) {
Text locationText = hintedLocation->GetParentRegion()->hintText->GetText();
Text finalHint = Hints::Prefix.GetText()+"#"+locationText+"# hoards #"+itemText+"#.";
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(finalHint.english);
PlacementLog_Msg("\n\n");
AddHint(finalHint, gossipStone, {QM_GREEN, QM_RED});
} else {
Text locationText = GetHintRegion(hintedLocation->GetParentRegion())->hintText->GetText();
Text finalHint = Hints::Prefix.GetText()+"#"+itemText+"# can be found at #"+locationText+"#.";
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(finalHint.english);
PlacementLog_Msg("\n\n");
AddHint(finalHint, gossipStone, {QM_RED, QM_GREEN});
}
}
static void CreateGoodItemHint() {
CreateRandomLocationHint(true);
}
static void CreateJunkHint() {
//duplicate junk hints are possible for now
const HintText* junkHint = RandomElement(Hints::junkHints);
LogicReset();
const std::vector<ItemLocation*> gossipStones = GetAccessibleLocations(gossipStoneLocations);
if (gossipStones.empty()) {
PlacementLog_Msg("\tNO GOSSIP STONES TO PLACE HINT\n\n");
return;
}
ItemLocation* gossipStone = RandomElement(gossipStones);
Text hintText = junkHint->GetText();
PlacementLog_Msg("\tMessage: ");
PlacementLog_Msg(hintText.english);
PlacementLog_Msg("\n\n");
AddHint(hintText, gossipStone);
}
static std::vector<ItemLocation*> CalculateBarrenRegions() {
std::vector<ItemLocation*> barrenLocations = {};
std::vector<ItemLocation*> potentiallyUsefulLocations = {};
for (ItemLocation* location : allLocations) {
if (location->GetPlacedItem().IsMajorItem()) {
AddElementsToPool(potentiallyUsefulLocations, std::vector{location});
} else {
if (location != &LinksPocket) { //Nobody cares to know if Link's Pocket is barren
AddElementsToPool(barrenLocations, std::vector{location});
}
}
}
//leave only locations at barren regions in the list
auto finalBarrenLocations = FilterFromPool(barrenLocations, [&potentiallyUsefulLocations](ItemLocation* loc){
for (ItemLocation* usefulLoc : potentiallyUsefulLocations) {
const HintText* barren = GetHintRegion(loc->GetParentRegion())->hintText;
const HintText* useful = GetHintRegion(usefulLoc->GetParentRegion())->hintText;
if (barren == useful) {
return false;
}
}
return true;
});
return finalBarrenLocations;
}
static void CreateTrialHints() {
//six trials
if (RandomGanonsTrials && GanonsTrialsCount.Is(6)) {
//get a random gossip stone
auto gossipStones = GetAccessibleGossipStones();
auto gossipStone = RandomElement(gossipStones, false);
//make hint
auto hintText = Hints::Prefix.GetText() + Hints::SixTrials.GetText();
AddHint(hintText, gossipStone, {QM_PINK});
//zero trials
} else if (RandomGanonsTrials && GanonsTrialsCount.Is(0)) {
//get a random gossip stone
auto gossipStones = GetAccessibleGossipStones();
auto gossipStone = RandomElement(gossipStones, false);
//make hint
auto hintText = Hints::Prefix.GetText() + Hints::ZeroTrials.GetText();
AddHint(hintText, gossipStone, {QM_YELLOW});
//4 or 5 required trials
} else if (GanonsTrialsCount.Is(5) || GanonsTrialsCount.Is(4)) {
//get skipped trials
std::vector<TrialInfo*> trials = {};
trials.assign(trialList.begin(), trialList.end());
auto skippedTrials = FilterFromPool(trials, [](TrialInfo* trial){return trial->IsSkipped();});
//create a hint for each skipped trial
for (auto& trial : skippedTrials) {
//get a random gossip stone
auto gossipStones = GetAccessibleGossipStones();
auto gossipStone = RandomElement(gossipStones, false);
//make hint
auto hintText = Hints::Prefix.GetText()+"#"+trial->GetName()+"#"+Hints::FourToFiveTrials.GetText();
AddHint(hintText, gossipStone, {QM_YELLOW});
}
//1 to 3 trials
} else if (GanonsTrialsCount.Value<u8>() >= 1 && GanonsTrialsCount.Value<u8>() <= 3) {
//get requried trials
std::vector<TrialInfo*> trials = {};
trials.assign(trialList.begin(), trialList.end());
auto requiredTrials = FilterFromPool(trials, [](TrialInfo* trial){return trial->IsRequired();});
//create a hint for each required trial
for (auto& trial : requiredTrials) {
//get a random gossip stone
auto gossipStones = GetAccessibleGossipStones();
auto gossipStone = RandomElement(gossipStones, false);
//make hint
auto hintText = Hints::Prefix.GetText()+"#"+trial->GetName()+"#"+Hints::OneToThreeTrials.GetText();
AddHint(hintText, gossipStone, {QM_PINK});
}
}
}
static void CreateGanonText() {
//funny ganon line
auto ganonText = RandomElement(Hints::ganonLines)->GetText();
CreateMessageFromTextObject(0x70CB, 0, 2, 3, AddColorsAndFormat(ganonText));
//Get the location of the light arrows
auto lightArrowLocation = FilterFromPool(allLocations, [](ItemLocation* loc){return loc->GetPlacedItem() == I_LightArrows;});
Text text;
//If there is no light arrow location, it was in the player's inventory at the start
if (lightArrowLocation.empty()) {
text = Hints::LightArrowLocation.GetText()+Hints::YourPocket.GetText();
} else {
text = Hints::LightArrowLocation.GetText()+GetHintRegion(lightArrowLocation[0]->GetParentRegion())->hintText->GetText();
}
text = text + "!";
CreateMessageFromTextObject(0x70CC, 0, 2, 3, AddColorsAndFormat(text));
}
void CreateAllHints() {
CreateGanonText();
PlacementLog_Msg("\nNOW CREATING HINTS\n");
const HintSetting& hintSetting = hintSettingTable[Settings::HintDistribution.Value<u8>()];
u8 remainingDungeonWothHints = hintSetting.dungeonsWothLimit;
u8 remainingDungeonBarrenHints = hintSetting.dungeonsBarrenLimit;
// Add 'always' location hints
if (hintSetting.distTable[static_cast<int>(HintType::Always)].copies > 0) {
// Only filter locations that had a random item placed at them (e.g. don't get cow locations if shuffle cows is off)
const auto alwaysHintLocations = FilterFromPool(allLocations, [](const ItemLocation* loc){
return loc->GetHintCategory() == HintCategory::Always &&
loc->IsHintable() && !loc->IsHintedAt();
});
for (ItemLocation* location : alwaysHintLocations) {
CreateLocationHint({location});
}
}
//Add 'trial' location hints
if (hintSetting.distTable[static_cast<int>(HintType::Trial)].copies > 0) {
CreateTrialHints();
}
//create a vector with each hint type proportional to it's weight in the distribution setting.
//ootr uses a weighted probability function to decide hint types, but selecting randomly from
//this vector will do for now
std::vector<HintType> remainingHintTypes = {};
for (HintDistributionSetting hds : hintSetting.distTable) {
remainingHintTypes.insert(remainingHintTypes.end(), hds.weight, hds.type);
}
Shuffle(remainingHintTypes);
//get barren regions
auto barrenLocations = CalculateBarrenRegions();
//while there are still gossip stones remaining
while (FilterFromPool(gossipStoneLocations, [](ItemLocation* loc){return loc->GetPlacedItem() == NoItem;}).size() != 0) {
//TODO: fixed hint types
if (remainingHintTypes.empty()) {
break;
}
//get a random hint type from the remaining hints
HintType type = RandomElement(remainingHintTypes, true);
PlacementLog_Msg("Attempting to make hint of type: ");
PlacementLog_Msg(std::to_string(static_cast<int>(type)));
PlacementLog_Msg("\n");
//create the appropriate hint for the type
if (type == HintType::Woth) {
CreateWothHint(&remainingDungeonWothHints);
} else if (type == HintType::Barren) {
CreateBarrenHint(&remainingDungeonBarrenHints, barrenLocations);
} else if (type == HintType::Sometimes){
std::vector<ItemLocation*> sometimesHintLocations = FilterFromPool(allLocations, [](ItemLocation* loc){return loc->GetHintCategory() == HintCategory::Sometimes && loc->IsHintable() && !loc->IsHintedAt();});
CreateLocationHint(sometimesHintLocations);
} else if (type == HintType::Random) {
CreateRandomLocationHint();
} else if (type == HintType::Item) {
CreateGoodItemHint();
} else if (type == HintType::Song){
std::vector<ItemLocation*> songHintLocations = FilterFromPool(allLocations, [](ItemLocation* loc){return loc->IsCategory(Category::cSong) && loc->IsHintable() && !loc->IsHintedAt();});
CreateLocationHint(songHintLocations);
} else if (type == HintType::Overworld){
std::vector<ItemLocation*> overworldHintLocations = FilterFromPool(allLocations, [](ItemLocation* loc){return loc->IsOverworld() && loc->IsHintable() && !loc->IsHintedAt();});
CreateLocationHint(overworldHintLocations);
} else if (type == HintType::Dungeon){
std::vector<ItemLocation*> dungeonHintLocations = FilterFromPool(allLocations, [](ItemLocation* loc){return loc->IsDungeon() && loc->IsHintable() && !loc->IsHintedAt();});
CreateLocationHint(dungeonHintLocations);
} else if (type == HintType::Junk) {
CreateJunkHint();
}
}
//Getting gossip stone locations temporarily sets one location to not be reachable.
//Call the function one last time to get rid of false positives on locations not
//being reachable.
GetAccessibleLocations({});
}
| 40.343053 | 212 | 0.669005 | [
"vector"
] |
6f15b419e5aa853f051ed141dec7872ed5b18448 | 4,634 | cc | C++ | asylo/identity/sgx/dcap_intel_architectural_enclave_interface.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | asylo/identity/sgx/dcap_intel_architectural_enclave_interface.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | asylo/identity/sgx/dcap_intel_architectural_enclave_interface.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 1 | 2019-01-02T22:04:21.000Z | 2019-01-02T22:04:21.000Z | /*
*
* Copyright 2019 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "asylo/identity/sgx/dcap_intel_architectural_enclave_interface.h"
#include <vector>
#include "include/sgx_key.h"
#include "include/sgx_report.h"
#include "QuoteGeneration/psw/pce_wrapper/inc/sgx_pce.h"
namespace asylo {
namespace sgx {
namespace {
Status PceErrorToStatus(sgx_pce_error_t pce_error) {
switch (pce_error) {
case SGX_PCE_SUCCESS:
return Status::OkStatus();
case SGX_PCE_UNEXPECTED:
return Status(error::GoogleError::INTERNAL, "Unexpected error");
case SGX_PCE_OUT_OF_EPC:
return Status(error::GoogleError::INTERNAL,
"Not enough EPC to load the PCE");
case SGX_PCE_INTERFACE_UNAVAILABLE:
return Status(error::GoogleError::INTERNAL, "Interface unavailable");
case SGX_PCE_CRYPTO_ERROR:
return Status(error::GoogleError::INTERNAL,
"Evaluation of REPORT.REPORTDATA failed");
case SGX_PCE_INVALID_PARAMETER:
return Status(error::GoogleError::INVALID_ARGUMENT, "Invalid parameter");
case SGX_PCE_INVALID_REPORT:
return Status(error::GoogleError::INVALID_ARGUMENT, "Invalid report");
case SGX_PCE_INVALID_TCB:
return Status(error::GoogleError::INVALID_ARGUMENT, "Invalid TCB");
case SGX_PCE_INVALID_PRIVILEGE:
return Status(error::GoogleError::PERMISSION_DENIED,
"Report must have the PROVISION_KEY attribute bit set");
default:
return Status(error::GoogleError::UNKNOWN, "Unknown error");
}
}
} // namespace
Status DcapIntelArchitecturalEnclaveInterface::GetPceTargetinfo(
Targetinfo *targetinfo, uint16_t *pce_svn) {
static_assert(
sizeof(Targetinfo) == sizeof(sgx_target_info_t),
"Targetinfo struct is not the same size as sgx_target_info_t struct");
sgx_pce_error_t result = sgx_pce_get_target(
reinterpret_cast<sgx_target_info_t *>(targetinfo), pce_svn);
return PceErrorToStatus(result);
}
Status DcapIntelArchitecturalEnclaveInterface::GetPceInfo(
const Report &report, absl::Span<const uint8_t> ppid_encryption_key,
uint8_t crypto_suite, std::string *ppid_encrypted, uint16_t *pce_svn,
uint16_t *pce_id, uint8_t *signature_scheme) {
static_assert(sizeof(Report) == sizeof(sgx_report_t),
"Report struct is not the same size as sgx_report_t struct");
std::vector<uint8_t> ppid_encrypted_tmp(ppid_encrypted->size());
uint32_t encrypted_ppid_out_size = 0;
sgx_pce_error_t result = sgx_get_pce_info(
reinterpret_cast<const sgx_report_t *>(&report),
ppid_encryption_key.data(), ppid_encryption_key.size(), crypto_suite,
ppid_encrypted_tmp.data(), ppid_encrypted_tmp.size(),
&encrypted_ppid_out_size, pce_svn, pce_id, signature_scheme);
if (result == SGX_PCE_SUCCESS) {
ppid_encrypted_tmp.resize(encrypted_ppid_out_size);
ppid_encrypted->insert(ppid_encrypted->begin(), ppid_encrypted_tmp.cbegin(),
ppid_encrypted_tmp.cend());
ppid_encrypted->resize(encrypted_ppid_out_size);
}
return PceErrorToStatus(result);
}
Status DcapIntelArchitecturalEnclaveInterface::PceSignReport(
const Report &report, uint16_t target_pce_svn,
UnsafeBytes<kCpusvnSize> target_cpu_svn, std::string *signature) {
static_assert(sizeof(target_cpu_svn) == sizeof(sgx_cpu_svn_t),
"target_cpusvn is not the same size as sgx_cpu_svn_t struct");
std::vector<uint8_t> signature_tmp(signature->size());
uint32_t signature_out_size = 0;
sgx_pce_error_t result = sgx_pce_sign_report(
&target_pce_svn, reinterpret_cast<sgx_cpu_svn_t *>(&target_cpu_svn),
reinterpret_cast<const sgx_report_t *>(&report), signature_tmp.data(),
signature_tmp.size(), &signature_out_size);
if (result == SGX_PCE_SUCCESS) {
signature_tmp.resize(signature_out_size);
signature->insert(signature->begin(), signature_tmp.cbegin(),
signature_tmp.cend());
signature->resize(signature_out_size);
}
return PceErrorToStatus(result);
}
} // namespace sgx
} // namespace asylo
| 38.297521 | 80 | 0.732628 | [
"vector"
] |
6f17cdeee4f3613f867dfe94526d596d80444260 | 541 | hpp | C++ | src/targets/gpu/include/migraphx/gpu/compile_hip.hpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | 72 | 2018-12-06T18:31:17.000Z | 2022-03-30T15:01:02.000Z | src/targets/gpu/include/migraphx/gpu/compile_hip.hpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | 1,006 | 2018-11-30T16:32:33.000Z | 2022-03-31T22:43:39.000Z | src/targets/gpu/include/migraphx/gpu/compile_hip.hpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | 36 | 2019-05-07T10:41:46.000Z | 2022-03-28T15:59:56.000Z | #ifndef MIGRAPHX_GUARD_RTGLIB_COMPILE_HIP_HPP
#define MIGRAPHX_GUARD_RTGLIB_COMPILE_HIP_HPP
#include <migraphx/config.hpp>
#include <migraphx/filesystem.hpp>
#include <migraphx/compile_src.hpp>
#include <string>
#include <utility>
#include <vector>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {
std::vector<std::vector<char>>
compile_hip_src(const std::vector<src_file>& srcs, std::string params, const std::string& arch);
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
#endif
| 23.521739 | 96 | 0.787431 | [
"vector"
] |
6f1e502d3e563da273e4f3372afb22fa4cf7bab6 | 5,412 | cpp | C++ | client/moc_changepassworddialog.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 1 | 2015-08-23T11:03:58.000Z | 2015-08-23T11:03:58.000Z | client/moc_changepassworddialog.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | null | null | null | client/moc_changepassworddialog.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 3 | 2016-12-05T02:43:52.000Z | 2021-06-30T21:35:46.000Z | /****************************************************************************
** Meta object code from reading C++ file 'changepassworddialog.h'
**
** Created: Wed Jun 24 21:01:08 2009
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "changepassworddialog.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'changepassworddialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_MoodBox__ChangePasswordRequest[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
2, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// signals: signature, parameters, type, tag, flags
45, 32, 31, 31, 0x05,
// slots: signature, parameters, type, tag, flags
143, 124, 31, 31, 0x08,
0 // eod
};
static const char qt_meta_stringdata_MoodBox__ChangePasswordRequest[] = {
"MoodBox::ChangePasswordRequest\0\0"
"fault,result\0"
"changePasswordRequestCompleted(Fault,AccountResultCode::AccountResultC"
"odeEnum)\0"
"state,fault,result\0"
"onGetChangePasswordRequestResult(QVariant,Fault,AccountResultCode::Acc"
"ountResultCodeEnum)\0"
};
const QMetaObject MoodBox::ChangePasswordRequest::staticMetaObject = {
{ &ServerRequest::staticMetaObject, qt_meta_stringdata_MoodBox__ChangePasswordRequest,
qt_meta_data_MoodBox__ChangePasswordRequest, 0 }
};
const QMetaObject *MoodBox::ChangePasswordRequest::metaObject() const
{
return &staticMetaObject;
}
void *MoodBox::ChangePasswordRequest::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MoodBox__ChangePasswordRequest))
return static_cast<void*>(const_cast< ChangePasswordRequest*>(this));
return ServerRequest::qt_metacast(_clname);
}
int MoodBox::ChangePasswordRequest::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = ServerRequest::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: changePasswordRequestCompleted((*reinterpret_cast< Fault(*)>(_a[1])),(*reinterpret_cast< AccountResultCode::AccountResultCodeEnum(*)>(_a[2]))); break;
case 1: onGetChangePasswordRequestResult((*reinterpret_cast< QVariant(*)>(_a[1])),(*reinterpret_cast< Fault(*)>(_a[2])),(*reinterpret_cast< AccountResultCode::AccountResultCodeEnum(*)>(_a[3]))); break;
default: ;
}
_id -= 2;
}
return _id;
}
// SIGNAL 0
void MoodBox::ChangePasswordRequest::changePasswordRequestCompleted(Fault _t1, AccountResultCode::AccountResultCodeEnum _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
static const uint qt_meta_data_MoodBox__ChangePasswordDialog[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
3, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// slots: signature, parameters, type, tag, flags
44, 31, 30, 30, 0x0a,
117, 30, 30, 30, 0x0a,
138, 30, 30, 30, 0x08,
0 // eod
};
static const char qt_meta_stringdata_MoodBox__ChangePasswordDialog[] = {
"MoodBox::ChangePasswordDialog\0\0"
"fault,result\0"
"onUpdatePasswordResponse(Fault,AccountResultCode::AccountResultCodeEnu"
"m)\0"
"onRequestCancelled()\0on_okButton_clicked()\0"
};
const QMetaObject MoodBox::ChangePasswordDialog::staticMetaObject = {
{ &ServerDialog::staticMetaObject, qt_meta_stringdata_MoodBox__ChangePasswordDialog,
qt_meta_data_MoodBox__ChangePasswordDialog, 0 }
};
const QMetaObject *MoodBox::ChangePasswordDialog::metaObject() const
{
return &staticMetaObject;
}
void *MoodBox::ChangePasswordDialog::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MoodBox__ChangePasswordDialog))
return static_cast<void*>(const_cast< ChangePasswordDialog*>(this));
if (!strcmp(_clname, "ChangePasswordDialogClass"))
return static_cast< ChangePasswordDialogClass*>(const_cast< ChangePasswordDialog*>(this));
return ServerDialog::qt_metacast(_clname);
}
int MoodBox::ChangePasswordDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = ServerDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: onUpdatePasswordResponse((*reinterpret_cast< Fault(*)>(_a[1])),(*reinterpret_cast< AccountResultCode::AccountResultCodeEnum(*)>(_a[2]))); break;
case 1: onRequestCancelled(); break;
case 2: on_okButton_clicked(); break;
default: ;
}
_id -= 3;
}
return _id;
}
QT_END_MOC_NAMESPACE
| 35.142857 | 209 | 0.661678 | [
"object"
] |
6f24d973858f00d24035621b8836a338f088b5e3 | 8,092 | cpp | C++ | snark-logic/libs-source/multiprecision/performance/gcd_bench.cpp | podlodkin/podlodkin-freeton-year-control | e394c11f2414804d2fbde93a092ae589d4359739 | [
"MIT"
] | 1 | 2021-09-14T18:09:38.000Z | 2021-09-14T18:09:38.000Z | snark-logic/libs-source/multiprecision/performance/gcd_bench.cpp | podlodkin/podlodkin-freeton-year-control | e394c11f2414804d2fbde93a092ae589d4359739 | [
"MIT"
] | null | null | null | snark-logic/libs-source/multiprecision/performance/gcd_bench.cpp | podlodkin/podlodkin-freeton-year-control | e394c11f2414804d2fbde93a092ae589d4359739 | [
"MIT"
] | 1 | 2021-08-31T06:27:19.000Z | 2021-08-31T06:27:19.000Z | // Copyright 2020 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
#include <iostream>
#include <benchmark/benchmark.h>
#include <nil/crypto3/multiprecision/cpp_int.hpp>
#include <nil/crypto3/multiprecision/gmp.hpp>
#include <boost/random.hpp>
#include <cmath>
#include <immintrin.h>
using namespace nil::crypto3::multiprecision;
using namespace boost::random;
namespace boost {
namespace multiprecision {
namespace backends {
template<unsigned MinBits1,
unsigned MaxBits1,
cpp_integer_type SignType1,
cpp_int_check_type Checked1,
class Allocator1>
inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if_c<
!is_trivial_cpp_int<cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>>::value>::type
eval_gcd_old(cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& result,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& a,
const cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1>& b) {
using default_ops::eval_get_sign;
using default_ops::eval_is_zero;
using default_ops::eval_lsb;
if (a.size() == 1) {
eval_gcd(result, b, *a.limbs());
return;
}
if (b.size() == 1) {
eval_gcd(result, a, *b.limbs());
return;
}
cpp_int_backend<MinBits1, MaxBits1, SignType1, Checked1, Allocator1> u(a), v(b);
int s = eval_get_sign(u);
/* GCD(0,x) := x */
if (s < 0) {
u.negate();
} else if (s == 0) {
result = v;
return;
}
s = eval_get_sign(v);
if (s < 0) {
v.negate();
} else if (s == 0) {
result = u;
return;
}
/* Let shift := lg K, where K is the greatest power of 2
dividing both u and v. */
unsigned us = eval_lsb(u);
unsigned vs = eval_lsb(v);
int shift = (std::min)(us, vs);
eval_right_shift(u, us);
eval_right_shift(v, vs);
do {
/* Now u and v are both odd, so diff(u, v) is even.
Let u = min(u, v), v = diff(u, v)/2. */
s = u.compare(v);
if (s > 0)
u.swap(v);
if (s == 0)
break;
while (((u.size() + 2 < v.size()) && (v.size() * 100 / u.size() > 105)) ||
((u.size() <= 2) && (v.size() > 4))) {
//
// Speical case: if u and v differ considerably in size, then a Euclid step
// is more efficient as we reduce v by several limbs in one go.
// Unfortunately it requires an expensive long division:
//
eval_modulus(v, v, u);
u.swap(v);
}
if (v.size() <= 2) {
//
// Special case: if v has no more than 2 limbs
// then we can reduce u and v to a pair of integers and perform
// direct integer gcd:
//
if (v.size() == 1)
u = eval_gcd(*v.limbs(), *u.limbs());
else {
double_limb_type i = v.limbs()[0] | (static_cast<double_limb_type>(v.limbs()[1])
<< sizeof(limb_type) * CHAR_BIT);
double_limb_type j = (u.size() == 1) ?
*u.limbs() :
u.limbs()[0] | (static_cast<double_limb_type>(u.limbs()[1])
<< sizeof(limb_type) * CHAR_BIT);
u = eval_gcd(i, j);
}
break;
}
//
// Regular binary gcd case:
//
eval_subtract(v, u);
vs = eval_lsb(v);
eval_right_shift(v, vs);
} while (true);
result = u;
eval_left_shift(result, shift);
}
} // namespace backends
} // namespace multiprecision
} // namespace boost
template<class T>
std::tuple<std::vector<T>, std::vector<T>, std::vector<T>>& get_test_vector(unsigned bits) {
static std::map<unsigned, std::tuple<std::vector<T>, std::vector<T>, std::vector<T>>> data;
std::tuple<std::vector<T>, std::vector<T>, std::vector<T>>& result = data[bits];
if (std::get<0>(result).size() == 0) {
mt19937 mt;
uniform_int_distribution<T> ui(T(1) << (bits - 1), T(1) << bits);
std::vector<T>& a = std::get<0>(result);
std::vector<T>& b = std::get<1>(result);
std::vector<T>& c = std::get<2>(result);
for (unsigned i = 0; i < 1000; ++i) {
a.push_back(ui(mt));
b.push_back(ui(mt));
if (b.back() > a.back())
b.back().swap(a.back());
c.push_back(0);
}
}
return result;
}
template<class T>
std::vector<T>& get_test_vector_a(unsigned bits) {
return std::get<0>(get_test_vector<T>(bits));
}
template<class T>
std::vector<T>& get_test_vector_b(unsigned bits) {
return std::get<1>(get_test_vector<T>(bits));
}
template<class T>
std::vector<T>& get_test_vector_c(unsigned bits) {
return std::get<2>(get_test_vector<T>(bits));
}
template<typename T>
static void BM_gcd_old(benchmark::State& state) {
int bits = state.range(0);
std::vector<T>& a = get_test_vector_a<T>(bits);
std::vector<T>& b = get_test_vector_b<T>(bits);
std::vector<T>& c = get_test_vector_c<T>(bits);
for (auto _ : state) {
for (unsigned i = 0; i < a.size(); ++i)
eval_gcd_old(c[i].backend(), a[i].backend(), b[i].backend());
}
state.SetComplexityN(bits);
}
template<typename T>
static void BM_gcd_current(benchmark::State& state) {
int bits = state.range(0);
std::vector<T>& a = get_test_vector_a<T>(bits);
std::vector<T>& b = get_test_vector_b<T>(bits);
std::vector<T>& c = get_test_vector_c<T>(bits);
for (auto _ : state) {
for (unsigned i = 0; i < a.size(); ++i)
eval_gcd(c[i].backend(), a[i].backend(), b[i].backend());
}
state.SetComplexityN(bits);
}
constexpr unsigned lower_range = 512;
constexpr unsigned upper_range = 1 << 15;
BENCHMARK_TEMPLATE(BM_gcd_old, cpp_int)
->RangeMultiplier(2)
->Range(lower_range, upper_range)
->Unit(benchmark::kMillisecond)
->Complexity();
BENCHMARK_TEMPLATE(BM_gcd_current, cpp_int)
->RangeMultiplier(2)
->Range(lower_range, upper_range)
->Unit(benchmark::kMillisecond)
->Complexity();
BENCHMARK_TEMPLATE(BM_gcd_old, cpp_int)
->RangeMultiplier(2)
->Range(lower_range, upper_range)
->Unit(benchmark::kMillisecond)
->Complexity();
BENCHMARK_TEMPLATE(BM_gcd_current, mpz_int)
->RangeMultiplier(2)
->Range(lower_range, upper_range)
->Unit(benchmark::kMillisecond)
->Complexity();
BENCHMARK_TEMPLATE(BM_gcd_current, mpz_int)
->RangeMultiplier(2)
->Range(lower_range, upper_range)
->Unit(benchmark::kMillisecond)
->Complexity();
BENCHMARK_MAIN();
| 36.125 | 119 | 0.494686 | [
"vector"
] |
6f25efaa454dbb669c9f9ecd54a7bcfb65a411a7 | 18,716 | cpp | C++ | src/plugin/Synthesize/SynthVHDL.cpp | salaheddinhetalani/Master_Thesis | 665c7a45f06559217b492e8c9f98bd7723c7a1dc | [
"MIT"
] | 1 | 2021-09-23T07:12:55.000Z | 2021-09-23T07:12:55.000Z | src/plugin/Synthesize/SynthVHDL.cpp | salaheddinhetalani/Master_Thesis | 665c7a45f06559217b492e8c9f98bd7723c7a1dc | [
"MIT"
] | null | null | null | src/plugin/Synthesize/SynthVHDL.cpp | salaheddinhetalani/Master_Thesis | 665c7a45f06559217b492e8c9f98bd7723c7a1dc | [
"MIT"
] | null | null | null | //
// Created by pmorku on 01.12.17.
//
#include <fstream>
#include <assert.h>
#include "../../optimizePPA/OptimizeSlave.h"
#include "../../optimizePPA/OptimizeMaster.h"
#include "../../optimizePPA/OptimizeOperations.h"
#include "OrganizeOpStmts.h"
#include "SynthVHDL.h"
#include "PrintStmt.h"
#include <Synthesize/RelocateOpStmts.h>
#include <Synthesize/VHDLPrintVisitor.h>
#include <StmtNodeAlloc.h>
#include <Synthesize/OperationPruning.h>
#define MERGE_OPERATION_COMMITMENTS 1
#define ENABLE_RESOURCE_SHARING 0
using namespace SCAM;
SynthVHDL::SynthVHDL(Module *module) : module(module) {
// use the optimized version of the state map
optimizeCommunicationFSM();
// resolve signals that combinational logic is sensitive to
resolveSensitivityList();
// structurize operations
organizedOpStmts = new OrganizeOpStmts(stateMap, module);
operationTable = organizedOpStmts->getOperationEntryTable();
ss << types();
ss << includes();
ss << entities();
ss << functions();
ss << architecture_synch();
}
std::string SynthVHDL::types() {
std::stringstream typeStream;
typeStream << "library ieee;\n";
typeStream << "use ieee.std_logic_1164.all;\n";
typeStream << "use ieee.numeric_std.all;\n";
typeStream << "\n";
typeStream << "package " + module->getName() << "_types is\n";
#if MERGE_OPERATION_COMMITMENTS
//Assignment enumeration
#if ENABLE_RESOURCE_SHARING
auto assignGroupTable = organizedOpStmts->getSeqAssignmentGroupTable();
#else
auto assignGroupTable = organizedOpStmts->getAssignmentGroupTable();
#endif
typeStream << "\ttype " + module->getName() + "_assign_t is (";
for (auto op_it = assignGroupTable.begin();
op_it != assignGroupTable.end(); op_it++) {
typeStream << (*op_it)->getName();
if (std::next(op_it) != assignGroupTable.end()) typeStream << ", ";
else typeStream << ");\n";
}
#else
//Operation enumeration
typeStream << "\ttype " + module->getName() + "_operation_t is (";
for (auto op_it = operationTable.begin(); op_it != operationTable.end(); op_it++) {
typeStream << (*op_it).second->getOperationName();
if (std::next(op_it) != operationTable.end()) typeStream << ", ";
else typeStream << ");\n";
}
#endif
//Other enumerators
for (auto type_it: DataTypes::getDataTypeMap()) {
std::string typeName = type_it.second->getName();
if (type_it.second->isEnumType()) {
if (typeName == module->getName() + "_SECTIONS") {
// commenting out SECTIONS enumerator because it is not used
typeStream << "\t--type ";
} else {
typeStream << "\ttype ";
}
typeStream << typeName << " is (";
for (auto iterator = type_it.second->getEnumValueMap().begin();
iterator != type_it.second->getEnumValueMap().end(); ++iterator) {
typeStream << iterator->first;
if (std::next(iterator) != type_it.second->getEnumValueMap().end()) {
typeStream << ", ";
}
}
typeStream << ");\n";
}
}
//Composite variables
for (auto type: DataTypes::getDataTypeMap()) {
if (type.second->isCompoundType()) {
std::string typeName = type.second->getName();
typeStream << "\ttype " + typeName << " is record\n";
for (auto sub_var: type.second->getSubVarMap()) {
typeStream << "\t\t" + sub_var.first << ": " << convertDataType(sub_var.second->getName()) << ";\n";
}
typeStream << "\tend record;\n";
}
}
typeStream << "end package " + module->getName() << "_types;\n\n";
return typeStream.str();
}
std::string SynthVHDL::includes() {
std::stringstream includeStream;
includeStream << "library ieee;\n";
includeStream << "use ieee.std_logic_1164.all;\n";
includeStream << "use ieee.numeric_std.all;\n";
includeStream << "use work." + module->getName() + "_types.all;\n\n";
return includeStream.str();
}
std::string SynthVHDL::entities() {
std::stringstream entityStream;
entityStream << "entity " + module->getName() + " is\n";
entityStream << "port(\t\n";
entityStream << "\tclk: in std_logic;\n";
entityStream << "\trst: in std_logic";
for (auto port : module->getPorts()) {
std::string name = port.first;
auto interface = port.second->getInterface();
// we use hardcoded clk signal and not the one that comes from module
if (name != "clk") {
entityStream << ";\n"; // finish the previous line
// data signal
entityStream << "\t" << name << "_sig: " << port.second->getInterface()->getDirection() << " "
<< convertDataType(port.second->getDataType()->getName());
// synchronisation signals
if (interface->isMasterOut()) {
entityStream << ";\n"; // finish the previous line
entityStream << "\t" + name + "_notify: out boolean";
} else if (interface->isSlaveIn()) {
entityStream << ";\n"; // finish the previous line
entityStream << "\t" + name + "_sync: in boolean";
} else if (interface->isBlocking()) {
entityStream << ";\n"; // finish the previous line
entityStream << "\t" + name + "_sync: in boolean;\n";
entityStream << "\t" + name + "_notify: out boolean";
}
}
}
entityStream << ");\n"; // finish the previous line
entityStream << "end " + module->getName() << ";\n\n";
return entityStream.str();
}
std::string SynthVHDL::architecture_synch() {
std::stringstream archStream;
//<editor-fold desc="Signal declarations">
archStream << "architecture " << module->getName() << "_arch of " + module->getName() + " is\n";
// define signals
archStream << "\tsignal active_state: " << module->getName() << "_state_t;\n";
#if MERGE_OPERATION_COMMITMENTS
archStream << "\tsignal active_assignment: " << module->getName() << "_assign_t;\n";
#else
archStream << "\tsignal active_operation: " << module->getName() << "_operation_t;\n";
#endif
// add variables
for (auto var_it: stateTopVarMap) {
archStream << "\tsignal " << var_it.second->getName();
archStream << ": " << convertDataType(var_it.second->getDataType()->getName()) << ";\n";
}
#if ENABLE_RESOURCE_SHARING
// add variables used for shared resources
for (auto adder_it: organizedOpStmts->getSharedAdders()->getAdderList()) {
for (auto var_it: adder_it->getVariableOperands()) {
archStream << "\tsignal " << var_it->getOperandName();
archStream << ": " << convertDataType(var_it->getDataType()->getName()) << ";\n";
}
}
#endif
archStream << "\n";
// description can be found one line below in the code
archStream << "\t-- Declaring state signals that are used by ITL properties for OneSpin\n";
for (auto state : stateMap) {
if (state.second->isInit()) continue;
archStream << "\tsignal " << state.second->getName() << ": boolean;\n";
}
archStream << "\n";
//</editor-fold>
// begin of architecture implementation
archStream << "begin\n";
#if ENABLE_RESOURCE_SHARING
archStream << "\t-- Shared resources\n";
for (auto var_it: organizedOpStmts->getSharedAdders()->getAdderList()) {
archStream << "\t" << VHDLPrintVisitor::toString(var_it->getAdderInst());
}
archStream << "\n";
#endif
//<editor-fold desc="Combinational logic that selects current operation">
archStream << "\t-- Combinational logic that selects current operation\n";
archStream << "\tprocess (";
archStream << printSensitivityList();
archStream << ")\n";
archStream << "\tbegin\n";
#if ENABLE_RESOURCE_SHARING
// default values for shared adders inputs
for (auto var_it: organizedOpStmts->getSharedAdders()->getAdderList()) {
archStream << "\t\t" << VHDLPrintVisitor::toString(var_it->getDefaultAssignmentLhs());
archStream << "\t\t" << VHDLPrintVisitor::toString(var_it->getDefaultAssignmentRhs());
}
#endif
archStream << "\t\tcase active_state is\n";
for (auto state_it: stateMap) {
bool commentOutEndIf = false;
if (state_it.second->isInit()) continue;
archStream << "\t\twhen " << printStateName(state_it.second) << " =>\n";
auto op_list = state_it.second->getOutgoingOperationList();
for (auto op_it = op_list.begin(); op_it != op_list.end(); ++op_it) {
auto opEntry = organizedOpStmts->getOperationEntry((*op_it)->getOp_id());
if (op_it == op_list.begin()) {
if (op_list.size() == 1) {
archStream << "\t\t\t--if (";
commentOutEndIf = true;
} else {
archStream << "\t\t\tif (";
}
} else if (std::next(op_it) == op_list.end()) {
// make last operation as default, saves some logic
archStream << "\t\t\telse--if(";
} else {
archStream << "\t\t\telsif (";
}
archStream << printAssumptions(opEntry->getOperation()->getAssumptionList());
archStream << ") then \n";
#if MERGE_OPERATION_COMMITMENTS
archStream << "\t\t\t\t-- Operation: " << opEntry->getOperationName() << ";\n";
#if ENABLE_RESOURCE_SHARING
archStream << "\t\t\t\tactive_assignment <= " << opEntry->getAssignmentGroup()->getSeqAssignmentGroup()->getName() << ";\n";
for (auto assign_it : opEntry->getAssignmentGroup()->getCombAssignments()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
#else
archStream << "\t\t\t\tactive_assignment <= " << opEntry->getAssignmentGroup()->getName() << ";\n";
#endif
#else
archStream << "\t\t\t\tactive_operation <= " << opEntry->getOperationName() << ";\n";
#if ENABLE_RESOURCE_SHARING
for (auto assign_it : opEntry->getAssignmentGroup()->getCombAssignments()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
#endif
#endif
}
if (commentOutEndIf) archStream << "\t\t\t--end if;\n";
else archStream << "\t\t\tend if;\n";
}
archStream << "\t\tend case;\n";
archStream << "\tend process;\n\n";
//</editor-fold>
//<editor-fold desc="Main process">
archStream << "\t-- Main process\n";
archStream << "\tprocess (clk, rst)\n";
archStream << "\tbegin\n";
archStream << "\t\tif (rst = '1') then\n";
for (auto assign_it : organizedOpStmts->getResetAssignmentGroup()->getCompleteAssignments()) {
archStream << "\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
archStream << "\t\telsif (clk = '1' and clk'event) then\n";
#if MERGE_OPERATION_COMMITMENTS
archStream << "\t\t\tcase active_assignment is\n";
#if ENABLE_RESOURCE_SHARING
for (auto assignGroup_it : organizedOpStmts->getSeqAssignmentGroupTable()) {
archStream << "\t\t\twhen " << assignGroup_it->getName() << " =>\n";
for (auto assign_it : assignGroup_it->getAssignmentSet()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
}
#else
for (auto assignGroup_it : organizedOpStmts->getAssignmentGroupTable()) {
archStream << "\t\t\twhen " << assignGroup_it->getName() << " =>\n";
for (auto assign_it : assignGroup_it->getCompleteAssignments()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
}
#endif
#else
archStream << "\t\t\tcase active_operation is\n";
for (auto op_it : organizedOpStmts->getOperationEntryTable()) {
archStream << "\t\t\twhen " << op_it.second->getOperationName() << " =>\n";
#if ENABLE_RESOURCE_SHARING
for (auto assign_it : op_it.second->getAssignmentGroup()->getSeqAssignmentGroup()->getAssignmentSet()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
#else
for (auto assign_it : op_it.second->getAssignmentGroup()->getCompleteAssignments()) {
archStream << "\t\t\t\t" << VHDLPrintVisitor::toString(assign_it);
}
#endif
}
#endif
archStream << "\t\t\tend case;\n";
archStream << "\t\tend if;\n";
archStream << "\tend process;\n\n";
//</editor-fold>
// description can be found one line below in the code
archStream << "\t-- Assigning state signals that are used by ITL properties for OneSpin\n";
for (auto state : stateMap) {
if (state.second->isInit()) continue;
archStream << "\t" << state.second->getName() << " <= active_state = " << printStateName(state.second)
<< ";\n";
}
archStream << "\nend " + module->getName() << "_arch;\n\n";
return archStream.str();
}
SynthVHDL::~SynthVHDL() {
delete organizedOpStmts;
}
std::string SynthVHDL::print() {
return ss.str();
}
std::string SynthVHDL::printAssumptions(const std::vector<Expr *> &exprList) {
std::stringstream assumptionsStream;
if (exprList.empty()) return "true";
for (auto expr = exprList.begin(); expr != exprList.end(); ++expr) {
assumptionsStream << VHDLPrintVisitor::toString(*expr);
if (expr != --exprList.end()) {
assumptionsStream << " and ";
}
}
return assumptionsStream.str();
}
void SynthVHDL::resolveSensitivityList() {
for (auto state_it: stateMap) {
if (state_it.second->isInit()) continue;
auto op_list = state_it.second->getOutgoingOperationList();
for (auto op_it = op_list.begin(); op_it != op_list.end(); ++op_it) {
for (auto assumption_it : (*op_it)->getAssumptionList()) {
auto tempSet1 = ExprVisitor::getUsedSynchSignals(assumption_it);
sensListSyncSignals.insert(tempSet1.begin(), tempSet1.end());
auto tempSet2 = ExprVisitor::getUsedDataSignals(assumption_it);
sensListDataSignals.insert(tempSet2.begin(), tempSet2.end());
auto tempSet3 = ExprVisitor::getUsedVariables(assumption_it);
sensListVars.insert(tempSet3.begin(), tempSet3.end());
}
}
}
}
std::string SynthVHDL::printSensitivityList() {
std::stringstream sensitivityListStream;
sensitivityListStream << "active_state";
for (auto it : sensListSyncSignals) {
sensitivityListStream << ", ";
sensitivityListStream << VHDLPrintVisitor::toString(it);
}
for (auto it : sensListDataSignals) {
sensitivityListStream << ", ";
sensitivityListStream << it->getFullName();
}
for (auto it : sensListVars) {
sensitivityListStream << ", ";
sensitivityListStream << it->getFullName();
}
return sensitivityListStream.str();
}
std::string SynthVHDL::convertDataType(std::string dataTypeName) {
if (dataTypeName == "bool") {
return "boolean";
} else if (dataTypeName == "int") {
// FIXME find way to determine variable sizes
return "signed(31 downto 0)";
} else if (dataTypeName == "unsigned") {
// FIXME find way to determine variable sizes
return "unsigned(31 downto 0)";
} else {
return dataTypeName;
}
}
std::string SynthVHDL::printStateName(State *state) {
std::stringstream stateNameStream;
stateNameStream << "st_" << state->getName();
return stateNameStream.str();
}
std::string SynthVHDL::functions() {
std::stringstream ss;
if(module->getFunctionMap().empty()) return ss.str();
ss << "\n\n-- FUNCTIONS --\n";
for(auto function: module->getFunctionMap()){
ss << "macro " + function.first << "(";
auto paramMap = function.second->getParamMap();
for (auto param = paramMap.begin(); param != paramMap.end(); ++param) {
if(param->second->getDataType()->isCompoundType()){
for (auto iterator = param->second->getDataType()->getSubVarMap().begin(); iterator != param->second->getDataType()->getSubVarMap().end(); ++iterator) {
ss << param->first << "_"<< iterator->first << ": "<< iterator->second->getName();
if(iterator != --param->second->getDataType()->getSubVarMap().end()) ss << ";";
}
}else{
ss << param->first << ": " << param->second->getDataType()->getName();
}
if(param != --paramMap.end()) ss << ";";
}
ss<< ") : "<< function.second->getReturnType()->getName() << " := \n";
if(function.second->getReturnValueConditionList().empty()) throw std::runtime_error(" No return value for function "+function.first+"()");
auto j = function.second->getReturnValueConditionList().size();
for(auto returnValue: function.second->getReturnValueConditionList()){
ss << "\t";
//Any conditions?
if(!returnValue.second.empty()){
if(j == function.second->getReturnValueConditionList().size()){
ss << "if(";
}else ss << "elsif(";
auto i = returnValue.second.size();
for(auto cond: returnValue.second ){
ss << VHDLPrintVisitor::toString(cond);
if(i>1) ss << " and ";
--i;
}
ss << ") then ";
ss << VHDLPrintVisitor::toString(returnValue.first->getReturnValue()) << "\n";
}else ss << VHDLPrintVisitor::toString(returnValue.first->getReturnValue()) << ";\n";
--j;
}
if(function.second->getReturnValueConditionList().size()>1) ss << "end if;\n";
ss << "end macro; \n\n";
}
return ss.str();
}
void SynthVHDL::optimizeCommunicationFSM() {
OptimizeMaster optimizeMaster(module->getFSM()->getStateMap(), module, module->getFSM()->getOperationPathMap());
OptimizeSlave optimizeSlave(optimizeMaster.getNewStateMap(), module, optimizeMaster.getOperationPathMap());
OptimizeOperations optimizeOperations(optimizeSlave.getNewStateMap(), module);
RelocateOpStmts relocateStmts(optimizeOperations.getNewStateMap());
stateTopVarMap = optimizeOperations.getStateTopVarMap();
OperationPruning operationPruning(optimizeOperations.getNewStateMap(), module);
stateMap = operationPruning.getNewStateMap();
}
| 37.810101 | 168 | 0.597296 | [
"vector"
] |
6f27cbe45c79ccff53c6a55f2104eebcbbfa8b83 | 8,987 | hpp | C++ | src/cpp/common/acsStream.hpp | RodrigoNaves/ginan-bitbucket-update-tests | 4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c | [
"Apache-2.0"
] | 73 | 2021-07-08T23:35:08.000Z | 2022-03-31T15:17:58.000Z | src/cpp/common/acsStream.hpp | RodrigoNaves/ginan-bitbucket-update-tests | 4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c | [
"Apache-2.0"
] | 5 | 2021-09-27T14:27:32.000Z | 2022-03-21T23:50:02.000Z | src/cpp/common/acsStream.hpp | RodrigoNaves/ginan-bitbucket-update-tests | 4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c | [
"Apache-2.0"
] | 39 | 2021-07-12T05:42:51.000Z | 2022-03-31T15:15:34.000Z |
#ifndef ACS_STREAM_H
#define ACS_STREAM_H
#include <iostream>
#include <sstream>
#include <utility>
#include <vector>
#include <string>
#include <thread>
#include <list>
#include <map>
using std::string;
using std::tuple;
using std::list;
using std::pair;
using std::map;
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
namespace B_io = boost::iostreams;
namespace B_asio = boost::asio;
using boost::asio::ip::tcp;
#ifndef WIN32
# include <dirent.h>
# include <time.h>
# include <sys/time.h>
# include <sys/stat.h>
# include <sys/types.h>
#endif
#include "ntripTrace.hpp"
#include "observations.hpp"
#include "navigation.hpp"
#include "constants.h"
#include "station.hpp"
#include "common.hpp"
#include "gTime.hpp"
#include "rinex.hpp"
#include "enum.h"
//interfaces
/** Interface for streams that supply observations
*/
struct ObsStream
{
RinexStation rnxStation = {};
list<ObsList> obsListList;
string sourceString;
/** Return a list of observations from the stream.
* This function may be overridden by objects that use this interface
*/
virtual ObsList getObs();
/** Return a list of observations from the stream, with a specified timestamp.
* This function may be overridden by objects that use this interface
*/
ObsList getObs(
GTime time, ///< Timestamp to get observations for
double delta = 0.5) ///< Acceptable tolerance around requested time
{
while (1)
{
ObsList obsList = getObs();
if (obsList.size() == 0)
{
return obsList;
}
if (time == GTime::noTime())
{
return obsList;
}
if (obsList.front().time < time - delta)
{
eatObs();
}
else if (obsList.front().time > time + delta)
{
return ObsList();
}
else
{
return obsList;
}
}
}
/** Check to see if this stream has run out of data
*/
virtual bool isDead()
{
return false;
}
/** Remove some observations from memory
*/
void eatObs()
{
if (obsListList.size() > 0)
{
obsListList.pop_front();
}
}
};
/** Interface for objects that provide navigation data
*/
struct NavStream
{
virtual void getNav()
{
}
};
#include "acsFileStream.hpp"
#include "acsRtcmStream.hpp"
#include "acsRinexStream.hpp"
#include "acsNtripStream.hpp"
struct networkData
{
std::string streamName;
GTime startTime;
GTime endTime;
long int numPreambleFound = 0;
long int numFramesFailedCRC = 0;
long int numFramesPassCRC = 0;
long int numFramesDecoded = 0;
long int numNonMessBytes = 0;
long int numMessagesLatency = 0;
double totalLatency = 0;
int disconnectionCount = 0;
boost::posix_time::time_duration connectedDuration = boost::posix_time::hours(0);
boost::posix_time::time_duration disconnectedDuration = boost::posix_time::hours(0);
int numberErroredChunks = 0;
int numberChunks = 0;
void clearStatistics(GTime tStart, GTime tEnd);
void accumulateStatisticsFrom(networkData dataToAdd);
std::string previousJSON;
std::string getJsonNetworkStatistics(GTime now);
};
/** Object that streams RTCM data from NTRIP castors.
* Overrides interface functions
*/
struct NtripRtcmStream : NtripStream, RtcmStream
{
/** NtripTrace is an object in this class as it is also used for the uploading
* stream and so it cannot inherit NtripStream and RtcmStream. The overide function
* provide for other classes to call functions for NtripTrace without a pointer or
* address both of which are problematic for code resuse and understanding.
*/
NtripTrace ntripTrace;
bool print_stream_statistics = false;
std::string connectionErrorJson = "";
std::string serverResponseJson = "";
networkData epochData;
networkData hourlyData;
networkData runData;
NtripRtcmStream(const string& url_str) : NtripStream(url_str)
{
ntripTrace.mountPoint = url.path;
//url = URL::parse(url_str); // (moved to ntripSocket.hpp)
sourceString = url_str; //# new
open();
}
void setUrl(const string& url_str)
{
sourceString = url_str;
NtripStream::setUrl(url_str);
}
void open()
{
// connect();
}
ObsList getObs() override
{
//get all data available from the ntrip stream and convert it to an iostream for processing
getData();
B_io::basic_array_source<char> input_source(receivedData.data(), receivedData.size());
B_io::stream<B_io::basic_array_source<char>> inputStream(input_source);
parseRTCM(inputStream);
int pos = inputStream.tellg();
if (pos < 0)
{
receivedData.clear();
}
else
{
receivedData.erase(receivedData.begin(), receivedData.begin() + pos);
}
//call the base function once it has been prepared
ObsList obsList = ObsStream::getObs();
return obsList;
}
void traceBroEph(Eph eph,E_Sys sys) override
{
ntripTrace.traceBroEph(eph,sys);
}
void traceSsrEph(SatSys Sat,SSREph ssrEph) override
{
ntripTrace.traceSsrEph(Sat,ssrEph);
}
void traceSsrClk(SatSys Sat,SSRClk ssrClk) override
{
ntripTrace.traceSsrClk(Sat,ssrClk);
}
void traceSsrCodeB(SatSys Sat,E_ObsCode mode, SSRBias ssrBias) override
{
ntripTrace.traceSsrCodeB(Sat,mode,ssrBias);
}
void traceSsrPhasB(SatSys Sat,E_ObsCode mode, SSRBias ssrBias) override
{
ntripTrace.traceSsrPhasB(Sat,mode,ssrBias);
}
void messageChunkLog(std::string message) override
{
ntripTrace.messageChunkLog(message);
}
void messageRtcmLog(std::string message) override
{
ntripTrace.messageRtcmLog(message);
}
void messageRtcmByteLog(std::string message) override
{
ntripTrace.messageRtcmByteLog(message);
}
void networkLog(std::string message) override
{
ntripTrace.networkLog(message);
}
void connectionError(const boost::system::error_code& err, std::string operation) override;
void serverResponse(unsigned int status_code, std::string http_version) override;
void traceMakeNetworkOverview(Trace& trace);
void traceWriteEpoch(Trace& trace)
{
traceMakeNetworkOverview(trace);
ntripTrace.traceWriteEpoch(trace);
}
std::vector<std::string> getJsonNetworkStatistics(GTime epochTime);
void getNav()
{
//get all data available from the ntrip stream and convert it to an iostream for processing
getData();
B_io::basic_array_source<char> input_source(receivedData.data(), receivedData.size());
B_io::stream<B_io::basic_array_source<char>> inputStream(input_source);
parseRTCM(inputStream);
int pos = inputStream.tellg();
if (pos < 0)
{
receivedData.clear();
}
else
{
receivedData.erase(receivedData.begin(), receivedData.begin() + pos);
}
}
};
/** Object that streams RTCM data from a file.
* Overrides interface functions
*/
struct FileRtcmStream : ACSFileStream, RtcmStream
{
FileRtcmStream(const string& path)
{
sourceString = path;
setPath(path);
open();
}
void open()
{
openFile();
}
int lastObsListSize = -1;
ObsList getObs() override
{
// getData(); not needed for files
FileState fileState = openFile();
if (obsListList.size() < 3)
{
parseRTCM(fileState.inputStream);
}
//call the base function once it has been prepared
ObsList obsList = ObsStream::getObs();
lastObsListSize = obsList.size();
return obsList;
}
bool isDead() override
{
if (filePos < 0)
{
return true;
}
FileState fileState = openFile();
if ( (lastObsListSize != 0)
||(fileState.inputStream))
{
return false;
}
else
{
return true;
}
}
};
/** Object that streams RINEX data from a file.
* Overrides interface functions
*/
struct FileRinexStream : ACSFileStream, RinexStream
{
FileRinexStream()
{
}
FileRinexStream(const string& path)
{
sourceString = path;
setPath(path);
open();
}
void open()
{
FileState fileState = openFile();
readRinexHeader(fileState.inputStream);
}
int lastObsListSize = -1;
ObsList getObs() override
{
FileState fileState = openFile();
// getData(); not needed for files
if (obsListList.size() < 2)
{
parseRINEX(fileState.inputStream);
}
//call the base function once it has been prepared
ObsList obsList = ObsStream::getObs();
lastObsListSize = obsList.size();
return obsList;
}
bool parse()
{
FileState fileState = openFile();
parseRINEX(fileState.inputStream);
return true;
}
bool isDead() override
{
if (filePos < 0)
{
return true;
}
FileState fileState = openFile();
if ( lastObsListSize != 0
||fileState.inputStream)
{
return false;
}
else
{
return true;
}
}
};
typedef std::shared_ptr<ObsStream> ACSObsStreamPtr;
typedef std::shared_ptr<NavStream> ACSNavStreamPtr;
#endif
| 19.536957 | 95 | 0.696228 | [
"object",
"vector"
] |
6f345e01cb843935a926a6919400b99cd3bce0d2 | 3,866 | cpp | C++ | trtc/src/v20190722/model/AudioParams.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | trtc/src/v20190722/model/AudioParams.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | trtc/src/v20190722/model/AudioParams.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/trtc/v20190722/model/AudioParams.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Trtc::V20190722::Model;
using namespace std;
AudioParams::AudioParams() :
m_sampleRateHasBeenSet(false),
m_channelHasBeenSet(false),
m_bitRateHasBeenSet(false)
{
}
CoreInternalOutcome AudioParams::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("SampleRate") && !value["SampleRate"].IsNull())
{
if (!value["SampleRate"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AudioParams.SampleRate` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_sampleRate = value["SampleRate"].GetUint64();
m_sampleRateHasBeenSet = true;
}
if (value.HasMember("Channel") && !value["Channel"].IsNull())
{
if (!value["Channel"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AudioParams.Channel` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_channel = value["Channel"].GetUint64();
m_channelHasBeenSet = true;
}
if (value.HasMember("BitRate") && !value["BitRate"].IsNull())
{
if (!value["BitRate"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AudioParams.BitRate` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_bitRate = value["BitRate"].GetUint64();
m_bitRateHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AudioParams::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_sampleRateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SampleRate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_sampleRate, allocator);
}
if (m_channelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Channel";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_channel, allocator);
}
if (m_bitRateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BitRate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_bitRate, allocator);
}
}
uint64_t AudioParams::GetSampleRate() const
{
return m_sampleRate;
}
void AudioParams::SetSampleRate(const uint64_t& _sampleRate)
{
m_sampleRate = _sampleRate;
m_sampleRateHasBeenSet = true;
}
bool AudioParams::SampleRateHasBeenSet() const
{
return m_sampleRateHasBeenSet;
}
uint64_t AudioParams::GetChannel() const
{
return m_channel;
}
void AudioParams::SetChannel(const uint64_t& _channel)
{
m_channel = _channel;
m_channelHasBeenSet = true;
}
bool AudioParams::ChannelHasBeenSet() const
{
return m_channelHasBeenSet;
}
uint64_t AudioParams::GetBitRate() const
{
return m_bitRate;
}
void AudioParams::SetBitRate(const uint64_t& _bitRate)
{
m_bitRate = _bitRate;
m_bitRateHasBeenSet = true;
}
bool AudioParams::BitRateHasBeenSet() const
{
return m_bitRateHasBeenSet;
}
| 26.29932 | 140 | 0.686756 | [
"model"
] |
6f40d8e3e2b7c633ac732eb7a177d3f2b874b49f | 8,336 | cpp | C++ | CameraCalibration/StereoCalibration/main.cpp | mikeschwendy/StereoOpenCV | fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49 | [
"BSD-2-Clause"
] | 1 | 2017-04-19T17:23:40.000Z | 2017-04-19T17:23:40.000Z | CameraCalibration/StereoCalibration/main.cpp | mikeschwendy/StereoOpenCV | fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49 | [
"BSD-2-Clause"
] | null | null | null | CameraCalibration/StereoCalibration/main.cpp | mikeschwendy/StereoOpenCV | fc5c9ba2c11f1dc179093fff1123b1b0fe4e0f49 | [
"BSD-2-Clause"
] | null | null | null | //
// main.cpp
// StereoCalibration
//
// Created by Michael Schwendeman on 8/11/15.
// Copyright (c) 2015 MSS. All rights reserved.
//
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
using namespace cv;
using namespace std;
using namespace boost::filesystem;
struct sort_function
{
bool operator ()(const path & a,const path & b)
{
string aStr = a.filename().string();
string bStr = b.filename().string();
size_t numStartA = aStr.find_last_of("-");
size_t numStartB = bStr.find_last_of("-");
//size_t numStartA = aStr.find_last_of("_");
//size_t numStartB = bStr.find_last_of("_");
long frameNumA = stol(aStr.substr(numStartA+1),nullptr);
long frameNumB = stol(bStr.substr(numStartB+1),nullptr);
return frameNumA < frameNumB;
}
};
int main() {
// Set paths
//path p1 = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1834UTC_flea18";
//path p2 = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1811UTC_flea21";
//path p = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/14Jan2015/1751UTC_stbdcalibration";
//int delay = 13;
path p1 = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1804UTC_flea34";
path p2 = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/15Jan2015/1740UTC_flea35";
path p = "/Volumes/Data/PAPA/TGTcruise2015/StereoSystem/23Dec2014/1745UTC_PortCalibration";
int delay = 11;
//path p = "/Volumes/Data/PAPA/TGTcruise2015/MikeScratchTGT/TGT_StereoVideo/CalibrationDataAndResults/TGTCalibration/23Dec2014_Port_1745UTC";
//int delay = 0;
// Set plot options
bool plotCheckerboard = false;
bool plotRectified = true;
if (plotCheckerboard)
{
namedWindow("Left Image", CV_WINDOW_AUTOSIZE); //create window for left image
namedWindow("Right Image", CV_WINDOW_AUTOSIZE); //create window for left image
}
if (plotRectified)
{
namedWindow("Left Image Rectified", CV_WINDOW_AUTOSIZE); //create window for left image
namedWindow("Right Image Rectified", CV_WINDOW_AUTOSIZE); //create window for left image
}
// Load individual calibrations
string inputFile1 = p1.string() + "/OpenCVCalibrationResults.yml";
FileStorage fs1(inputFile1, FileStorage::READ);
Mat intrinsic1;
fs1["Intrinsic Matrix"] >> intrinsic1;
Mat distCoeffs1;
fs1["Distortion Coefficients"] >> distCoeffs1;
fs1.release();
string inputFile2 = p2.string() + "/OpenCVCalibrationResults.yml";
FileStorage fs2(inputFile2, FileStorage::READ);
Mat intrinsic2;
fs2["Intrinsic Matrix"] >> intrinsic2;
Mat distCoeffs2;
fs2["Distortion Coefficients"] >> distCoeffs2;
fs2.release();
// Load and sort stereo image files
vector<path> allFiles, imageVec1, imageVec2;
string extStr, fileStr;
copy(directory_iterator(p),directory_iterator(),back_inserter(allFiles));
for (vector<path>::const_iterator it (allFiles.begin()); it != allFiles.end(); ++it) {
extStr = (*it).extension().string();
// fileStr = (*it).filename().string().substr(0,4);
fileStr = (*it).filename().string().substr(0,6);
if (extStr == ".pgm" && fileStr == "flea34")
imageVec1.push_back(*it);
else if (extStr == ".pgm" && fileStr == "flea35")
imageVec2.push_back(*it);
}
sort(imageVec1.begin(),imageVec1.end(),sort_function());
sort(imageVec2.begin(),imageVec2.end(),sort_function());
// Setup checkerboard
int numCornersHor = 9;
int numCornersVer = 4;
int numSquares = numCornersHor * numCornersVer;
Size board_sz = Size(numCornersHor, numCornersVer);
vector<vector<Point3f>> object_points;
vector<vector<Point2f>> image_points1, image_points2;
vector<Point2f> corners1, corners2;
vector<Point3f> obj;
for(int j=0;j<numSquares;j++)
obj.push_back(Point3f((j/numCornersHor)*8*25.4, (j%numCornersHor)*8*25.4, 0.0f));
// Detect checkerboard
Mat image1, image2;
string filename1, filename2;
int skip = 100;
int iframe = 0;
vector<path>::const_iterator it1 = imageVec1.begin();
vector<path>::const_iterator it2 = imageVec2.begin();
delay >= 0 ? advance(it2, delay) : advance(it1,-delay);
while ( it1 != imageVec1.end() && it2 != imageVec2.end())
{
if (iframe % skip == 0)
{
filename1 = it1->string();
image1 = imread(filename1,CV_LOAD_IMAGE_GRAYSCALE);
filename2 = it2->string();
image2 = imread(filename2,CV_LOAD_IMAGE_GRAYSCALE);
bool found1 = findChessboardCorners(image1, board_sz, corners1, CV_CALIB_CB_NORMALIZE_IMAGE | CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
bool found2 = findChessboardCorners(image2, board_sz, corners2, CV_CALIB_CB_NORMALIZE_IMAGE | CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
if(found1 && found2)
{
if (plotCheckerboard)
{
drawChessboardCorners(image1, board_sz, corners1, found1);
drawChessboardCorners(image2, board_sz, corners2, found2);
imshow("Left Image",image1);
imshow("Right Image",image2);
waitKey(0);
}
cornerSubPix(image1, corners1, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
cornerSubPix(image2, corners2, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
image_points1.push_back(corners1);
image_points2.push_back(corners2);
object_points.push_back(obj);
}
}
it1++;
it2++;
iframe++;
}
// Calculate calibration
Mat E = Mat(3, 3, CV_32FC1);
Mat F = Mat(3, 3, CV_32FC1);
Mat R = Mat::eye(3,3,CV_32FC1);
Mat T = (Mat_<double>(3,1) << -2000.0, 0.0, 0.0);
TermCriteria criteria= TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 1000, DBL_EPSILON);
Size imageSize = image1.size();
double reprojectError = stereoCalibrate(object_points, image_points1, image_points2, intrinsic1, distCoeffs1, intrinsic2, distCoeffs2, imageSize, R, T, E, F, CV_CALIB_FIX_INTRINSIC, criteria);
// RECTIFY
Mat R1, R2, P1, P2, Q;
Rect roiRight, roiLeft;
stereoRectify(intrinsic1, distCoeffs1,intrinsic2, distCoeffs2, imageSize, R, T, R1, R2, P1, P2, Q, CALIB_ZERO_DISPARITY, 1, imageSize, &roiLeft, &roiRight);
Mat rmap[2][2];
initUndistortRectifyMap(intrinsic1, distCoeffs1, R1, P1, imageSize, CV_16SC2, rmap[0][0], rmap[0][1]);
initUndistortRectifyMap(intrinsic2, distCoeffs2, R2, P2, imageSize, CV_16SC2, rmap[1][0], rmap[1][1]);
Mat rimg1, rimg2;
it1 = imageVec1.begin();
it2 = imageVec2.begin();
delay >= 0 ? advance(it2, delay) : advance(it1,-delay);
while ( it1 != imageVec1.end() && it2 != imageVec2.end())
{
if (iframe % skip == 0)
{
filename1 = it1->string();
image1 = imread(filename1,CV_LOAD_IMAGE_GRAYSCALE);
filename2 = it2->string();
image2 = imread(filename2,CV_LOAD_IMAGE_GRAYSCALE);
remap(image1, rimg1, rmap[0][0], rmap[0][1], INTER_LINEAR);
remap(image2, rimg2, rmap[1][0], rmap[1][1], INTER_LINEAR);
imshow("Left Image Rectified",rimg1);
imshow("Right Image Rectified",rimg2);
waitKey(0);
}
it1++;
it2++;
iframe++;
}
destroyAllWindows();
// Save intrinsic matrix and distortion coefficients
string outputFile;
outputFile = p.string() + "/OpenCVCalibrationResults.yml";
FileStorage fs(outputFile, FileStorage::WRITE);
fs << "Left Intrinsic Matrix" << intrinsic1;
fs << "Left Distortion Coefficients" << distCoeffs1;
fs << "Right Intrinsic Matrix" << intrinsic2;
fs << "Right Distortion Coefficients" << distCoeffs2;
fs << "Rotation Matrix" << R;
fs << "Translation Vector" << T;
fs.release();
return 0;} | 39.320755 | 196 | 0.634837 | [
"vector"
] |
6f4341dacab5e11bb6704903a332133024d16966 | 1,149 | cpp | C++ | src/types/FE_Polygon.cpp | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | src/types/FE_Polygon.cpp | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | src/types/FE_Polygon.cpp | antsouchlos/OxygenEngine | 11ecc13e60f8e1e3a89dee18d07b25ac5e1b0e48 | [
"MIT"
] | null | null | null | #include "FE_Polygon.h"
FE_Polygon::FE_Polygon(int indexa, int v1, int v2, int v3)
{
createMutex();
n = indexa;
vertexNums[0] = (v1);
vertexNums[1] = (v2);
vertexNums[2] = (v3);
}
FE_Polygon::~FE_Polygon()
{
//vertexNums.clear();
}
FE_Polygon* FE_Polygon::setIndex(int a_name){
lockMutex();
n = a_name;
unlockMutex();
return this;
}
int FE_Polygon::getIndex(){
lockMutex();
auto output = n;
unlockMutex();
return output;
}
FE_Polygon* FE_Polygon::setNormal(FE_Vec4 a_name){
lockMutex();
normal = a_name;
unlockMutex();
return this;
}
FE_Vec4 FE_Polygon::getNormal(){
lockMutex();
auto output = normal;
unlockMutex();
return output;
}
FE_Polygon* FE_Polygon::setVertices(int v1, int v2, int v3){
lockMutex();
vertexNums[0] = v1; vertexNums[1] = v2; vertexNums[2] = v3;
unlockMutex();
return this;
}
vector<size_t> FE_Polygon::getVertices(){
lockMutex();
vector<size_t> output;
output.push_back(vertexNums[0]);
output.push_back(vertexNums[1]);
output.push_back(vertexNums[2]);
unlockMutex();
return output;
}
| 18.532258 | 63 | 0.631854 | [
"vector"
] |
6f43e060b6ebf30dd4918f5cef02d318b2fc6226 | 9,283 | cpp | C++ | test/test_value_set.cpp | friendlyanon/cpp_enum_set | 248a98ee768def5b4a32d3719d6ee46863377114 | [
"MIT"
] | 21 | 2021-05-25T07:59:08.000Z | 2021-06-04T01:54:23.000Z | test/test_value_set.cpp | friendlyanon/cpp_enum_set | 248a98ee768def5b4a32d3719d6ee46863377114 | [
"MIT"
] | 11 | 2021-05-25T09:28:51.000Z | 2021-07-01T09:59:15.000Z | test/test_value_set.cpp | friendlyanon/cpp_enum_set | 248a98ee768def5b4a32d3719d6ee46863377114 | [
"MIT"
] | 2 | 2021-05-25T11:52:04.000Z | 2021-06-02T16:17:24.000Z | #include "testing.hpp"
#include <enum_set/standard_types.hpp>
#include <enum_set/type_set.hpp>
#include <enum_set/value_set.hpp>
#include <type_traits>
#include <utility>
#include <vector>
// explicitly instantiate to make sure the class is well defined
template class ::enum_set::value_set<int, 0, 2, 1>;
using test_set = ::enum_set::value_set<int, 0, 2, 1>;
namespace
{
struct test_fixture
{
static constexpr auto empty = test_set();
static constexpr auto x0 = test_set::make<0>();
static constexpr auto x1 = test_set::make<1>();
static constexpr auto x2 = test_set::make<2>();
static constexpr auto all = x0 | x1 | x2;
};
constexpr test_set test_fixture::empty;
constexpr test_set test_fixture::x0;
constexpr test_set test_fixture::x1;
constexpr test_set test_fixture::x2;
constexpr test_set test_fixture::all;
struct test_visitor
{
std::vector<std::pair<int, size_t>>& result;
test_visitor(std::vector<std::pair<int, size_t>>& result)
: result{result} {}
template <int V>
void operator()()
{
result.push_back(std::make_pair(V, test_set::index<V>()));
}
};
} // namespace
namespace enum_set
{
TEST_CASE("base type of value set is as expected")
{
STATIC_CHECK(
(std::is_base_of<
type_set<value<int, 0>>,
value_set<int, 0>
>::value),
"value set of size 1 is a type set of 1 index");
STATIC_CHECK(
(std::is_base_of<
type_set<
value<int, 0>,
value<int, 1>
>,
value_set<int, 0, 1>
>::value),
"value set of size 2 is a type set of 2 indices");
STATIC_CHECK(
(std::is_base_of<
type_set<
value<int, 0>,
value<int, 1>,
value<int, 2>
>,
value_set<int, 0, 1, 2>
>::value),
"value set of size 3 is a type set of 3 indices");
STATIC_CHECK(
(std::is_base_of<
type_set<
value<int, 0>,
value<int, 1>,
value<int, 2>,
value<int, 3>
>,
value_set<int, 0, 1, 2, 3>
>::value),
"value set of size 4 is a type set of 4 indices");
}
TEST_CASE("base class converting constructor works")
{
test_set::base_type base = test_set::base_type::make<value<int, 1>>();
test_set derived(base);
CHECK(!derived.has<0>());
CHECK(derived.has<1>());
CHECK(!derived.has<2>());
}
TEST_CASE("variadic constructor works")
{
constexpr test_set X = {1, 2};
STATIC_CHECK(!X.has<0>(), "Value set does not contain 0");
STATIC_CHECK( X.has<1>(), "Value set does contain 1");
STATIC_CHECK( X.has<2>(), "Value set does contain 2");
}
TEST_CASE("variadic constructor throws exception for invalid value")
{
CHECK_THROWS(test_set{3});
}
TEST_CASE("size of value set_of specified size is as expected")
{
STATIC_CHECK(sizeof(value_set<int, 0>) == 1,
"Typeset of size 1 requires 1 byte");
STATIC_CHECK(sizeof(value_set<int, 0, 1, 2, 3, 4, 5, 6, 7>) == 1,
"Typeset of size 8 requires 1 byte");
STATIC_CHECK(sizeof(value_set<int, 0, 1, 2, 3, 4, 5, 6, 7, 8>) == 2,
"Typeset of size 9 requires 2 bytes");
}
TEST_CASE_FIXTURE(test_fixture, "value set has the expected elements")
{
STATIC_CHECK(!empty.has<0>(), "Empty value set does not contain anything");
STATIC_CHECK(!empty.has<1>(), "Empty value set does not contain anything");
STATIC_CHECK(!empty.has<2>(), "Empty value set does not contain anything");
STATIC_CHECK(x0.has<0>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x0.has<1>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x0.has<2>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x1.has<0>(), "Singleton value set contains the expected element");
STATIC_CHECK(x1.has<1>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x1.has<2>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x2.has<0>(), "Singleton value set contains the expected element");
STATIC_CHECK(!x2.has<1>(), "Singleton value set contains the expected element");
STATIC_CHECK(x2.has<2>(), "Singleton value set contains the expected element");
}
TEST_CASE("value set index methods returns the expected indices")
{
STATIC_CHECK(test_set::index<0>() == 0, "Index of 0 is 0");
STATIC_CHECK(test_set::index<1>() == 2, "Index of 1 is 2");
STATIC_CHECK(test_set::index<2>() == 1, "Index of 1 is 2");
}
TEST_CASE("value set add method works as expected")
{
test_set values;
CHECK(values.empty());
values.add<0>();
CHECK(values.has<0>());
CHECK(!values.has<1>());
CHECK(!values.has<2>());
values.add<0>();
CHECK(values.has<0>());
CHECK(!values.has<1>());
CHECK(!values.has<2>());
values.add<2>();
CHECK(values.has<0>());
CHECK(!values.has<1>());
CHECK(values.has<2>());
values.add<1>();
CHECK(values.has<0>());
CHECK(values.has<1>());
CHECK(values.has<2>());
}
TEST_CASE_FIXTURE(test_fixture, "value set remove method works as expected")
{
test_set values = x0 | x1 | x2;
CHECK(values.has<0>());
CHECK(values.has<1>());
CHECK(values.has<2>());
values.remove<0>();
CHECK(!values.has<0>());
CHECK(values.has<1>());
CHECK(values.has<2>());
values.remove<0>();
CHECK(!values.has<0>());
CHECK(values.has<1>());
CHECK(values.has<2>());
values.remove<2>();
CHECK(!values.has<0>());
CHECK(values.has<1>());
CHECK(!values.has<2>());
values.remove<1>();
CHECK(values.empty());
}
TEST_CASE_FIXTURE(test_fixture, "value set complement operator works")
{
constexpr test_set x = {0, 2};
STATIC_CHECK(~x == test_set{1}, "Complement of {0, 2} w.r.t to {0, 1, 2} is {1}");
}
TEST_CASE_FIXTURE(test_fixture, "value set union operator works")
{
STATIC_CHECK( (x0 | x2).has<0>(), "{0, 2} has 0");
STATIC_CHECK(!(x0 | x2).has<1>(), "{0, 2} do not have 1");
STATIC_CHECK( (x0 | x2).has<2>(), "{0, 2} has 2");
}
TEST_CASE_FIXTURE(test_fixture, "value set intersection operator works")
{
STATIC_CHECK((all & x0) == x0, "all intersect with x0 is x0");
STATIC_CHECK((all & x1) == x1, "all intersect with x1 is x1");
STATIC_CHECK((all & x2) == x2, "all intersect with x2 is x2");
constexpr auto x01 = x0 | x1;
constexpr auto x12 = x1 | x2;
STATIC_CHECK((x01 & x12) == x1, "{0, 1} intersect with {1, 2} is {1}");
}
TEST_CASE_FIXTURE(test_fixture, "value set difference operator works")
{
STATIC_CHECK((all / x0) == (x1 | x2), "all without x0 is x1 | x2");
STATIC_CHECK((all / x1) == (x0 | x2), "all without x1 is x0 | x2");
STATIC_CHECK((all / x2) == (x0 | x1), "all without x2 is x0 | x1");
}
TEST_CASE_FIXTURE(test_fixture, "value set symmetric difference operator works")
{
constexpr auto x01 = x0 | x1;
constexpr auto x12 = x1 | x2;
STATIC_CHECK((x01 ^ x12) == (x0 | x2), "Symmetric diff between {0, 1} and {1, 2} is {0, 2}");
}
TEST_CASE_FIXTURE(test_fixture, "value set in place union works")
{
auto x = x0;
x |= x1;
CHECK(x == (x0 | x1));
}
TEST_CASE_FIXTURE(test_fixture, "value set in place intersection works")
{
auto x = x0 | x1;
const auto y = x1 | x2;
x &= y;
CHECK(x == x1);
}
TEST_CASE_FIXTURE(test_fixture, "value set in place difference works")
{
auto x = all;
x /= x1;
CHECK(x == ~x1);
}
TEST_CASE_FIXTURE(test_fixture, "value set in place symmetric difference works")
{
auto x = x0 | x1;
const auto y = x1 | x2;
x ^= y;
CHECK(x == ~x1);
}
TEST_CASE_FIXTURE(test_fixture, "value set iterator increments as expected")
{
test_set x = test_set::make<0>() | test_set::make<2>();
auto it = x.begin();
CHECK(*it == 0);
CHECK(*(++it) == 2);
CHECK(++it == x.end());
CHECK_THROWS(*it);
}
TEST_CASE_FIXTURE(test_fixture, "value set visit visits the expected types")
{
std::vector<std::pair<int, size_t>> result;
SUBCASE("empty set")
{
visit(test_visitor(result), empty);
REQUIRE(result.empty());
}
SUBCASE("for x1")
{
visit(test_visitor(result), x1);
REQUIRE(result.size() == 1);
CHECK(result.at(0) == std::pair<int, size_t>{1, 2});
}
SUBCASE("for x0 | x1")
{
visit(test_visitor(result), x0 | x1);
REQUIRE(result.size() == 2);
CHECK(result.at(0) == std::pair<int, size_t>{0, 0});
CHECK(result.at(1) == std::pair<int, size_t>{1, 2});
}
SUBCASE("for x1 | x2")
{
visit(test_visitor(result), x1 | x2);
REQUIRE(result.size() == 2);
CHECK(result.at(0) == std::pair<int, size_t>{2, 1});
CHECK(result.at(1) == std::pair<int, size_t>{1, 2});
}
SUBCASE("for x0 | x1 | x2 ")
{
visit(test_visitor(result), x0 | x1 | x2);
REQUIRE(result.size() == 3);
CHECK(result.at(0) == std::pair<int, size_t>{0, 0});
CHECK(result.at(1) == std::pair<int, size_t>{2, 1});
CHECK(result.at(2) == std::pair<int, size_t>{1, 2});
}
}
} // namespace enum_set
| 29.658147 | 98 | 0.597436 | [
"vector"
] |
6f46495c35fc591dc03dc1eaed4af912dcf5c51f | 5,510 | hpp | C++ | include/monitor/monitoring_utils.hpp | stolet/anna | a2aa8cd962371d1e0ed38b636d1d4c6054eeb228 | [
"Apache-2.0"
] | 489 | 2019-08-09T18:50:19.000Z | 2022-03-31T20:06:30.000Z | include/monitor/monitoring_utils.hpp | stolet/anna | a2aa8cd962371d1e0ed38b636d1d4c6054eeb228 | [
"Apache-2.0"
] | 46 | 2019-08-27T12:13:09.000Z | 2021-10-06T06:05:33.000Z | include/monitor/monitoring_utils.hpp | stolet/anna | a2aa8cd962371d1e0ed38b636d1d4c6054eeb228 | [
"Apache-2.0"
] | 109 | 2019-08-16T03:07:12.000Z | 2022-02-26T01:31:17.000Z | // Copyright 2019 U.C. Berkeley RISE Lab
//
// 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 KVS_INCLUDE_MONITOR_MONITORING_UTILS_HPP_
#define KVS_INCLUDE_MONITOR_MONITORING_UTILS_HPP_
#include "hash_ring.hpp"
#include "metadata.pb.h"
#include "requests.hpp"
// define monitoring threshold (in second)
const unsigned kMonitoringThreshold = 30;
// define the grace period for triggering elasticity action (in second)
const unsigned kGracePeriod = 120;
// the default number of nodes to add concurrently for storage
const unsigned kNodeAdditionBatchSize = 2;
// define capacity for both tiers
const double kMaxMemoryNodeConsumption = 0.6;
const double kMinMemoryNodeConsumption = 0.3;
const double kMaxEbsNodeConsumption = 0.75;
const double kMinEbsNodeConsumption = 0.5;
// define threshold for promotion/demotion
const unsigned kKeyPromotionThreshold = 0;
const unsigned kKeyDemotionThreshold = 1;
// define minimum number of nodes for each tier
const unsigned kMinMemoryTierSize = 1;
const unsigned kMinEbsTierSize = 0;
// value size in KB
const unsigned kValueSize = 256;
struct SummaryStats {
void clear() {
key_access_mean = 0;
key_access_std = 0;
total_memory_access = 0;
total_ebs_access = 0;
total_memory_consumption = 0;
total_ebs_consumption = 0;
max_memory_consumption_percentage = 0;
max_ebs_consumption_percentage = 0;
avg_memory_consumption_percentage = 0;
avg_ebs_consumption_percentage = 0;
required_memory_node = 0;
required_ebs_node = 0;
max_memory_occupancy = 0;
min_memory_occupancy = 1;
avg_memory_occupancy = 0;
max_ebs_occupancy = 0;
min_ebs_occupancy = 1;
avg_ebs_occupancy = 0;
min_occupancy_memory_public_ip = Address();
min_occupancy_memory_private_ip = Address();
avg_latency = 0;
total_throughput = 0;
}
SummaryStats() { clear(); }
double key_access_mean;
double key_access_std;
unsigned total_memory_access;
unsigned total_ebs_access;
unsigned long long total_memory_consumption;
unsigned long long total_ebs_consumption;
double max_memory_consumption_percentage;
double max_ebs_consumption_percentage;
double avg_memory_consumption_percentage;
double avg_ebs_consumption_percentage;
unsigned required_memory_node;
unsigned required_ebs_node;
double max_memory_occupancy;
double min_memory_occupancy;
double avg_memory_occupancy;
double max_ebs_occupancy;
double min_ebs_occupancy;
double avg_ebs_occupancy;
Address min_occupancy_memory_public_ip;
Address min_occupancy_memory_private_ip;
double avg_latency;
double total_throughput;
};
void collect_internal_stats(
GlobalRingMap &global_hash_rings, LocalRingMap &local_hash_rings,
SocketCache &pushers, MonitoringThread &mt, zmq::socket_t &response_puller,
logger log, unsigned &rid,
map<Key, map<Address, unsigned>> &key_access_frequency,
map<Key, unsigned> &key_size, StorageStats &memory_storage,
StorageStats &ebs_storage, OccupancyStats &memory_occupancy,
OccupancyStats &ebs_occupancy, AccessStats &memory_access,
AccessStats &ebs_access);
void compute_summary_stats(
map<Key, map<Address, unsigned>> &key_access_frequency,
StorageStats &memory_storage, StorageStats &ebs_storage,
OccupancyStats &memory_occupancy, OccupancyStats &ebs_occupancy,
AccessStats &memory_access, AccessStats &ebs_access,
map<Key, unsigned> &key_access_summary, SummaryStats &ss, logger log,
unsigned &server_monitoring_epoch);
void collect_external_stats(map<string, double> &user_latency,
map<string, double> &user_throughput,
SummaryStats &ss, logger log);
KeyReplication create_new_replication_vector(unsigned gm, unsigned ge,
unsigned lm, unsigned le);
void prepare_replication_factor_update(
const Key &key,
map<Address, ReplicationFactorUpdate> &replication_factor_map,
Address server_address, map<Key, KeyReplication> &key_replication_map);
void change_replication_factor(map<Key, KeyReplication> &requests,
GlobalRingMap &global_hash_rings,
LocalRingMap &local_hash_rings,
vector<Address> &routing_ips,
map<Key, KeyReplication> &key_replication_map,
SocketCache &pushers, MonitoringThread &mt,
zmq::socket_t &response_puller, logger log,
unsigned &rid);
void add_node(logger log, string tier, unsigned number, unsigned &adding,
SocketCache &pushers, const Address &management_ip);
void remove_node(logger log, ServerThread &node, string tier,
bool &removing_flag, SocketCache &pushers,
map<Address, unsigned> &departing_node_map,
MonitoringThread &mt);
#endif // KVS_INCLUDE_MONITOR_MONITORING_UTILS_HPP_
| 37.482993 | 79 | 0.729583 | [
"vector"
] |
6f480982c76f76503ec7837765eb75371cb5b020 | 6,123 | hpp | C++ | stapl_release/stapl/skeletons/param_deps/alltoall_hybrid_pd.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/param_deps/alltoall_hybrid_pd.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/skeletons/param_deps/alltoall_hybrid_pd.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_SKELETONS_PARAM_DEPS_ALLTOALL_HYBRID_PD_HPP
#define STAPL_SKELETONS_PARAM_DEPS_ALLTOALL_HYBRID_PD_HPP
#include <type_traits>
#include <stapl/utility/tuple/tuple.hpp>
#include <stapl/utility/tuple/front.hpp>
#include <stapl/skeletons/utility/identity_helpers.hpp>
#include <stapl/skeletons/utility/filters.hpp>
#include <stapl/skeletons/operators/elem_helpers.hpp>
#include <stapl/skeletons/param_deps/utility.hpp>
#include "alltoall_helpers.hpp"
namespace stapl {
namespace skeletons {
namespace skeletons_impl {
//////////////////////////////////////////////////////////////////////
/// @brief The hybrid @c alltoall parametric dependency is used
/// for alltoall skeleton in the cases of having large messages. The
/// parametric dependency in this case is defined as a hybrid of the
/// flat and butterfly-based version of alltoall.
///
/// In this case, there are log2(n) stages. In each stage,
/// each participant at the upper half of a butterfly communicates with
/// every participant in the lower half of the same butterfly, and vice versa.
///
/// @note The dependencies at each step are permuted to avoid network pressure
/// on a single node at the same time.
///
/// @ingroup skeletonsParamDepsInternal
//////////////////////////////////////////////////////////////////////
template <typename T>
class alltoall_pd<T, tags::hybrid>
: public param_deps_defaults
{
public:
static constexpr std::size_t in_port_size = 1;
static constexpr std::size_t op_arity = 2;
using consumer_count_filter_type = skeletons::filters::filter<2>;
using op_type = alltoall_merge<T, tags::hybrid>;
//////////////////////////////////////////////////////////////////////
/// @brief If coord is <i, h, ...> it wraps the @c WF with the
/// following inputs and sends it to the visitor along with the @c m_wf
/// @li in<0>[0, ..., n]
///
/// @param skeleton_size <n, m, p, ...> where each element is
/// potentially multi-dimensional.
/// @param coord <i, j, k, ...> where i < n, j < m, k < p
/// @param visitor the information about WF and input is passed
/// so that later this information can be converted
/// to a node in the dependence graph
/// @param in_flow a tuple of input flows to consume from
//////////////////////////////////////////////////////////////////////
template <typename Coord, typename Visitor, typename In>
void case_of(Coord const& skeleton_size, Coord const& coord,
Visitor& visitor, In&& in_flow) const
{
if (stapl::get<0>(skeleton_size) == 1) {
visitor(stapl::identity<std::vector<T>>(), no_mapper(),
stapl::get<0>(in_flow).consume_from(stapl::make_tuple(0)));
}
else {
std::size_t const i = tuple_ops::front(coord);
std::size_t const bflied_index = butterflied_index(skeleton_size, coord);
std::size_t const bfly_size = butterfly_size(skeleton_size, coord);
std::size_t const offset = bflied_index - bflied_index % bfly_size;
std::size_t const max = offset + bfly_size;
std::vector<stapl::tuple<std::size_t>> deps;
deps.reserve(bfly_size);
for (std::size_t i = offset; i < max; ++i) {
deps.push_back(stapl::make_tuple(i));
}
std::random_shuffle(deps.begin(), deps.end());
visitor(alltoall_merge<T, tags::hybrid>(deps),
no_mapper(),
stapl::get<0>(in_flow).consume_from(stapl::make_tuple(i)),
stapl::get<0>(in_flow).consume_from_many(
deps, alltoall_filter<T, tags::hybrid>(i)));
}
}
template <typename Coord>
std::size_t
butterfly_size(Coord const& skeleton_size, Coord const& coord) const
{
return 1ul << (stapl::get<1>(skeleton_size) - stapl::get<1>(coord) - 1);
}
template <typename Coord>
std::size_t
butterflied_index(Coord const& skeleton_size, Coord const& coord) const
{
std::size_t cur_index = stapl::get<0>(coord);
std::size_t bfly_size = butterfly_size(skeleton_size, coord);
const int direction = cur_index % (bfly_size * 2) >= bfly_size ? -1 : 1;
return (cur_index + direction * bfly_size);
}
//////////////////////////////////////////////////////////////////////
/// @brief determines how many of the instances of this parametric
/// dependency will be consuming from a producer with a given coordinate.
/// This is a reverse query as compared to case_of.
///
/// @param skeleton_size the size of this skeleton
/// @param producer_coord the coordinate of the producer element
/// which is providing data to this parametric
/// dependency
/// @tparam FlowIndex the flow index on which this request is
/// sent
//////////////////////////////////////////////////////////////////////
template <typename Size, typename Coord, typename FlowIndex>
std::size_t consumer_count(Size const& skeleton_size,
Coord const& producer_coord,
FlowIndex const& /*flow_index*/) const
{
if (tuple_ops::front(skeleton_size) == 1) {
return 1;
}
else {
//the number of consumers are set as the butterfly size
//since we are reading from the consumer side, it is similar to the
//original butterfly size + 1
std::size_t depth = static_cast<std::size_t>(
log(stapl::get<0>(skeleton_size)) / log(2));
return (1ul << (depth - stapl::get<1>(producer_coord) - 2)) + 1;
}
}
};
} // namespace skeletons_impl
} // namespace skeletons
} // namespace stapl
#endif //STAPL_SKELETONS_PARAM_DEPS_ALLTOALL_HYBRID_PD_HPP
| 39.503226 | 79 | 0.616528 | [
"vector"
] |
6f49f0cc99f5b4742f84c0d9e04c146de3a0e5de | 5,814 | cc | C++ | minidump/minidump_thread_name_list_writer.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | minidump/minidump_thread_name_list_writer.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | minidump/minidump_thread_name_list_writer.cc | venge-vimeo/crashpad | 7c30a508eb1c5fba3533a1e5570e79b9b2ad37d5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "minidump/minidump_thread_name_list_writer.h"
#include <utility>
#include "base/logging.h"
#include "minidump/minidump_thread_id_map.h"
#include "snapshot/thread_snapshot.h"
#include "util/file/file_writer.h"
#include "util/numeric/safe_assignment.h"
namespace crashpad {
MinidumpThreadNameWriter::MinidumpThreadNameWriter()
: MinidumpWritable(), rva_of_thread_name_(), thread_id_(), name_() {}
MinidumpThreadNameWriter::~MinidumpThreadNameWriter() {}
void MinidumpThreadNameWriter::InitializeFromSnapshot(
const ThreadSnapshot* thread_snapshot,
const MinidumpThreadIDMap& thread_id_map) {
DCHECK_EQ(state(), kStateMutable);
const auto it = thread_id_map.find(thread_snapshot->ThreadID());
DCHECK(it != thread_id_map.end());
SetThreadId(it->second);
SetThreadName(thread_snapshot->ThreadName());
}
RVA64 MinidumpThreadNameWriter::RvaOfThreadName() const {
DCHECK_EQ(state(), kStateWritable);
return rva_of_thread_name_;
}
uint32_t MinidumpThreadNameWriter::ThreadId() const {
DCHECK_EQ(state(), kStateWritable);
return thread_id_;
}
bool MinidumpThreadNameWriter::Freeze() {
DCHECK_EQ(state(), kStateMutable);
name_->RegisterRVA(&rva_of_thread_name_);
return MinidumpWritable::Freeze();
}
void MinidumpThreadNameWriter::SetThreadName(const std::string& name) {
DCHECK_EQ(state(), kStateMutable);
if (!name_) {
name_.reset(new internal::MinidumpUTF16StringWriter());
}
name_->SetUTF8(name);
}
size_t MinidumpThreadNameWriter::SizeOfObject() {
DCHECK_GE(state(), kStateFrozen);
// This object doesn’t directly write anything itself. Its parent writes the
// MINIDUMP_THREAD_NAME objects as part of a MINIDUMP_THREAD_NAME_LIST, and
// its children are responsible for writing themselves.
return 0;
}
std::vector<internal::MinidumpWritable*> MinidumpThreadNameWriter::Children() {
DCHECK_GE(state(), kStateFrozen);
DCHECK(name_);
std::vector<MinidumpWritable*> children;
children.emplace_back(name_.get());
return children;
}
bool MinidumpThreadNameWriter::WriteObject(FileWriterInterface* file_writer) {
DCHECK_EQ(state(), kStateWritable);
// This object doesn’t directly write anything itself. Its
// MINIDUMP_THREAD_NAME is written by its parent as part of a
// MINIDUMP_THREAD_NAME_LIST, and its children are responsible for writing
// themselves.
return true;
}
MinidumpThreadNameListWriter::MinidumpThreadNameListWriter()
: MinidumpStreamWriter(), thread_names_() {}
MinidumpThreadNameListWriter::~MinidumpThreadNameListWriter() {}
void MinidumpThreadNameListWriter::InitializeFromSnapshot(
const std::vector<const ThreadSnapshot*>& thread_snapshots,
const MinidumpThreadIDMap& thread_id_map) {
DCHECK_EQ(state(), kStateMutable);
DCHECK(thread_names_.empty());
for (const ThreadSnapshot* thread_snapshot : thread_snapshots) {
auto thread = std::make_unique<MinidumpThreadNameWriter>();
thread->InitializeFromSnapshot(thread_snapshot, thread_id_map);
AddThreadName(std::move(thread));
}
}
void MinidumpThreadNameListWriter::AddThreadName(
std::unique_ptr<MinidumpThreadNameWriter> thread_name) {
DCHECK_EQ(state(), kStateMutable);
thread_names_.emplace_back(std::move(thread_name));
}
bool MinidumpThreadNameListWriter::Freeze() {
DCHECK_EQ(state(), kStateMutable);
if (!MinidumpStreamWriter::Freeze()) {
return false;
}
size_t thread_name_count = thread_names_.size();
if (!AssignIfInRange(&thread_name_list_.NumberOfThreadNames,
thread_name_count)) {
LOG(ERROR) << "thread_name_count " << thread_name_count << " out of range";
return false;
}
return true;
}
size_t MinidumpThreadNameListWriter::SizeOfObject() {
DCHECK_GE(state(), kStateFrozen);
return sizeof(thread_name_list_) +
thread_names_.size() * sizeof(MINIDUMP_THREAD_NAME);
}
std::vector<internal::MinidumpWritable*>
MinidumpThreadNameListWriter::Children() {
DCHECK_GE(state(), kStateFrozen);
std::vector<MinidumpWritable*> children;
children.reserve(thread_names_.size());
for (const auto& thread_name : thread_names_) {
children.emplace_back(thread_name.get());
}
return children;
}
bool MinidumpThreadNameListWriter::WriteObject(
FileWriterInterface* file_writer) {
DCHECK_EQ(state(), kStateWritable);
WritableIoVec iov;
iov.iov_base = &thread_name_list_;
iov.iov_len = sizeof(thread_name_list_);
std::vector<WritableIoVec> iovecs(1, iov);
iovecs.reserve(thread_names_.size() + 1);
std::vector<MINIDUMP_THREAD_NAME> minidump_thread_names;
minidump_thread_names.reserve(thread_names_.size());
for (const auto& thread_name : thread_names_) {
auto& minidump_thread_name = minidump_thread_names.emplace_back();
minidump_thread_name.ThreadId = thread_name->ThreadId();
minidump_thread_name.RvaOfThreadName = thread_name->RvaOfThreadName();
iov.iov_base = &minidump_thread_name;
iov.iov_len = sizeof(minidump_thread_name);
iovecs.push_back(iov);
}
return file_writer->WriteIoVec(&iovecs);
}
MinidumpStreamType MinidumpThreadNameListWriter::StreamType() const {
return kMinidumpStreamTypeThreadNameList;
}
} // namespace crashpad
| 30.28125 | 79 | 0.759202 | [
"object",
"vector"
] |
6f49fbe05147b810b64bc855435582b0ec61aa95 | 22,286 | cpp | C++ | src/gtirb_pprinter/MasmPrettyPrinter.cpp | GrammaTech/gtirb-pprinter | d3c7063ea0a6a4edefa6be76bf4d56527ba63855 | [
"MIT"
] | 36 | 2018-11-09T15:57:13.000Z | 2022-03-02T20:07:56.000Z | src/gtirb_pprinter/MasmPrettyPrinter.cpp | GrammaTech/gtirb-pprinter | d3c7063ea0a6a4edefa6be76bf4d56527ba63855 | [
"MIT"
] | 10 | 2020-04-14T03:55:14.000Z | 2022-02-21T19:39:27.000Z | src/gtirb_pprinter/MasmPrettyPrinter.cpp | GrammaTech/gtirb-pprinter | d3c7063ea0a6a4edefa6be76bf4d56527ba63855 | [
"MIT"
] | 14 | 2019-04-17T21:11:39.000Z | 2022-03-02T20:07:58.000Z | //===- MasmPrinter.cpp ------------------------------------------*- C++ -*-===//
//
// Copyright (C) 2019 GrammaTech, Inc.
//
// This code is licensed under the MIT license. See the LICENSE file in the
// project root for license terms.
//
// This project is sponsored by the Office of Naval Research, One Liberty
// Center, 875 N. Randolph Street, Arlington, VA 22203 under contract #
// N68335-17-C-0700. The content of the information does not necessarily
// reflect the position or policy of the Government and no official
// endorsement should be inferred.
//
//===----------------------------------------------------------------------===//
#include "MasmPrettyPrinter.hpp"
#include "AuxDataSchema.hpp"
#include "file_utils.hpp"
#include "regex"
#include "string_utils.hpp"
#include <boost/algorithm/string/replace.hpp>
namespace gtirb_pprint {
std::string MasmSyntax::formatSectionName(const std::string& S) const {
// Valid MASM identifiers are describe as ...
// Max Length: 247
// Grammar: id ::= alpha | id alpha | id decdigit
// alpa ::= a-z | A-Z | @ _ $ ?
// decdigit ::= 0-9
std::string Name(S);
// Rewrite standard dot-prefixed names by convention,
// e.g. '.text` to `_TEXT'
if (Name[0] == '.') {
Name[0] = '_';
Name = ascii_str_toupper(Name);
}
// Truncate long section Names.
if (Name.length() > 247) {
Name.resize(247);
}
// Replace non-alpha characters with '?' characters.
for (size_t I = 0; I < Name.size(); I++) {
switch (Name[I]) {
case '@':
case '_':
case '$':
case '?':
continue;
default:
if (!std::isalnum(Name[I])) {
Name[I] = '?';
}
continue;
}
}
return Name;
}
std::string MasmSyntax::formatFunctionName(const std::string& x) const {
std::string name(x);
if (name[0] == '.')
name[0] = '$';
return name;
}
std::string MasmSyntax::formatSymbolName(const std::string& x) const {
std::string name = avoidRegNameConflicts(x);
if (name[0] == '.')
name[0] = '$';
return name;
}
MasmPrettyPrinter::MasmPrettyPrinter(gtirb::Context& context_,
gtirb::Module& module_,
const MasmSyntax& syntax_,
const Assembler& assembler_,
const PrintingPolicy& policy_)
: PePrettyPrinter(context_, module_, syntax_, assembler_, policy_),
masmSyntax(syntax_) {
// Setup Capstone.
cs_mode Mode = CS_MODE_64;
if (module.getISA() == gtirb::ISA::IA32) {
Mode = CS_MODE_32;
}
[[maybe_unused]] cs_err err = cs_open(CS_ARCH_X86, Mode, &this->csHandle);
assert(err == CS_ERR_OK && "Capstone failure");
// TODO: Evaluate this syntax option.
// cs_option(this->csHandle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_MASM);
BaseAddress = module.getPreferredAddr();
if (auto It = module.findSymbols("__ImageBase"); !It.empty()) {
ImageBase = &*It.begin();
ImageBase->setReferent(module.addProxyBlock(context));
if (module.getISA() == gtirb::ISA::IA32) {
ImageBase->setName("___ImageBase");
}
}
if (gtirb::CodeBlock* Block = module.getEntryPoint();
Block && Block->getAddress()) {
if (auto It = module.findSymbols(*Block->getAddress()); !It.empty()) {
// Use an existing symbol to the entry block.
EntryPoint = &*It.begin();
} else {
// Create a new symbol for the entry block.
EntryPoint =
gtirb::Symbol::Create(context, *Block->getAddress(), "__EntryPoint");
(*EntryPoint)->setReferent<gtirb::CodeBlock>(Block);
module.addSymbol(*EntryPoint);
}
}
const auto* ImportedSymbols =
module.getAuxData<gtirb::schema::PeImportedSymbols>();
if (ImportedSymbols) {
for (const auto& UUID : *ImportedSymbols) {
Imports.insert(UUID);
}
}
const auto* ExportedSymbols =
module.getAuxData<gtirb::schema::PeExportedSymbols>();
if (ExportedSymbols) {
for (const auto& UUID : *ExportedSymbols) {
Exports.insert(UUID);
}
}
}
void MasmPrettyPrinter::printIncludes(std::ostream& os) {
const auto* libraries = module.getAuxData<gtirb::schema::Libraries>();
if (libraries) {
for (const auto& library : *libraries) {
// Include import libs later generated using synthesized DEF files passed
// through lib.exe. Have observed .dll and .drv files
os << "INCLUDELIB " << gtirb_bprint::replaceExtension(library, ".lib")
<< '\n';
}
}
os << '\n';
}
void MasmPrettyPrinter::printExterns(std::ostream& os) {
// Declare EXTERN symbols
if (const auto* symbolForwarding =
module.getAuxData<gtirb::schema::SymbolForwarding>()) {
std::set<std::string> Externs;
for (auto& forward : *symbolForwarding) {
if (const auto* symbol = dyn_cast_or_null<gtirb::Symbol>(
gtirb::Node::getByUUID(context, forward.second))) {
std::string Name = getSymbolName(*symbol);
// This is not completely understood why, but link.exe (msvc) mangles
// differently. We'll apply this heuristic until it's fully understood.
Externs.insert(module.getISA() == gtirb::ISA::IA32 && Name[0] != '?'
? "_" + Name
: Name);
}
}
for (auto& Name : Externs) {
// Since we don't know up front if the references to an export are direct,
// indirect, or both, we will define both as extern conservatively. This
// should have no impact at runtime, and both with be defined in the
// import library regardless.
os << masmSyntax.extrn() << " "
<< "__imp_" << Name << ":PROC\n";
os << masmSyntax.extrn() << " " << Name << ":PROC\n";
}
}
os << '\n';
os << masmSyntax.extrn() << " "
<< (module.getISA() == gtirb::ISA::IA32 ? "___ImageBase" : "__ImageBase")
<< ":BYTE\n";
os << '\n';
}
void MasmPrettyPrinter::printHeader(std::ostream& os) {
if (module.getISA() == gtirb::ISA::IA32) {
os << ".686p\n"
<< ".XMM\n"
<< ".MODEL FLAT\n"
<< "ASSUME FS:NOTHING\n"
<< "ASSUME GS:NOTHING\n"
<< "\n";
}
printIncludes(os);
printExterns(os);
if (EntryPoint) {
os << masmSyntax.global() << " " << (*EntryPoint)->getName() << "\n";
}
}
void MasmPrettyPrinter::printSectionHeader(std::ostream& os,
const gtirb::Section& section) {
std::string sectionName = section.getName();
os << '\n';
printBar(os);
printSectionHeaderDirective(os, section);
printSectionProperties(os, section);
os << '\n';
printBar(os);
os << '\n';
}
void MasmPrettyPrinter::printSectionHeaderDirective(
std::ostream& Stream, const gtirb::Section& Section) {
std::string Name = syntax.formatSectionName(Section.getName());
if (Name.empty()) {
gtirb::UUID UUID = Section.getUUID();
if (!RenamedSections.count(UUID)) {
size_t N = RenamedSections.size() + 1;
RenamedSections[UUID] = "unnamed_section_" + std::to_string(N);
}
Name = RenamedSections[UUID];
}
Stream << Name << ' ' << syntax.section();
}
void MasmPrettyPrinter::printSectionProperties(std::ostream& os,
const gtirb::Section& section) {
const auto* peSectionProperties =
module.getAuxData<gtirb::schema::PeSectionProperties>();
if (!peSectionProperties)
return;
const auto sectionProperties = peSectionProperties->find(section.getUUID());
if (sectionProperties == peSectionProperties->end())
return;
uint64_t flags = sectionProperties->second;
if (flags & IMAGE_SCN_MEM_READ)
os << " READ";
if (flags & IMAGE_SCN_MEM_WRITE)
os << " WRITE";
if (flags & IMAGE_SCN_MEM_EXECUTE)
os << " EXECUTE";
if (flags & IMAGE_SCN_MEM_SHARED)
os << " SHARED";
if (flags & IMAGE_SCN_MEM_NOT_PAGED)
os << " NOPAGE";
if (flags & IMAGE_SCN_MEM_NOT_CACHED)
os << " NOCACHE";
if (flags & IMAGE_SCN_MEM_DISCARDABLE)
os << " DISCARD";
if (flags & IMAGE_SCN_CNT_CODE)
os << " 'CODE'";
if (flags & IMAGE_SCN_CNT_INITIALIZED_DATA)
os << " 'DATA'";
};
void MasmPrettyPrinter::printSectionFooterDirective(
std::ostream& Stream, const gtirb::Section& Section) {
std::string Name = syntax.formatSectionName(Section.getName());
if (RenamedSections.count(Section.getUUID())) {
Name = RenamedSections[Section.getUUID()];
}
Stream << Name << ' ' << masmSyntax.ends() << '\n';
}
void MasmPrettyPrinter::printFunctionHeader(std::ostream& /* os */,
gtirb::Addr /* addr */) {
// TODO
}
void MasmPrettyPrinter::printFunctionFooter(std::ostream& /* os */,
gtirb::Addr /* addr */) {
// TODO
}
void MasmPrettyPrinter::fixupInstruction(cs_insn& inst) {
cs_x86& Detail = inst.detail->x86;
// Change GAS-specific MOVABS opcode to equivalent MOV opcode.
if (inst.id == X86_INS_MOVABS) {
std::string_view mnemonic(inst.mnemonic);
if (mnemonic.size() > 3) {
inst.mnemonic[3] = '\0';
}
}
// PBLENDVB/BLENDVPS have an implicit third argument (XMM0) required by MASM
if (inst.id == X86_INS_PBLENDVB || inst.id == X86_INS_BLENDVPS) {
if (Detail.op_count == 2) {
Detail.op_count = 3;
cs_x86_op& Op = Detail.operands[2];
Op.type = X86_OP_REG;
Op.reg = X86_REG_XMM0;
}
}
// TODO: These next two fixups of one-operand floating-point instructions need
// much more consideration.
// Floating point one-operand operations with an implicit FIRST operand.
// e.g fmul st(1) needs to be fmul st(0),st(1)
switch (inst.id) {
case X86_INS_FDIV:
case X86_INS_FDIVR:
case X86_INS_FSUB:
case X86_INS_FMUL:
if (Detail.op_count == 1) {
cs_x86_op& Op = Detail.operands[0];
if (Op.type == X86_OP_REG) {
Detail.operands[1] = Detail.operands[0];
Detail.operands[0].reg = X86_REG_ST0;
Detail.op_count = 2;
}
}
}
// Floating point one-operand operations with an implicit SECOND operand.
// e.g faddp st(2) needs to be faddp st(2),st(0)
switch (inst.id) {
case X86_INS_FADD:
case X86_INS_FMULP:
case X86_INS_FDIVP:
case X86_INS_FSUBR:
case X86_INS_FSUBP:
case X86_INS_FSUBRP:
case X86_INS_FDIVRP:
if (Detail.op_count == 1) {
cs_x86_op& Op = Detail.operands[0];
if (Op.type == X86_OP_REG) {
Detail.operands[1] = Detail.operands[0];
Detail.operands[1].reg = X86_REG_ST0;
Detail.op_count = 2;
}
}
}
// FUCOMPI has an implicit first operand and a different mnemonic.
// e.g. fucompi ST(1) should be fucomip ST(0),ST(1)
if (inst.id == X86_INS_FUCOMPI || inst.id == X86_INS_FUCOMI)
if (Detail.op_count == 1) {
cs_x86_op& Op = Detail.operands[0];
if (Op.type == X86_OP_REG && Op.reg == X86_REG_ST1) {
Detail.operands[1] = Detail.operands[0];
Detail.operands[0].reg = X86_REG_ST0;
Detail.op_count = 2;
inst.mnemonic[5] = 'i';
inst.mnemonic[6] = 'p';
}
}
// Omit implicit operands for scan string instructions.
switch (inst.id) {
case X86_INS_SCASB:
case X86_INS_SCASW:
case X86_INS_SCASD:
Detail.op_count = 0;
}
// The k1 register from AVX512 instructions is frequently set to NULL.
if (inst.id == X86_INS_KMOVB) {
cs_x86_op& Op = Detail.operands[0];
if (Op.type == X86_OP_REG && Op.reg == X86_REG_INVALID) {
Op.reg = X86_REG_K1;
}
}
if (inst.id == X86_INS_VCVTTPS2UQQ || inst.id == X86_INS_VCVTTPS2QQ) {
if (Detail.op_count > 1) {
cs_x86_op& Op = Detail.operands[1];
if (Op.type == X86_OP_REG && Op.reg == X86_REG_INVALID) {
Op.reg = X86_REG_K1;
}
}
}
// Change ATT-specific mnemonics PUSHAL/POPAL.
if (inst.id == X86_INS_PUSHAL) {
strcpy(inst.mnemonic, "pushad");
}
if (inst.id == X86_INS_POPAL) {
strcpy(inst.mnemonic, "popad");
}
// Omit LODSD operands.
if (inst.id == X86_INS_LODSD || inst.id == X86_INS_LODSB) {
Detail.op_count = 0;
}
// BOUND does not have a 64-bit mode.
if (inst.id == X86_INS_BOUND && Detail.op_count == 2 &&
Detail.operands[1].size == 8) {
Detail.operands[1].size = 4;
}
// BNDSTX and BNDLDX do not have 128-bit registers.
if (inst.id == X86_INS_BNDSTX || inst.id == X86_INS_BNDLDX) {
for (int i = 0; i < Detail.op_count; i++) {
if (Detail.operands[i].size == 16) {
Detail.operands[i].size = 4;
}
}
}
x86FixupInstruction(inst);
}
std::optional<std::string>
MasmPrettyPrinter::getForwardedSymbolName(const gtirb::Symbol* symbol) const {
if (std::optional<std::string> Name =
PrettyPrinterBase::getForwardedSymbolName(symbol)) {
return module.getISA() == gtirb::ISA::IA32 && (*Name)[0] != '?'
? "_" + *Name
: Name;
}
return std::nullopt;
}
std::string MasmPrettyPrinter::getRegisterName(unsigned int Reg) const {
// Uppercase `k1' causes a syntax error with MASM. Yes, really.
if (Reg == X86_REG_K1) {
return "k1";
}
return PrettyPrinterBase::getRegisterName(Reg);
}
void MasmPrettyPrinter::printSymbolDefinition(std::ostream& os,
const gtirb::Symbol& symbol) {
bool Exported = Exports.count(symbol.getUUID()) > 0;
if (symbol.getReferent<gtirb::DataBlock>()) {
if (Exported) {
os << syntax.global() << ' ' << getSymbolName(symbol) << '\n';
}
os << getSymbolName(symbol) << (symbol.getAtEnd() ? ":\n" : " ");
} else {
if (Exported) {
os << symbol.getName() << ' ' << masmSyntax.proc() << " EXPORT\n"
<< symbol.getName() << ' ' << masmSyntax.endp() << '\n';
} else {
os << getSymbolName(symbol) << ":\n";
}
}
}
void MasmPrettyPrinter::printSymbolDefinitionRelativeToPC(
std::ostream& os, const gtirb::Symbol& symbol, gtirb::Addr pc) {
auto symAddr = *symbol.getAddress();
os << getSymbolName(symbol) << " = " << syntax.programCounter();
if (symAddr > pc) {
os << " + " << (symAddr - pc);
} else if (symAddr < pc) {
os << " - " << (pc - symAddr);
}
os << "\n";
}
void MasmPrettyPrinter::printIntegralSymbol(std::ostream& os,
const gtirb::Symbol& symbol) {
if (*symbol.getAddress() == gtirb::Addr(0)) {
return;
}
os << getSymbolName(symbol) << " = " << std::hex
<< static_cast<uint64_t>(*symbol.getAddress()) << "H\n";
}
void MasmPrettyPrinter::printOpRegdirect(std::ostream& os, const cs_insn& inst,
uint64_t index) {
const cs_x86_op& op = inst.detail->x86.operands[index];
assert(op.type == X86_OP_REG &&
"printOpRegdirect called without a register operand");
os << getRegisterName(op.reg);
}
void MasmPrettyPrinter::printOpImmediate(
std::ostream& os, const gtirb::SymbolicExpression* symbolic,
const cs_insn& inst, uint64_t index) {
cs_x86& detail = inst.detail->x86;
const cs_x86_op& op = detail.operands[index];
assert(op.type == X86_OP_IMM &&
"printOpImmediate called without an immediate operand");
bool is_call = cs_insn_group(this->csHandle, &inst, CS_GRP_CALL);
bool is_jump = cs_insn_group(this->csHandle, &inst, CS_GRP_JUMP);
if (const gtirb::SymAddrConst* s = this->getSymbolicImmediate(symbolic)) {
// The operand is symbolic.
gtirb::Symbol& sym = *(s->Sym);
if (!is_call && !is_jump && !shouldSkip(sym)) {
// MASM variables are given a 64-bit type for PE32+, which results in an
// error when the symbol is written to a 32-bit register.
bool omit = false;
if (module.getISA() == gtirb::ISA::X64) {
if (auto addr = sym.getAddress(); addr && !sym.hasReferent()) {
// Integral symbol ...
for (int i = 0; i < detail.op_count; i++) {
if (detail.operands[i].size == 4 &&
detail.operands[i].access == CS_AC_WRITE) {
// written to a 32-bit operand.
omit = true;
break;
}
}
}
}
if (!omit) {
os << masmSyntax.offset() << ' ';
}
}
printSymbolicExpression(os, s, !is_call && !is_jump);
} else {
// The operand is just a number.
os << op.imm;
}
}
void MasmPrettyPrinter::printOpIndirect(
std::ostream& os, const gtirb::SymbolicExpression* symbolic,
const cs_insn& inst, uint64_t index) {
const cs_x86& detail = inst.detail->x86;
const cs_x86_op& op = detail.operands[index];
assert(op.type == X86_OP_MEM &&
"printOpIndirect called without a memory operand");
bool first = true;
uint64_t size = op.size;
// Indirect references to imported symbols should refer to the IAT entry,
// i.e.
// "__imp_foo"
if (const auto* s = std::get_if<gtirb::SymAddrConst>(symbolic)) {
std::optional<std::string> forwardedName = getForwardedSymbolName(s->Sym);
if (forwardedName) {
// If this references code, then it is (and should continue to) reference
// the jmp thunk of the import which will have the unprefixed "foo" symbol
// on it. If this references data, then it is (and should continue to)
// reference the relocation address (IAT entry) name "__imp_foo"
if (s->Sym->getReferent<gtirb::CodeBlock>())
os << *forwardedName;
else {
if (std::optional<std::string> Size = syntax.getSizeName(size * 8)) {
os << *Size << " PTR ";
}
os << "__imp_" << *forwardedName;
}
return;
}
}
//////////////////////////////////////////////////////////////////////////////
// Capstone incorrectly gives memory operands XMMWORD size.
if (inst.id == X86_INS_COMISD || inst.id == X86_INS_VCOMISD) {
size = 8;
}
if (inst.id == X86_INS_COMISS) {
size = 4;
}
//////////////////////////////////////////////////////////////////////////////
if (std::optional<std::string> sizeName = syntax.getSizeName(size * 8))
os << *sizeName << " PTR ";
if (op.mem.segment != X86_REG_INVALID)
os << getRegisterName(op.mem.segment) << ':';
os << '[';
if (op.mem.base != X86_REG_INVALID && op.mem.base != X86_REG_RIP) {
first = false;
os << getRegisterName(op.mem.base);
}
if (op.mem.index != X86_REG_INVALID) {
if (!first)
os << '+';
first = false;
os << getRegisterName(op.mem.index) << '*' << std::to_string(op.mem.scale);
}
if (const auto* s = std::get_if<gtirb::SymAddrConst>(symbolic)) {
if (!first)
os << '+';
printSymbolicExpression(os, s, false);
} else if (const auto* rel = std::get_if<gtirb::SymAddrAddr>(symbolic)) {
if (std::optional<gtirb::Addr> Addr = rel->Sym1->getAddress(); Addr) {
os << "+(" << masmSyntax.imagerel() << ' ' << getSymbolName(*rel->Sym1)
<< ")";
printAddend(os, rel->Offset, false);
}
} else {
printAddend(os, op.mem.disp, first);
}
os << ']';
}
void MasmPrettyPrinter::printSymbolicExpression(
std::ostream& os, const gtirb::SymAddrConst* sexpr, bool IsNotBranch) {
PrettyPrinterBase::printSymbolicExpression(os, sexpr, IsNotBranch);
}
void MasmPrettyPrinter::printSymbolicExpression(std::ostream& os,
const gtirb::SymAddrAddr* sexpr,
bool IsNotBranch) {
if (IsNotBranch && sexpr->Sym2 == ImageBase) {
os << masmSyntax.imagerel() << ' ';
printSymbolReference(os, sexpr->Sym1);
return;
}
PrettyPrinterBase::printSymbolicExpression(os, sexpr, IsNotBranch);
}
void MasmPrettyPrinter::printByte(std::ostream& os, std::byte byte) {
// Byte constants must start with a number for the MASM assembler.
os << syntax.byteData() << " 0" << std::hex << std::setfill('0')
<< std::setw(2) << static_cast<uint32_t>(byte) << 'H' << std::dec << '\n';
}
void MasmPrettyPrinter::printZeroDataBlock(std::ostream& os,
const gtirb::DataBlock& dataObject,
uint64_t offset) {
os << syntax.tab();
os << "DB " << (dataObject.getSize() - offset) << " DUP(0)" << '\n';
}
bool MasmPrettyPrinter::printSymbolReference(std::ostream& Stream,
const gtirb::Symbol* Symbol) {
if (Symbol && Symbol->getReferent<gtirb::DataBlock>()) {
if (std::optional<std::string> Name = getForwardedSymbolName(Symbol)) {
Stream << "__imp_" << *Name;
return true;
}
}
return PrettyPrinterBase::printSymbolReference(Stream, Symbol);
}
void MasmPrettyPrinter::printString(std::ostream& os, const gtirb::DataBlock& x,
uint64_t offset) {
std::string Chunk{""};
auto Range = x.bytes<uint8_t>();
for (uint8_t b :
boost::make_iterator_range(Range.begin() + offset, Range.end())) {
// NOTE: MASM only supports strings smaller than 256 bytes.
// and MASM only supports statements with 50 comma-separated items.
if (Chunk.size() >= 64) {
boost::replace_all(Chunk, "'", "''");
os << syntax.tab() << syntax.string() << " '" << Chunk << "'\n";
Chunk.clear();
}
// Aggegrate printable characters
if (std::isprint(b)) {
Chunk.append(1, b);
continue;
}
// Found non-printable character, output previous chunk and print byte
if (!Chunk.empty()) {
boost::replace_all(Chunk, "'", "''");
os << syntax.tab() << syntax.string() << " '" << Chunk << "'\n";
Chunk.clear();
}
os << syntax.tab();
printByte(os, static_cast<std::byte>(b));
}
}
void MasmPrettyPrinter::printFooter(std::ostream& os) {
os << '\n' << masmSyntax.end();
}
std::unique_ptr<PrettyPrinterBase>
MasmPrettyPrinterFactory::create(gtirb::Context& context, gtirb::Module& module,
const PrintingPolicy& policy) {
static const MasmSyntax syntax{};
static const Assembler assembler{};
return std::make_unique<MasmPrettyPrinter>(context, module, syntax, assembler,
policy);
}
} // namespace gtirb_pprint
| 32.251809 | 80 | 0.592794 | [
"model"
] |
6f4bf05f8cffc2900fdfbb9c0fa5abca8ad5fa9d | 71,960 | cxx | C++ | SkeletalRepresentationInitializer/Logic/vtkSlicerSkeletalRepresentationInitializerLogic.cxx | lopezmt/SlicerSkeletalRepresentation | 3d1deb599d4026e0931fad8721f8ce9c793a757f | [
"Apache-2.0"
] | null | null | null | SkeletalRepresentationInitializer/Logic/vtkSlicerSkeletalRepresentationInitializerLogic.cxx | lopezmt/SlicerSkeletalRepresentation | 3d1deb599d4026e0931fad8721f8ce9c793a757f | [
"Apache-2.0"
] | null | null | null | SkeletalRepresentationInitializer/Logic/vtkSlicerSkeletalRepresentationInitializerLogic.cxx | lopezmt/SlicerSkeletalRepresentation | 3d1deb599d4026e0931fad8721f8ce9c793a757f | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
==============================================================================*/
// SkeletalRepresentationInitializer Logic includes
#include "vtkSlicerSkeletalRepresentationInitializerLogic.h"
#include "vtkSmartPointer.h"
#include "vtkPolyDataReader.h"
#include "vtkPolyData.h"
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLModelNode.h>
#include <vtkMRMLModelDisplayNode.h>
#include <vtkMRMLDisplayNode.h>
#include <vtkMRMLMarkupsDisplayNode.h>
#include <vtkMRMLMarkupsFiducialNode.h>
#include <vtkMRMLMarkupsNode.h>
#include "vtkSlicerMarkupsLogic.h"
// VTK includes
#include <vtkIntArray.h>
#include <vtkMath.h>
#include <vtkNew.h>
#include <vtkDoubleArray.h>
#include <vtkCenterOfMass.h>
#include <vtkObjectFactory.h>
#include <vtkCurvatures.h>
#include <vtkVector.h>
#include <vtkWindowedSincPolyDataFilter.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkParametricEllipsoid.h>
#include <vtkParametricFunctionSource.h>
#include <vtkImplicitPolyDataDistance.h>
#include <vtkPolyDataNormals.h>
#include <vtkPoints.h>
#include <vtkLine.h>
#include <vtkQuad.h>
#include <vtkPolyData.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkDoubleArray.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkMassProperties.h>
// Eigen includes
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
// STD includes
#include <cassert>
#include <iostream>
// vtk system tools
#include <vtksys/SystemTools.hxx>
#include "vtkBackwardFlowLogic.h"
#include "qSlicerApplication.h"
#include <QString>
#define MAX_FILE_NAME 256
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkSlicerSkeletalRepresentationInitializerLogic);
//----------------------------------------------------------------------------
vtkSlicerSkeletalRepresentationInitializerLogic::vtkSlicerSkeletalRepresentationInitializerLogic()
{
}
//----------------------------------------------------------------------------
vtkSlicerSkeletalRepresentationInitializerLogic::~vtkSlicerSkeletalRepresentationInitializerLogic()
{
}
//----------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//---------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic::SetMRMLSceneInternal(vtkMRMLScene * newScene)
{
vtkNew<vtkIntArray> events;
events->InsertNextValue(vtkMRMLScene::NodeAddedEvent);
events->InsertNextValue(vtkMRMLScene::NodeRemovedEvent);
events->InsertNextValue(vtkMRMLScene::EndBatchProcessEvent);
this->SetAndObserveMRMLSceneEventsInternal(newScene, events.GetPointer());
}
//-----------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic::RegisterNodes()
{
assert(this->GetMRMLScene() != 0);
}
//---------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic::UpdateFromMRMLScene()
{
assert(this->GetMRMLScene() != 0);
}
//---------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic
::OnMRMLSceneNodeAdded(vtkMRMLNode* vtkNotUsed(node))
{
}
//---------------------------------------------------------------------------
void vtkSlicerSkeletalRepresentationInitializerLogic
::OnMRMLSceneNodeRemoved(vtkMRMLNode* vtkNotUsed(node))
{
}
// flow surface in one step
// basic idea: When the user select a mesh file, make a copy of vtk file in the application path.
// In each step of flow, read in that copy, flow it and save it the same place with same name.
// TODO: cleanup the hard disk when the module exits
int vtkSlicerSkeletalRepresentationInitializerLogic::FlowSurfaceOneStep(double dt, double smooth_amount)
{
std::cout << "flow one step : dt-" << dt << std::endl;
std::cout << "flow one step : smooth amount-" << smooth_amount << std::endl;
std::string tempFileName(this->GetApplicationLogic()->GetTemporaryPath());
tempFileName += "/temp_output.vtk";
vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(tempFileName.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> mesh = reader->GetOutput();
if(mesh == NULL)
{
vtkErrorMacro("No mesh has read in this module. Please select input mesh file first.");
return -1;
}
vtkSmartPointer<vtkMassProperties> mass_filter =
vtkSmartPointer<vtkMassProperties>::New();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double original_volume = mass_filter->GetVolume();
// std::cout << "Original Volume: " << original_volume << std::endl;
vtkSmartPointer<vtkWindowedSincPolyDataFilter> smooth_filter =
vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
smooth_filter->SetPassBand(smooth_amount);
smooth_filter->NonManifoldSmoothingOn();
smooth_filter->NormalizeCoordinatesOn();
smooth_filter->SetNumberOfIterations(20);
smooth_filter->FeatureEdgeSmoothingOff();
smooth_filter->BoundarySmoothingOff();
smooth_filter->SetInputData(mesh);
smooth_filter->Update();
if(smooth_amount > 0) {
mesh = smooth_filter->GetOutput();
}
// normal filter
vtkSmartPointer<vtkPolyDataNormals> normal_filter =
vtkSmartPointer<vtkPolyDataNormals>::New();
normal_filter->SplittingOff();
normal_filter->ComputeCellNormalsOff();
normal_filter->ComputePointNormalsOn();
normal_filter->SetInputData(mesh);
normal_filter->Update();
// curvature filter
vtkSmartPointer<vtkCurvatures> curvature_filter =
vtkSmartPointer<vtkCurvatures>::New();
curvature_filter->SetCurvatureTypeToMean();
curvature_filter->SetInputData(mesh);
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> H =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Mean_Curvature"));
if(H == NULL) {
vtkErrorMacro("error in getting mean curvature");
return -1;
}
vtkDataArray* N = normal_filter->GetOutput()->GetPointData()->GetNormals();
if(N == NULL) {
vtkErrorMacro("error in getting normals");
return -1;
}
// perform the flow
vtkSmartPointer<vtkPoints> points = mesh->GetPoints();
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
double curr_N[3];
N->GetTuple(i, curr_N);
double curr_H = H->GetValue(i);
for(int idx = 0; idx < 3; ++idx) {
p[idx] -= dt * curr_H * curr_N[idx];
}
points->SetPoint(i, p);
}
points->Modified();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double curr_volume = mass_filter->GetVolume();
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
for(int j = 0; j < 3; ++j) {
p[j] *= std::pow( original_volume / curr_volume , 1.0 / 3.0 );
}
// points->SetPoint(i, p);
}
points->Modified();
// firstly get other intermediate result invisible
HideNodesByNameByClass("curvature_flow_result","vtkMRMLModelNode");
HideNodesByNameByClass("best_fitting_ellipsoid_polydata", "vtkMRMLModelNode");
// then add this new intermediate result
const std::string modelName("curvature_flow_result");
AddModelNodeToScene(mesh, modelName.c_str(), true);
vtkSmartPointer<vtkPolyDataWriter> writer =
vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetInputData(mesh);
writer->SetFileName(tempFileName.c_str());
writer->Update();
// compute the fitting ellipsoid
vtkSmartPointer<vtkCenterOfMass> centerMassFilter =
vtkSmartPointer<vtkCenterOfMass>::New();
centerMassFilter->SetInputData(mesh);
centerMassFilter->SetUseScalarsAsWeights(false);
centerMassFilter->Update();
double center[3];
centerMassFilter->GetCenter(center);
// ShowFittingEllipsoid(points, curr_volume, center);
return 0;
}
void vtkSlicerSkeletalRepresentationInitializerLogic::SetInputFileName(const std::string &filename)
{
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(filename.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> mesh;
mesh = reader->GetOutput();
// output the original mesh
const std::string modelName("original");
AddModelNodeToScene(mesh, modelName.c_str(), true, 0.88, 0.88, 0.88);
// save
const std::string tempDir(this->GetApplicationLogic()->GetTemporaryPath());
std::string tempFileName;
tempFileName = tempDir + "/initial_surface.vtk";
vtkSmartPointer<vtkPolyDataWriter> writer =
vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetInputData(mesh);
writer->SetFileName(tempFileName.c_str());
writer->Update();
}
// flow surface to the end: either it's ellipsoidal enough or reach max_iter
int vtkSlicerSkeletalRepresentationInitializerLogic::FlowSurfaceMesh(const std::string &filename, double dt, double smooth_amount, int max_iter, int freq_output)
{
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(filename.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> mesh =
vtkSmartPointer<vtkPolyData>::New();
mesh = reader->GetOutput();
vtkSmartPointer<vtkMassProperties> mass_filter =
vtkSmartPointer<vtkMassProperties>::New();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double original_volume = mass_filter->GetVolume();
// default parameters
// double dt = 0.001;
// double smooth_amount = 0.03;
// int max_iter = 500;
int iter = 0;
double tolerance = 0.05;
double q = 1.0;
// create folder if not exist
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
std::string forwardFolder;
forwardFolder = tempFolder + "/forward";
std::cout << "forward folder" << forwardFolder << std::endl;
if (!vtksys::SystemTools::FileExists(forwardFolder, false))
{
if (!vtksys::SystemTools::MakeDirectory(forwardFolder))
{
std::cout << "Failed to create folder : " << forwardFolder << std::endl;
}
}
while(q > tolerance && iter < max_iter) {
// smooth filter
vtkSmartPointer<vtkWindowedSincPolyDataFilter> smooth_filter =
vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
smooth_filter->SetPassBand(smooth_amount);
smooth_filter->NonManifoldSmoothingOn();
smooth_filter->NormalizeCoordinatesOn();
smooth_filter->SetNumberOfIterations(20);
smooth_filter->FeatureEdgeSmoothingOff();
smooth_filter->BoundarySmoothingOff();
smooth_filter->SetInputData(mesh);
smooth_filter->Update();
if(smooth_amount > 0) {
mesh = smooth_filter->GetOutput();
}
// normal filter
vtkSmartPointer<vtkPolyDataNormals> normal_filter =
vtkSmartPointer<vtkPolyDataNormals>::New();
normal_filter->SplittingOff();
normal_filter->ComputeCellNormalsOff();
normal_filter->ComputePointNormalsOn();
normal_filter->SetInputData(mesh);
normal_filter->Update();
// curvature filter
vtkSmartPointer<vtkCurvatures> curvature_filter =
vtkSmartPointer<vtkCurvatures>::New();
curvature_filter->SetCurvatureTypeToMean();
curvature_filter->SetInputData(mesh);
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> H =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Mean_Curvature"));
if(H == NULL) {
std::cerr << "error in getting mean curvature" << std::endl;
return EXIT_FAILURE;
}
vtkDataArray* N = normal_filter->GetOutput()->GetPointData()->GetNormals();
if(N == NULL) {
std::cerr << "error in getting normals" << std::endl;
return EXIT_FAILURE;
}
// perform the flow
vtkSmartPointer<vtkPoints> points = mesh->GetPoints();
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
double curr_N[3];
N->GetTuple(i, curr_N);
double curr_H = H->GetValue(i);
for(int idx = 0; idx < 3; ++idx) {
p[idx] -= dt * curr_H * curr_N[idx];
}
points->SetPoint(i, p);
}
points->Modified();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double curr_volume = mass_filter->GetVolume();
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
for(int j = 0; j < 3; ++j) {
p[j] *= std::pow( original_volume / curr_volume , 1.0 / 3.0 );
}
// points->SetPoint(i, p);
}
points->Modified();
// save the result for the purpose of backward flow
std::string fileName;
fileName = forwardFolder + "/" + std::to_string(iter+1) + ".vtk";
vtkSmartPointer<vtkPolyDataWriter> writer =
vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetInputData(mesh);
writer->SetFileName(fileName.c_str());
writer->Update();
if((iter +1) % freq_output == 0)
{
const std::string modelName = "output" + std::to_string(iter+1);
AddModelNodeToScene(mesh, modelName.c_str(), false);
vtkSmartPointer<vtkCenterOfMass> centerMassFilter =
vtkSmartPointer<vtkCenterOfMass>::New();
centerMassFilter->SetInputData(mesh);
centerMassFilter->SetUseScalarsAsWeights(false);
centerMassFilter->Update();
double center[3];
centerMassFilter->GetCenter(center);
}
q -= 0.0001;
iter++;
}
forwardCount = iter;
double rx, ry, rz;
ShowFittingEllipsoid(mesh, rx, ry, rz);
GenerateSrepForEllipsoid(mesh, 5, 5, forwardCount);
return 1;
}
void vtkSlicerSkeletalRepresentationInitializerLogic::AddModelNodeToScene(vtkPolyData* mesh, const char* modelName, bool isModelVisible, double r, double g, double b)
{
std::cout << "AddModelNodeToScene: parameters:" << modelName << std::endl;
vtkMRMLScene *scene = this->GetMRMLScene();
if(!scene)
{
vtkErrorMacro(" Invalid scene");
return;
}
// model node
vtkSmartPointer<vtkMRMLModelNode> modelNode;
modelNode = vtkSmartPointer<vtkMRMLModelNode>::New();
modelNode->SetScene(scene);
modelNode->SetName(modelName);
modelNode->SetAndObservePolyData(mesh);
// display node
vtkSmartPointer<vtkMRMLModelDisplayNode> displayModelNode;
displayModelNode = vtkSmartPointer<vtkMRMLModelDisplayNode>::New();
if(displayModelNode == NULL)
{
vtkErrorMacro("displayModelNode is NULL");
return;
}
displayModelNode->SetColor(r, g, b);
displayModelNode->SetScene(scene);
displayModelNode->SetLineWidth(2.0);
displayModelNode->SetBackfaceCulling(0);
displayModelNode->SetRepresentation(1);
if(isModelVisible)
{
// make the 1st mesh after flow visible
displayModelNode->SetVisibility(1);
}
else
{
displayModelNode->SetVisibility(0);
}
scene->AddNode(displayModelNode);
modelNode->AddAndObserveDisplayNodeID(displayModelNode->GetID());
scene->AddNode(modelNode);
}
void vtkSlicerSkeletalRepresentationInitializerLogic::ShowFittingEllipsoid(vtkPolyData* mesh, double &rx, double &ry, double &rz)
{
vtkSmartPointer<vtkPoints> points = mesh->GetPoints();
Eigen::MatrixXd point_matrix(points->GetNumberOfPoints(), 3);
for(int i = 0; i < points->GetNumberOfPoints(); ++i)
{
double p[3];
points->GetPoint(i, p);
point_matrix.row(i) << p[0], p[1], p[2];
}
// compute best fitting ellipsoid
// For now assume that the surface is centered and rotationally aligned
// 1. compute the second moment after centering the data points
Eigen::MatrixXd center = point_matrix.colwise().mean();
Eigen::MatrixXd centered_point_mat = point_matrix - center.replicate(point_matrix.rows(), 1);
Eigen::MatrixXd point_matrix_transposed = centered_point_mat.transpose();
Eigen::Matrix3d second_moment = point_matrix_transposed * centered_point_mat;
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(second_moment);
Eigen::VectorXd radii = es.eigenvalues();
radii(0) = sqrt(radii(0));
radii(1) = sqrt(radii(1));
radii(2) = sqrt(radii(2));
double ellipsoid_volume = 4 / 3.0 * vtkMath::Pi() * radii(0) * radii(1) * radii(2);
vtkSmartPointer<vtkMassProperties> mass =
vtkSmartPointer<vtkMassProperties>::New();
mass->SetInputData(mesh);
mass->Update();
double volume_factor = pow(mass->GetVolume() / ellipsoid_volume, 1.0 / 3.0);
radii(0) *= volume_factor;
radii(1) *= volume_factor;
radii(2) *= volume_factor;
// obtain the best fitting ellipsoid from the second moment matrix
vtkSmartPointer<vtkParametricEllipsoid> ellipsoid =
vtkSmartPointer<vtkParametricEllipsoid>::New();
ellipsoid->SetXRadius(radii(0));
ellipsoid->SetYRadius(radii(1));
ellipsoid->SetZRadius(radii(2));
vtkSmartPointer<vtkParametricFunctionSource> parametric_function =
vtkSmartPointer<vtkParametricFunctionSource>::New();
parametric_function->SetParametricFunction(ellipsoid);
parametric_function->SetUResolution(30);
parametric_function->SetVResolution(30);
parametric_function->Update();
vtkSmartPointer<vtkPolyData> ellipsoid_polydata = parametric_function->GetOutput();
using namespace Eigen;
// Get ellipsoid points into the matrix
MatrixXd ellipsoid_points_matrix(ellipsoid_polydata->GetNumberOfPoints(), 3);
for(int i = 0; i < ellipsoid_polydata->GetNumberOfPoints(); ++i) {
double p[3];
ellipsoid_polydata->GetPoint(i,p);
ellipsoid_points_matrix(i,0) = p[0];
ellipsoid_points_matrix(i,1) = p[1];
ellipsoid_points_matrix(i,2) = p[2];
}
MatrixXd rotation;
rotation = es.eigenvectors(); // 3 by 3 rotation matrix
// rotate the points
MatrixXd rotated_ellipsoid_points = rotation * (ellipsoid_points_matrix.transpose());
rotated_ellipsoid_points.transposeInPlace(); // n x 3
// translate the points
MatrixXd translated_points = rotated_ellipsoid_points + center.replicate(rotated_ellipsoid_points.rows(),1);
// convert eigen matrix to vtk polydata
vtkSmartPointer<vtkPolyData> best_fitting_ellipsoid_polydata =
vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> best_fitting_ellipsoid_points =
vtkSmartPointer<vtkPoints>::New();
for(int i = 0; i < translated_points.rows(); ++i) {
double p[3] = {translated_points(i,0), translated_points(i,1), translated_points(i,2)};
best_fitting_ellipsoid_points->InsertNextPoint(p);
}
best_fitting_ellipsoid_polydata->SetPoints(best_fitting_ellipsoid_points);
best_fitting_ellipsoid_polydata->SetPolys(ellipsoid_polydata->GetPolys());
best_fitting_ellipsoid_polydata->Modified();
AddModelNodeToScene(best_fitting_ellipsoid_polydata, "best_fitting_ellipsoid", true, 1, 1, 0);
rx = radii(2); ry = radii(1); rz = radii(0);
// output to file
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
const std::string ellipsoidFile = tempFolder + "/ellipsoid.vtk";
vtkSmartPointer<vtkPolyDataWriter> writer =
vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetInputData(best_fitting_ellipsoid_polydata);
writer->SetFileName(ellipsoidFile.c_str());
writer->Update();
}
const double ELLIPSE_SCALE = 0.9;
const double EPS = 0.0001;
void vtkSlicerSkeletalRepresentationInitializerLogic::GenerateSrepForEllipsoid(vtkPolyData *mesh,
int nRows, int nCols, int totalNum)
{
// create folder if not exist
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
const std::string modelFolder = tempFolder + "/model";
std::cout << "s-reps folder" << modelFolder << std::endl;
if (!vtksys::SystemTools::FileExists(modelFolder, false))
{
if (!vtksys::SystemTools::MakeDirectory(modelFolder))
{
std::cout << "Failed to create folder : " << modelFolder << std::endl;
}
}
// copy surface of ellipsoid to model folder
const std::string ellSurfaceFile = tempFolder + "/ellipsoid.vtk";
const std::string newEllSurfaceFile = tempFolder + "/forward/" + std::to_string(totalNum + 1) + ".vtk";
vtksys::SystemTools::CopyAFile(ellSurfaceFile, newEllSurfaceFile, true);
using namespace Eigen;
// the number of rows should be odd number
double shift = 0.02; // shift fold curve off the inner spokes
nRows = 5; nCols = 5; // TODO: accept input values from user interface
// 1. derive the best fitting ellipsoid from the deformed mesh
vtkSmartPointer<vtkPoints> points = mesh->GetPoints();
MatrixXd point_matrix(points->GetNumberOfPoints(), 3);
for(int i = 0; i < points->GetNumberOfPoints(); ++i)
{
double p[3];
points->GetPoint(i, p);
point_matrix.row(i) << p[0], p[1], p[2];
}
MatrixXd center = point_matrix.colwise().mean();
MatrixXd centered_point_mat = point_matrix - center.replicate(point_matrix.rows(), 1);
MatrixXd point_matrix_transposed = centered_point_mat.transpose();
Matrix3d second_moment = point_matrix_transposed * centered_point_mat;
SelfAdjointEigenSolver<Eigen::MatrixXd> es_obj(second_moment);
VectorXd radii = es_obj.eigenvalues();
double rz = sqrt(radii(0));
double ry = sqrt(radii(1));
double rx = sqrt(radii(2));
double ellipsoid_volume = 4 / 3.0 * vtkMath::Pi() * rx * ry * rz;
vtkSmartPointer<vtkMassProperties> mass =
vtkSmartPointer<vtkMassProperties>::New();
mass->SetInputData(mesh);
mass->Update();
double volume_factor = pow(mass->GetVolume() / ellipsoid_volume, 1.0 / 3.0);
rz *= volume_factor;
ry *= volume_factor;
rx *= volume_factor;
double mrx_o = (rx*rx-rz*rz)/rx;
double mry_o = (ry*ry-rz*rz)/ry;
double mrb = mry_o * ELLIPSE_SCALE;
double mra = mrx_o * ELLIPSE_SCALE;
// 2. compute the skeletal points
int nCrestPoints = nRows*2 + (nCols-2)*2;
double deltaTheta = 2*vtkMath::Pi()/nCrestPoints;
MatrixXd skeletal_points_x(nRows, nCols);
MatrixXd skeletal_points_y(nRows, nCols);
//MatrixXd skeletal_points_z(nRows, nCols);
int r = 0, c = 0;
for(int i = 0; i < nCrestPoints; ++i)
{
double theta = vtkMath::Pi() - deltaTheta * floor(nRows/2) - deltaTheta*i;
double x = mra * cos(theta);
double y = mrb * sin(theta);
// these crest points have no inward points (side or corner of the s-rep)
skeletal_points_x(r, c) = x;
skeletal_points_y(r, c) = y;
//skeletal_points_z(r, c) = z;
if(i < nCols - 1)
{
// top row of crest points
c += 1;
}
else if(i < nCols - 1 + nRows - 1)
{
// right side col of crest points ( if the top-left point is the origin)
r = r + 1;
}
else if(i < nCols - 1 + nRows - 1 + nCols - 1)
{
// bottom row of crest points
c = c - 1;
}
else
{
// left side col of crest points
r = r - 1;
}
if((i < nCols - 1 && i > 0) || (i > nCols + nRows - 2 && i < 2*nCols + nRows - 3))
{
// compute skeletal points inward
double mx_ = (mra * mra - mrb * mrb) * cos(theta) / mra; // this is the middle line
double my_ = .0;
double dx_ = x - mx_;
double dy_ = y - my_;
int numSteps = floor(nRows/2); // steps from crest point to the skeletal point
double stepSize = 1.0 / double(numSteps); // step size on the half side of srep
for(int j = 0; j <= numSteps; ++j)
{
double tempX_ = mx_ + stepSize * j * dx_;
double tempY_ = my_ + stepSize * j * dy_;
if(i < nCols - 1)
{
// step from medial to top at current iteration on the top line
int currR = numSteps - j;
skeletal_points_x(currR, c-1) = tempX_;
skeletal_points_y(currR, c-1) = tempY_;
}
else
{
int currR = j + numSteps;
skeletal_points_x(currR, c+1) = tempX_;
skeletal_points_y(currR, c+1) = tempY_;
}
}
}
}
// 3. compute the head points of spokes
MatrixXd skeletal_points(nRows*nCols, 3);
MatrixXd bdry_points_up(nRows*nCols, 3);
MatrixXd bdry_points_down(nRows*nCols, 3);
MatrixXd bdry_points_crest(nCrestPoints, 3);
MatrixXd skeletal_points_crest(nCrestPoints, 3);
int id_pt = 0; int id_crest = 0;
MatrixXd shift_dir(nCrestPoints, 3); // shift direction for every crest point
for(int i = 0; i < nRows; ++i)
{
for(int j = 0; j < nCols; ++j)
{
double mx = skeletal_points_x(i,j);
double my = skeletal_points_y(i,j);
double sB = my * mrx_o;
double cB = mx * mry_o;
double l = sqrt(sB*sB + cB*cB);
double sB_n, cB_n;
if(l == 0)
{
sB_n = sB;
cB_n = cB;
}
else
{
sB_n = sB / l;
cB_n = cB / l;
}
double cA = l / (mrx_o * mry_o);
double sA = sqrt(1 - cA*cA);
double sx = rx * cA * cB_n - mx;
double sy = ry * cA * sB_n - my;
double sz = rz * sA;
double bx = (sx + mx);
double by = (sy + my);
double bz = (sz);
skeletal_points.row(id_pt) << mx, my, 0.0;
bdry_points_up.row(id_pt) << bx, by, bz;
bdry_points_down.row(id_pt) << bx, by, -bz;
id_pt++;
// fold curve
if(i == 0 || i == nRows - 1 || j == 0 || j == nCols - 1)
{
double cx = rx * cB_n - mx;
double cy = ry * sB_n - my;
double cz = 0;
Vector3d v, v2, v3;
v << cx, cy, cz;
v2 << sx, sy, 0.0;
double v_n = v.norm();
v2.normalize(); // v2 is the unit vector pointing out to norm dir
v3 = v_n * v2;
double bx = (v3(0) + mx);
double by = (v3(1) + my);
double bz = v3(2);
bdry_points_crest.row(id_crest) << bx, by, bz;
skeletal_points_crest.row(id_crest) << mx, my, 0.0;
shift_dir.row(id_crest) << v2(0), v2(1), v2(2);
id_crest++;
}
}
}
// 4. transform the s-rep
MatrixXd transpose_srep = skeletal_points.transpose(); // 3xn
Matrix3d srep_secondMoment = transpose_srep * skeletal_points; // 3x3
SelfAdjointEigenSolver<Eigen::MatrixXd> es_srep(srep_secondMoment);
Matrix3d rotation;
rotation = es_obj.eigenvectors(); // 3 by 3 rotation relative to deformed object
Matrix3d rot_srep;
rot_srep = es_srep.eigenvectors().transpose();
rotation = rotation * rot_srep;
// all skeletal points
MatrixXd trans_srep = (rotation * transpose_srep).transpose();
MatrixXd transformed_skeletal_points = trans_srep+
center.replicate(trans_srep.rows(), 1);
// up spoke head point on the bdry
MatrixXd transpose_up_pdm = bdry_points_up.transpose();
MatrixXd trans_up_pdm = (rotation * transpose_up_pdm).transpose();
MatrixXd transformed_up_pdm = trans_up_pdm +
center.replicate(trans_up_pdm.rows(), 1);
// down spoke head point on the bdry
MatrixXd transpose_down_pdm = bdry_points_down.transpose();
MatrixXd trans_down_pdm = (rotation * transpose_down_pdm).transpose();
MatrixXd transformed_down_pdm = trans_down_pdm +
center.replicate(trans_down_pdm.rows(), 1);
// crest head point on the bdry
MatrixXd transpose_crest_pdm = bdry_points_crest.transpose();
MatrixXd trans_crest_pdm = (rotation * transpose_crest_pdm).transpose();
MatrixXd transformed_crest_pdm = trans_crest_pdm + center.replicate(trans_crest_pdm.rows(), 1);
// crest base point on the skeletal sheet
MatrixXd transpose_crest_base = skeletal_points_crest.transpose();
MatrixXd trans_crest_base = (rotation * transpose_crest_base).transpose();
MatrixXd transformed_crest_base = trans_crest_base + center.replicate(trans_crest_base.rows(), 1);
// 5. transfer points to polydata
// srep_poly is supposed to form a mesh grid connecting skeletal points
vtkSmartPointer<vtkPolyData> srep_poly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> skeletal_sheet = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> skeletal_mesh = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPolyData> upSpokes_poly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> upSpokes_pts = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> upSpokes_lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPolyData> downSpokes_poly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> downSpokes_pts = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> downSpokes_lines = vtkSmartPointer<vtkCellArray>::New();
// TODO:crest spokes should be a little off the inner spokes
vtkSmartPointer<vtkPolyData> crestSpokes_poly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> crestSpokes_pts = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> crestSpokes_lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPolyData> foldCurve_poly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> foldCurve_pts = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> fold_curve = vtkSmartPointer<vtkCellArray>::New();
skeletal_sheet->SetDataTypeToDouble();
upSpokes_pts->SetDataTypeToDouble();
downSpokes_pts->SetDataTypeToDouble();
crestSpokes_pts->SetDataTypeToDouble();
foldCurve_pts->SetDataTypeToDouble();
vtkSmartPointer<vtkDoubleArray> upSpokeLengths = vtkSmartPointer<vtkDoubleArray>::New();
vtkSmartPointer<vtkDoubleArray> downSpokeLengths = vtkSmartPointer<vtkDoubleArray>::New();
vtkSmartPointer<vtkDoubleArray> crestSpokeLengths = vtkSmartPointer<vtkDoubleArray>::New();
upSpokeLengths->SetNumberOfComponents(1);
downSpokeLengths->SetNumberOfComponents(1);
crestSpokeLengths->SetNumberOfComponents(1);
upSpokeLengths->SetName("spokeLength");
downSpokeLengths->SetName("spokeLength");
crestSpokeLengths->SetName("spokeLength");
vtkSmartPointer<vtkDoubleArray> upSpokeDirs = vtkSmartPointer<vtkDoubleArray>::New();
vtkSmartPointer<vtkDoubleArray> downSpokeDirs = vtkSmartPointer<vtkDoubleArray>::New();
vtkSmartPointer<vtkDoubleArray> crestSpokeDirs = vtkSmartPointer<vtkDoubleArray>::New();
upSpokeDirs->SetNumberOfComponents(3);
downSpokeDirs->SetNumberOfComponents(3);
crestSpokeDirs->SetNumberOfComponents(3);
upSpokeDirs->SetName("spokeDirection");
downSpokeDirs->SetName("spokeDirection");
crestSpokeDirs->SetName("spokeDirection");
for(int i = 0; i < nRows * nCols; ++i)
{
// skeletal points
double mx = transformed_skeletal_points(i,0);
double my = transformed_skeletal_points(i,1);
double mz = transformed_skeletal_points(i,2);
int id0 = upSpokes_pts->InsertNextPoint(mx,my, mz);
double bx_up = transformed_up_pdm(i, 0);
double by_up = transformed_up_pdm(i, 1);
double bz_up = transformed_up_pdm(i, 2);
int id1 = upSpokes_pts->InsertNextPoint(bx_up, by_up, bz_up);
// spoke length and dir
vtkVector3d upSpoke(bx_up-mx, by_up-my, bz_up-mz);
double upSpokeLength = upSpoke.Normalize();
upSpokeLengths->InsertNextTuple1(upSpokeLength);
upSpokeDirs->InsertNextTuple3(upSpoke.GetX(), upSpoke.GetY(), upSpoke.GetZ());
// form up spokes
vtkSmartPointer<vtkLine> up_arrow = vtkSmartPointer<vtkLine>::New();
up_arrow->GetPointIds()->SetId(0, id0);
up_arrow->GetPointIds()->SetId(1, id1);
upSpokes_lines->InsertNextCell(up_arrow);
// form down spokes
int id2 = downSpokes_pts->InsertNextPoint(mx, my, mz);
double bx_down = transformed_down_pdm(i,0);
double by_down = transformed_down_pdm(i,1);
double bz_down = transformed_down_pdm(i,2);
int id3 = downSpokes_pts->InsertNextPoint(bx_down,by_down,bz_down);
// spoke length and dir
vtkVector3d downSpoke(bx_down-mx, by_down-my, bz_down-mz);
double downSpokeLength = downSpoke.Normalize();
downSpokeLengths->InsertNextTuple1(downSpokeLength);
downSpokeDirs->InsertNextTuple3(downSpoke.GetX(), downSpoke.GetY(), downSpoke.GetZ());
vtkSmartPointer<vtkLine> down_arrow = vtkSmartPointer<vtkLine>::New();
down_arrow->GetPointIds()->SetId(0, id2);
down_arrow->GetPointIds()->SetId(1, id3);
downSpokes_lines->InsertNextCell(down_arrow);
}
// display up spokes
upSpokes_poly->SetPoints(upSpokes_pts);
upSpokes_poly->SetLines(upSpokes_lines);
upSpokes_poly->GetPointData()->AddArray(upSpokeDirs);
upSpokes_poly->GetPointData()->SetActiveVectors("spokeDirection");
upSpokes_poly->GetPointData()->AddArray(upSpokeLengths);
upSpokes_poly->GetPointData()->SetActiveScalars("spokeLength");
AddModelNodeToScene(upSpokes_poly, "up spokes for ellipsoid", true, 0, 1, 1);
// write to file
vtkSmartPointer<vtkPolyDataWriter> upSpokeWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
const std::string upFileName = modelFolder + "/up" + std::to_string(totalNum) + ".vtk";
const std::string downFileName = modelFolder + "/down" + std::to_string(totalNum) + ".vtk";
const std::string crestFileName = modelFolder + "/crest" + std::to_string(totalNum) + ".vtk";
upSpokeWriter->SetFileName(upFileName.c_str());
upSpokeWriter->SetInputData(upSpokes_poly);
upSpokeWriter->Update();
// display down spokes
downSpokes_poly->SetPoints(downSpokes_pts);
downSpokes_poly->SetLines(downSpokes_lines);
downSpokes_poly->GetPointData()->AddArray(downSpokeDirs);
downSpokes_poly->GetPointData()->SetActiveVectors("spokeDirection");
downSpokes_poly->GetPointData()->AddArray(downSpokeLengths);
downSpokes_poly->GetPointData()->SetActiveScalars("spokeLength");
AddModelNodeToScene(downSpokes_poly, "down spokes for ellipsoid", true, 1, 0, 1);
vtkSmartPointer<vtkPolyDataWriter> downSpokeWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
downSpokeWriter->SetFileName(downFileName.c_str());
downSpokeWriter->SetInputData(downSpokes_poly);
downSpokeWriter->Update();
// deal with skeletal mesh
for(int i = 0; i < nRows * nCols; ++i)
{
double mx = transformed_skeletal_points(i, 0);
double my = transformed_skeletal_points(i, 1);
double mz = transformed_skeletal_points(i, 2);
int current_id = skeletal_sheet->InsertNextPoint(mx, my, mz);
int current_row = floor(i / nRows);
int current_col = i - current_row * nRows;
if(current_col >= 0 && current_row >= 0
&& current_row < nRows-1 && current_col < nCols - 1)
{
vtkSmartPointer<vtkQuad> quad = vtkSmartPointer<vtkQuad>::New();
quad->GetPointIds()->SetId(0, current_id);
quad->GetPointIds()->SetId(1, current_id + nCols);
quad->GetPointIds()->SetId(2, current_id + nCols + 1);
quad->GetPointIds()->SetId(3, current_id + 1);
skeletal_mesh->InsertNextCell(quad);
}
}
srep_poly->SetPoints(skeletal_sheet);
srep_poly->SetPolys(skeletal_mesh);
AddModelNodeToScene(srep_poly, "skeletal mesh for ellipsoid", true, 0, 0, 0);
const std::string meshFileName = modelFolder + "/mesh" + std::to_string(totalNum) + ".vtk";
vtkSmartPointer<vtkPolyDataWriter> meshWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
meshWriter->SetFileName(meshFileName.c_str());
meshWriter->SetInputData(srep_poly);
meshWriter->Update();
// deal with crest spokes
for(int i = 0; i < nCrestPoints; ++i)
{
// tail point
double cx_t = transformed_crest_base(i, 0);
double cy_t = transformed_crest_base(i, 1);
double cz_t = transformed_crest_base(i, 2);
// head point (_b means boundary)
double cx_b = transformed_crest_pdm(i, 0);
double cy_b = transformed_crest_pdm(i, 1);
double cz_b = transformed_crest_pdm(i, 2);
if(shift > 0)
{
double shift_x = (cx_b - cx_t) * shift;
double shift_y = (cy_b - cy_t) * shift;
double shift_z = (cz_b - cz_t) * shift;
cx_t += shift_x;
cy_t += shift_y;
cz_t += shift_z;
}
int id0 = crestSpokes_pts->InsertNextPoint(cx_t, cy_t, cz_t);
int id1 = crestSpokes_pts->InsertNextPoint(cx_b, cy_b, cz_b);
vtkSmartPointer<vtkLine> crest_arrow = vtkSmartPointer<vtkLine>::New();
crest_arrow->GetPointIds()->SetId(0, id0);
crest_arrow->GetPointIds()->SetId(1, id1);
crestSpokes_lines->InsertNextCell(crest_arrow);
vtkVector3d crestSpoke(cx_b-cx_t, cy_b-cy_t, cz_b-cz_t);
double crestSpokeLength = crestSpoke.Normalize();
crestSpokeLengths->InsertNextTuple1(crestSpokeLength);
crestSpokeDirs->InsertNextTuple3(crestSpoke.GetX(), crestSpoke.GetY(), crestSpoke.GetZ());
}
crestSpokes_poly->SetPoints(crestSpokes_pts);
crestSpokes_poly->SetLines(crestSpokes_lines);
crestSpokes_poly->GetPointData()->AddArray(crestSpokeDirs);
crestSpokes_poly->GetPointData()->SetActiveVectors("spokeDirection");
crestSpokes_poly->GetPointData()->AddArray(crestSpokeLengths);
crestSpokes_poly->GetPointData()->SetActiveScalars("spokeLength");
AddModelNodeToScene(crestSpokes_poly, "crest spokes for ellipsoid", true, 1, 0, 0);
vtkSmartPointer<vtkPolyDataWriter> crestSpokeWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
crestSpokeWriter->SetFileName(crestFileName.c_str());
crestSpokeWriter->SetInputData(crestSpokes_poly);
crestSpokeWriter->Update();
// deal with fold curve
for(int i = 0; i < nCrestPoints; ++i)
{
double cx_t = transformed_crest_base(i, 0);
double cy_t = transformed_crest_base(i, 1);
double cz_t = transformed_crest_base(i, 2);
double cx_b = transformed_crest_pdm(i, 0);
double cy_b = transformed_crest_pdm(i, 1);
double cz_b = transformed_crest_pdm(i, 2);
if(shift > 0)
{
double shift_x = (cx_b - cx_t) * shift;
double shift_y = (cy_b - cy_t) * shift;
double shift_z = (cz_b - cz_t) * shift;
cx_t += shift_x;
cy_t += shift_y;
cz_t += shift_z;
}
int id0 = foldCurve_pts->InsertNextPoint(cx_t, cy_t, cz_t);
if(id0 > 0 && i < nCols)
{
// first row
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, id0-1);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
if(i > nCols && i < nCols + 2*(nRows-2) + 1 && (i-nCols) % 2 == 1)
{
// right side of crest
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, id0-2);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
if(i > nCols && i < nCols + 2*(nRows-2) + 1 && (i-nCols) % 2 == 0)
{
// part of left side
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, id0-2);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
if(i == nCols)
{
// remaining part of left side
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, 0);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
if(i > nCols + 2*(nRows-2))
{
//bottom side
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, id0-1);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
if(i == nCrestPoints - 1)
{
// bottome right
vtkSmartPointer<vtkLine> fold_seg = vtkSmartPointer<vtkLine>::New();
fold_seg->GetPointIds()->SetId(0, id0-nCols);
fold_seg->GetPointIds()->SetId(1, id0);
fold_curve->InsertNextCell(fold_seg);
}
}
foldCurve_poly->SetPoints(foldCurve_pts);
foldCurve_poly->SetLines(fold_curve);
AddModelNodeToScene(foldCurve_poly, "fold curve of ellipsoid", true, 1, 1, 0);
const std::string curveFileName = modelFolder + "/curve" + std::to_string(totalNum) + ".vtk";
vtkSmartPointer<vtkPolyDataWriter> curveWriter = vtkSmartPointer<vtkPolyDataWriter>::New();
curveWriter->SetFileName(curveFileName.c_str());
curveWriter->SetInputData(foldCurve_poly);
curveWriter->Update();
}
void vtkSlicerSkeletalRepresentationInitializerLogic::HideNodesByNameByClass(const std::string & nodeName, const std::string &className)
{
std::cout << "node name:" << nodeName << std::endl;
std::cout << "class name:" << className << std::endl;
std::vector<vtkMRMLNode*> vectModelNodes;
vtkSmartPointer<vtkCollection> modelNodes = this->GetMRMLScene()->GetNodesByClassByName(className.c_str(), nodeName.c_str());
modelNodes->InitTraversal();
for(int i = 0; i < modelNodes->GetNumberOfItems(); i++)
{
vtkSmartPointer<vtkMRMLModelNode> thisModelNode = vtkMRMLModelNode::SafeDownCast(modelNodes->GetNextItemAsObject());
vtkSmartPointer<vtkMRMLModelDisplayNode> displayNode;
displayNode = thisModelNode->GetModelDisplayNode();
if(displayNode == NULL)
{
continue;
}
displayNode->SetVisibility(0);
}
}
void vtkSlicerSkeletalRepresentationInitializerLogic::HideNodesByClass(const std::string &className)
{
std::cout << "Hide node class name:" << className << std::endl;
std::vector<vtkMRMLNode*> vectModelNodes;
vtkSmartPointer<vtkCollection> modelNodes = this->GetMRMLScene()->GetNodesByClass(className.c_str());
modelNodes->InitTraversal();
for(int i = 0; i < modelNodes->GetNumberOfItems(); i++)
{
vtkSmartPointer<vtkMRMLModelNode> thisModelNode = vtkMRMLModelNode::SafeDownCast(modelNodes->GetNextItemAsObject());
vtkSmartPointer<vtkMRMLModelDisplayNode> displayNode;
displayNode = thisModelNode->GetModelDisplayNode();
if(displayNode == NULL)
{
continue;
}
displayNode->SetVisibility(0);
}
}
int vtkSlicerSkeletalRepresentationInitializerLogic::InklingFlow(const std::string &filename, double dt, double smooth_amount, int max_iter, int freq_output, double /*threshold*/)
{
//std::cout << threshold << std::endl;
std::cout << filename << std::endl;
std::cout << dt << std::endl;
std::cout << smooth_amount << std::endl;
std::cout << max_iter << std::endl;
std::cout << freq_output << std::endl;
std::string tempFileName(this->GetApplicationLogic()->GetTemporaryPath());
tempFileName += "/temp_output.vtk";
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName(tempFileName.c_str());
reader->Update();
vtkSmartPointer<vtkPolyData> mesh =
vtkSmartPointer<vtkPolyData>::New();
mesh = reader->GetOutput();
vtkSmartPointer<vtkMassProperties> mass_filter =
vtkSmartPointer<vtkMassProperties>::New();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double original_volume = mass_filter->GetVolume();
int iter = 0;
double tolerance = 0.05;
double q = 1.0;
while(q > tolerance && iter < max_iter)
{
// smooth filter
vtkSmartPointer<vtkWindowedSincPolyDataFilter> smooth_filter =
vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
smooth_filter->SetPassBand(smooth_amount);
smooth_filter->NonManifoldSmoothingOn();
smooth_filter->NormalizeCoordinatesOn();
smooth_filter->SetNumberOfIterations(20);
smooth_filter->FeatureEdgeSmoothingOff();
smooth_filter->BoundarySmoothingOff();
smooth_filter->SetInputData(mesh);
smooth_filter->Update();
if(smooth_amount > 0) {
mesh = smooth_filter->GetOutput();
}
// normal filter
vtkSmartPointer<vtkPolyDataNormals> normal_filter =
vtkSmartPointer<vtkPolyDataNormals>::New();
normal_filter->SplittingOff();
normal_filter->ComputeCellNormalsOff();
normal_filter->ComputePointNormalsOn();
normal_filter->SetInputData(mesh);
normal_filter->Update();
vtkDataArray* N = normal_filter->GetOutput()->GetPointData()->GetNormals();
if(N == NULL) {
std::cerr << "error in getting normals" << std::endl;
return EXIT_FAILURE;
}
// mean curvature filter
vtkSmartPointer<vtkCurvatures> curvature_filter =
vtkSmartPointer<vtkCurvatures>::New();
curvature_filter->SetCurvatureTypeToMean();
curvature_filter->SetInputData(mesh);
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> H =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Mean_Curvature"));
if(H == NULL) {
std::cerr << "error in getting mean curvature" << std::endl;
return EXIT_FAILURE;
}
curvature_filter->SetCurvatureTypeToGaussian();
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> K =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Gauss_Curvature"));
if(K == NULL) {
std::cerr << "error in getting Gaussian curvature" << std::endl;
return EXIT_FAILURE;
}
curvature_filter->SetCurvatureTypeToMaximum();
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> MC =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Maximum_Curvature"));
if(MC == NULL) {
std::cerr << "error in getting max curvature" << std::endl;
return EXIT_FAILURE;
}
curvature_filter->SetCurvatureTypeToMinimum();
curvature_filter->Update();
vtkSmartPointer<vtkDoubleArray> MinC =
vtkDoubleArray::SafeDownCast(curvature_filter->GetOutput()->GetPointData()->GetArray("Minimum_Curvature"));
if(MinC == NULL)
{
std::cout << "error in getting min curvature" << std::endl;
return -1;
}
// perform the flow
vtkSmartPointer<vtkPoints> points = mesh->GetPoints();
double maxVal = -10000.0;
double maxIndex = -1;
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
double curr_N[3];
N->GetTuple(i, curr_N);
double curr_H = H->GetValue(i);
//double curr_K = K->GetValue(i);
double curr_max = MC->GetValue(i);
double curr_min = MinC->GetValue(i);
double delta = 0.0;
double diffK = curr_max - curr_min;
delta = dt * curr_H; // * 1 / (diffK * diffK);
diffK = abs(diffK);
if(diffK > maxVal)
{
maxVal = diffK;
maxIndex = i;
}
if(curr_max >= 0 && curr_min >= 0)
{
delta = dt * curr_max;
}
else if(curr_max < 0 && curr_min < 0)
{
delta = dt * curr_min;
}
else
{
delta = dt * curr_H;
}
for(int idx = 0; idx < 3; ++idx)
{
p[idx] -= delta * curr_N[idx]; //dt * curr_H * curr_N[idx];
}
points->SetPoint(i, p);
}
points->Modified();
mass_filter->SetInputData(mesh);
mass_filter->Update();
double curr_volume = mass_filter->GetVolume();
for(int i = 0; i < points->GetNumberOfPoints(); ++i) {
double p[3];
points->GetPoint(i, p);
for(int j = 0; j < 3; ++j) {
p[j] *= std::pow( original_volume / curr_volume , 1.0 / 3.0 );
}
}
points->Modified();
double testRender[3];
points->GetPoint(maxIndex, testRender);
// AddPointToScene(testRender[0], testRender[1], testRender[2], 13); // sphere3D
HideNodesByNameByClass("output_inkling","vtkMRMLModelNode");
// then add this new intermediate result
// vtkSmartPointer<vtkPolyDataWriter> writer =
// vtkSmartPointer<vtkPolyDataWriter>::New();
// writer->SetInputData(mesh);
// writer->SetFileName("temp_output.vtk");
// writer->Update();
// char modelName[128];
// sprintf(modelName, "output_inkling");
// AddModelNodeToScene(mesh, modelName, true);
if((iter +1) % freq_output == 0)
{
std::string modelName("output_inkling");
modelName += std::to_string(iter+1);
AddModelNodeToScene(mesh, modelName.c_str(), false);
}
q -= 0.0001;
iter++;
}
return 1;
}
void vtkSlicerSkeletalRepresentationInitializerLogic::AddPointToScene(double x, double y, double z, int glyphType, double r, double g, double b)
{
std::cout << "AddPointToScene: parameters:" << x << ", y:" << y << ", z:" << z << std::endl;
vtkMRMLScene *scene = this->GetMRMLScene();
if(!scene)
{
vtkErrorMacro(" Invalid scene");
return;
}
// node which controls display properties
vtkSmartPointer<vtkMRMLMarkupsDisplayNode> displayNode;
displayNode = vtkSmartPointer<vtkMRMLMarkupsDisplayNode>::New();
// this->SetDisplayNodeToDefaults(displayNode);
displayNode->SetGlyphScale(1.10);
displayNode->SetTextScale(3.40);
displayNode->SetSelectedColor(r, g, b);
displayNode->SetGlyphType(glyphType); // 13: sphere3D
scene->AddNode(displayNode);
// model node
vtkSmartPointer<vtkMRMLMarkupsFiducialNode> fidNode;
fidNode = vtkSmartPointer<vtkMRMLMarkupsFiducialNode>::New();
if(fidNode == NULL)
{
vtkErrorMacro("fidNode is NULL");
return;
}
fidNode->SetAndObserveDisplayNodeID(displayNode->GetID());
fidNode->SetLocked(true);
fidNode->SetName("Hi");
scene->AddNode(fidNode);
fidNode->AddFiducial(x, y, z);
}
// compute and apply tps transformation matrix
void vtkSlicerSkeletalRepresentationInitializerLogic::ComputePairwiseTps(int totalNum)
{
typedef itkThinPlateSplineExtended TransformType;
typedef itk::Point< CoordinateRepType, 3 > PointType;
typedef TransformType::PointSetType PointSetType;
typedef PointSetType::PointIdentifier PointIdType;
// create folder if not exist
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
const std::string backwardFolder = tempFolder + "/backward";
std::cout << "backward folder" << backwardFolder << std::endl;
if (!vtksys::SystemTools::FileExists(backwardFolder, false))
{
if (!vtksys::SystemTools::MakeDirectory(backwardFolder))
{
std::cout << "Failed to create folder : " << backwardFolder << std::endl;
}
}
// compute transformation matrix by current surface and backward surface
vtkSmartPointer<vtkPolyDataReader> sourceSurfaceReader = vtkSmartPointer<vtkPolyDataReader>::New();
vtkSmartPointer<vtkPolyDataReader> targetSurfaceReader = vtkSmartPointer<vtkPolyDataReader>::New();
std::cout << "Computing pairwise transformation matrix via TPS for " << totalNum << " cases..." << std::endl;
for(int stepNum = totalNum; stepNum > 1; --stepNum)
{
const std::string inputMeshFile = tempFolder + "/forward/" + std::to_string(stepNum) + ".vtk";
const std::string nextMeshFile = tempFolder + "/forward/" + std::to_string(stepNum - 1) + ".vtk";
sourceSurfaceReader->SetFileName(inputMeshFile.c_str());
sourceSurfaceReader->Update();
// current surface mesh
vtkSmartPointer<vtkPolyData> polyData_source = sourceSurfaceReader->GetOutput();
targetSurfaceReader->SetFileName(nextMeshFile.c_str());
targetSurfaceReader->Update();
// next surface mesh which back flow to
vtkSmartPointer<vtkPolyData> polyData_target = targetSurfaceReader->GetOutput();
PointSetType::Pointer sourceLandMarks = PointSetType::New();
PointSetType::Pointer targetLandMarks = PointSetType::New();
PointType p1; PointType p2; // same as double p1[3];
PointSetType::PointsContainer::Pointer sourceLandMarkContainer
= sourceLandMarks->GetPoints();
PointSetType::PointsContainer::Pointer targetLandMarkContainer
= targetLandMarks->GetPoints();
PointIdType id_s = itk::NumericTraits< PointIdType >::Zero;
PointIdType id_t = itk::NumericTraits< PointIdType >::Zero;
// Read in the source points set
for(unsigned int i = 0; i < polyData_source->GetNumberOfPoints(); i += 10){
double p[3];
polyData_source->GetPoint(i,p);
p1[0] = p[0];
p1[1] = p[1];
p1[2] = p[2];
sourceLandMarkContainer->InsertElement(id_s, p1);
id_s++;
}
// Read in the target points set
for(unsigned int i = 0; i < polyData_target->GetNumberOfPoints(); i += 10){
double p[3];
polyData_target->GetPoint(i,p);
p2[0] = p[0];
p2[1] = p[1];
p2[2] = p[2];
targetLandMarkContainer->InsertElement(id_t, p2);
id_t++;
}
TransformType::Pointer tps = TransformType::New();
tps->SetSourceLandmarks(sourceLandMarks);
tps->SetTargetLandmarks(targetLandMarks);
tps->ComputeWMatrix();
// Apply tps on the srep in future (from the ellipsoid)
// srep of totalNum == srep of ellipsoid
// std::cout << "Applying transformation matrix on from step:" << stepNum << " to " << stepNum-1 << std::endl;
std::string upFileName = tempFolder + "/model/up" + std::to_string(stepNum) + ".vtk";
std::string downFileName = tempFolder + "/model/down" + std::to_string(stepNum) + ".vtk";
std::string crestFileName = tempFolder + "/model/crest" + std::to_string(stepNum) + ".vtk";
// read source srep
vtkSmartPointer<vtkPolyDataReader> upSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
upSpokeReader->SetFileName(upFileName.c_str());
upSpokeReader->Update();
vtkSmartPointer<vtkPolyData> upSpokes = upSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> downSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
downSpokeReader->SetFileName(downFileName.c_str());
downSpokeReader->Update();
vtkSmartPointer<vtkPolyData> downSpokes = downSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> crestSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
crestSpokeReader->SetFileName(crestFileName.c_str());
crestSpokeReader->Update();
vtkSmartPointer<vtkPolyData> crestSpokes = crestSpokeReader->GetOutput();
upFileName = tempFolder + "/model/up" + std::to_string(stepNum - 1) + ".vtk";
std::string upOutputFile(upFileName.c_str());
TransformNOutput(tps, upSpokes, upOutputFile);
// display upspokes
downFileName = tempFolder + "/model/down" + std::to_string(stepNum - 1) + ".vtk";
std::string downOutputFile(downFileName.c_str());
TransformNOutput(tps, downSpokes, downOutputFile);
crestFileName = tempFolder + "/model/crest" + std::to_string(stepNum - 1) + ".vtk";
std::string crestOutputFile(crestFileName.c_str());
TransformNOutput(tps, crestSpokes, crestOutputFile);
// Apply transformation matrix on the skeletal sheet and fold curve
std::string meshFileName(tempFolder);
meshFileName = tempFolder + "/model/mesh" + std::to_string(stepNum) + ".vtk";// Transform input
vtkSmartPointer<vtkPolyDataReader> meshReader = vtkSmartPointer<vtkPolyDataReader>::New();
meshReader->SetFileName(meshFileName.c_str());
meshReader->Update();
vtkSmartPointer<vtkPolyData> meshPoly = meshReader->GetOutput();
meshFileName = tempFolder + "/model/mesh" + std::to_string(stepNum-1) + ".vtk";// output
TransformPoints(tps, meshPoly, meshFileName);
std::string curveFileName(tempFolder);
curveFileName = tempFolder + "/model/curve" + std::to_string(stepNum) + ".vtk"; // Transform input
vtkSmartPointer<vtkPolyDataReader> curveReader = vtkSmartPointer<vtkPolyDataReader>::New();
curveReader->SetFileName(curveFileName.c_str());
curveReader->Update();
vtkSmartPointer<vtkPolyData> curvePoly = curveReader->GetOutput();
curveFileName = tempFolder + "/model/curve" + std::to_string(stepNum-1) + ".vtk"; // output
TransformPoints(tps, curvePoly, curveFileName);
}
}
void vtkSlicerSkeletalRepresentationInitializerLogic::BackwardFlow(int totalNum)
{
// 1. compute pairwise TPS
ComputePairwiseTps(totalNum);
std::cout << "Finished computing transformation matrix." << std::endl;
std::cout << "Finished applying transformation matrix." << std::endl;
// 2. display the srep for the initial object
DisplayResultSrep();
}
int vtkSlicerSkeletalRepresentationInitializerLogic::ApplyTps(int totalNum)
{
std::cout << "Applying transformation matrix to s-reps..." << std::endl;
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
typedef double CoordinateRepType;
typedef itkThinPlateSplineExtended TransformType;
typedef itk::Point< CoordinateRepType, 3 > PointType;
typedef TransformType::PointSetType PointSetType;
typedef PointSetType::PointIdentifier PointIdType;
for(int stepNum = totalNum; stepNum > 0; --stepNum)
{
const std::string transformFileName = tempFolder + "/backward/" + std::to_string(stepNum) + ".txt";
ifstream inFile;
inFile.open(transformFileName);
if(!inFile) {
std::cerr << "Unable to open the file: " << transformFileName << std::endl;
return -1;
}
itkThinPlateSplineExtended::DMatrixType D;
itkThinPlateSplineExtended::AMatrixType A;
itkThinPlateSplineExtended::BMatrixType B;
// first read in the size
std::string buffer;
std::getline(inFile,buffer);
std::istringstream ss1(buffer);
int nRows = 0;
int nCols = 0;
char tmp;
ss1 >> nRows >> tmp >> nCols;
D.set_size(nRows,nCols);
for(int i = 0; i < nRows; i++) {
for(int j = 0; j < nCols; j++) {
std::string buffer2;
std::getline(inFile, buffer2, ',');
double entry = atof(buffer2.c_str());
D(i,j) = entry;
}
}
buffer.clear();
std::getline(inFile, buffer);
std::getline(inFile, buffer);
for(unsigned int i = 0; i < A.rows(); i++) {
for(unsigned int j = 0; j < A.cols(); j++) {
std::string buffer2;
std::getline(inFile, buffer2,',');
double entry = atof(buffer2.c_str());
A(i,j) = entry;
}
}
buffer.clear();
std::getline(inFile, buffer);
std::getline(inFile, buffer);
for(unsigned int i = 0; i < B.size(); i++) {
std::string buffer2;
std::getline(inFile, buffer2, ',');
double entry = atof(buffer2.c_str());
B(i) = entry;
}
TransformType::Pointer tps = TransformType::New();
tps->setDMatrix(D);
tps->setAMatrix(A);
tps->setBVector(B);
PointSetType::Pointer sourceLandMarks = PointSetType::New();
PointSetType::PointsContainer::Pointer sourceLandMarkContainer = sourceLandMarks->GetPoints();
vtkSmartPointer<vtkPolyDataReader> reader_source = vtkSmartPointer<vtkPolyDataReader>::New();
vtkSmartPointer<vtkPolyData> polyData_source = vtkSmartPointer<vtkPolyData>::New();
const std::string sourceLandMarkFileName = tempFolder + "/forward/" + std::to_string(stepNum + 1) + ".vtk";
reader_source->SetFileName(sourceLandMarkFileName.c_str());
reader_source->Update();
polyData_source = reader_source->GetOutput();
PointIdType id_s = itk::NumericTraits< PointIdType >::Zero;
PointType p1;
// Read in the source points set
for(unsigned int i = 0; i < polyData_source->GetNumberOfPoints(); i += 10){
double p[3];
polyData_source->GetPoint(i,p);
// This is identical to:
// polydata->GetPoints()->GetPoint(i,p);
p1[0] = p[0];
p1[1] = p[1];
p1[2] = p[2];
sourceLandMarkContainer->InsertElement(id_s, p1);
id_s++;
}
tps->SetSourceLandmarks(sourceLandMarks);
std::string upFileName(tempFolder);
std::string downFileName(tempFolder);
std::string crestFileName(tempFolder);
upFileName = upFileName + "/model/up" + std::to_string(stepNum + 1) + ".vtk";
downFileName = downFileName + "/model/down" + std::to_string(stepNum + 1) + ".vtk";
crestFileName = crestFileName + "/model/crest" + std::to_string(stepNum + 1) + ".vtk";
// read source srep
vtkSmartPointer<vtkPolyDataReader> upSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
upSpokeReader->SetFileName(upFileName.c_str());
upSpokeReader->Update();
vtkSmartPointer<vtkPolyData> upSpokes = upSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> downSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
downSpokeReader->SetFileName(downFileName.c_str());
downSpokeReader->Update();
vtkSmartPointer<vtkPolyData> downSpokes = downSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> crestSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
crestSpokeReader->SetFileName(crestFileName.c_str());
crestSpokeReader->Update();
vtkSmartPointer<vtkPolyData> crestSpokes = crestSpokeReader->GetOutput();
upFileName = tempFolder + "/model/up" + std::to_string(stepNum);
std::string upOutputFile(upFileName.c_str());
TransformNOutput(tps, upSpokes, upOutputFile);
// display upspokes
downFileName = tempFolder + "/model/down" + std::to_string(stepNum);
std::string downOutputFile(downFileName.c_str());
TransformNOutput(tps, downSpokes, downOutputFile);
crestFileName = tempFolder + "/model/crest" + std::to_string(stepNum);
std::string crestOutputFile(crestFileName.c_str());
TransformNOutput(tps, crestSpokes, crestOutputFile);
}
return 0;
}
void vtkSlicerSkeletalRepresentationInitializerLogic::DisplayResultSrep()
{
// Hide other nodes.
HideNodesByClass("vtkMRMLModelNode");
const std::string tempFolder(this->GetApplicationLogic()->GetTemporaryPath());
const std::string upFileName = tempFolder + "/model/up1.vtk";
const std::string downFileName = tempFolder + "/model/down1.vtk";
const std::string crestFileName = tempFolder +"/model/crest1.vtk";
const std::string meshFileName = tempFolder + "/model/mesh1.vtk";;
const std::string curveFileName = tempFolder + "/model/curve1.vtk";
vtkSmartPointer<vtkPolyDataReader> upSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
upSpokeReader->SetFileName(upFileName.c_str());
upSpokeReader->Update();
vtkSmartPointer<vtkPolyData> upSpoke_poly = upSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> downSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
downSpokeReader->SetFileName(downFileName.c_str());
downSpokeReader->Update();
vtkSmartPointer<vtkPolyData> downSpoke_poly = downSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> crestSpokeReader = vtkSmartPointer<vtkPolyDataReader>::New();
crestSpokeReader->SetFileName(crestFileName.c_str());
crestSpokeReader->Update();
vtkSmartPointer<vtkPolyData> crestSpoke_poly = crestSpokeReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> meshReader = vtkSmartPointer<vtkPolyDataReader>::New();
meshReader->SetFileName(meshFileName.c_str());
meshReader->Update();
vtkSmartPointer<vtkPolyData> meshPoly = meshReader->GetOutput();
vtkSmartPointer<vtkPolyDataReader> curveReader = vtkSmartPointer<vtkPolyDataReader>::New();
curveReader->SetFileName(curveFileName.c_str());
curveReader->Update();
vtkSmartPointer<vtkPolyData> curvePoly = curveReader->GetOutput();
AddModelNodeToScene(upSpoke_poly, "up spokes for initial object", true, 0, 1, 1);
AddModelNodeToScene(downSpoke_poly, "down spokes for initial object", true, 1, 0, 1);
AddModelNodeToScene(crestSpoke_poly, "crest spokes for initial object", true, 1, 0, 0);
AddModelNodeToScene(meshPoly, "skeletal mesh for initial object", true, 0, 0, 0);
AddModelNodeToScene(curvePoly, "fold curve for initial object", true, 1, 1, 0);
}
void vtkSlicerSkeletalRepresentationInitializerLogic::TransformNOutput(itkThinPlateSplineExtended::Pointer tps, vtkPolyData* spokes, const std::string& outputFileName)
{
vtkPoints* newPoints = vtkPoints::New();
newPoints->SetDataTypeToDouble();
vtkSmartPointer<vtkPolyData> newSpokePoly = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> spokeLines = vtkSmartPointer<vtkCellArray>::New();
for(int i = 0; i < spokes->GetNumberOfPoints(); i += 2)
{
double p[3];
spokes->GetPoint(i,p);
// transform medial point by tps
PointType hub;
hub[0] = p[0];
hub[1] = p[1];
hub[2] = p[2];
PointType transHub = tps->TransformPoint(hub);
double newP[3];
newP[0] = transHub[0];
newP[1] = transHub[1];
newP[2] = transHub[2];
int id0 = newPoints->InsertNextPoint(newP);
// transform implied boundary point by tps
double p_bdry[3];
spokes->GetPoint(i+1, p_bdry);
PointType bdry;
bdry[0] = p_bdry[0];
bdry[1] = p_bdry[1];
bdry[2] = p_bdry[2];
PointType transB = tps->TransformPoint(bdry);
double newB[3];
newB[0] = transB[0];
newB[1] = transB[1];
newB[2] = transB[2];
int id1 = newPoints->InsertNextPoint(newB);
vtkSmartPointer<vtkLine> arrow = vtkSmartPointer<vtkLine>::New();
arrow->GetPointIds()->SetId(0, id0);
arrow->GetPointIds()->SetId(1, id1);
spokeLines->InsertNextCell(arrow);
}
newSpokePoly->SetPoints(newPoints);
newSpokePoly->SetLines(spokeLines);
vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetFileName(outputFileName.c_str());
writer->SetInputData(newSpokePoly);
writer->Update();
}
void vtkSlicerSkeletalRepresentationInitializerLogic::TransformPoints(itkThinPlateSplineExtended::Pointer tps,
vtkPolyData *poly, const std::string &outputFileName)
{
vtkSmartPointer<vtkPoints> pts = poly->GetPoints();
for(int i = 0; i < poly->GetNumberOfPoints(); ++i)
{
double pt[3];
poly->GetPoint(i, pt);
PointType itkPt;
itkPt[0] = pt[0];
itkPt[1] = pt[1];
itkPt[2] = pt[2];
PointType transPt = tps->TransformPoint(itkPt);
pts->SetPoint(i, transPt[0], transPt[1], transPt[2]);
}
pts->Modified();
vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetFileName(outputFileName.c_str());
writer->SetInputData(poly);
writer->Update();
}
double vtkSlicerSkeletalRepresentationInitializerLogic::CalculateSpokeLength(PointType tail, PointType tip){
PointType spokeVector;
for(unsigned int dim = 0; dim < 3; dim++){
spokeVector[dim] = tip[dim] - tail[dim];
}
// Compute the spoke length
double spokeRadiu=0;
for(unsigned int dim=0; dim<3; dim++){
spokeRadiu += spokeVector[dim] * spokeVector[dim];
}
return sqrt(spokeRadiu);
}
void vtkSlicerSkeletalRepresentationInitializerLogic::CalculateSpokeDirection(PointType tail,
PointType tip,
double *x, double *y, double *z){
// Compute the spoke length
double spokeRadiu = CalculateSpokeLength(tail, tip);
// Normalize the spoke's direction to a unit vector
*x=((tip[0] - tail[0]) / spokeRadiu);
*y=((tip[1] - tail[1]) / spokeRadiu);
*z=((tip[2] - tail[2]) / spokeRadiu);
}
| 39.95558 | 179 | 0.639314 | [
"mesh",
"object",
"vector",
"model",
"transform",
"3d"
] |
6f4fb4093cf352a95ca48120b27d0edbf4cce1e0 | 1,269 | cpp | C++ | src/process.cpp | s9rA16Bf4/headache | b401e7e75c0f0ade9f8b9a4f919f5f1357484670 | [
"MIT"
] | null | null | null | src/process.cpp | s9rA16Bf4/headache | b401e7e75c0f0ade9f8b9a4f919f5f1357484670 | [
"MIT"
] | null | null | null | src/process.cpp | s9rA16Bf4/headache | b401e7e75c0f0ade9f8b9a4f919f5f1357484670 | [
"MIT"
] | null | null | null | #include "process.hpp"
std::vector<std::string> process::readGuts(std::string filePath){
std::ifstream openFile(filePath);
std::vector<std::string> toReturn;
if (openFile.is_open()){
std::string line = "";
while(std::getline(openFile,line)){
if (line[0] != '%'){ toReturn.push_back(line); } // Ignoring comments
}
openFile.close();
}else{ std::cerr << "Failed to open file [" << filePath << "]"<< std::endl; }
return toReturn;
}
std::vector<std::string> process::split(std::string line, std::string delimiter){
std::vector<std::string> toReturn;
std::size_t delimPrev = 0, delimPos = 0;
while(line.size() > delimPrev && line.size() > delimPos){
delimPos = line.find(delimiter, delimPrev);
if (delimPos == std::string::npos){ delimPos = line.size(); }
std::string subStr = line.substr(delimPrev, delimPos-delimPrev);
if (!subStr.empty()){ toReturn.push_back(subStr); }
delimPrev = delimPos+delimiter.size();
}
return toReturn;
}
bool process::compare(std::string a, std::string b){
bool toReturn = false;
if (a.size() == b.size()){
for (unsigned int i = 0; i < a.size(); i++){
if (a[i] == b[i]){ toReturn = true; }
else{ toReturn = false; break; }
}
}
return toReturn;
}
| 28.2 | 81 | 0.623325 | [
"vector"
] |
6f57ccb9cf9a9c2a32c4d0bc64c29d8800d6bbfc | 4,409 | hh | C++ | include/cbrainx/activationLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | 1 | 2022-03-02T20:03:49.000Z | 2022-03-02T20:03:49.000Z | include/cbrainx/activationLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | null | null | null | include/cbrainx/activationLayer.hh | mansoormemon/cbrainx | 1b7fa699e4470bf5fc39006cb719dcfc48a7688c | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 CBrainX
// Project URL: https://github.com/mansoormemon/cbrainx
//
// 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.
// Copyright (c) 2021 Mansoor Ahmed Memon <mansoorahmed.one@gmail.com>
#ifndef CBRAINX__ACTIVATION_LAYER_HH_
#define CBRAINX__ACTIVATION_LAYER_HH_
#include "abstractLayer.hh"
#include "activationFunctions.hh"
#include "typeAliases.hh"
namespace cbx {
/// \brief The `ActivationLayer` class represents a layer that encompasses the functionality of an activation
/// function.
///
/// \details
/// The activation function is an essential component of neural network design. It determines whether or not a
/// neuron activates. The goal of an activation function is to introduce non-linearity into the output of a
/// neuron. The type of activation function in the hidden layer determines how well the network model will learn
/// during training.
///
/// The forward pass of this layer performs the subsequent operation.
///
/// Formula: Ô = ζ(Î)
///
/// where:
/// ζ - Activation function
/// Î - Input (Matrix) : Shape => (m, n)
/// Ô - Output (Matrix) : Shape => (m, n)
///
/// \see Activation
class ActivationLayer : public AbstractLayer {
private:
/// \brief The number of neurons in the layer.
size_type neurons_ = {};
/// \brief The activation function to be applied.
ActFuncWrapper act_func_ = {};
public:
// /////////////////////////////////////////////
// Constructors and Destructors
// /////////////////////////////////////////////
/// \brief Parameterized constructor.
/// \param[in] inputs The number of neurons in the input layer.
/// \param[in] activation The activation to be applied.
ActivationLayer(size_type inputs, Activation activation);
/// \brief Default copy constructor.
/// \param[in] other Source layer.
ActivationLayer(const ActivationLayer &other) = default;
/// \brief Move constructor.
/// \param[in] other Source layer.
ActivationLayer(ActivationLayer &&other) noexcept;
/// \brief Default destructor.
~ActivationLayer() override = default;
// /////////////////////////////////////////////
// Assignment Operators
// /////////////////////////////////////////////
/// \brief Default copy assignment operator.
/// \param[in] other Source layer.
/// \return A reference to self.
auto operator=(const ActivationLayer &other) -> ActivationLayer & = default;
/// \brief Move assignment operator.
/// \param[in] other Source layer.
/// \return A reference to self.
auto operator=(ActivationLayer &&other) noexcept -> ActivationLayer &;
// /////////////////////////////////////////////
// Query Functions
// /////////////////////////////////////////////
/// \brief Returns the number of neurons in the layer.
/// \return The number of neurons in the layer.
[[nodiscard]] auto neurons() const -> size_type override;
/// \brief Returns the number of modifiable parameters in the layer.
/// \return The number of modifiable parameters in the layer.
[[nodiscard]] auto parameters() const -> size_type override;
/// \brief Returns the type of the layer.
/// \return The type of the layer.
///
/// \see LayerType
[[nodiscard]] auto type() const -> LayerType override;
// /////////////////////////////////////////////
// Informative
// /////////////////////////////////////////////
/// \brief Returns a string with information about the layer's properties.
/// \return Information about the layer's properties as a string.
[[nodiscard]] auto property() const -> std::string override;
// /////////////////////////////////////////////
// Core Functionality
// /////////////////////////////////////////////
/// \brief Forward pass.
/// \param[in] input The input layer.
/// \return A reference to self.
[[nodiscard]] auto forward_pass(const container &input) const -> const AbstractLayer & override;
};
}
#endif
| 34.445313 | 112 | 0.630755 | [
"shape",
"model"
] |
6f589c0c2abf02f1fed69cb24cacd3d68ad223af | 3,658 | cpp | C++ | Leetcode & GFG/day01.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | 5 | 2020-06-30T12:44:25.000Z | 2021-07-14T06:35:57.000Z | Leetcode & GFG/day01.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | null | null | null | Leetcode & GFG/day01.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | null | null | null | 442. Find All Duplicates in an Array
class Solution {
public:
vector<int> findDuplicates(vector<int>& a) {
int n = a.size();
vector<int> ans;
for(int i=0;i<n;i++){
// u -> v
// we make already visited elements negative
int u = i;
int v = abs(a[i])-1;
if(a[v] < 0){
ans.push_back(v+1);
}
else{
a[v] *= -1;
}
}
return ans;
}
};
287. Find the Duplicate Number
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int ans = -1;
for(int num : nums){
num = abs(num);
if(nums[num] < 0){
ans = num;
break;
}
nums[num] *= -1;
}
return ans;
}
};
75. Sort Colors
class Solution {
public:
void sortColors(vector<int>& nums) {
map<int, int> f;
for(auto num : nums){
f[num]++;
}
int s = 0;
for(int num = 0; num < 3 ; num++)
while(f[num]!=0){
nums[s] = num;
s++;
f[num]--;
}
return ;
}
};
268. Missing Number
class Solution {
public:
int missingNumber(vector<int>& nums) {
int ans1 = 0, ans2 = 0;
int n = nums.size();
for(int i=0;i<n;i++){
ans1 ^= nums[i];
ans2 ^= i+1;
}
return ans1^ans2;
}
};
88. Merge Sorted Array
// with O(n) space
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> temp;
int i=0, j=0;
while(i<m and j<n){
if(nums1[i] <= nums2[j]){
temp.push_back(nums1[i]);
i++;
}
else{
temp.push_back(nums2[j]);
j++;
}
}
for( ; i<m; i++)
temp.push_back(nums1[i]);
for( ; j<n; j++)
temp.push_back(nums2[j]);
for(int k=0;k<m+n;k++)
nums1[k]=temp[k];
}
};
// with O(1) space
53. Maximum Subarray
// Kadanes Algorithm
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int max_till_now = 0, ans = std::numeric_limits<int>::min();
for(int i=0;i<n;i++) {
max_till_now += nums[i];
ans = max(ans, max_till_now);
if(max_till_now < 0) {
max_till_now = 0;
}
}
return ans;
}
};
56. Merge Intervals
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b){
if(a[0] <= b[0]){
if(a[0]==b[0]){
if(a[1]<b[1]) return true;
else return false;
}
return true;
}
else{
return false;
}
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), cmp);
vector< vector<int> > ans;
int n = intervals.size();
int i=0;
while(i<n){
int l1 = intervals[i][0];
int r1 = intervals[i][1];
int j=i+1;
while(j<n){
int l2 = intervals[j][0];
int r2 = intervals[j][1];
if(r1 >= l2){
r1 = max(r1,r2);
j++;
}
else break;
}
ans.push_back({l1,r1});
i=j;
}
return ans;
}
};
| 18.758974 | 70 | 0.405139 | [
"vector"
] |
6f592efdb4edb62fd893ce349bb0af802214df3e | 15,743 | cpp | C++ | mbvtbuilder/test/Test.cpp | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | 6 | 2018-06-27T17:43:35.000Z | 2021-06-29T18:50:49.000Z | mbvtbuilder/test/Test.cpp | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | 22 | 2019-04-10T06:38:09.000Z | 2022-01-20T08:12:02.000Z | mbvtbuilder/test/Test.cpp | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | 5 | 2019-03-12T10:25:20.000Z | 2021-12-28T10:18:56.000Z | #define BOOST_TEST_MODULE GEOJSONVT
#include "Clipper.h"
#include "Simplifier.h"
#include "MBVTLayerEncoder.h"
#include "MBVTTileBuilder.h"
#include "mapnikvt/mbvtpackage/MBVTPackage.pb.h"
#include <picojson/picojson.h>
#include <boost/math/constants/constants.hpp>
#include <boost/test/included/unit_test.hpp>
using namespace carto::mbvtbuilder;
static std::vector<std::vector<cglib::vec2<float>>> decodeGeometry(const vector_tile::Tile::Feature& feature, float scale = 1.0f / 4096.0f) {
std::vector<std::vector<cglib::vec2<float>>> verticesList;
int cx = 0, cy = 0;
int cmd = 0, length = 0;
std::vector<cglib::vec2<float>> vertices;
vertices.reserve(feature.geometry_size());
for (int i = 0; i < feature.geometry_size(); ) {
if (length == 0) {
int cmdLength = feature.geometry(i++);
length = cmdLength >> 3;
cmd = cmdLength & 7;
if (length == 0) {
continue;
}
}
length--;
if ((cmd == 1 || cmd == 2) && i + 2 <= feature.geometry_size()) {
if (cmd == 1) {
if (!vertices.empty()) {
verticesList.emplace_back();
std::swap(verticesList.back(), vertices);
}
}
int dx = feature.geometry(i++);
int dy = feature.geometry(i++);
dx = ((dx >> 1) ^ (-(dx & 1)));
dy = ((dy >> 1) ^ (-(dy & 1)));
cx += dx;
cy += dy;
vertices.emplace_back(static_cast<float>(cx) * scale, static_cast<float>(cy) * scale);
}
else if (cmd == 7) {
if (!vertices.empty()) {
if (vertices.front() != vertices.back()) {
cglib::vec2<float> p = vertices.front();
vertices.emplace_back(p);
}
}
}
}
if (!vertices.empty()) {
verticesList.emplace_back();
std::swap(verticesList.back(), vertices);
}
return verticesList;
}
static cglib::vec2<double> wgs84ToWM(const cglib::vec2<double>& posWgs84) {
static constexpr double EARTH_RADIUS = 6378137.0;
static constexpr double PI = boost::math::constants::pi<double>();
double x = EARTH_RADIUS * posWgs84(0) * PI / 180.0;
double a = posWgs84(1) * PI / 180.0;
double y = 0.5 * EARTH_RADIUS * std::log((1.0 + std::sin(a)) / (1.0 - std::sin(a)));
return cglib::vec2<double>(x, y);
}
// Test clipper for different primitives
BOOST_AUTO_TEST_CASE(clipper) {
typedef cglib::vec2<double> Point;
Clipper<double> clipper(cglib::bbox2<double>({ -1.0,-1.0 }, { 1.0, 1.0 }));
{
BOOST_CHECK(clipper.testPoint({ -0.9, 0.9 }));
BOOST_CHECK(clipper.testPoint({ -1, 1 }));
BOOST_CHECK(!clipper.testPoint({ -1.1, 1 }));
}
{
BOOST_CHECK((clipper.clipLineString(std::vector<Point> { { -1, 0 }, { 1, 0 } }) == std::vector<std::vector<Point>> { { { -1, 0 }, { 1, 0 } } }));
BOOST_CHECK((clipper.clipLineString(std::vector<Point> { { -2, 0 }, { 2, 0 } }) == std::vector<std::vector<Point>> { { { -1, 0 }, { 1, 0 } } }));
BOOST_CHECK((clipper.clipLineString(std::vector<Point> { { -2, -2 }, { 2, 2 } }) == std::vector<std::vector<Point>> { { { -1, -1 }, { 1, 1 } } }));;
BOOST_CHECK((clipper.clipLineString(std::vector<Point> { { -4, 0 }, { 0, 2 } }) == std::vector<std::vector<Point>> { }));
BOOST_CHECK((clipper.clipLineString(std::vector<Point> { { -4, 0 }, { 0, 0 }, { 4, 0.5 }, { 0, 0.5 } }) == std::vector<std::vector<Point>> { { { -1, 0 }, { 0, 0 }, { 1, 0.125 } }, { { 1, 0.5 }, { 0, 0.5 } } }));
}
{
BOOST_CHECK((clipper.clipPolygonRing(std::vector<Point> { { -1, 0 }, { 1, 0 }, { 0, 1 } }) == std::vector<Point> { { -1, 0 }, { 1, 0 }, { 0, 1 } }));
BOOST_CHECK((clipper.clipPolygonRing(std::vector<Point> { { -1, -1 }, { -1, 1 }, { 1, 1 }, { 1, -1 } }) == std::vector<Point> { { -1, -1 }, { -1, 1 }, { 1, 1 }, { 1, -1 } }));
BOOST_CHECK((clipper.clipPolygonRing(std::vector<Point> { { -2, -2 }, { -2, 2 }, { 2, 2 }, { 2, -2 } }) == std::vector<Point> { { -1, -1 }, { -1, 1 }, { 1, 1 }, { 1, -1 } }));
BOOST_CHECK((clipper.clipPolygonRing(std::vector<Point> { { -2, 0 }, { 0, 2 }, { 2, 0 }, { 0, -2 } }) == std::vector<Point> { { -1, -1 }, { -1, 1 }, { 1, 1 }, { 1, -1 }, { 0, -1 } }));
}
}
// Test simplifier for line strings
BOOST_AUTO_TEST_CASE(simplifier) {
typedef cglib::vec2<double> Point;
Simplifier<double> simplifier(1.0);
{
BOOST_CHECK((simplifier.simplifyLineString(std::vector<Point> { { -1, 0 }, { 1, 0 } }) == std::vector<Point> { { -1, 0 }, { 1, 0 } }));
BOOST_CHECK((simplifier.simplifyLineString(std::vector<Point> { { -1, 0 }, { 1, 0 }, { 2, 0 } }) == std::vector<Point> { { -1, 0 }, { 2, 0 } }));
BOOST_CHECK((simplifier.simplifyLineString(std::vector<Point> { { -1, 0 }, { 1, 1 }, { 2, 0 } }) == std::vector<Point> { { -1, 0 }, { 1, 1 }, { 2, 0 } }));
BOOST_CHECK((simplifier.simplifyLineString(std::vector<Point> { { -1, 0 }, { 1, 2 }, { 2, 0 } }) == std::vector<Point> { { -1, 0 }, { 1, 2 }, { 2, 0 } }));
BOOST_CHECK((simplifier.simplifyLineString(std::vector<Point> { { -1, 0 }, { 1, 0.5 }, { 2, 0 } }) == std::vector<Point> { { -1, 0 }, { 2, 0 } }));
}
}
// Test that properties are encoded correctly in vector tiles
BOOST_AUTO_TEST_CASE(propertiesEncoding) {
std::vector<vector_tile::Tile_Layer> layers;
auto encodeAndDecodeValue = [&layers](const picojson::value& value) -> vector_tile::Tile_Value {
MBVTLayerEncoder encoder("");
encoder.addMultiPoint(0, { cglib::vec2<float>(0, 0) }, picojson::value(picojson::object({ { "_key_", value } })));
auto encodedMsg = encoder.buildLayer();
protobuf::message msg(encodedMsg.data().data(), encodedMsg.data().size());
layers.emplace_back(msg);
BOOST_ASSERT(layers.back().keys().at(0) == "_key_");
return layers.back().values().at(0);
};
auto encodeAndDecodeKeyValue = [&layers](const std::string& key, const picojson::value& value) -> std::pair<std::string, std::string> {
MBVTLayerEncoder encoder("");
encoder.addMultiPoint(0, { cglib::vec2<float>(0, 0) }, picojson::value(picojson::object({ { key, value } })));
auto encodedMsg = encoder.buildLayer();
protobuf::message msg(encodedMsg.data().data(), encodedMsg.data().size());
layers.emplace_back(msg);
BOOST_ASSERT(layers.back().values().at(0).has_string_value());
return std::make_pair(layers.back().keys().at(0), layers.back().values().at(0).string_value());
};
BOOST_CHECK(encodeAndDecodeValue(picojson::value(false)).bool_value() == false);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(true)).bool_value() == true);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(1LL)).uint_value() == 1);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(-1LL)).sint_value() == -1);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(-1564564561LL)).sint_value() == -1564564561);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(91564564561LL)).uint_value() == 91564564561);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(16.25)).float_value() == 16.25f);
BOOST_CHECK(encodeAndDecodeValue(picojson::value(99916.251111111)).double_value() == 99916.251111111);
BOOST_CHECK(encodeAndDecodeValue(picojson::value("Test str")).string_value() == "Test str");
BOOST_CHECK((encodeAndDecodeKeyValue("key1", picojson::value(picojson::object { { "a", picojson::value("XX") } })) == std::make_pair(std::string("key1.a"), std::string("XX"))));
BOOST_CHECK((encodeAndDecodeKeyValue("key2", picojson::value(picojson::array { { picojson::value("XX") } })) == std::make_pair(std::string("key2[0]"), std::string("XX"))));
}
// Test that point geometry is encoded correctly in vector tiles
BOOST_AUTO_TEST_CASE(pointEncoding) {
typedef cglib::vec2<float> Point;
auto encodeAndDecodeGeometry = [](const std::vector<Point>& geom) -> std::vector<Point> {
MBVTLayerEncoder encoder("");
encoder.addMultiPoint(0, geom, picojson::value());
auto encodedMsg = encoder.buildLayer();
protobuf::message msg(encodedMsg.data().data(), encodedMsg.data().size());
vector_tile::Tile_Layer layer(msg);
BOOST_ASSERT(layer.features_size() == 1);
auto decodedGeom = decodeGeometry(layer.features(0));
std::vector<Point> points;
for (auto& decodedPoint : decodedGeom) {
BOOST_ASSERT(decodedPoint.size() == 1);
points.push_back(decodedPoint.at(0));
}
return points;
};
BOOST_CHECK((encodeAndDecodeGeometry({ Point(0, 0) }) == std::vector<Point> { Point(0, 0) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(0, 1) }) == std::vector<Point> { Point(0, 1) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(-0.125f, 1.25f) }) == std::vector<Point> { Point(-0.125f, 1.25f) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(-0.125f, 1.25f), Point(-0.125f, 1.25f) }) == std::vector<Point> { Point(-0.125f, 1.25f), Point(-0.125f, 1.25f) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(-0.125f, 1.25f), Point(0.125f, -1.25f) }) == std::vector<Point> { Point(-0.125f, 1.25f), Point(0.125f, -1.25f) }));
}
// Test that linestring geometry is encoded correctly in vector tiles
BOOST_AUTO_TEST_CASE(lineStringEncoding) {
typedef cglib::vec2<float> Point;
auto encodeAndDecodeGeometry = [](const std::vector<Point>& geom) -> std::vector<Point> {
MBVTLayerEncoder encoder("");
encoder.addMultiLineString(0, { geom }, picojson::value());
auto encodedMsg = encoder.buildLayer();
protobuf::message msg(encodedMsg.data().data(), encodedMsg.data().size());
vector_tile::Tile_Layer layer(msg);
BOOST_ASSERT(layer.features_size() == 1);
auto decodedGeom = decodeGeometry(layer.features(0));
BOOST_ASSERT(decodedGeom.size() == 1);
return decodedGeom.at(0);
};
BOOST_CHECK((encodeAndDecodeGeometry({ Point(0, 0), Point(1, 0) }) == std::vector<Point> { Point(0, 0), Point(1, 0) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(0, 0), Point(1, 0), Point(0, 1) }) == std::vector<Point> { Point(0, 0), Point(1, 0), Point(0, 1) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(0, 0), Point(1, 0), Point(1, 0) }) == std::vector<Point> { Point(0, 0), Point(1, 0) }));
BOOST_CHECK((encodeAndDecodeGeometry({ Point(-0.125f, 1.25f), Point(0.125f, -1.25f) }) == std::vector<Point> { Point(-0.125f, 1.25f), Point(0.125f, -1.25f) }));
}
// Test that polygon geometry is encoded correctly in vector tiles
BOOST_AUTO_TEST_CASE(polygonEncoding) {
typedef cglib::vec2<float> Point;
auto encodeAndDecodeGeometry = [](const std::vector<std::vector<Point>>& geom) -> std::vector<std::vector<Point>> {
MBVTLayerEncoder encoder("");
encoder.addMultiPolygon(0, geom, picojson::value());
auto encodedMsg = encoder.buildLayer();
protobuf::message msg(encodedMsg.data().data(), encodedMsg.data().size());
vector_tile::Tile_Layer layer(msg);
BOOST_ASSERT(layer.features_size() == 1);
auto decodedGeom = decodeGeometry(layer.features(0));
BOOST_ASSERT(decodedGeom.size() == 1);
return decodedGeom;
};
BOOST_CHECK((encodeAndDecodeGeometry({ { Point(0, 0), Point(1, 0), Point(0, 1) } }) == std::vector<std::vector<Point>> { { Point(0, 0), Point(1, 0), Point(0, 1), Point(0, 0) } }));
BOOST_CHECK((encodeAndDecodeGeometry({ { Point(0, 0), Point(1, 0), Point(1, 0), Point(0, 1) } }) == std::vector<std::vector<Point>> { { Point(0, 0), Point(1, 0), Point(0, 1), Point(0, 0) } }));
BOOST_CHECK((encodeAndDecodeGeometry({ { Point(1, 1), Point(-0.125f, 1.25f), Point(0.125f, -1.25f) } }) == std::vector<std::vector<Point>> { { Point(1, 1), Point(-0.125f, 1.25f), Point(0.125f, -1.25f), Point(1, 1) } }));
}
// Test high-level tile builder functionality
BOOST_AUTO_TEST_CASE(tileBuilder) {
typedef cglib::vec2<double> Point;
{
MBVTTileBuilder tileBuilder(18, 18);
tileBuilder.addMultiPoint(0, { Point(0, 0) }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 1);
}
{
MBVTTileBuilder tileBuilder(18, 18);
tileBuilder.addMultiPoint(0, { Point(0, 0), Point(1, 1) }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 1);
}
{
MBVTTileBuilder tileBuilder(18, 18);
auto layerIndex = tileBuilder.createLayer("", 0.0000001f);
tileBuilder.addMultiPoint(layerIndex, { Point(0.5, 0.5), Point(100000, 1) }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 2);
}
{
MBVTTileBuilder tileBuilder(18, 18);
auto layerIndex = tileBuilder.createLayer("", 0.0000001f);
tileBuilder.addMultiLineString(layerIndex, { { Point(0.5, 0.5), Point(100000, 1) } }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 655);
}
{
MBVTTileBuilder tileBuilder(18, 18);
auto layerIndex = tileBuilder.createLayer("", 0.0000001f);
tileBuilder.addMultiLineString(layerIndex, { { Point(0.5, 0.5), Point(10000, 10000) } }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 196);
}
{
MBVTTileBuilder tileBuilder(18, 18);
auto layerIndex = tileBuilder.createLayer("", 0.0000001f);
tileBuilder.addMultiPolygon(layerIndex, { { { Point(0.5, 0.5), Point(0.5, 10000), Point(10000, 5000) } } }, picojson::value());
std::vector<protobuf::encoded_message> encodedTiles;
tileBuilder.buildTiles([&encodedTiles](int zoom, int tileX, int tileY, const protobuf::encoded_message& encodedTile) { encodedTiles.push_back(encodedTile); });
BOOST_CHECK(encodedTiles.size() == 2211);
}
}
// Test high-level tile builder functionality, simplifier part
BOOST_AUTO_TEST_CASE(tileBuilderSimplifier) {
typedef cglib::vec2<double> Point;
{
MBVTTileBuilder tileBuilder(0, 18);
std::vector<Point> coords;
for (int i = 0; i < 10000; i++) {
double a = static_cast<double>(i) / 10000 * std::atan(1.0) * 8;
double r = 80;
coords.emplace_back(wgs84ToWM(cglib::vec2<double>(std::cos(a), std::sin(a)) * r));
}
tileBuilder.addMultiPolygon(0, { { coords } }, picojson::value());
protobuf::encoded_message encodedTile;
tileBuilder.buildTile(0, 0, 0, encodedTile);
}
}
| 52.302326 | 224 | 0.608397 | [
"geometry",
"object",
"vector"
] |
6f5e8486c67ff09a0d710826ea76af0400ddffd0 | 20,522 | cpp | C++ | src/cpp/smithy.cpp | CoolDadTx/arxnet | 9d2d51d7de57a67d56881aac80bf8f1f8018432e | [
"MIT"
] | null | null | null | src/cpp/smithy.cpp | CoolDadTx/arxnet | 9d2d51d7de57a67d56881aac80bf8f1f8018432e | [
"MIT"
] | null | null | null | src/cpp/smithy.cpp | CoolDadTx/arxnet | 9d2d51d7de57a67d56881aac80bf8f1f8018432e | [
"MIT"
] | null | null | null |
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <stdio.h>
#include <iomanip>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "player.h"
#include "font.h"
#include "display.h"
#include "game.h"
#include "encounter.h"
#include "misc.h"
#include "smithy.h"
#include "items.h"
#include "lyrics.h"
#include "actor.h" // For weapons
using namespace std;
unsigned char citySmithyBinary[citySmithyFileSize];
extern sf::Clock clock1;
extern int iCounter;
sf::Music smithyMusic;
int itemChoice;
int itemNo, itemCost;
int menuStartItem;
int maxMenuItems = 6;
int smithyNo;
struct Smithy
{
string name;
float minimumPriceFactor;
float initialPriceFactor;
int location; // match with location text description number
int openingHour;
int closingHour;
};
//MLT: Double to float
Smithy Smithies[4] =
{
{"Sharp Weaponsmiths", 1.25F, 1.65F, 55, 4, 20},
{"Occum's Weaponsmiths", 1.10F, 1.35F, 56, 5, 21},
{"Best Armorers", 1.50F, 2.40F, 57, 8, 19},
{"Knight's Armorers", 1.60F, 2.35F, 58, 11, 15}
};
bool smithyWaresCheck[4][23]; // markers used to check for duplicate items
extern int smithyDailyWares[4][10];
struct smithyItem
{
string name;
int type; // 177 - armour, 178 - weapon
int basePrice;
int itemRef;
};
smithyItem smithyWares[23] =
{
{"a Stiletto", 178,113, 0xAA},
{"a Dagger", 178,129, 0xCB},
{"a Whip", 178,396, 0xE9},
{"a War Net", 178,908, 0x24},
{"Padded Armor", 177,2200, 1},
{"a Small Shield", 178,2460, 0x86},
{"a Shortsword", 178,3146, 0x105},
{"a Shield", 178,4290, 0x68},
{"a Flail", 178,4620, 0x128},
{"Leather Armor", 177,4840, 2},
{"a Spiked Shield", 178,6160, 0x43},
{"a Battle Axe", 178,16930, 0x145},
{"Studded Armor", 177,7260, 3},
{"a Sword", 178,7680, 0x167},
{"a Tower Shield", 178,9488, 0x0},
{"Ring Mail", 177,10010, 4},
{"a Battle Hammer", 178,10285, 0x184},
{"a Longsword", 178,11193, 0x1A9},
{"Scale Mail", 177,14245, 5},
{"Splint Mail", 177,18975, 6},
{"Chain Mail", 177,24640, 7},
{"Banded Armor", 177,32000, 8},
{"Plate Armor", 177,41500, 9}
};
/*
smithyItem smithyWares[23] =
{
{"a Stiletto", 178,113, 61},
{"a Dagger", 178,129, 62},
{"a Whip", 178,396, 63},
{"a War Net", 178,908, 57},
{"Padded Armor", 177,2200, 1},
{"a Small Shield", 178,2460, 60},
{"a Shortsword", 178,3146, 64},
{"a Shield", 178,4290, 59},
{"a Flail", 178,4620, 65},
{"Leather Armor", 177,4840, 2},
{"a Spiked Shield", 178,6160, 58},
{"a Battle Axe", 178,16930, 66},
{"Studded Armor", 177,7260, 3},
{"a Sword", 178,7680, 67},
{"a Tower Shield", 178,9488, 56},
{"Ring Mail", 177,10010, 4},
{"a Battle Hammer", 178,10285, 68},
{"a Longsword", 178,11193, 69},
{"Scale Mail", 177,14245, 5},
{"Splint Mail", 177,18975, 6},
{"Chain Mail", 177,24640, 7},
{"Banded Armor", 177,32000, 8},
{"Plate Armor", 177,41500, 9}
};
*/
void shopSmithy()
{
if (plyr.timeOfDay == 1) { loadShopImage(8); } else { loadShopImage(9); }
int offerStatus = 0; // 0 is normal, 1 is demanding, 2 is bartering
int offerRounds = 0;
int itemLowestCost, smithyOffer;
if (plyr.timeOfDay == 1) { loadShopImage(8); } else { loadShopImage(9); }
smithyNo = getSmithyNo();
bool musicPlaying = false;
int smithyMenu = 1; // high level menu
string str,key;
plyr.status = 2; // shopping
menuStartItem = 0; // menu starts at item 0
if ((Smithies[smithyNo].closingHour<=plyr.hours) || (Smithies[smithyNo].openingHour>plyr.hours)) {smithyMenu = 5;}
while (smithyMenu > 0)
{
while (smithyMenu == 5) // closed
{
smithyDisplayUpdate();
cyText (1, "Sorry, we are closed. Come back@during our working hours.");
str = "We are open from " + itos(Smithies[smithyNo].openingHour) + ":00 in the morning@to " + itos(Smithies[smithyNo].closingHour) + ":00 in the evening.";
if (Smithies[smithyNo].closingHour == 15) { str = "We are open from " + itos(Smithies[smithyNo].openingHour) + ":00 in the morning@to " + itos(Smithies[smithyNo].closingHour) + ":00 in the afternoon."; }
cyText (4, str);
cyText (9,"( Press a key )");
updateDisplay();
key = getSingleKey();
if ((key!="") && (key!="up")) { smithyMenu = 0; }
}
while (smithyMenu == 1) // main menu
{
smithyDisplayUpdate();
bText (13,0, "Welcome Stranger!");
bText (7,3, "Do you wish to see our wares?");
cyText (5, "( es or o)");
SetFontColour(40, 96, 244, 255);
cyText (5, " Y N ");
SetFontColour(215, 215, 215, 255);
displayCoins();
updateDisplay();
if (!musicPlaying)
{
//int Random = randn(0, 2);
if (plyr.musicStyle==0)
{ smithyMusic.openFromFile("data/audio/armor.ogg"); }
else
{ smithyMusic.openFromFile("data/audio/B/armor.ogg"); }
loadLyrics("armor.txt");
smithyMusic.play();
musicPlaying = true;
}
key = getSingleKey();
if ( key=="Y" ) { smithyMenu = 2; }
if ( key=="N" ) { smithyMenu = 0; }
if ( key=="down" ) { smithyMenu = 0; }
}
while (smithyMenu == 2)
{
offerStatus = 0;
offerRounds = 0;
smithyDisplayUpdate();
cyText (0, "What would you like? ( to leave)");
SetFontColour(40, 96, 244, 255);
cyText (0, " 0 ");
SetFontColour(215, 215, 215, 255);
smithyNo = getSmithyNo();
for (int i=0 ; i<maxMenuItems ; i++)
{
int itemNo = smithyDailyWares[smithyNo][menuStartItem+i];
str = ") " + smithyWares[itemNo].name;
//if ((smithyWares[itemNo].itemRef) > 10) { str = ") " + Weapons[smithyWares[itemNo].itemRef].name; }
bText(3,(2+i), str); //was 4
bText(1,(2+i), " coppers");
}
displayCoins();
int itemCost, x;
for (int i=0 ; i<maxMenuItems ; i++) // Max number of item prices in this menu display
{
string itemCostDesc;
x = 28;
int itemNo = smithyDailyWares[smithyNo][menuStartItem+i];
//MLT: Downcast to int
itemCost = (int)(Smithies[smithyNo].initialPriceFactor * smithyWares[itemNo].basePrice);
//itemCost = smithyWares[itemNo].basePrice;
if (itemCost<1000) { x = 30;}
if (itemCost>999) { x = 28;}
if (itemCost>9999) { x = 27;}
itemCostDesc = toCurrency(itemCost);
bText (x,(i+2),itemCostDesc);
}
SetFontColour(40, 96, 244, 255);
bText (2,2, "1");
bText (2,3, "2");
bText (2,4, "3");
bText (2,5, "4");
bText (2,6, "5");
bText (2,7, "6");
if (menuStartItem!=0) { bText (2,1, "}"); }
if (menuStartItem!=4) { bText (2,8, "{"); }
SetFontColour(215, 215, 215, 255);
updateDisplay();
key = getSingleKey();
if ( key=="1" ) { itemChoice = 0; smithyMenu = 20; }
if ( key=="2" ) { itemChoice = 1; smithyMenu = 20; }
if ( key=="3" ) { itemChoice = 2; smithyMenu = 20; }
if ( key=="4" ) { itemChoice = 3; smithyMenu = 20; }
if ( key=="5" ) { itemChoice = 4; smithyMenu = 20; }
if ( key=="6" ) { itemChoice = 5; smithyMenu = 20; }
if ( (key=="up") && (menuStartItem>0) ) { menuStartItem--; }
if ( (key=="down") && (menuStartItem<4) ) { menuStartItem++; }
if ( key=="ESC" ) { smithyMenu = 0; }
if ( key=="0" ) { smithyMenu = 0; }
}
while (smithyMenu == 20) // buy item?
{
smithyNo = getSmithyNo();
itemNo = smithyDailyWares[smithyNo][menuStartItem+itemChoice];
//MLT: Downcast to int
itemCost = (int)(Smithies[smithyNo].initialPriceFactor * smithyWares[itemNo].basePrice);
float tempitemcost = Smithies[smithyNo].initialPriceFactor * smithyWares[itemNo].basePrice;
float temp = (tempitemcost/100)*75;
//MLT: Downcast to int
itemLowestCost = (int)temp;
smithyOffer = itemCost;
smithyMenu = 3;
}
while (smithyMenu == 3) // buy item
{
smithyDisplayUpdate();
if (offerStatus==0)
{
str = "The cost for " + smithyWares[itemNo].name;
cyText (0,str);
str = "is " + toCurrency(smithyOffer) + " coppers. Agreed?";
cyText (1,str);
}
if (offerStatus==1)
{
str = "I demand at least " + toCurrency(smithyOffer) + " silvers!";
cyText (1,str);
}
if (offerStatus==2)
{
str = "Would you consider " + toCurrency(smithyOffer) + "?";
cyText (1,str);
}
bText (11,3," ) Agree to price");
bText (11,4," ) Make an offer");
bText (11,5," ) No sale");
bText (11,6," ) Leave");
displayCoins();
SetFontColour(40, 96, 244, 255);
bText (11,3,"1");
bText (11,4,"2");
bText (11,5,"3");
bText (11,6,"0");
SetFontColour(215, 215, 215, 255);
updateDisplay();
key = getSingleKey();
if ( key=="1" )
{
if (!checkCoins(0,0,smithyOffer)) { smithyMenu = 5; } // offended!
else { smithyMenu = 4; }
}
if ( key=="2" ) { smithyMenu = 16; }
if ( key=="3" ) { smithyMenu = 2; }
if ( key=="0" ) { smithyMenu = 0; }
}
while (smithyMenu == 16) // what is your offer
{
int coppers = inputValue("What is your offer? (in coppers)",9);
// check offer
if ( coppers==0 ) { smithyMenu = 2; }
if ( coppers >= itemCost )
{
smithyOffer = coppers; // accepted the players offer
offerStatus = 2;
smithyMenu = 20;
}
if (( coppers >= itemLowestCost ) && ( coppers < itemCost ))
{
offerStatus = 2;
offerRounds++;
if ( offerRounds > 2 ) { smithyOffer = coppers; smithyMenu = 20; }
else
{
smithyOffer = randn(coppers,itemCost);
itemLowestCost = coppers;
smithyMenu = 3;
}
}
if (( coppers < itemLowestCost ) && (coppers > 0))
{
offerStatus=1;
offerRounds++;
smithyOffer = itemLowestCost;
if ( offerRounds > 1 ) { smithyMenu = 19; }
else { smithyMenu = 3; }
}
}
while (smithyMenu == 20) // Offer accepted (subject to funds check)
{
smithyDisplayUpdate();
cText ("Agreed!");
updateDisplay();
key = getSingleKey();
if ( key!="" )
{
if (!checkCoins(0,0,smithyOffer)) { smithyMenu = 5; }
else { plyr.smithyFriendships[smithyNo]++; if (plyr.smithyFriendships[smithyNo] > 4) { plyr.smithyFriendships[smithyNo] = 4; } smithyMenu = 4; }
}
}
while (smithyMenu == 19) // Leave my shop
{
smithyDisplayUpdate();
cText ("Leave my shoppe and don't return@@until you are ready to make a decent@@offer!");
updateDisplay();
key = getSingleKey();
if ( key!="" ) { plyr.smithyFriendships[smithyNo]--; if (plyr.smithyFriendships[smithyNo] < 0) { plyr.smithyFriendships[smithyNo] = 0; } smithyMenu = 0; } // Thrown out
}
while (smithyMenu == 5) // insufficient funds!
{
smithyDisplayUpdate();
cText ("THAT OFFENDS ME DEEPLY!@Why don't you get serious and only@agree to something that you can afford!");
cyText (9,"( Press a key )");
updateDisplay();
key = getSingleKey();
if ( key!="" ) { smithyMenu = 2; } // back to purchases
}
while (smithyMenu == 4) // Agree to buy item and have funds
{
smithyDisplayUpdate();
cText ("An excellent choice!");
cyText (9,"( Press a key )");
updateDisplay();
key = getSingleKey();
if ( key!="" )
{
// Add a weight & inventory limit check prior to taking money
deductCoins(0,0,smithyOffer);
int objectNumber = smithyWares[itemNo].itemRef; // ref within Weapons array
//int weaponNumber = smithyWares[itemNo].itemRef; // ref within Weapons array
if ((objectNumber>10) || (objectNumber == 0))
{
// Weapon item
createCitySmithyInventoryItem(objectNumber);
}
// Create an armour set
if (objectNumber==1)
{
// Padded armor set - buying group of items
createCitySmithyInventoryItem(0x1CA);
createCitySmithyInventoryItem(0x1EE);
createCitySmithyInventoryItem(0x217);
createCitySmithyInventoryItem(0x23E);
}
if (objectNumber==2)
{
// Leather armor set - buying group of items
createCitySmithyInventoryItem(0x263);
createCitySmithyInventoryItem(0x288);
createCitySmithyInventoryItem(0x2B2);
createCitySmithyInventoryItem(0x2DA);
}
if (objectNumber==3)
{
// Studded armor set - buying group of items
createCitySmithyInventoryItem(0x300);
createCitySmithyInventoryItem(0x325);
createCitySmithyInventoryItem(0x34F);
createCitySmithyInventoryItem(0x377);
}
if (objectNumber==4)
{
// Ring mail set - buying group of items
createCitySmithyInventoryItem(0x39D);
createCitySmithyInventoryItem(0x3C1);
createCitySmithyInventoryItem(0x3E5);
}
if (objectNumber==5)
{
// Scale mail set - buying group of items
createCitySmithyInventoryItem(0x40D);
createCitySmithyInventoryItem(0x432);
createCitySmithyInventoryItem(0x457);
}
if (objectNumber==6)
{
// Splint mail set - buying group of items
createCitySmithyInventoryItem(0x480);
createCitySmithyInventoryItem(0x4A6);
createCitySmithyInventoryItem(0x4CC);
}
if (objectNumber==7)
{
// Chain mail set - buying group of items
createCitySmithyInventoryItem(0x4F6);
createCitySmithyInventoryItem(0x51B);
createCitySmithyInventoryItem(0x540);
}
if (objectNumber==8)
{
// Banded mail set - buying group of items
createCitySmithyInventoryItem(0x569);
createCitySmithyInventoryItem(0x58D);
createCitySmithyInventoryItem(0x5B6);
createCitySmithyInventoryItem(0x5DD);
}
if (objectNumber==9)
{
// Plate mail set - buying group of items
createCitySmithyInventoryItem(0x602);
createCitySmithyInventoryItem(0x626);
createCitySmithyInventoryItem(0x64F);
createCitySmithyInventoryItem(0x676);
}
smithyMenu = 2; // back to purchases
}
}
}
smithyMusic.stop();
leaveShop();
}
int getSmithyNo()
{
int smithy_no;
for (int i=0 ; i<4 ; i++) // Max number of smithy objects
{
if (Smithies[i].location == plyr.location)
{
smithy_no = i; // The number of the smithy you have entered
}
}
return smithy_no;
}
void stockSmithyWares()
{
// Run each day to randomly pick 10 items for sale at each of the 4 smithies
// Check for duplicates using smithyWaresCheck array of bools
// Set bools for duplicate items check to false
int itemNo = 0;
for (int x=0; x<4; x++)
{
for (int y=0; y<23; y++)
{
smithyWaresCheck[x][y] = false;
}
}
for (int smithyNo=0 ; smithyNo<4 ; smithyNo++)
{
for (int waresNo=0 ; waresNo<10 ; waresNo++)
{
// Current code may create duplicate items in each smithy
bool uniqueItem = false;
while (!uniqueItem)
{
itemNo = randn(0,22);
if (!smithyWaresCheck[smithyNo][itemNo])
{
smithyDailyWares[smithyNo][waresNo] = itemNo; // its not a duplicate
smithyWaresCheck[smithyNo][itemNo] = true;
uniqueItem = true;
}
}
}
}
// Simple sort of items in numeric order
sort(smithyDailyWares[0], smithyDailyWares[0]+10);
sort(smithyDailyWares[1], smithyDailyWares[1]+10);
sort(smithyDailyWares[2], smithyDailyWares[2]+10);
sort(smithyDailyWares[3], smithyDailyWares[3]+10);
// Always make sure a stiletto will be available
smithyDailyWares[0][0] = 0;
smithyDailyWares[1][0] = 0;
smithyDailyWares[2][0] = 0;
smithyDailyWares[3][0] = 0;
}
void smithyDisplayUpdate()
{
clock1.restart();
clearShopDisplay();
updateLyrics();
iCounter++;
}
string readSmithyItemString(int stringOffset)
{
stringstream ss;
int z = stringOffset; // current location in the binary
int c = 0; // current byte
string result = "";
while (!(citySmithyBinary[z]==0))
{
c = citySmithyBinary[z];
ss << (char) c;
z++;
}
result = ss.str();
return result;
}
void loadCitySmithyBinary()
{
// Loads armour and weapons binary data into the "citySmithyBinary" array
FILE *fp; // file pointer - used when reading files
char tempString[100]; // temporary string
sprintf(tempString,"%s%s","data/map/","smithyItems.bin");
fp = fopen(tempString, "rb");
if( fp != NULL )
{
for(int i=0;i<citySmithyFileSize;i++)
{
citySmithyBinary[i] = fgetc(fp);
}
}
fclose(fp);
}
// Take a binary offset within citySmithyBinary and create a new inventory item from the binary data (weapon or armour)
// Item types: 0x83 - weapon, 0x84 - armour
//TODO: MLT No return value
void createCitySmithyInventoryItem(int startByte)
{
int index,alignment,weight,wAttributes,melee,ammo,blunt,sharp,earth,air,fire,water,power,magic,good,evil,cold,
minStrength,minDexterity,hp,maxHP,flags,parry,useStrength;
int offset = startByte;
int itemType = citySmithyBinary[offset];
string itemName = readSmithyItemString((offset+6));
if (itemType == 0x83)
{
itemType = 178; // ARX value for weapon
index = 0; // No longer required
useStrength = 0;
alignment = citySmithyBinary[offset+3];
weight = citySmithyBinary[offset+4];
wAttributes = (offset + citySmithyBinary[offset+1])-19; // Working out from the end of the weapon object
melee = 0xFF; //citySmithyBinary[wAttributes+1];
ammo = 0; //citySmithyBinary[wAttributes+2];
blunt = citySmithyBinary[wAttributes+3];
sharp = citySmithyBinary[wAttributes+4];
earth = citySmithyBinary[wAttributes+5];
air = citySmithyBinary[wAttributes+6];
fire = citySmithyBinary[wAttributes+7];
water = citySmithyBinary[wAttributes+8];
power = citySmithyBinary[wAttributes+9];
magic = citySmithyBinary[wAttributes+10];
good = citySmithyBinary[wAttributes+11];
evil = citySmithyBinary[wAttributes+12];
cold = 0; // No cold damage for City items
citySmithyBinary[wAttributes+13];
minStrength = citySmithyBinary[wAttributes+13];
minDexterity = citySmithyBinary[wAttributes+14];
hp = 44; //citySmithyBinary[wAttributes+15];
maxHP = 44; //citySmithyBinary[wAttributes+16];
flags = citySmithyBinary[wAttributes+17];
//flags = 1;
parry = citySmithyBinary[wAttributes+18];
}
if (itemType == 0x84)
{
itemType = 177; // ARX value for armour
index = 0; // No longer required
useStrength = 0;
alignment = citySmithyBinary[offset+3];
weight = citySmithyBinary[offset+4];
wAttributes = (offset + citySmithyBinary[offset+1])-17; // Working out from the end of the weapon object
melee = citySmithyBinary[wAttributes+13]; // Body part
if (melee == 1) melee = 0;
if (melee == 2) melee = 1;
if (melee == 4) melee = 2;
if (melee == 8) melee = 3;
if (melee == 6) melee = 1;
ammo = 0; // Not used
blunt = citySmithyBinary[wAttributes+2]; // ERROR ONWARDS
sharp = citySmithyBinary[wAttributes+3];
earth = citySmithyBinary[wAttributes+4];
air = citySmithyBinary[wAttributes+5];
fire = citySmithyBinary[wAttributes+6];
water = citySmithyBinary[wAttributes+7];
power = citySmithyBinary[wAttributes+8];
magic = citySmithyBinary[wAttributes+9];
good = citySmithyBinary[wAttributes+10];
evil = citySmithyBinary[wAttributes+11];
cold = 0;
minStrength = 0;
minDexterity = 0;
hp = 56; //citySmithyBinary[wAttributes+12];
maxHP = 56; //255;
flags = 0;
parry = 0;
}
//cout << itemName << " " << std::hex << "HP:" << hp << " Bl:" << blunt << " " << "Sh:" << sharp << "\n";
int newItemRef = createItem(itemType,index,itemName,hp,maxHP,flags,minStrength,minDexterity,useStrength,blunt,
sharp,earth,air,fire,water,power,magic,good,evil,cold,weight,alignment,melee,ammo,parry);
itemBuffer[newItemRef].location = 10; // Add to player inventory - 10
}
| 29.443329 | 206 | 0.598041 | [
"object"
] |
6f5fb1fb07e95ef7db7fc7d84501e7177742d59f | 2,653 | cpp | C++ | Source/Test/Test.cpp | i-saint/USDForMetasequoia | e589d47434df913ae4d037c503a89373b5c7938c | [
"MIT"
] | 8 | 2020-03-13T01:17:07.000Z | 2021-06-27T08:42:17.000Z | Source/Test/Test.cpp | i-saint/AlembicForMetasequoia | 9efa6c9a3428a88ec37482abb760990318a01434 | [
"MIT"
] | 1 | 2020-04-07T09:20:15.000Z | 2020-04-07T09:20:15.000Z | Source/Test/Test.cpp | i-saint/AlembicForMetasequoia | 9efa6c9a3428a88ec37482abb760990318a01434 | [
"MIT"
] | 1 | 2020-05-06T11:42:43.000Z | 2020-05-06T11:42:43.000Z | #include "pch.h"
#include "Test.h"
static std::string g_log;
void PrintImpl(const char *format, ...)
{
const int MaxBuf = 4096;
char buf[MaxBuf];
va_list args;
va_start(args, format);
vsprintf(buf, format, args);
g_log += buf;
#ifdef _WIN32
::OutputDebugStringA(buf);
#endif
printf("%s", buf);
va_end(args);
fflush(stdout);
}
struct ArgEntry
{
std::string name;
std::string value;
template<class T> bool getValue(T& dst) const;
};
template<> bool ArgEntry::getValue(std::string& dst) const
{
dst = value;
return true;
}
template<> bool ArgEntry::getValue(int& dst) const
{
dst = std::atoi(value.c_str());
return dst != 0;
}
template<> bool ArgEntry::getValue(float& dst) const
{
dst = (float)std::atof(value.c_str());
return dst != 0.0f;
}
static std::vector<ArgEntry>& GetArgs()
{
static std::vector<ArgEntry> s_instance;
return s_instance;
}
template<class T> bool GetArg(const char *name, T& dst)
{
auto& args = GetArgs();
auto it = std::find_if(args.begin(), args.end(), [name](auto& e) { return e.name == name; });
if (it != args.end())
return it->getValue(dst);
return false;
}
template bool GetArg(const char *name, std::string& dst);
template bool GetArg(const char *name, int& dst);
template bool GetArg(const char *name, float& dst);
struct TestEntry
{
std::string name;
std::function<void()> body;
};
static std::vector<TestEntry>& GetTests()
{
static std::vector<TestEntry> s_instance;
return s_instance;
}
void RegisterTestEntryImpl(const char *name, const std::function<void()>& body)
{
GetTests().push_back({name, body});
}
static void RunTestImpl(const TestEntry& v)
{
Print("%s begin\n", v.name.c_str());
auto begin = Now();
v.body();
auto end = Now();
Print("%s end (%.2fms)\n\n", v.name.c_str(), NS2MS(end-begin));
}
testExport const char* GetLogMessage()
{
return g_log.c_str();
}
testExport void RunTest(char *name)
{
g_log.clear();
for (auto& entry : GetTests()) {
if (entry.name == name) {
RunTestImpl(entry);
}
}
}
testExport void RunAllTests()
{
g_log.clear();
for (auto& entry : GetTests()) {
RunTestImpl(entry);
}
}
int main(int argc, char *argv[])
{
int run_count = 0;
for (int i = 1; i < argc; ++i) {
if (char *sep = std::strstr(argv[i], "=")) {
*(sep++) = '\0';
GetArgs().push_back({ argv[i] , sep });
}
else {
RunTest(argv[i]);
++run_count;
}
}
if (run_count == 0) {
RunAllTests();
}
}
| 20.251908 | 97 | 0.588767 | [
"vector"
] |
6f69d8e4cb4f1c85dc4755d735ae2ae951d01734 | 2,499 | cpp | C++ | src/0037_sudoku_solver.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | src/0037_sudoku_solver.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | src/0037_sudoku_solver.cpp | Dephilia/leetcode_cpp | 2f0d85d842fafd43cae8d5ae99817c9e243d58e4 | [
"MIT"
] | null | null | null | /*
* This is a DFS problem.
* Try to use recursive function to solve.
*
*/
#include <leetcode.hpp>
class Solution {
public:
// Just for convenience
using Board = vector<vector<char>>;
bool isValid(Board& board, int& row, int& col, char& ch) {
/*
* Input row, column and char, determine if the char is valid
*/
// Check row
for (auto& i:board) {
if (i[col] == ch) return false;
}
// Check column
for (auto& i:board[row]) {
if (i == ch) return false;
}
// Check 3x3 Box
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
char val = board[row/3*3+i][col/3*3+j];
if (val == ch) return false;
}
}
return true;
}
bool solveOnce(Board& board, int num) {
// If overboard, return true (complete solving)
if (num < 0 || num > 80) return true;
// If the block is solved, move to next block
int row = num / 9;
int col = num % 9;
if (board[row][col] != '.') return solveOnce(board, num+1);
// Try to fill the block with 1 to 9
for (char ch='1'; ch <= '9'; ch++){
if (isValid(board, row, col, ch)) {
// If the number is valid, fill it and move to next
board[row][col] = ch; // Set state
if (solveOnce(board, num+1)) return true;
// If next state never become true, it means the number is wrong.
board[row][col] = '.'; // Important, reset state
}
}
return false;
}
void solveSudoku(Board& board) {
solveOnce(board,0);
}
};
/*
* Main
*/
void printBoard(vector<vector<char>>& board) {
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
cout << board[i][j];
}
cout << endl;
}
}
int main() {
vector<vector<char>> board{
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'}
};
Solution sol;
sol.solveSudoku(board);
printBoard(board);
return 0;
}
| 24.742574 | 81 | 0.411765 | [
"vector"
] |
6f69de6d7abc37a7447d8200be9063c8c234b841 | 2,235 | cc | C++ | chrome/browser/sync/sessions/test_util.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-02-20T14:25:04.000Z | 2019-12-13T13:58:28.000Z | chrome/browser/sync/sessions/test_util.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | chrome/browser/sync/sessions/test_util.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/sessions/test_util.h"
namespace browser_sync {
namespace sessions {
namespace test_util {
void SimulateHasMoreToSync(sessions::SyncSession* session,
SyncerStep begin, SyncerStep end) {
session->status_controller()->update_conflicts_resolved(true);
ASSERT_TRUE(session->HasMoreToSync());
}
void SimulateDownloadUpdatesFailed(sessions::SyncSession* session,
SyncerStep begin, SyncerStep end) {
// Note that a non-zero value of changes_remaining once a session has
// completed implies that the Syncer was unable to exhaust this count during
// the GetUpdates cycle. This is an indication that an error occurred.
session->status_controller()->set_num_server_changes_remaining(1);
}
void SimulateCommitFailed(sessions::SyncSession* session,
SyncerStep begin, SyncerStep end) {
// Note that a non-zero number of unsynced handles once a session has
// completed implies that the Syncer was unable to make forward progress
// during a commit, indicating an error occurred.
// See implementation of SyncSession::HasMoreToSync.
std::vector<int64> handles;
handles.push_back(1);
session->status_controller()->set_unsynced_handles(handles);
}
void SimulateSuccess(sessions::SyncSession* session,
SyncerStep begin, SyncerStep end) {
if (session->HasMoreToSync()) {
ADD_FAILURE() << "Shouldn't have more to sync";
}
ASSERT_EQ(0U, session->status_controller()->num_server_changes_remaining());
ASSERT_EQ(0U, session->status_controller()->unsynced_handles().size());
}
void SimulateThrottledImpl(sessions::SyncSession* session,
const base::TimeDelta& delta) {
session->delegate()->OnSilencedUntil(base::TimeTicks::Now() + delta);
}
void SimulatePollIntervalUpdateImpl(sessions::SyncSession* session,
const base::TimeDelta& new_poll) {
session->delegate()->OnReceivedLongPollIntervalUpdate(new_poll);
}
} // namespace test_util
} // namespace sessions
} // namespace browser_sync
| 38.534483 | 78 | 0.730201 | [
"vector"
] |
6f6a2fcb09cea2e1382d139afb0febcac9941eb6 | 3,895 | cpp | C++ | modules/task_2/votyakova_d_jacoby_method/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_2/votyakova_d_jacoby_method/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/votyakova_d_jacoby_method/main.cpp | Stepakrap/pp_2021_autumn | 716803a14183172337d51712fb28fe8e86891a3d | [
"BSD-3-Clause"
] | 3 | 2022-02-23T14:20:50.000Z | 2022-03-30T09:00:02.000Z | // Copyright 2021 Votyakova Daria
#include <gtest/gtest.h>
#include <vector>
#include <gtest-mpi-listener.hpp>
#include "./jacoby_method.h"
TEST(JACOBI_METHOD_MPI, TEST_Equation_1) {
fflush(stdout);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<double> A, b;
if (rank == 0) {
A = {4., 1., 1., 1., 6., -1., 1., 2., 5};
b = {9., 10., 20.};
std::vector<double> x = getJacobiSequential(A, b, 3);
double error = getError(A, x, b);
fflush(stdout);
ASSERT_LE(error, eps);
}
std::vector<double> x = getJacobiParallel(A, b, 3);
if (rank == 0) {
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
fflush(stdout);
}
TEST(JACOBI_METHOD_MPI, TEST_Equation_2) {
fflush(stdout);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<double> A, b;
if (rank == 0) {
A = {32., 2., 1., 3., 1., 1., 8., 3., 1., 3., 1., 2., 16.,
3., 1., 1., 2., 3., 56., 1., 1., 2., 1., 3., 32.};
b = {43., 14., -3., 169., -19.};
std::vector<double> x = getJacobiSequential(A, b, 5);
double error = getError(A, x, b);
fflush(stdout);
ASSERT_LE(error, eps);
}
std::vector<double> x = getJacobiParallel(A, b, 5);
if (rank == 0) {
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
fflush(stdout);
}
TEST(JACOBI_METHOD_MPI, TEST_Random_Equation_3) {
fflush(stdout);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<double> A, b;
int size = 100;
if (rank == 0) {
A = getDiagonallyDominantMatrix(size);
b = getB(size);
std::vector<double> x = getJacobiSequential(A, b, size);
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
std::vector<double> x = getJacobiParallel(A, b, size);
if (rank == 0) {
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
fflush(stdout);
}
TEST(JACOBI_METHOD_MPI, TEST_Random_Equation_4) {
fflush(stdout);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<double> A, b;
int size = 500;
if (rank == 0) {
A = getDiagonallyDominantMatrix(size);
b = getB(size);
std::vector<double> x = getJacobiSequential(A, b, size);
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
std::vector<double> x = getJacobiParallel(A, b, size);
if (rank == 0) {
double error = getError(A, x, b);
ASSERT_LE(error, eps);
}
fflush(stdout);
}
TEST(JACOBI_METHOD_MPI, TEST_Random_Equation_5) {
fflush(stdout);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<double> A, b;
// double start, end, stime, ptime;
int size = 1000;
if (rank == 0) {
A = getDiagonallyDominantMatrix(size);
b = getB(size);
// start = MPI_Wtime();
std::vector<double> x = getJacobiSequential(A, b, size);
// end = MPI_Wtime();
double error = getError(A, x, b);
// stime = end - start;
// printf("Sequential error: %f\n", error);
// printf("Sequential time: %f\n", stime);
ASSERT_LE(error, eps);
// start = MPI_Wtime();
}
std::vector<double> x = getJacobiParallel(A, b, size);
if (rank == 0) {
// end = MPI_Wtime();
double error = getError(A, x, b);
// ptime = end - start;
// printf("Parallel error: %f\n", error);
// printf("Parallel time: %f\n", ptime);
// printf("Speedup: %f\n", stime / ptime);
ASSERT_LE(error, eps);
}
fflush(stdout);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 23.463855 | 76 | 0.61181 | [
"vector"
] |
6f6a42e2b32b5f0e337c0c5c46fb8bb5dd12ae90 | 1,699 | cpp | C++ | src/PersistenceManager.cpp | barulicm/cupola | 90ef07ccadc31cdc5cce2ce5b142987dc4425c8d | [
"MIT"
] | null | null | null | src/PersistenceManager.cpp | barulicm/cupola | 90ef07ccadc31cdc5cce2ce5b142987dc4425c8d | [
"MIT"
] | null | null | null | src/PersistenceManager.cpp | barulicm/cupola | 90ef07ccadc31cdc5cce2ce5b142987dc4425c8d | [
"MIT"
] | null | null | null | #include <iostream>
#include "PersistenceManager.h"
PersistenceManager::PersistenceManager(QObject *parent)
: QObject(parent),
m_settings("barulicm","Cupola")
{
}
void PersistenceManager::loadRepositoryListModel(RepositoryListModel &model) {
model.clear();
int repoCount = m_settings.beginReadArray("repos");
for(auto i_repos = 0; i_repos < repoCount; i_repos++) {
m_settings.setArrayIndex(i_repos);
Repository repo;
repo.setName(m_settings.value("name").toString());
repo.setLocalPath(m_settings.value("localPath").toString());
int notificationsCount = m_settings.beginReadArray("notifications");
for(auto i_notifications = 0; i_notifications < notificationsCount; i_notifications++) {
m_settings.setArrayIndex(i_notifications);
repo.addNotification(m_settings.value("message").toString());
}
m_settings.endArray();
model.addRepository(repo);
}
m_settings.endArray();
}
void PersistenceManager::saveRepositoryListModel(RepositoryListModel *model) {
auto repoCount = model->rowCount();
m_settings.beginWriteArray("repos", repoCount);
for(int i_repo = 0; i_repo < repoCount; i_repo++) {
m_settings.setArrayIndex(i_repo);
const auto& repo = model->get(i_repo);
m_settings.setValue("name", repo.name());
m_settings.setValue("localPath", repo.localPath());
m_settings.beginWriteArray("notifications", repo.notifications().size());
auto i_notifications = 0;
for(const auto& notification : repo.notifications()) {
m_settings.setArrayIndex(i_notifications);
m_settings.setValue("message", notification);
i_notifications++;
}
m_settings.endArray();
}
m_settings.endArray();
}
| 35.395833 | 92 | 0.723367 | [
"model"
] |
4cf6956d90202eb6f27a5acc2c63f02d94e95768 | 7,634 | cc | C++ | Algorithms/TrackMaintainer/TrackMaintainer.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/TrackMaintainer/TrackMaintainer.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/TrackMaintainer/TrackMaintainer.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include "boost/bind.hpp"
#include "Algorithms/Controller.h"
#include "Logger/Log.h"
#include "Messages/RadarConfig.h"
#include "Messages/TSPI.h"
#include "Messages/Track.h"
#include "Time/TimeStamp.h"
#include "TrackMaintainer.h"
#include "TrackMaintainer_defaults.h"
#include "Utils/Utils.h"
#include "QtCore/QString"
#include "QtCore/QVariant"
using namespace SideCar;
using namespace SideCar::Messages;
using namespace SideCar::Algorithms;
TrackMaintainer::TrackMaintainer(Controller& controller, Logger::Log& log) :
Super(controller, log), enabled_(Parameter::BoolValue::Make("enabled", "Enabled", kDefaultEnabled)),
hitsBeforePromote_(Parameter::PositiveIntValue::Make("hitsBeforePromote",
"The number of detections associated with a "
"track before it is promoted to firm",
kDefaultHitsBeforePromote)),
missesBeforeDrop_(Parameter::PositiveIntValue::Make("missesBeforeDrop",
"The number of missed scans allowed before a "
"track is dropped",
kDefaultMissesBeforeDrop))
{
;
}
bool
TrackMaintainer::startup()
{
registerProcessor<TrackMaintainer, Track>("corrected", &TrackMaintainer::processInput);
setAlarm(5); // set an alarm to go off every 5 seconds
return registerParameter(enabled_) && registerParameter(missesBeforeDrop_) &&
registerParameter(hitsBeforePromote_) && Super::startup();
}
bool
TrackMaintainer::reset()
{
trackDatabase_.clear();
return Super::reset();
}
/** This method will get called whenever the timer for this Algorithm goes off
*/
void
TrackMaintainer::processAlarm()
{
static Logger::ProcLog log("processAlarm", getLog());
LOGINFO << "checking database - trks " << trackDatabase_.size() << std::endl;
checkDatabase();
}
bool
TrackMaintainer::shutdown()
{
trackDatabase_.clear();
return Super::shutdown();
}
bool
TrackMaintainer::processInput(const Messages::Track::Ref& msg)
{
static Logger::ProcLog log("processInput", getLog());
LOGDEBUG << msg->headerPrinter() << std::endl;
LOGDEBUG << msg->dataPrinter() << std::endl;
if (msg->getFlags() == Track::kNew || msg->getFlags() == Track::kCorrected) { updateDatabase(msg); }
return true;
}
void
TrackMaintainer::updateDatabase(const Messages::Track::Ref& msg)
{
static Logger::ProcLog log("updateDatabase", getLog());
LOGDEBUG << "track database has " << trackDatabase_.size() << " entries" << std::endl;
// Find existing entry in map or create a new one
//
Mapping::iterator it = trackDatabase_.find(msg->getTrackNumber());
if (it == trackDatabase_.end()) {
LOGDEBUG << "new entry for track num " << msg->getTrackNumber() << std::endl;
it = trackDatabase_.insert(Mapping::value_type(msg->getTrackNumber(), TrackMsgVector())).first;
}
// Add the given message to the track vector
//
it->second.push_back(msg);
// Update the offset between message time and wall time.
//
Time::TimeStamp now = Time::TimeStamp::Now();
epoch_ = now.asDouble() - msg->getExtractionTime();
LOGDEBUG << "epoch " << epoch_ << std::endl;
}
/** This method checks for tracks that need to be promoted from tentative to firm and also for tracks that have
not been updated recently and need to be dropped. If a track needs to be promoted or dropped, this method
will send out a Track message to this effect.
This method should be careful not to use current time to compare against
because we need to be able to accomodate data playback, which may contain
data with timestamps that are far in the past.
*/
void
TrackMaintainer::checkDatabase()
{
static Logger::ProcLog log("checkDatabase", getLog());
LOGINFO << "track database has " << trackDatabase_.size() << " entries" << std::endl;
double dropLimit = RadarConfig::GetRotationDuration() * missesBeforeDrop_->getValue();
LOGDEBUG << "drop duration " << dropLimit << std::endl;
// Loop through the data base.
//
Mapping::iterator it = trackDatabase_.begin();
while (it != trackDatabase_.end()) {
LOGDEBUG << "track database entry " << it->first << std::endl;
const TrackMsgVector& tracks(it->second);
const Messages::Track::Ref& track(tracks.back());
Messages::Track::Ref report;
// Check to see if track is promotable
//
if (track->getType() == Track::kTentative) {
LOGDEBUG << "tentative track with " << tracks.size()
<< " msgs. Threshold= " << hitsBeforePromote_->getValue() << std::endl;
if (tracks.size() >= hitsBeforePromote_->getValue()) {
LOGDEBUG << "track should be promoted " << std::endl;
report = Track::Make("TrackMaintainer", track);
report->setFlags(Track::kPromoted);
}
}
// Check to see if track should be dropped
//
double now = Time::TimeStamp::Now().asDouble();
if ((now - (epoch_ + track->getExtractionTime())) > dropLimit) {
LOGWARNING << "dropping track " << it->first << std::endl;
report = Track::Make("TrackMaintainer", track);
report->setFlags(Track::kDropping);
// NOTE: erasing the current item only affects the current iterator but no others, so we
// post-increment so that we have a valid iterator to the next element after the erasure.
//
trackDatabase_.erase(it++);
} else {
// Not deleting track, so safe to advance the iterator to the next one.
//
++it;
}
// If we created a report above, send it out.
//
if (report) {
send(report);
std::string flag;
switch (report->getFlags()) {
case Track::kDropping: flag = " dropping"; break;
case Track::kNew: flag = "new"; break;
case Track::kPromoted: flag = "promoted"; break;
case Track::kNeedsPrediction: flag = "needs prediction"; break;
case Track::kNeedsCorrection: flag = "needs correction"; break;
case Track::kPredicted: flag = "predicted"; break;
case Track::kCorrected: flag = "corrected"; break;
default: break;
};
std::string type;
switch (report->getType()) {
case Track::kTentative: type = "tentative"; break;
case Track::kConfirmed: type = "confirmed"; break;
default: break;
};
LOGDEBUG << "maintained track: " << report->getTrackNumber() << " flag: " << flag << " type: " << type
<< std::endl;
}
}
}
void
TrackMaintainer::setInfoSlots(IO::StatusBase& status)
{
status.setSlot(kEnabled, enabled_->getValue());
}
extern "C" ACE_Svc_Export QVariant
FormatInfo(const IO::StatusBase& status, int role)
{
if (role != Qt::DisplayRole) return QVariant();
if (!status[TrackMaintainer::kEnabled])
return "Disabled";
else
return "Enabled";
}
// Factory function for the DLL that will create a new instance of the ABTracker class. DO NOT CHANGE!
//
extern "C" ACE_Svc_Export Algorithm*
TrackMaintainerMake(Controller& controller, Logger::Log& log)
{
return new TrackMaintainer(controller, log);
}
| 34.387387 | 114 | 0.61213 | [
"vector"
] |
4cff7d3a1c51b6181de8543f0d129447ce93bf03 | 22,519 | cc | C++ | microbench/rdma/rdma_micro.cc | FlyingHObb1t/drtm_forked | b86ae25f9954733df86e5a032c005f992d26af77 | [
"Apache-2.0"
] | 42 | 2015-12-17T04:42:22.000Z | 2021-07-16T14:40:24.000Z | microbench/rdma/rdma_micro.cc | FlyingHObb1t/drtm_forked | b86ae25f9954733df86e5a032c005f992d26af77 | [
"Apache-2.0"
] | null | null | null | microbench/rdma/rdma_micro.cc | FlyingHObb1t/drtm_forked | b86ae25f9954733df86e5a032c005f992d26af77 | [
"Apache-2.0"
] | 9 | 2015-12-19T00:45:37.000Z | 2021-11-07T16:50:14.000Z | /*
* The code is part of our project called DrTM, which leverages HTM and RDMA for speedy distributed
* in-memory transactions.
*
*
* Copyright (C) 2015 Institute of Parallel and Distributed Systems (IPADS), Shanghai Jiao Tong University
* 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.
*
* For more about this software, visit: http://ipads.se.sjtu.edu.cn/drtm.html
*
*/
//a file for testing rdma read performance
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <set>
#include <vector>
#include <unordered_map>
#include "network_node.h"
#include <sys/mman.h>
#include "rdma_resource.h"
#include "rdma_cuckoohash.h"
#include "rdma_hophash.h"
#include "rdma_clusterhash.h"
int THREAD_NUM = 6;
uint64_t cycles_per_second;
RdmaResource *rdma = NULL;
//for binding
int socket_0[] = {
0,2,4,6,8,10,12,14,16,18
};
int socket_1[] = {
1,3,5,7,9,11,13,15,17,19
};
void pin_to_core(size_t core) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(core , &mask);
int result=sched_setaffinity(0, sizeof(mask), &mask);
}
inline uint64_t
rdtsc(void)
{
uint32_t hi, lo;
__asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo)|(((uint64_t)hi)<<32);
}
struct Thread_config {
int id;
double throughput;
int latency;
void * ptr;
int * buffer;
};
uint64_t rdma_size;
uint64_t val_num=1000*1000;
double rate=0.9;
int current_partition ;
int total_partition ;
int target_partition ;
void Run(void *info) ;
void Run1(void *info);
void Run2(void *info);
struct cache_entry{
//pthread_spinlock_t lock;
uint64_t seq_num;
uint64_t key;
uint64_t loc;
};
struct cache_entry *limited_cache;
uint64_t cache_num;
void limited_cache_init(){
cache_num = val_num ;
limited_cache = new cache_entry[cache_num];
for(int i=0;i<cache_num;i++){
limited_cache[i].seq_num=0;
}
}
void limited_cache_clear(){
for(int i=0;i<cache_num;i++){
limited_cache[i].seq_num=0;
limited_cache[i].key=-1;
limited_cache[i].loc=-1;
}
}
bool limited_cache_lookup(uint64_t key){
bool ret=false;
uint64_t old_seq=limited_cache[key%cache_num].seq_num;
if(old_seq%2==1)
return false;
if(limited_cache[key%cache_num].key==key)
ret=true;
uint64_t new_seq=limited_cache[key%cache_num].seq_num;
if(new_seq==old_seq)
return ret;
return false;
}
void limited_cache_insert(uint64_t key,uint64_t loc){
uint64_t old_seq=limited_cache[key%cache_num].seq_num;
if(old_seq%2==1)
return;
if(__sync_bool_compare_and_swap(&limited_cache[key%cache_num].seq_num,old_seq,old_seq+1) == false){
return ;
}
limited_cache[key%cache_num].key=key;
limited_cache[key%cache_num].loc=loc;
limited_cache[key%cache_num].seq_num=old_seq+2;
return ;
}
int val_length;
int main(int argc,char** argv){
void (* ptr)(void *) = Run;
int id = atoi(argv[1]);
current_partition = id;
total_partition = atoi(argv[2]);
target_partition = 0;
ptr = Run2;
if(current_partition== target_partition){
ptr = Run1;
}
ibv_fork_init();
fprintf(stdout,"Start with %d threads.\n",THREAD_NUM);
// main tests
void *status;
uint64_t start_t = rdtsc();
sleep(1);
cycles_per_second = rdtsc() - start_t;
Thread_config *configs = new Thread_config[THREAD_NUM];
pthread_t *thread = new pthread_t[THREAD_NUM];
rdma_size = 1024*1024*1024; //1G
rdma_size = rdma_size*20; //20G
uint64_t total_size=rdma_size+1024*1024*1024;
// rdma_size = 1024*4; //4K
// //rdma_size = rdma_size*20; //20G
// uint64_t total_size=rdma_size+1024*4;
Network_Node *node = new Network_Node(total_partition,current_partition,THREAD_NUM);
fprintf(stdout,"size %ld ... ",total_size);
char *buffer= (char*) malloc(total_size);
char data[2050];
val_num=1000*1000;
val_num=val_num*20;
limited_cache_init();
//Rdma_3_1_CuckooHash *table = new Rdma_3_1_CuckooHash(val_length,val_num,buffer);
//RdmaHopHash *table = new RdmaHopHash(val_length,val_num,buffer);
RdmaClusterHash *table = new RdmaClusterHash(val_length,val_num,buffer);
for(uint64_t i=0;i<val_num*rate;i++){
table->Insert(i,data);
}
limited_cache_clear();
rdma=new RdmaResource(total_partition,THREAD_NUM,current_partition,(char *)buffer,total_size,1024*1024*128,rdma_size);
//rdma=new RdmaResource(total_partition,THREAD_NUM,current_partition,(char *)buffer,total_size,512,rdma_size);
rdma->node = node;
rdma->Servicing();
rdma->Connect();
for(size_t id = 0;id < THREAD_NUM;++id) {
configs[id].buffer = NULL;
}
fprintf(stdout,"connection done\n");
val_length=64;
while(true){
//val_length=val_length*2;
if(val_length>2048)
break;
limited_cache_clear();
for(size_t id = 0;id < THREAD_NUM;++id) {
configs[id].id = id;
configs[id].throughput=0;
configs[id].ptr=table;
pthread_create (&(thread[id]), NULL, ptr, (void *) &(configs[id]));
}
for(size_t t = 0 ; t < THREAD_NUM; t++) {
int rc = pthread_join(thread[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
int total_throughput=0;
for(size_t t = 0 ; t < THREAD_NUM; t++){
total_throughput+=configs[t].throughput;
}
int average_latency=0;
for(size_t t = 0 ; t < THREAD_NUM; t++){
average_latency+=configs[t].latency;
}
average_latency=average_latency / THREAD_NUM;
//last partition will print the total throughput of all clients
if(current_partition == total_partition-1){
for(int i=1;i<current_partition;i++){
std::string str=node->Recv();
//first 2 char is for internal usage
int tmp=std::stoi(str.substr(2));
total_throughput+=tmp;
}
for(int i=1;i<current_partition;i++){
node->Send(i,THREAD_NUM,std::to_string(total_throughput));
}
//barrier();
for(int i=1;i<current_partition;i++){
std::string str=node->Recv();
//first 2 char is for internal usage
int tmp=std::stoi(str.substr(2));
average_latency+=tmp;
}
average_latency=average_latency/(total_partition-1);
for(int i=1;i<current_partition;i++){
node->Send(i,THREAD_NUM,std::to_string(total_throughput));
}
printf("val_length\t%d\tthroughput\t%d\tlatency\t%d\n",val_length,total_throughput,average_latency);
} else {
node->Send(total_partition-1,THREAD_NUM,std::to_string(total_throughput));
std::string str=node->Recv();
node->Send(total_partition-1,THREAD_NUM,std::to_string(average_latency));
str=node->Recv();
printf("local throughput:%d\n",total_throughput);
}
}
}
void random_read(void *ptr,uint64_t key,uint64_t val_length){
struct Thread_config *config = (struct Thread_config*) ptr;
int id = config->id;
uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(id);
uint64_t start_addr=(key%(rdma_size/val_length))*val_length;
rdma->RdmaRead(id,target_partition,(char *)local_buffer,val_length,start_addr);
}
int cuckoo_read(void *ptr,uint64_t key,uint64_t val_length){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
Rdma_3_1_CuckooHash *table = (Rdma_3_1_CuckooHash *) (config->ptr);
uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(id);
uint64_t loc=0;
uint64_t p[3];
p[0]=table->GetHash(key);
int count=0;
for(uint64_t slot=0;slot<3;slot++){
count++;
if(slot==1)
p[1]=table->GetHash2(key);
if(slot==2)
p[2]=table->GetHash3(key);
loc = p[slot]* table->bucketsize;
rdma->RdmaRead(id,target_partition,(char *)local_buffer,sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode),loc);
Rdma_3_1_CuckooHash::RdmaArrayNode * node =(Rdma_3_1_CuckooHash::RdmaArrayNode *)local_buffer;
if(node->valid==true && node->key==key){
loc = table->get_dataloc(node->index);
break;
}
}
//assert(rdma->RdmaRead(id,target_partition,(char *)local_buffer ,val_length , 0) == 0);
uint64_t index = ((key *key) %(val_num));
uint64_t start_addr=index*val_length;
//while(start_addr>off)
// start_addr=start_addr/2;
rdma->RdmaRead(id,target_partition,(char *)local_buffer,val_length,start_addr);
count++;
return count;
}
void Run(void *ptr) {
struct Thread_config *config = (struct Thread_config*) ptr;
int id = config->id;
pin_to_core(socket_1[id]);
int num_operations=1000000;//*16;
int seed=id+current_partition*THREAD_NUM;
sleep(2);
uint64_t start_t = rdtsc();
int count=0;
for(int i=0;i<num_operations;i++){
uint64_t key =rand_r(&seed)% ((int)(val_num*rate));
//int val_length=64;
uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(id);
uint64_t start_addr=(key%(rdma_size/val_length))*val_length;
count+=cuckoo_read(ptr,key,val_length);
// rdma->post(id,target_partition,(char *)local_buffer+(i%32)*val_length,val_length,start_addr,IBV_WR_RDMA_READ);
// if(i%32==31){
// for(int tmp=0;tmp<32;tmp++)
// rdma->poll(id,target_partition);
// }
}
printf("count %f\n",count*1.0/num_operations);
uint64_t cycle_num = rdtsc() - start_t;
config->throughput=cycles_per_second *1.0*num_operations/ cycle_num;
}
const int batch_factor=4;//32;
struct post_window{
uint64_t key;
uint64_t loc;
uint64_t start;
int stage;
int winid;
};
void rdmaread_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
int id = config->id;
uint64_t *local_buffer = (uint64_t *)rdma->GetMsgAddr(id)+win.winid*val_length;//2048;//val_length ;
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
}
post_window rdmaread_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
int id = config->id;
rdma->poll(id,target_partition);
win.stage=-1;
return win;
}
void cuckoo_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
Rdma_3_1_CuckooHash *table = (Rdma_3_1_CuckooHash *) (config->ptr);
//char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
int node_size=sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*std::max(32,val_length);
uint64_t loc=0;
uint64_t hash;
if(win.stage==0){
hash=table->GetHash(win.key);
loc = hash * table->bucketsize;
rdma->post(id,target_partition,(char *)local_buffer,sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode),loc,IBV_WR_RDMA_READ);
} else if(win.stage==1){
hash=table->GetHash2(win.key);
loc = hash * table->bucketsize;
rdma->post(id,target_partition,(char *)local_buffer,sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode),loc,IBV_WR_RDMA_READ);
} else if(win.stage==2){
hash=table->GetHash3(win.key);
loc = hash * table->bucketsize;
rdma->post(id,target_partition,(char *)local_buffer,sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode),loc,IBV_WR_RDMA_READ);
} else {
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
}
}
post_window cuckoo_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
Rdma_3_1_CuckooHash *table = (Rdma_3_1_CuckooHash *) (config->ptr);
//char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
int node_size=sizeof(Rdma_3_1_CuckooHash::RdmaArrayNode);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*std::max(32,val_length);
uint64_t loc=0;
rdma->poll(id,target_partition);
if(win.stage==0 || win.stage==1 || win.stage==2){
Rdma_3_1_CuckooHash::RdmaArrayNode * node =(Rdma_3_1_CuckooHash::RdmaArrayNode *)local_buffer;
if(node->valid==true && node->key==win.key){
loc = table->get_dataloc(node->index);
win.stage=3;
return win;
} else {
win.stage=win.stage+1;
return win;
}
} else {
win.stage=-1;
return win;
}
}
void hop_indirect_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaHopHash *table = (RdmaHopHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
uint64_t hash;
if(win.stage==0){
hash = table->GetHash(win.key);
uint64_t read_header = 8*(sizeof(uint64_t)+16);
uint64_t loc = read_header / 2 * hash;
rdma->post(id,target_partition,(char *)local_buffer,read_header,loc,IBV_WR_RDMA_READ);
} else if(win.stage==1){
uint64_t read_chain = (sizeof(RdmaHopHash::RdmaChainNode));
rdma->post(id,target_partition,(char *)local_buffer,read_chain,loc,IBV_WR_RDMA_READ);
} else {
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
}
}
post_window hop_indirect_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaHopHash *table = (RdmaHopHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
rdma->poll(id,target_partition);
if(win.stage==0){
uint64_t hash = table->GetHash(win.key);
if(hash%100<5){
win.stage=1;
} else {
win.stage=2;
}
return win;
} else if(win.stage==1){
win.stage=2;
return win;
} else {
win.stage=-1;
return win;
}
}
void hop_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaHopHash *table = (RdmaHopHash *) (config->ptr);
//int msg_size=2*(sizeof(RdmaHopHash::RdmaHopNode)+4*val_length);
//char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*msg_size;//*10;///batch_factor*128 ;
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;//*10;///batch_factor*128 ;
uint64_t loc=0;
uint64_t hash;
if(win.stage==0){
hash = table->GetHash(win.key);
uint64_t read_header = 2*(sizeof(RdmaHopHash::RdmaHopNode)+4*val_length);
uint64_t loc = read_header / 2 * hash;
rdma->post(id,target_partition,(char *)local_buffer,read_header,loc,IBV_WR_RDMA_READ);
} else {
uint64_t read_chain = (sizeof(RdmaHopHash::RdmaChainNode)+2* val_length);
rdma->post(id,target_partition,(char *)local_buffer,read_chain,loc,IBV_WR_RDMA_READ);
}
}
post_window hop_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaHopHash *table = (RdmaHopHash *) (config->ptr);
//int msg_size=2*(sizeof(RdmaHopHash::RdmaHopNode)+4*val_length);
//char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*msg_size;//*10;///batch_factor*128 ;
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;//*10;///batch_factor*128 ;
uint64_t loc=0;
rdma->poll(id,target_partition);
if(win.stage==0){
uint64_t hash = table->GetHash(win.key);
if(hash%100<5){
win.stage=1;
} else {
win.stage=-1;
}
return win;
} else {
win.stage=-1;
return win;
}
}
void clustering_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaClusterHash *table = (RdmaClusterHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
uint64_t hash;
hash = table->GetHash(win.key);
uint64_t read_header = CLUSTER_H*(sizeof(uint64_t)+8);
if(win.stage==0){
uint64_t loc = read_header * hash;
rdma->post(id,target_partition,(char *)local_buffer,read_header,loc,IBV_WR_RDMA_READ);
} else if(win.stage==1){
rdma->post(id,target_partition,(char *)local_buffer,read_header,0,IBV_WR_RDMA_READ);
} else {
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
}
}
post_window clustering_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaClusterHash *table = (RdmaClusterHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
rdma->poll(id,target_partition);
if(win.stage==0){
uint64_t hash = table->GetHash(win.key);
if(hash%100<10){
win.stage=1;
} else {
win.stage=2;
}
return win;
} else if(win.stage==1){
win.stage=2;
return win;
} else {
win.stage=-1;
return win;
}
}
post_window clustering_limited_cache_post(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaClusterHash *table = (RdmaClusterHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
if(win.stage==0){
if(limited_cache_lookup(win.key)){
win.stage=2;
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
} else {
uint64_t index = table->GetHash(win.key);
uint64_t loc = table->getHeaderNode_loc(index);
rdma->post(id,target_partition,(char *)local_buffer,sizeof(RdmaClusterHash::HeaderNode),loc,IBV_WR_RDMA_READ);
}
} else if(win.stage==1){
uint64_t loc = win.loc;
rdma->post(id,target_partition,(char *)local_buffer,sizeof(RdmaClusterHash::HeaderNode),loc,IBV_WR_RDMA_READ);
} else {
uint64_t start_addr=(win.key%(rdma_size/val_length))*val_length;
rdma->post(id,target_partition,(char *)local_buffer,val_length,start_addr,IBV_WR_RDMA_READ);
}
return win;
}
post_window clustering_limited_cache_poll(void *ptr,post_window win){
struct Thread_config *config = (struct Thread_config*) ptr;
uint64_t id = config->id;
RdmaClusterHash *table = (RdmaClusterHash *) (config->ptr);
char *local_buffer = (char *)rdma->GetMsgAddr(id)+win.winid*2048;///batch_factor*128 ;
uint64_t loc=0;
rdma->poll(id,target_partition);
if(win.stage==0 || win.stage==1){
//win.stage==0 means cache miss , and first time to read data
//win.stage==1 means read the next ptr
RdmaClusterHash::HeaderNode* node= (RdmaClusterHash::HeaderNode*)local_buffer;
bool found=false;
for(int i=0;i<CLUSTER_H;i++){
if(node->indexes[i]!=0){
loc = table->getDataNode_loc(node->indexes[i]);
loc+= sizeof(RdmaClusterHash::DataNode);
limited_cache_insert(node->keys[i],loc);
}
}
for(int i=0;i<CLUSTER_H;i++){
if(node->keys[i]==win.key && node->indexes[i]!=0){
loc = table->getDataNode_loc(node->indexes[i]);
loc+= sizeof(RdmaClusterHash::DataNode);
found=true;
break;
}
}
if(found){
win.stage=2;
} else {
//stage 1 will read the next pointer
win.stage=1;
if(node->next !=NULL){
win.loc = table->getHeaderNode_loc(node->next) ;
}
else{
assert(false);
}
}
return win;
} else {
win.stage=-1;
return win;
}
}
void Run2(void *ptr) {
struct Thread_config *config = (struct Thread_config*) ptr;
int id = config->id;
pin_to_core(socket_1[id]);
int num_operations=1000000*20;
;//00*16;
int seed=id+current_partition*THREAD_NUM;
post_window window[batch_factor];
for(int i=0;i<batch_factor;i++){
window[i].stage=-1;
window[i].winid=i;
}
/*
if(config->buffer==NULL){
char filename[]="/home/datanfs/nfs0/zipf_data/0output";
filename[29]+=id;
std::ifstream infile(filename);
config->buffer=new int[num_operations];
for(int i=0;i<num_operations;i++){
if(infile>> config->buffer[i])//=dist.get_zipf_random(&seed)% ((int)(val_num*rate));
continue;
else {
printf("error when loading zipf data\n");
assert(false);
}
}
printf("%d loading zipf data OK\n",id);
}
*/
sleep(2);
uint64_t start_t = rdtsc();
int finish_ops=0;
int num_post=0;
int count=0;
int curr_op=0;
uint64_t latency_accum=0;
while(true){
if(finish_ops+batch_factor>=num_operations)
break;
for(int k=0;k<batch_factor;k++){
if(window[k].stage == -1){
//window[k].key = config->buffer[curr_op];
//curr_op++;
window[k].key = rand_r(&seed)% ((int)(val_num*rate));
window[k].stage=0;
window[k].start=rdtsc();
}
count++;
//this line is special, because when cache hit , it will modify window
window[k]=clustering_limited_cache_post(ptr,window[k]);
//rdmaread_post(ptr,window[k]);
//hop_post(ptr,window[k]);
//clustering_post(ptr,window[k]);
//hop_indirect_post(ptr,window[k]);
//cuckoo_post(ptr,window[k]);
}
for(int k=0;k<batch_factor;k++){
window[k]=clustering_limited_cache_poll(ptr,window[k]);
//window[k]=rdmaread_poll(ptr,window[k]);
//window[k]=hop_poll(ptr,window[k]);
//window[k]=clustering_poll(ptr,window[k]);
//window[k]=hop_indirect_poll(ptr,window[k]);
//window[k]=cuckoo_poll(ptr,window[k]);
if(window[k].stage == -1){
latency_accum+=(rdtsc()-window[k].start);
finish_ops++;
}
}
}
uint64_t cycle_num = rdtsc() - start_t;
//printf("count %d\n",count);
//printf("average latency %ld ns\n",latency_accum/finish_ops*1000000000 /cycles_per_second );
//printf("average cycle_num %ld ns\n",cycle_num*1000000000/finish_ops /cycles_per_second );
config->latency=latency_accum/finish_ops*1000000000 /cycles_per_second;
config->throughput=0;
config->throughput=cycles_per_second *1.0*num_operations/ cycle_num;
}
void Run1(void *ptr) {
fprintf(stdout,"polling...\n");
while(1) {
sleep(1);
}
}
| 32.308465 | 121 | 0.683778 | [
"vector"
] |
980078e2cd84e60f0993e2e6a27b052bd476368e | 7,001 | cc | C++ | parallel_clustering/clustering/clusterers/parallel-modularity-clusterer.cc | jeshi96/google-research | b769d51bb71eefe0a732eb0286716feb62117e2d | [
"Apache-2.0"
] | null | null | null | parallel_clustering/clustering/clusterers/parallel-modularity-clusterer.cc | jeshi96/google-research | b769d51bb71eefe0a732eb0286716feb62117e2d | [
"Apache-2.0"
] | null | null | null | parallel_clustering/clustering/clusterers/parallel-modularity-clusterer.cc | jeshi96/google-research | b769d51bb71eefe0a732eb0286716feb62117e2d | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "clustering/clusterers/parallel-modularity-clusterer.h"
#include <algorithm>
#include <iterator>
#include <utility>
#include <vector>
#include <iomanip>
#include <iostream>
#include "absl/memory/memory.h"
#include "absl/status/statusor.h"
#include "clustering/clusterers/parallel-correlation-clusterer.h"
#include "clustering/config.pb.h"
#include "clustering/gbbs-graph.h"
#include "clustering/in-memory-clusterer.h"
#include "parallel/parallel-graph-utils.h"
#include "clustering/status_macros.h"
namespace research_graph {
namespace in_memory {
double ComputeModularity(
InMemoryClusterer::Clustering& initial_clustering,
gbbs::symmetric_ptr_graph<gbbs::symmetric_vertex, float>& graph,
double total_edge_weight, std::vector<gbbs::uintE>& cluster_ids,
double resolution){
total_edge_weight = 0;
double modularity = 0;
for (std::size_t i = 0; i < graph.n; i++) {
auto vtx = graph.get_vertex(i);
auto nbhrs = vtx.getOutNeighbors();
double deg_i = vtx.getOutDegree();
for (std::size_t j = 0; j < deg_i; j++) {
total_edge_weight++;
auto nbhr = std::get<0>(nbhrs[j]);
//double deg_nbhr = graph.get_vertex(nbhr).getOutDegree();
if (cluster_ids[i] == cluster_ids[nbhr]) {
modularity++;
}
}
}
//modularity = modularity / 2; // avoid double counting
for (std::size_t i = 0; i < initial_clustering.size(); i++) {
double degree = 0;
for (std::size_t j = 0; j < initial_clustering[i].size(); j++) {
auto vtx_id = initial_clustering[i][j];
auto vtx = graph.get_vertex(vtx_id);
degree += vtx.getOutDegree();
}
modularity -= (resolution * degree * degree) / (total_edge_weight);
}
modularity = modularity / (total_edge_weight);
return modularity;
}
absl::Status ParallelModularityClusterer::RefineClusters(
const ClustererConfig& clusterer_config2,
InMemoryClusterer::Clustering* initial_clustering) const {
std::cout << "Begin modularity" << std::endl;
pbbs::timer t; t.start();
// TODO: we just use correlation config
const auto& config = clusterer_config2.correlation_clusterer_config();
auto modularity_config= ComputeModularityConfig(graph_.Graph(), config.resolution());
ClustererConfig clusterer_config;
clusterer_config.CopyFrom(clusterer_config2);
clusterer_config.mutable_correlation_clusterer_config()->set_resolution(std::get<1>(modularity_config));
clusterer_config.mutable_correlation_clusterer_config()->set_edge_weight_offset(0);
t.stop(); t.reportTotal("Actual Modularity Config Time: ");
auto status = ParallelCorrelationClusterer::RefineClusters(clusterer_config, initial_clustering,
std::get<0>(modularity_config), config.resolution());
std::vector<gbbs::uintE> cluster_ids(graph_.Graph()->n);
for (std::size_t i = 0; i < initial_clustering->size(); i++) {
for (std::size_t j = 0; j < ((*initial_clustering)[i]).size(); j++) {
cluster_ids[(*initial_clustering)[i][j]] = i;
}
}
double modularity = ComputeModularity(*initial_clustering,
*graph_.Graph(), std::get<2>(modularity_config), cluster_ids, config.resolution());
std::cout << "Modularity: " << std::setprecision(17) << modularity << std::endl;
return absl::OkStatus();
}
double ParallelModularityClusterer::ComputeModularity2(const ClustererConfig& clusterer_config,
InMemoryClusterer::Clustering* initial_clustering) {
const auto& config = clusterer_config.correlation_clusterer_config();
std::size_t total_edge_weight = 0;
for (std::size_t i = 0; i < graph_.Graph()->n; i++) {
auto vtx = graph_.Graph()->get_vertex(i);
auto wgh = vtx.getOutDegree();
// TODO: this assumes unit edge weights
total_edge_weight += wgh;
}
std::vector<gbbs::uintE> cluster_ids(graph_.Graph()->n);
for (std::size_t i = 0; i < initial_clustering->size(); i++) {
for (std::size_t j = 0; j < ((*initial_clustering)[i]).size(); j++) {
cluster_ids[(*initial_clustering)[i][j]] = i;
}
}
double modularity = ComputeModularity(*initial_clustering,
*graph_.Graph(), total_edge_weight, cluster_ids, config.resolution());
return modularity;
}
double ParallelModularityClusterer::ComputeObjective2(
const ClustererConfig& clusterer_config,
InMemoryClusterer::Clustering* initial_clustering) {
auto n = graph_.Graph()->n;
const auto& config = clusterer_config.correlation_clusterer_config();
std::vector<double> shifted_edge_weight(n);
std::vector<gbbs::uintE> cluster_ids(n);
for (std::size_t i = 0; i < initial_clustering->size(); i++) {
for (std::size_t j = 0; j < ((*initial_clustering)[i]).size(); j++) {
cluster_ids[(*initial_clustering)[i][j]] = i;
}
}
std::vector<gbbs::uintE> cluster_weights(n);
for (std::size_t i = 0; i < n; i++) {
cluster_weights[cluster_ids[i]]++;
}
// Compute cluster statistics contributions of each vertex
pbbs::parallel_for(0, n, [&](std::size_t i) {
gbbs::uintE cluster_id_i = cluster_ids[i];
auto add_m = pbbslib::addm<double>();
auto intra_cluster_sum_map_f = [&](gbbs::uintE u, gbbs::uintE v,
float weight) -> double {
// This assumes that the graph is undirected, and self-loops are counted
// as half of the weight.
if (cluster_id_i == cluster_ids[v])
return (weight - config.edge_weight_offset()) / 2;
return 0;
};
shifted_edge_weight[i] = graph_.Graph()->get_vertex(i).reduceOutNgh<double>(
i, intra_cluster_sum_map_f, add_m);
});
double objective =
parallel::ReduceAdd(absl::Span<const double>(shifted_edge_weight));
auto resolution_seq = pbbs::delayed_seq<double>(n, [&](std::size_t i) {
auto cluster_weight = cluster_weights[cluster_ids[i]];
return 1 * (cluster_weight - 1);
});
objective -= config.resolution() * pbbslib::reduce_add(resolution_seq) / 2;
return objective;
}
absl::StatusOr<InMemoryClusterer::Clustering>
ParallelModularityClusterer::Cluster(
const ClustererConfig& clusterer_config) const {
InMemoryClusterer::Clustering clustering(graph_.Graph()->n);
// Create all-singletons initial clustering
pbbs::parallel_for(0, graph_.Graph()->n, [&](std::size_t i) {
clustering[i] = {static_cast<gbbs::uintE>(i)};
});
RETURN_IF_ERROR(RefineClusters(clusterer_config, &clustering));
return clustering;
}
} // namespace in_memory
} // namespace research_graph
| 37.438503 | 106 | 0.700614 | [
"vector"
] |
9801b2dbb68af67982093820f24885a629d75abc | 1,067 | hpp | C++ | satellite/include/App.hpp | terra-render/Terra | fe2404b70f828ac807f776b25d4f5d702952c25b | [
"MIT"
] | 10 | 2017-05-18T12:33:49.000Z | 2019-11-05T00:21:16.000Z | satellite/include/App.hpp | sparkon/Terra | 49ba88604dea35b450b0b61b3048ad1d3ef0d27b | [
"MIT"
] | 1 | 2019-08-15T04:09:05.000Z | 2019-08-15T23:55:35.000Z | satellite/include/App.hpp | sparkon/Terra | 49ba88604dea35b450b0b61b3048ad1d3ef0d27b | [
"MIT"
] | 1 | 2018-02-04T07:14:12.000Z | 2018-02-04T07:14:12.000Z | #pragma once
// Satellite
#include <Visualization.hpp>
#include <Renderer.hpp>
#include <Graphics.hpp>
#include <Scene.hpp>
#include <Console.hpp>
// stdlib
#include <vector>
#include <memory>
#include <functional>
// The App is a container for Window, Presentation layers
// registers itself to the UI callbacks and passes events around
class App {
public:
App ( int argc, char** argv );
~App();
int run ();
private:
int _boot();
void _init_ui();
void _init_cmd_map();
void _shutdown();
int _opt_set ( int opt, int value );
int _opt_set ( int opt, const std::string& value );
int _opt_set ( bool clear, std::function<int() > setter );
void _clear();
void _on_config_change ( bool clear );
GFXLayer _gfx;
Scene _scene;
TerraRenderer _renderer;
// Presentation
Console _console;
Visualizer _visualizer;
// Callbacks
using CommandMap = std::map<std::string, CommandCallback>;
CommandMap _c_map;
}; | 21.34 | 65 | 0.616682 | [
"vector"
] |
9803d586cdcf3bfc0408ac8922dc5706fd3a0d0e | 758 | cpp | C++ | src/Core/Geometry/DCEL/HalfEdge.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/Core/Geometry/DCEL/HalfEdge.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/Core/Geometry/DCEL/HalfEdge.cpp | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #include <Core/Geometry/DCEL/HalfEdge.hpp>
#include <Core/Geometry/DCEL/Face.hpp>
#include <Core/Geometry/DCEL/Vertex.hpp>
namespace Ra {
namespace Core {
/// CONSTRUCTOR
HalfEdge::HalfEdge( const Container::Index& index ) :
IndexedObject( index ),
m_v( nullptr ),
m_next( nullptr ),
m_prev( nullptr ),
m_twin( nullptr ),
m_f( nullptr ) {}
HalfEdge::HalfEdge( const Vertex_ptr& v, const HalfEdge_ptr& next, const HalfEdge_ptr& prev,
const HalfEdge_ptr& twin, const Face_ptr& f, const Container::Index& index ) :
IndexedObject( index ),
m_v( v ),
m_next( next ),
m_prev( prev ),
m_twin( twin ),
m_f( f ) {}
/// DESTRUCTOR
HalfEdge::~HalfEdge() {}
} // namespace Core
} // namespace Ra
| 23.6875 | 98 | 0.64248 | [
"geometry"
] |
98095d95bb9831da44f28b3273d0cdefae083472 | 26,072 | hpp | C++ | include/Newtonsoft/Json/Serialization/JsonTypeReflector.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Serialization/JsonTypeReflector.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Newtonsoft/Json/Serialization/JsonTypeReflector.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Nullable`1
#include "System/Nullable_1.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Newtonsoft::Json::Serialization
namespace Newtonsoft::Json::Serialization {
// Forward declaring type: NamingStrategy
class NamingStrategy;
}
// Forward declaring namespace: Newtonsoft::Json::Utilities
namespace Newtonsoft::Json::Utilities {
// Forward declaring type: ThreadSafeStore`2<TKey, TValue>
template<typename TKey, typename TValue>
class ThreadSafeStore_2;
// Forward declaring type: ReflectionObject
class ReflectionObject;
// Forward declaring type: ReflectionDelegateFactory
class ReflectionDelegateFactory;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
// Forward declaring type: Attribute
class Attribute;
}
// Forward declaring namespace: System::ComponentModel
namespace System::ComponentModel {
// Forward declaring type: TypeConverter
class TypeConverter;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: DataContractAttribute
class DataContractAttribute;
// Forward declaring type: DataMemberAttribute
class DataMemberAttribute;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MemberInfo
class MemberInfo;
}
// Forward declaring namespace: Newtonsoft::Json
namespace Newtonsoft::Json {
// Forward declaring type: MemberSerialization
struct MemberSerialization;
// Forward declaring type: JsonConverter
class JsonConverter;
// Forward declaring type: JsonContainerAttribute
class JsonContainerAttribute;
}
// Completed forward declares
// Type namespace: Newtonsoft.Json.Serialization
namespace Newtonsoft::Json::Serialization {
// Forward declaring type: JsonTypeReflector
class JsonTypeReflector;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Newtonsoft::Json::Serialization::JsonTypeReflector);
DEFINE_IL2CPP_ARG_TYPE(::Newtonsoft::Json::Serialization::JsonTypeReflector*, "Newtonsoft.Json.Serialization", "JsonTypeReflector");
// Type namespace: Newtonsoft.Json.Serialization
namespace Newtonsoft::Json::Serialization {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Newtonsoft.Json.Serialization.JsonTypeReflector
// [TokenAttribute] Offset: FFFFFFFF
// [NullableAttribute] Offset: 6739C8
// [NullableContextAttribute] Offset: 6739C8
class JsonTypeReflector : public ::Il2CppObject {
public:
// Nested type: ::Newtonsoft::Json::Serialization::JsonTypeReflector::$$c__DisplayClass22_0
class $$c__DisplayClass22_0;
// Nested type: ::Newtonsoft::Json::Serialization::JsonTypeReflector::$$c
class $$c;
// Get static field: static private System.Nullable`1<System.Boolean> _fullyTrusted
static ::System::Nullable_1<bool> _get__fullyTrusted();
// Set static field: static private System.Nullable`1<System.Boolean> _fullyTrusted
static void _set__fullyTrusted(::System::Nullable_1<bool> value);
// [NullableAttribute] Offset: 0x677674
// Get static field: static private readonly Newtonsoft.Json.Utilities.ThreadSafeStore`2<System.Type,System.Func`2<System.Object[],System.Object>> CreatorCache
static ::Newtonsoft::Json::Utilities::ThreadSafeStore_2<::System::Type*, ::System::Func_2<::ArrayW<::Il2CppObject*>, ::Il2CppObject*>*>* _get_CreatorCache();
// Set static field: static private readonly Newtonsoft.Json.Utilities.ThreadSafeStore`2<System.Type,System.Func`2<System.Object[],System.Object>> CreatorCache
static void _set_CreatorCache(::Newtonsoft::Json::Utilities::ThreadSafeStore_2<::System::Type*, ::System::Func_2<::ArrayW<::Il2CppObject*>, ::Il2CppObject*>*>* value);
// [NullableAttribute] Offset: 0x6776E8
// Get static field: static private readonly Newtonsoft.Json.Utilities.ThreadSafeStore`2<System.Type,System.Type> AssociatedMetadataTypesCache
static ::Newtonsoft::Json::Utilities::ThreadSafeStore_2<::System::Type*, ::System::Type*>* _get_AssociatedMetadataTypesCache();
// Set static field: static private readonly Newtonsoft.Json.Utilities.ThreadSafeStore`2<System.Type,System.Type> AssociatedMetadataTypesCache
static void _set_AssociatedMetadataTypesCache(::Newtonsoft::Json::Utilities::ThreadSafeStore_2<::System::Type*, ::System::Type*>* value);
// [NullableAttribute] Offset: 0x677758
// Get static field: static private Newtonsoft.Json.Utilities.ReflectionObject _metadataTypeAttributeReflectionObject
static ::Newtonsoft::Json::Utilities::ReflectionObject* _get__metadataTypeAttributeReflectionObject();
// Set static field: static private Newtonsoft.Json.Utilities.ReflectionObject _metadataTypeAttributeReflectionObject
static void _set__metadataTypeAttributeReflectionObject(::Newtonsoft::Json::Utilities::ReflectionObject* value);
// static public System.Boolean get_FullyTrusted()
// Offset: 0x1341A04
static bool get_FullyTrusted();
// static public Newtonsoft.Json.Utilities.ReflectionDelegateFactory get_ReflectionDelegateFactory()
// Offset: 0x1340F84
static ::Newtonsoft::Json::Utilities::ReflectionDelegateFactory* get_ReflectionDelegateFactory();
// static private System.Void .cctor()
// Offset: 0x1341B34
static void _cctor();
// static public T GetCachedAttribute(System.Object attributeProvider)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T>
static T GetCachedAttribute(::Il2CppObject* attributeProvider) {
static_assert(std::is_convertible_v<T, ::System::Attribute*>);
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Serialization::JsonTypeReflector::GetCachedAttribute");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Newtonsoft.Json.Serialization", "JsonTypeReflector", "GetCachedAttribute", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(attributeProvider)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodRethrow<T, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, attributeProvider);
}
// static public System.Boolean CanTypeDescriptorConvertString(System.Type type, out System.ComponentModel.TypeConverter typeConverter)
// Offset: 0x133FE54
static bool CanTypeDescriptorConvertString(::System::Type* type, ByRef<::System::ComponentModel::TypeConverter*> typeConverter);
// static public System.Runtime.Serialization.DataContractAttribute GetDataContractAttribute(System.Type type)
// Offset: 0x134005C
static ::System::Runtime::Serialization::DataContractAttribute* GetDataContractAttribute(::System::Type* type);
// static public System.Runtime.Serialization.DataMemberAttribute GetDataMemberAttribute(System.Reflection.MemberInfo memberInfo)
// Offset: 0x1340134
static ::System::Runtime::Serialization::DataMemberAttribute* GetDataMemberAttribute(::System::Reflection::MemberInfo* memberInfo);
// static public Newtonsoft.Json.MemberSerialization GetObjectMemberSerialization(System.Type objectType, System.Boolean ignoreSerializableAttribute)
// Offset: 0x1340760
static ::Newtonsoft::Json::MemberSerialization GetObjectMemberSerialization(::System::Type* objectType, bool ignoreSerializableAttribute);
// static public Newtonsoft.Json.JsonConverter GetJsonConverter(System.Object attributeProvider)
// Offset: 0x13408DC
static ::Newtonsoft::Json::JsonConverter* GetJsonConverter(::Il2CppObject* attributeProvider);
// static public Newtonsoft.Json.JsonConverter CreateJsonConverterInstance(System.Type converterType, System.Object[] args)
// Offset: 0x1340A18
static ::Newtonsoft::Json::JsonConverter* CreateJsonConverterInstance(::System::Type* converterType, ::ArrayW<::Il2CppObject*> args);
// static public Newtonsoft.Json.Serialization.NamingStrategy CreateNamingStrategyInstance(System.Type namingStrategyType, System.Object[] args)
// Offset: 0x1340B20
static ::Newtonsoft::Json::Serialization::NamingStrategy* CreateNamingStrategyInstance(::System::Type* namingStrategyType, ::ArrayW<::Il2CppObject*> args);
// static public Newtonsoft.Json.Serialization.NamingStrategy GetContainerNamingStrategy(Newtonsoft.Json.JsonContainerAttribute containerAttribute)
// Offset: 0x1340C28
static ::Newtonsoft::Json::Serialization::NamingStrategy* GetContainerNamingStrategy(::Newtonsoft::Json::JsonContainerAttribute* containerAttribute);
// static private System.Func`2<System.Object[],System.Object> GetCreator(System.Type type)
// Offset: 0x1340CFC
static ::System::Func_2<::ArrayW<::Il2CppObject*>, ::Il2CppObject*>* GetCreator(::System::Type* type);
// static private System.Type GetAssociatedMetadataType(System.Type type)
// Offset: 0x1341020
static ::System::Type* GetAssociatedMetadataType(::System::Type* type);
// static private System.Type GetAssociateMetadataTypeFromAttribute(System.Type type)
// Offset: 0x13410AC
static ::System::Type* GetAssociateMetadataTypeFromAttribute(::System::Type* type);
// static private T GetAttribute(System.Type type)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T>
static T GetAttribute(::System::Type* type) {
static_assert(std::is_convertible_v<T, ::System::Attribute*>);
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Newtonsoft.Json.Serialization", "JsonTypeReflector", "GetAttribute", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodRethrow<T, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, type);
}
// static private T GetAttribute(System.Reflection.MemberInfo memberInfo)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T>
static T GetAttribute(::System::Reflection::MemberInfo* memberInfo) {
static_assert(std::is_convertible_v<T, ::System::Attribute*>);
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Newtonsoft.Json.Serialization", "JsonTypeReflector", "GetAttribute", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(memberInfo)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodRethrow<T, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, memberInfo);
}
// static public System.Boolean IsNonSerializable(System.Object provider)
// Offset: 0x134197C
static bool IsNonSerializable(::Il2CppObject* provider);
// static public System.Boolean IsSerializable(System.Object provider)
// Offset: 0x1340854
static bool IsSerializable(::Il2CppObject* provider);
// static public T GetAttribute(System.Object provider)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T>
static T GetAttribute(::Il2CppObject* provider) {
static_assert(std::is_convertible_v<T, ::System::Attribute*>);
static auto ___internal__logger = ::Logger::get().WithContext("::Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Newtonsoft.Json.Serialization", "JsonTypeReflector", "GetAttribute", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(provider)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodRethrow<T, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, provider);
}
}; // Newtonsoft.Json.Serialization.JsonTypeReflector
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::get_FullyTrusted
// Il2CppName: get_FullyTrusted
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&Newtonsoft::Json::Serialization::JsonTypeReflector::get_FullyTrusted)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "get_FullyTrusted", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::get_ReflectionDelegateFactory
// Il2CppName: get_ReflectionDelegateFactory
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::Utilities::ReflectionDelegateFactory* (*)()>(&Newtonsoft::Json::Serialization::JsonTypeReflector::get_ReflectionDelegateFactory)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "get_ReflectionDelegateFactory", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Newtonsoft::Json::Serialization::JsonTypeReflector::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetCachedAttribute
// Il2CppName: GetCachedAttribute
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::CanTypeDescriptorConvertString
// Il2CppName: CanTypeDescriptorConvertString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ByRef<::System::ComponentModel::TypeConverter*>)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::CanTypeDescriptorConvertString)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* typeConverter = &::il2cpp_utils::GetClassFromName("System.ComponentModel", "TypeConverter")->this_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "CanTypeDescriptorConvertString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, typeConverter});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetDataContractAttribute
// Il2CppName: GetDataContractAttribute
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Serialization::DataContractAttribute* (*)(::System::Type*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetDataContractAttribute)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetDataContractAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetDataMemberAttribute
// Il2CppName: GetDataMemberAttribute
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Runtime::Serialization::DataMemberAttribute* (*)(::System::Reflection::MemberInfo*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetDataMemberAttribute)> {
static const MethodInfo* get() {
static auto* memberInfo = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetDataMemberAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{memberInfo});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetObjectMemberSerialization
// Il2CppName: GetObjectMemberSerialization
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::MemberSerialization (*)(::System::Type*, bool)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetObjectMemberSerialization)> {
static const MethodInfo* get() {
static auto* objectType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* ignoreSerializableAttribute = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetObjectMemberSerialization", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{objectType, ignoreSerializableAttribute});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetJsonConverter
// Il2CppName: GetJsonConverter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::JsonConverter* (*)(::Il2CppObject*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetJsonConverter)> {
static const MethodInfo* get() {
static auto* attributeProvider = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetJsonConverter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{attributeProvider});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::CreateJsonConverterInstance
// Il2CppName: CreateJsonConverterInstance
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::JsonConverter* (*)(::System::Type*, ::ArrayW<::Il2CppObject*>)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::CreateJsonConverterInstance)> {
static const MethodInfo* get() {
static auto* converterType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* args = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "CreateJsonConverterInstance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{converterType, args});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::CreateNamingStrategyInstance
// Il2CppName: CreateNamingStrategyInstance
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::Serialization::NamingStrategy* (*)(::System::Type*, ::ArrayW<::Il2CppObject*>)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::CreateNamingStrategyInstance)> {
static const MethodInfo* get() {
static auto* namingStrategyType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* args = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "CreateNamingStrategyInstance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{namingStrategyType, args});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetContainerNamingStrategy
// Il2CppName: GetContainerNamingStrategy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Newtonsoft::Json::Serialization::NamingStrategy* (*)(::Newtonsoft::Json::JsonContainerAttribute*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetContainerNamingStrategy)> {
static const MethodInfo* get() {
static auto* containerAttribute = &::il2cpp_utils::GetClassFromName("Newtonsoft.Json", "JsonContainerAttribute")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetContainerNamingStrategy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{containerAttribute});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetCreator
// Il2CppName: GetCreator
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Func_2<::ArrayW<::Il2CppObject*>, ::Il2CppObject*>* (*)(::System::Type*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetCreator)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetCreator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetAssociatedMetadataType
// Il2CppName: GetAssociatedMetadataType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (*)(::System::Type*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetAssociatedMetadataType)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetAssociatedMetadataType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetAssociateMetadataTypeFromAttribute
// Il2CppName: GetAssociateMetadataTypeFromAttribute
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (*)(::System::Type*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::GetAssociateMetadataTypeFromAttribute)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "GetAssociateMetadataTypeFromAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute
// Il2CppName: GetAttribute
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute
// Il2CppName: GetAttribute
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::IsNonSerializable
// Il2CppName: IsNonSerializable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppObject*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::IsNonSerializable)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "IsNonSerializable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::IsSerializable
// Il2CppName: IsSerializable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppObject*)>(&Newtonsoft::Json::Serialization::JsonTypeReflector::IsSerializable)> {
static const MethodInfo* get() {
static auto* provider = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Serialization::JsonTypeReflector*), "IsSerializable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{provider});
}
};
// Writing MetadataGetter for method: Newtonsoft::Json::Serialization::JsonTypeReflector::GetAttribute
// Il2CppName: GetAttribute
// Cannot write MetadataGetter for generic methods!
| 72.623955 | 335 | 0.772821 | [
"object",
"vector"
] |
980c09def1506254bb13b62c13181cecadc61d30 | 16,812 | hpp | C++ | include/GTGE/Scripting.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | include/GTGE/Scripting.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | include/GTGE/Scripting.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_Scripting
#define GT_Scripting
#include <GTGE/Core/Serializer.hpp>
#include <GTGE/Core/Deserializer.hpp>
#include <GTGE/Core/Windowing/MouseButtons.hpp>
#include <GTGE/Core/Windowing/Keys.hpp>
#include <GTGE/Script.hpp>
#include "Scripting/Scripting_Game.hpp"
#include "Scripting/Scripting_Math.hpp"
#include "Scripting/Scripting_Rendering.hpp"
#include "Scripting/Scripting_Audio.hpp"
#include "Scripting/Scripting_Scene.hpp"
#include "Scripting/Scripting_SceneNode.hpp"
#include "Scripting/Scripting_Components.hpp"
#include "Scripting/Scripting_Particles.hpp"
#include "Scripting/Scripting_Editor.hpp"
#include "Scripting/Scripting_Animation.hpp"
namespace GT
{
// TODO: Combine these two functions into one: LoadGTScriptLibrary().
/// Loads the core GT script library into the given script.
bool LoadGTCoreScriptLibrary(Script &script);
/// Loads the GTEngine script library into the given script.
///
/// @param script [in] The script to load the GTEngine script library into.
///
/// @return True if the library is loaded successfully; false otherwise.
///
/// @remarks
/// This only loads the content in the GTEngine namespace/table. This will NOT load any game-specific functionality.
bool LoadGTEngineScriptLibrary(GT::Script &script);
/// Creates and pushes a new Serializer object onto the top of the stack.
///
/// @param serializer [in] A reference to the internal serializer object.
void PushNewSerializer(Script &script, Serializer &serializer);
/// Creates and pushes a new Deserializer object onto the top of the stack.
///
/// @param deserializer [in] A reference to the internal deserializer object.
void PushNewDeserializer(Script &script, Deserializer &deserializer);
/// Post a global MouseMove event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param mousePosX [in] The x mouse position.
/// @param mousePosY [in] The y mouse position.
void PostEvent_OnMouseMove(GT::Script &script, int mousePosX, int mousePosY);
/// Post a global MouseWheel event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param mousePosX [in] The x mouse position.
/// @param mousePosY [in] The y mouse position.
/// @param delta [in] The scroll delta.
void PostEvent_OnMouseWheel(GT::Script &script, int mousePosX, int mousePosY, int delta);
/// Post a global MouseButtonDown event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param mousePosX [in] The x mouse position.
/// @param mousePosY [in] The y mouse position.
/// @param button [in] The button code.
void PostEvent_OnMouseButtonDown(GT::Script &script, int mousePosX, int mousePosY, MouseButton button);
/// Post a global MouseButtonUp event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param mousePosX [in] The x mouse position.
/// @param mousePosY [in] The y mouse position.
/// @param button [in] The button code.
void PostEvent_OnMouseButtonUp(GT::Script &script, int mousePosX, int mousePosY, MouseButton button);
/// Post a global MouseButtonDoubleClick event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param mousePosX [in] The x mouse position.
/// @param mousePosY [in] The y mouse position.
/// @param button [in] The button code.
void PostEvent_OnMouseButtonDoubleClick(GT::Script &script, int mousePosX, int mousePosY, MouseButton button);
/// Post a global KeyPressed event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param key [in] The key code.
void PostEvent_OnKeyPressed(GT::Script &script, Key key);
/// Post a global KeyReleased event to everything relevant.
///
/// @param script [in] A reference to the main script object.
/// @param key [in] The key code.
void PostEvent_OnKeyReleased(GT::Script &script, Key key);
/// Posts a global OnGamePause event to everything relevant.
///
/// @param script [in] A reference to the main script object.
void PostEvent_OnGamePause(GT::Script &script);
/// Posts a global OnGamePause event to everything relevant.
///
/// @param script [in] A reference to the main script object.
void PostEvent_OnGameResume(GT::Script &script);
///////////////////////////////////////////////////////////////
// Script Definitions
/// Loads a scene node script, replacing the old one if it exists.
///
/// @param script [in] A reference to the script to load the scene node script into.
/// @param scriptAbsolutePath [in] The absolute path of the script.
/// @param scriptString [in] The actual script content.
bool LoadScriptDefinition(GT::Script &script, const char* scriptAbsolutePath, const char* scriptString);
/// Unloads a scene node script.
///
/// @param script [in] A reference to the script to unload the scene node script from.
/// @param scriptAbsolutePath [in] The absolute path of the script to unload.
void UnloadScriptDefinition(GT::Script &script, const char* scriptAbsolutePath);
namespace FFI
{
/// Retrieves the contents of the given directory.
///
/// @remarks
/// Argument 1: The name of the directory whose contents are being retrieved.
/// Argument 2: The table that will receive the directory names.
/// Argument 3: The table that will receive the file names.
/// @par
/// The returned strings will be in alphabetical order, indexed by an integer.
int GetDirectoryContents(Script &script);
/// Converts the given absolute path to a relative path.
///
/// @remarks
/// Argument 1: The path to convert to a relative path.
/// Argument 2: The path to be relative to.
int ToRelativePath(Script &script);
/// Retrieves the executable directory.
int GetExecutableDirectory(GT::Script &script);
/// Retrieves the version string.
int GetVersionString(GT::Script &script);
/// Determines if the given file path is a model file, based on it's extension.
int IsModelFile(GT::Script &script);
/// Determines if the given file path is an image file, based on it's extension.
int IsImageFile(GT::Script &script);
/// Determines if the given file path is a sound file, based on it's extension.
int IsSoundFile(GT::Script &script);
/// Determines if the given file path is a scene file, based on it's extension.
int IsSceneFile(GT::Script &script);
/// Determines if the given file path is a prefab file, based on it's extension.
int IsPrefabFile(GT::Script &script);
/// Determines if the given file path is a script file, based on it's extension.
int IsScriptFile(GT::Script &script);
/// Creates a prefab file from a scene node.
///
/// @remarks
/// Argument 1: The absolute path of the file to create or replace.
/// Argument 2: The path to make the absolute path relative to.
/// Argument 3: A pointer to the scene node to create the prefrab file from.
int CreatePrefab(GT::Script &script);
/// Executes the script defined in the given file.
///
/// @remarks
/// Argument 1: The name of the script file to load and execute.
int ExecuteFile(GT::Script &script);
/// Executes the given script text.
///
/// @remarks
/// Argument 1: The script text to execute.
int ExecuteScript(GT::Script &script);
/// Retrieves the last script error.
int GetLastScriptError(GT::Script &script);
/// Generates a random number between the two given numbers.
///
/// @remarks
/// Argument 1: The low bound.
/// Argument 2: The high bound.
int RandomInteger(GT::Script &script);
int RandomFloat(GT::Script &script);
namespace IOFFI
{
/// Returns the file information of the given path.
///
/// @param path [in] The path whose info is being retrieved.
///
/// @remarks
/// This function should only be used internally. Thus, it starts with '__'
int __GetFileInfo(Script &script);
/// Retrieves the path of the parent.
///
/// @remarks
/// Put simply, this just removes the last item and slash from the path.
int GetParentDirectoryPath(Script &script);
/// Retrieves the file name portion of the given path.
///
/// @remarks
/// This just deletes every path segment except the last. This will also work for directories.
int GetFileNameFromPath(Script &script);
/// Retrieves the extension of the given file name.
int GetExtension(Script &script);
/// Returns a string with the extension of the given string removed.
int RemoveExtension(Script &script);
/// Determines whether or not the given file exists.
int FileExists(Script &script);
/// Creates a folder at the given path.
int CreateDirectory(Script &script);
/// Deletes a folder at the given path.
int DeleteDirectory(Script &script);
/// Creates an empty file at the given path.
///
/// @remarks
/// This will not leave the file handle open.
int CreateEmptyFile(Script &script);
/// Deletes a file at the given path.
int DeleteFile(Script &script);
/// Determines if the file with the given path refers to an existing directory.
int IsDirectory(Script &script);
/// Retrieves the absolute path from the given relative path.
int FindAbsolutePath(Script &script);
}
namespace TimingFFI
{
/// Retrieves the current time in seconds.
int GetTimeInSeconds(Script &script);
/// Retrieves the current time in milliseconds.
int GetTimeInMilliseconds(Script &script);
}
namespace SystemFFI
{
/// Opens a file or URL in the preferred application.
///
/// @remarks
/// Argument 1: The URL or path of the file to open.
int OpenFileOrURL(Script &script);
}
////////////////////////////////////
// Serializer
namespace SerializerFFI
{
/// Serializes an 8-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The integer to serialize.
int WriteInt8(Script &script);
/// Serializes a 16-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The integer to serialize.
int WriteInt16(Script &script);
/// Serializes a 32-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The integer to serialize.
int WriteInt32(Script &script);
/// Serializes a 32-bit floating point number.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The number fo serialize.
int WriteFloat32(Script &script);
/// Serializes a 64-bit floating point number.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The number fo serialize.
int WriteFloat64(Script &script);
/// Serializes a boolean.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The boolean to serialize.
int WriteBool(Script &script);
/// Serializes a string using the Serializer::WriteString() method.
///
/// @remarks
/// Argument 1: A pointer to the Serializer object.
/// Argument 2: The string to serialize.
int WriteString(Script &script);
}
////////////////////////////////////
// Deserializer
namespace DeserializerFFI
{
/// Creates and returns a pointer to a file deserializer.
///
/// @remarks
/// Argument 1: The path of the file.
/// Return 1: A pointer to the file deserializer.
/// Return 2: The file handle.
int CreateFromFile(Script &script);
/// Deletes the give deserializer object.
///
/// @param
/// Argument 1: A pointer to the deserializer to delete.
/// Argument 2: The file handle to close.
int DeleteFromFile(Script &script);
/// Deserializes an 8-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized integer.
int ReadInt8(Script &script);
/// Deserializes a 16-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized integer.
int ReadInt16(Script &script);
/// Deserializes a 32-bit integer.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized integer.
int ReadInt32(Script &script);
/// Deserializes a 32-bit floating point number.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized number.
int ReadFloat32(Script &script);
/// Deserializes a 64-bit floating point number.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized number.
int ReadFloat64(Script &script);
/// Deserializes a boolean.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized boolean.
int ReadBool(Script &script);
/// Deserializes a string using the Serializer::WriteString() method.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Return: The deserialized string
int ReadString(Script &script);
/// Marks the beginning of the reading of a protected chunk of data.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Argument 2: The size in bytes of the chunk.
int StartChunk(Script &script);
/// Marks the end of the reading of a protected chunk of data.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// @par
/// If the current read position is not sitting at the end of the chunk, it will be seeked to it.
int EndChunk(Script &script);
/// Determines whether or not there is room in the chunk for reading the given amount of bytes.
///
/// @remarks
/// Argument 1: A pointer to the Deserializer object.
/// Argument 2: The number of bytes to check.
int HasRoomInChunk(Script &script);
}
namespace DebuggingFFI
{
/// Triggers a breakpoint.
int Breakpoint(Script &script);
/// Prints the call stack.
int PrintCallStack(Script &script);
}
}
}
#endif
| 37.030837 | 124 | 0.581906 | [
"object",
"model"
] |
980e007f56c31bc44e46a8cb1841e412bc5d30c2 | 750 | cpp | C++ | platforms/leetcode/0065_daily_temperatures.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | 2 | 2020-09-17T09:04:00.000Z | 2020-11-20T19:43:18.000Z | platforms/leetcode/0065_daily_temperatures.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/leetcode/0065_daily_temperatures.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | #include "../../template.hpp"
using i32 = std::int32_t;
using i64 = std::int64_t;
//const i32 INF = 1000000000 + 7;
const i32 fastio_ = ([](){std::ios_base::sync_with_stdio(0); std::cin.tie(0);return 0;})();
vector<i32> tab(vector<i32> arr) {
i32 n = arr.size();
vector<i32> mq;
vector<i32> ans(n);
for (i32 i = n - 1; i >= 0; --i) {
while (not mq.empty() and arr[i] >= arr[mq.back()]) {
mq.pop_back();
}
ans[i] = mq.empty() ? 0 : (mq.back() - i);
mq.push_back(i);
}
return ans;
}
int main() { TimeMeasure _;
cout << tab({73,74,75,71,69,72,76,73}) << endl; // 1,1,4,2,1,1,0,0
cout << tab({30,40,50,60}) << endl; // 1,1,1,0
cout << tab({30,60,90}) << endl; // 1,1,0
}
| 27.777778 | 91 | 0.512 | [
"vector"
] |
980ecefb961dcc3b370ceae045ee2072022509e5 | 2,630 | cpp | C++ | codeforces/B - String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/B - String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/B - String/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Apr/27/2018 14:23
* solution_verdict: Accepted language: GNU C++14
* run_time: 124 ms memory_used: 85400 KB
* problem: https://codeforces.com/contest/128/problem/B
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const long N=1e5;
long last,sz,occur[N+N];
long k,dp[N+N];
vector<long>v[N+N];
string s;
struct automata
{
long len,link,next[26],clone;
}st[N+N+N];
void insrt(long c)
{
long now=++sz;
st[now].len=st[last].len+1;
occur[now]=1;
st[now].clone=0;
long p,q,cl;
for(p=last;p!=-1&&!st[p].next[c];p=st[p].link)
st[p].next[c]=now;
if(p==-1)
st[now].link=0;
else
{
q=st[p].next[c];
if(st[p].len+1==st[q].len)
st[now].link=q;
else
{
cl=++sz;
st[cl].clone=1;
st[cl].len=st[p].len+1;
st[cl].link=st[q].link;
memcpy(st[cl].next,st[q].next,sizeof(st[cl].next));
for( ;p!=-1&&st[p].next[c]==q;p=st[p].link)
st[p].next[c]=cl;
st[now].link=st[q].link=cl;
}
}
last=now;
}
void process(void)
{
for(long i=1;i<=sz;i++)
v[st[i].len].push_back(i);
for(long i=s.size();i>=1;i--)
for(auto x:v[i])
occur[st[x].link]+=occur[x];
}
long dfs(long now)
{
if(dp[now]!=-1)return dp[now];
long cnt=occur[now];
if(now==0)cnt=0;
for(long i=0;i<26;i++)
if(st[now].next[i])
cnt+=dfs(st[now].next[i]);
return dp[now]=cnt;
}
long match(void)
{
cin>>s;
long now=0;
for(long i=0;s[i];i++)
{
long c=s[i]-'a';
if(st[now].next[c]==0)return 0;
now=st[now].next[c];
}
return dp[now];
}
void lex(long k)
{
long now=0;
string ans;
while(true)
{
for(long i=0;i<26;i++)
{
if(st[now].next[i]==0)continue;
long nxt=dp[st[now].next[i]];
if(k<=nxt)
{
ans.push_back(char(i+'a'));
k-=occur[st[now].next[i]];
now=st[now].next[i];
break;
}
else k-=nxt;
}
if(k<=0)break;
}
cout<<ans<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>s;
long l=s.size();
st[0].link=-1;
for(long i=0;s[i];i++)insrt(s[i]-'a');
process();
memset(dp,-1,sizeof(dp));
dfs(0);
cin>>k;
if(k>((l*(l+1))/2))cout<<"No such line."<<endl;
else lex(k);
return 0;
} | 22.478632 | 111 | 0.461597 | [
"vector"
] |
9811b233641e6225ee4b5804f933c414ab87ea0d | 5,555 | cpp | C++ | tests/test_multiple_value.cpp | sara-nl/surfsara-cli-args-cpp | 92db59808e808ae6a629cde240425c7655282ffa | [
"MIT"
] | 1 | 2018-02-01T20:46:46.000Z | 2018-02-01T20:46:46.000Z | tests/test_multiple_value.cpp | sara-nl/surfsara-cli-args-cpp | 92db59808e808ae6a629cde240425c7655282ffa | [
"MIT"
] | 1 | 2018-02-01T21:04:58.000Z | 2018-02-01T21:04:58.000Z | tests/test_multiple_value.cpp | sara-nl/surfsara-cli-args-cpp | 92db59808e808ae6a629cde240425c7655282ffa | [
"MIT"
] | null | null | null | /*****************************************************************************
MIT License
Copyright (c) 2018 stefan-wolfsheimer
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 <catch2/catch.hpp>
#include "cli_multiple_value.h"
#include "cli_positional_multiple_value.h"
using IntMultipleValue = Cli::MultipleValue<int>;
using PositionalMulitipleIntValue = Cli::PositionalMultipleValue<int>;
TEST_CASE("multiple-value-constructor-with-name", "[Value]")
{
std::vector<int> v;
REQUIRE_FALSE(IntMultipleValue::make(v, "name")->isFlag());
REQUIRE(IntMultipleValue::make(v, "name")->getName() == "name");
REQUIRE(IntMultipleValue::make(v, "name")->getShortName() == '\0');
REQUIRE_FALSE(IntMultipleValue::make(v, "name")->isSet());
}
TEST_CASE("multiple-value-constructor-with-short-name", "[Value]")
{
std::vector<int> v;
REQUIRE_FALSE(IntMultipleValue::make(v, 'n')->isFlag());
REQUIRE(IntMultipleValue::make(v, 'n')->getName() == "");
REQUIRE(IntMultipleValue::make(v, 'n')->getShortName() == 'n');
REQUIRE_FALSE(IntMultipleValue::make(v, 'n')->isSet());
}
TEST_CASE("multiple-value-constructor-with-name-and-short-name", "[Value]")
{
std::vector<int> v;
REQUIRE_FALSE(IntMultipleValue::make(v, 'n', "name")->isFlag());
REQUIRE(IntMultipleValue::make(v, 'n', "name")->getName() == "name");
REQUIRE(IntMultipleValue::make(v, 'n', "name")->getShortName() == 'n');
REQUIRE_FALSE(IntMultipleValue::make(v, 'n')->isSet());
}
TEST_CASE("multiple-value-constructor-positional", "[Value]")
{
std::vector<int> v;
REQUIRE_FALSE(PositionalMulitipleIntValue::make(v)->isFlag());
REQUIRE(PositionalMulitipleIntValue::make(v, "ARG")->getName() == "ARG");
REQUIRE(PositionalMulitipleIntValue::make(v)->getShortName() == '\0');
REQUIRE_FALSE(PositionalMulitipleIntValue::make(v)->isSet());
}
TEST_CASE("multiple-value-parse", "[Value]")
{
std::vector<int> v;
auto value = IntMultipleValue::make(v, "name");
int argc;
const char * argv[] = { "progr", "--name", "12" };
std::vector<std::string> err;
int i = 1;
REQUIRE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.empty());
REQUIRE(value->isSet());
REQUIRE(i == 2);
REQUIRE(v == std::vector<int>({12}));
}
TEST_CASE("multiple-value-parse-twice", "[Value]")
{
std::vector<int> v;
auto value = IntMultipleValue::make(v, "name");
int argc;
const char * argv1[] = { "progr", "--name", "12" };
const char * argv2[] = { "progr", "--name", "13" };
std::vector<std::string> err;
int i = 1;
REQUIRE(value->parse(sizeof(argv1)/sizeof(char*), argv1, i, err));
REQUIRE(err.empty());
REQUIRE(value->isSet());
REQUIRE(i == 2);
REQUIRE_FALSE(value->parse(sizeof(argv2)/sizeof(char*), argv2, i, err));
REQUIRE(err.size() == 1u);
REQUIRE(v == std::vector<int>({12}));
REQUIRE(value->valueCast<std::vector<int>>() == std::vector<int>({12}));
REQUIRE_THROWS(value->valueCast<std::string>());
}
TEST_CASE("multiple-value-parse-argument-required", "[Value]")
{
std::vector<int> v;
auto value = IntMultipleValue::make(v, "name");
int argc;
const char * argv[] = { "progr", "--name" };
std::vector<std::string> err;
int i = 1;
REQUIRE_FALSE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.size() == 1u);
REQUIRE_FALSE(value->isSet());
REQUIRE(i == 1);
REQUIRE(v.empty());
}
TEST_CASE("multiple-value-parse-invalid-value", "[Value]")
{
std::vector<int> v;
auto value = IntMultipleValue::make(v, "name");
int argc;
const char * argv[] = { "progr", "--name", "12xx" };
std::vector<std::string> err;
int i = 1;
REQUIRE_FALSE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.size() == 1u);
REQUIRE(value->isSet());
REQUIRE(i == 2);
REQUIRE(v.empty());
}
TEST_CASE("multiple-value-parse-positional", "[Value]")
{
std::vector<int> v;
auto value = PositionalMulitipleIntValue::make(v);
int argc;
const char * argv[] = { "progr", "1", "2", "3" };
std::vector<std::string> err;
int i = 1;
REQUIRE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.empty());
REQUIRE(value->isSet());
REQUIRE(i == 1);
REQUIRE(v == std::vector<int>({1}));
i++;
REQUIRE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.empty());
REQUIRE(value->isSet());
REQUIRE(i == 2);
REQUIRE(v == std::vector<int>({1,2}));
i++;
REQUIRE(value->parse(sizeof(argv)/sizeof(char*), argv, i, err));
REQUIRE(err.empty());
REQUIRE(value->isSet());
REQUIRE(i == 3);
REQUIRE(v == std::vector<int>({1,2,3}));
}
| 34.290123 | 78 | 0.664086 | [
"vector"
] |
981874f5ea50032e0e63b8c7b87ef443a83deb85 | 1,999 | cxx | C++ | test/itkTrackerDirectionPickerImageBaseTest.cxx | bloyl/DiffusionImagingTK | 0516d32b7b0d41ed161134812746ef02aab000de | [
"Apache-2.0"
] | 4 | 2016-01-09T19:02:28.000Z | 2017-07-31T19:41:32.000Z | test/itkTrackerDirectionPickerImageBaseTest.cxx | bloyl/DiffusionImagingTK | 0516d32b7b0d41ed161134812746ef02aab000de | [
"Apache-2.0"
] | null | null | null | test/itkTrackerDirectionPickerImageBaseTest.cxx | bloyl/DiffusionImagingTK | 0516d32b7b0d41ed161134812746ef02aab000de | [
"Apache-2.0"
] | 2 | 2016-08-06T00:58:26.000Z | 2019-02-18T01:03:13.000Z | /*=========================================================================
*
* Copyright Section of Biomedical Image Analysis
* University of Pennsylvania
*
* 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.txt
*
* 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 <itkTestingMacros.h>
#include <itkTrackerDirectionPickerImageBase.h>
#include <itkDiffusionTensor3D.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <limits.h>
#include <cmath>
#include <stdio.h>
#include <vector>
using namespace itk;
int itkTrackerDirectionPickerImageBaseTest( int, char ** )
{
typedef itk::DiffusionTensor3D<double> PixelType;
typedef itk::Image<PixelType,3> ImageType;
typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double>
InterpType;
typedef itk::TrackerDirectionPickerImageBase<InterpType>
PickerType;
PickerType::Pointer picker = PickerType::New();
EXERCISE_BASIC_OBJECT_METHODS( picker, PickerType );
if (picker->IsInitialized())
{
std::cout << "picker is not intialized but returns that it is";
return EXIT_FAILURE;
}
// InterpType::Pointer interp = InterpType::New();
// interp->SetInputImage(gradIm);
// std::cout << "Passed" << std::endl;
return EXIT_SUCCESS;
}
| 29.835821 | 77 | 0.644822 | [
"vector"
] |
981b4fa30cd250f6886b8f382e62c3d3f81a5b82 | 5,992 | cpp | C++ | Tutorial3/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | 1 | 2017-06-19T22:19:30.000Z | 2017-06-19T22:19:30.000Z | Tutorial3/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | 4 | 2017-06-16T23:25:37.000Z | 2017-07-01T01:33:25.000Z | Tutorial3/main.cpp | asm128/gpftw | 984eec9a0cb6047000dda98c03696592406154a8 | [
"MIT"
] | null | null | null | // Tip: Hold Left ALT + SHIFT while tapping or holding the arrow keys in order to select multiple columns and write on them at once.
// Also useful for copy & paste operations in which you need to copy a bunch of variable or function names and you can't afford the time of copying them one by one.
//
#include <stdio.h> // for printf()
#include <windows.h> // for interacting with Windows
#define TILE_GRASS 0 // define some values to represent our terrain tiles. #define is a preprocessor directive that allows to replace the defined identifier with a constant value or text.
#define TILE_WALL 1 // We use it to put some name to the values we're going to use to represent the map tiles.
#define TILE_WATER 2
#define TILE_LAVA 3
#define MAX_MAP_WIDTH 64 // define some constant values for setting a maximum size to our game map
#define MAX_MAP_DEPTH 64
struct SMap // The struct is a block of variables to be used to store our map information.
// We can create instances of a structure whenever we need such variables instead of declaring each variable every time
{ // Here we begin the block of the struct definition.
int Width; // Declare Width and Depth variables which will hold the active map size
short int Depth;
short int FloorCells[MAX_MAP_DEPTH][MAX_MAP_WIDTH]; // 2-Dimensional array of integers which can be accessed as FloorCells[y][x] and will hold values for representing the terrain
}; // struct definitions need to end with a semicolon as with any other statement. This is because declaring a struct can be part of a larger statement.
// ------ We need to declare the functions here so we can use it from main(). However we define then later because we will eventually move them to another file where main() won't have access to.
void setup ( SMap* activeMap ); // Accepts as parameter an address pointing to an SMap
void update ( SMap* activeMap ); // Accepts as parameter an address pointing to an SMap
void draw ( SMap someMap ); // Accepts as parameter a copy of the contents of an SMap
int main () {
// The program starts from here
SMap gameMap; // declare a variable of type SMap. This is almost the same as defining each variable of SMap but shorter, and we can acess to the members with a dot, as in gameMap.Width or gameMap.FloorCells[z][x]
setup( &gameMap ); // call setup() and send the address of our gameMap as parameter
int frameCounter = 0; // declare a variable for keeping track of the number of frame since execution began, where "int" stands for "integer"
while( true ) { // execute code block {} while the condition that's inside parenthesis () is true
printf("Current frame number: %i\n", frameCounter);
update ( &gameMap ); // update frame, send map address to update() call
draw ( gameMap ); // render frame, send copy of the data to be displayed by draw()
if(GetAsyncKeyState(VK_ESCAPE)) // check for escape key pressed
break; // exit while(). If the code that executes when the if() evaluates to true doesn't have braces, then the block that executes when the condition evaluates to true ends in the next semicolon (;). The same applies for "for()" and "while()".
Sleep(50); // Wait some time to give visual stability to the frame (printf() is really ugly for displaying realtime games but for now it will do fine enough).
frameCounter = frameCounter + 1; // Increment our frame counter
}
return 0; // return an int
}
void setup ( SMap* activeMap ) { // Accepts an address pointing to an SMap
printf("- setup() called.\n");
activeMap->Width = 32; // Set a proper width for our map, which has to be less than MAX_MAP_WIDTH
activeMap->Depth = 21; // Same for map depth
// The "for" statement allows us to iterate over the indices or cells of our map. The syntax of a for() statement is something as follows:
//
// for( [initial statement]; [conditionToContinueIterating]; [statement to execute after each iteration] )
// {
// [your statements];
// }
for( int z = 0; z < activeMap->Depth; z = z + 1 ) { // iterate over every row. This loop ends when z is equal to the map depth. At the end of each iteration, z is incremented by one.
for( int x = 0; x < activeMap->Width; x++ ) { // iterate over every column for the x row. This loop ends when x is equal to the map width
activeMap->FloorCells[z][x] = TILE_GRASS; // initialize the (x,z) map cell to "grass"
}
}
// set a wall border
for( int x = 0; x < activeMap->Width; ++x ) {
activeMap->FloorCells[0][x] = TILE_WALL; // set all cells in the first row [0]
activeMap->FloorCells[activeMap->Depth - 1][x] = TILE_WALL; // set all cells in the last row [depth-1]
}
for( int z = 0; z < activeMap->Depth; ++z ) {
activeMap->FloorCells[z][0] = TILE_WALL; // set all cells in the first column [0]
activeMap->FloorCells[z][activeMap->Width - 1] = TILE_WALL; // set all cells in the last column [width-1]
}
}
// Currently our update() function still does nothing.
void update ( SMap* activeMap ) { (void)activeMap; printf("- update() called.\n"); } // Accepts an address pointing to an SMap
// The draw() function will display our generated map in the console screen.
void draw ( SMap someMap ) // Accepts a copy of the contents of an SMap
{
printf("- draw() called.\n");
for( int z=0; z< someMap.Depth; z++ ) // iterate over every row
{
for( int x=0; x< someMap.Width; x++ ) // iterate over every column for the z row
printf( "%c", someMap.FloorCells[z][x] ); // draw the contents of the cell at (x,z) as an ascii character
printf( "\n" ); // \n is the code character for "new line" inside a text. We use it to display the next cells in the next row of the console screen.
}
}
| 61.142857 | 247 | 0.676736 | [
"render"
] |
982724fe249deb94684e864ab31cf818459bd597 | 16,669 | cpp | C++ | source/lib/PccLibMetrics/source/PCCMetrics.cpp | giterator/mpeg-pcc-tmc2 | 4262af3b405e69f3823eedbd6ebb70d81c5f502a | [
"BSD-3-Clause"
] | 80 | 2019-07-02T22:05:26.000Z | 2022-03-29T12:46:31.000Z | source/lib/PccLibMetrics/source/PCCMetrics.cpp | ricardjidcc/mpeg-pcc-tmc2 | 588abd7750d24057f2ce8b1088cc92868a39bc16 | [
"BSD-3-Clause"
] | null | null | null | source/lib/PccLibMetrics/source/PCCMetrics.cpp | ricardjidcc/mpeg-pcc-tmc2 | 588abd7750d24057f2ce8b1088cc92868a39bc16 | [
"BSD-3-Clause"
] | 34 | 2019-07-18T11:58:14.000Z | 2022-03-18T06:47:48.000Z | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2017, ISO/IEC
* 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 ISO/IEC 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 "PCCCommon.h"
#include "PCCGroupOfFrames.h"
#include "PCCPointSet.h"
#include "PCCKdTree.h"
#include <tbb/tbb.h>
#include "PCCMetrics.h"
using namespace std;
using namespace pcc;
float getPSNR( float dist, float p, float factor = 1.0 ) {
float max_energy = p * p;
float psnr = 10 * log10( ( factor * max_energy ) / dist );
return psnr;
}
void convertRGBtoYUVBT709( const PCCColor3B& rgb, std::vector<float>& yuv ) {
yuv.resize( 3 );
yuv[0] = float( ( 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2] ) / 255.0 );
yuv[1] = float( ( -0.1146 * rgb[0] - 0.3854 * rgb[1] + 0.5000 * rgb[2] ) / 255.0 + 0.5000 );
yuv[2] = float( ( 0.5000 * rgb[0] - 0.4542 * rgb[1] - 0.0458 * rgb[2] ) / 255.0 + 0.5000 );
}
QualityMetrics::QualityMetrics() :
c2cMse_( 0.0F ),
c2cHausdorff_( 0.0F ),
c2cPsnr_( 0.0F ),
c2cHausdorffPsnr_( 0.0F ),
c2pMse_( 0.0F ),
c2pHausdorff_( 0.0F ),
c2pPsnr_( 0.0F ),
c2pHausdorffPsnr_( 0.0F ),
psnr_( 0.0F ),
reflectanceMse_( 0.0F ),
reflectancePsnr_( 0.0F ) {
colorMse_[0] = colorMse_[0] = colorMse_[0] = 0.0F;
colorPsnr_[0] = colorPsnr_[0] = colorPsnr_[0] = 0.0F;
}
void QualityMetrics::setParameters( const PCCMetricsParameters& params ) { params_ = params; }
void QualityMetrics::compute( const PCCPointSet3& pointcloudA, const PCCPointSet3& pointcloudB ) {
double maxC2c = ( std::numeric_limits<double>::min )();
double maxC2p = ( std::numeric_limits<double>::min )();
double sseC2p = 0;
double sseC2c = 0;
double sseReflectance = 0;
size_t num = 0;
double sseColor[3] = {0.0, 0.0, 0.0};
psnr_ = params_.resolution_;
PCCKdTree kdtree( pointcloudB );
PCCNNResult result;
const size_t num_results_max = 30;
const size_t num_results_incr = 5;
auto& normalsB = pointcloudB.getNormals();
for ( size_t indexA = 0; indexA < pointcloudA.getPointCount(); indexA++ ) {
// For point 'i' in A, find its nearest neighbor in B. store it in 'j'
size_t num_results = 0;
do {
num_results += num_results_incr;
kdtree.search( pointcloudA[indexA], num_results, result );
} while ( result.dist( 0 ) == result.dist( num_results - 1 ) && num_results + num_results_incr <= num_results_max );
// Compute point-to-point, which should be equal to sqrt( dist[0] )
double distProjC2c = result.dist( 0 );
// Build the list of all the points of same distances.
std::vector<size_t> sameDistList;
if ( params_.computeColor_ || params_.computeC2p_ ) {
for ( size_t j = 0; j < num_results && ( fabs( result.dist( 0 ) - result.dist( j ) ) < 1e-8 ); j++ ) {
sameDistList.push_back( result.indices( j ) );
}
}
std::sort( sameDistList.begin(), sameDistList.end() );
// Compute point-to-plane, normals in B will be used for point-to-plane
double distProjC2p = 0.0;
if ( params_.computeC2p_ && pointcloudB.hasNormals() && pointcloudA.hasNormals() ) {
for ( auto& indexB : sameDistList ) {
std::vector<double> errVector( 3 );
for ( size_t j = 0; j < 3; j++ ) { errVector[j] = pointcloudA[indexA][j] - pointcloudB[indexB][j]; }
double dist = pow( errVector[0] * normalsB[indexB][0] + errVector[1] * normalsB[indexB][1] +
errVector[2] * normalsB[indexB][2],
2.F );
distProjC2p += dist;
}
distProjC2p /= sameDistList.size();
}
size_t indexB = result.indices( 0 );
double distColor[3];
distColor[0] = distColor[1] = distColor[2] = 0.0;
if ( params_.computeColor_ && pointcloudA.hasColors() && pointcloudB.hasColors() ) {
std::vector<float> yuvA;
std::vector<float> yuvB;
PCCColor3B rgb;
convertRGBtoYUVBT709( pointcloudA.getColor( indexA ), yuvA );
if ( params_.neighborsProc_ != 0 ) {
switch ( params_.neighborsProc_ ) {
case 0: break;
case 1: // Average
case 2: // Weighted average
{
int nbdupcumul = 0;
unsigned int r = 0;
unsigned int g = 0;
unsigned int b = 0;
for ( unsigned long long i : sameDistList ) {
int nbdup = 1; // pointcloudB.xyz.nbdup[ indices_sameDst[n] ];
r += nbdup * pointcloudB.getColor( i )[0];
g += nbdup * pointcloudB.getColor( i )[1];
b += nbdup * pointcloudB.getColor( i )[2];
nbdupcumul += nbdup;
}
rgb[0] = static_cast<unsigned char>( round( static_cast<double>( r ) / nbdupcumul ) );
rgb[1] = static_cast<unsigned char>( round( static_cast<double>( g ) / nbdupcumul ) );
rgb[2] = static_cast<unsigned char>( round( static_cast<double>( b ) / nbdupcumul ) );
convertRGBtoYUVBT709( rgb, yuvB );
for ( size_t i = 0; i < 3; i++ ) { distColor[i] = pow( yuvA[i] - yuvB[i], 2.F ); }
} break;
case 3: // Min
case 4: // Max
{
float distBest = 0;
size_t indexBest = 0;
for ( auto index : sameDistList ) {
convertRGBtoYUVBT709( pointcloudB.getColor( index ), yuvB );
float dist =
pow( yuvA[0] - yuvB[0], 2.F ) + pow( yuvA[1] - yuvB[1], 2.F ) + pow( yuvA[2] - yuvB[2], 2.F );
if ( ( ( params_.neighborsProc_ == 3 ) && ( dist < distBest ) ) ||
( ( params_.neighborsProc_ == 4 ) && ( dist > distBest ) ) ) {
distBest = dist;
indexBest = index;
}
}
convertRGBtoYUVBT709( pointcloudB.getColor( indexBest ), yuvB );
} break;
}
} else {
convertRGBtoYUVBT709( pointcloudB.getColor( indexB ), yuvB );
}
for ( size_t i = 0; i < 3; i++ ) { distColor[i] = pow( yuvA[i] - yuvB[i], 2.F ); }
}
double distReflectance = 0.0;
if ( params_.computeReflectance_ && pointcloudA.hasReflectances() && pointcloudB.hasReflectances() ) {
distReflectance = pow( pointcloudA.getReflectance( indexA ) - pointcloudB.getReflectance( indexB ), 2.F );
}
num++;
// mean square distance
if ( params_.computeC2c_ ) {
sseC2c += distProjC2c;
if ( distProjC2c > maxC2c ) { maxC2c = distProjC2c; }
}
if ( params_.computeC2p_ ) {
sseC2p += distProjC2p;
if ( distProjC2p > maxC2p ) { maxC2p = distProjC2p; }
}
if ( params_.computeColor_ ) {
for ( size_t i = 0; i < 3; i++ ) { sseColor[i] += distColor[i]; }
}
if ( params_.computeReflectance_ && pointcloudA.hasReflectances() && pointcloudB.hasReflectances() ) {
sseReflectance += distReflectance;
}
}
if ( params_.computeC2c_ ) {
c2cMse_ = float( sseC2c / num );
c2cPsnr_ = getPSNR( c2cMse_, psnr_, 3 );
if ( params_.computeHausdorff_ ) {
c2cHausdorff_ = float( maxC2c );
c2cHausdorffPsnr_ = getPSNR( c2cHausdorff_, psnr_, 3 );
}
}
if ( params_.computeC2p_ ) {
c2pMse_ = float( sseC2p / num );
c2pPsnr_ = getPSNR( c2pMse_, psnr_, 3 );
if ( params_.computeHausdorff_ ) {
c2pHausdorff_ = float( maxC2p );
c2pHausdorffPsnr_ = getPSNR( c2pHausdorff_, psnr_, 3 );
}
}
if ( params_.computeColor_ ) {
for ( size_t i = 0; i < 3; i++ ) {
colorMse_[i] = float( sseColor[i] / num );
colorPsnr_[i] = getPSNR( colorMse_[i], 1.0 );
}
}
if ( params_.computeLidar_ ) {
reflectanceMse_ = float( sseReflectance / num );
reflectancePsnr_ = getPSNR( float( reflectanceMse_ ), float( ( std::numeric_limits<unsigned short>::max )() ) );
}
}
void QualityMetrics::print( char code ) {
switch ( code ) {
case '1':
std::cout << "1. Use infile1 (A) as reference, loop over A, use normals "
"on B. (A->B)."
<< std::endl;
break;
case '2':
std::cout << "2. Use infile2 (B) as reference, loop over B, use normals "
"on A. (B->A)."
<< std::endl;
break;
case 'F': std::cout << "3. Final (symmetric)." << std::endl; break;
default:
std::cout << "Mode not supported. " << std::endl;
exit( -1 );
break;
}
if ( params_.computeC2c_ ) {
std::cout << " mse" << code << " (p2point): " << c2cMse_ << std::endl;
std::cout << " mse" << code << ",PSNR (p2point): " << c2cPsnr_ << std::endl;
}
if ( params_.computeC2p_ ) {
std::cout << " mse" << code << " (p2plane): " << c2pMse_ << std::endl;
std::cout << " mse" << code << ",PSNR (p2plane): " << c2pPsnr_ << std::endl;
}
if ( params_.computeHausdorff_ ) {
if ( params_.computeC2c_ ) {
std::cout << " h. " << code << "(p2point): " << c2cHausdorff_ << std::endl;
std::cout << " h.,PSNR " << code << "(p2point): " << c2cHausdorffPsnr_ << std::endl;
}
if ( params_.computeC2p_ ) {
std::cout << " h. " << code << "(p2plane): " << c2cHausdorff_ << std::endl;
std::cout << " h.,PSNR " << code << "(p2plane): " << c2cHausdorffPsnr_ << std::endl;
}
}
if ( params_.computeColor_ ) {
for ( size_t i = 0; i < 3; i++ ) {
std::cout << " c[" << i << "], " << code << " : " << colorMse_[i] << std::endl;
}
for ( size_t i = 0; i < 3; i++ ) {
std::cout << " c[" << i << "],PSNR" << code << " : " << colorPsnr_[i] << std::endl;
}
}
if ( params_.computeReflectance_ ) {
std::cout << " r, " << code << " : " << reflectanceMse_ << std::endl;
std::cout << " r,PSNR " << code << " : " << reflectancePsnr_ << std::endl;
}
}
PCCMetrics::PCCMetrics() :
sourcePoints_( 0 ),
sourceDuplicates_( 0 ),
reconstructPoints_( 0 ),
reconstructDuplicates_( 0 ) {}
PCCMetrics::~PCCMetrics() = default;
void PCCMetrics::setParameters( const PCCMetricsParameters& params ) { params_ = params; }
QualityMetrics QualityMetrics::operator+( const QualityMetrics& metric ) const {
QualityMetrics result;
// Derive the final symmetric metric
if ( params_.computeC2c_ ) {
result.c2cMse_ = ( std::max )( c2cMse_, metric.c2cMse_ );
result.c2cPsnr_ = ( std::min )( c2cPsnr_, metric.c2cPsnr_ );
}
if ( params_.computeC2p_ ) {
result.c2pMse_ = ( std::max )( c2pMse_, metric.c2pMse_ );
result.c2pPsnr_ = ( std::min )( c2pPsnr_, metric.c2pPsnr_ );
}
if ( params_.computeHausdorff_ ) {
if ( params_.computeC2c_ ) {
result.c2cHausdorff_ = ( std::max )( c2cHausdorff_, metric.c2cHausdorff_ );
result.c2cHausdorffPsnr_ = ( std::min )( c2cHausdorffPsnr_, metric.c2cHausdorffPsnr_ );
}
if ( params_.computeC2p_ ) {
result.c2pHausdorff_ = ( std::max )( c2pHausdorff_, metric.c2pHausdorff_ );
result.c2pHausdorffPsnr_ = ( std::min )( c2pHausdorffPsnr_, metric.c2pHausdorffPsnr_ );
}
}
if ( params_.computeColor_ ) {
for ( size_t i = 0; i < 3; i++ ) {
result.colorMse_[i] = ( std::max )( colorMse_[i], metric.colorMse_[i] );
result.colorPsnr_[i] = ( std::min )( colorPsnr_[i], metric.colorPsnr_[i] );
}
}
if ( params_.computeReflectance_ ) {
result.reflectanceMse_ = ( std::max )( reflectanceMse_, metric.reflectanceMse_ );
result.reflectancePsnr_ = ( std::min )( reflectancePsnr_, metric.reflectancePsnr_ );
}
return result;
}
void PCCMetrics::compute( const PCCGroupOfFrames& sources,
const PCCGroupOfFrames& reconstructs,
const PCCGroupOfFrames& normals ) {
PCCPointSet3 normalEmpty;
if ( normals.getFrameCount() != 0 && sources.getFrameCount() != normals.getFrameCount() ) {
params_.computeC2p_ = false;
}
if ( ( sources.getFrameCount() != reconstructs.getFrameCount() ) ) {
printf(
"Error: group of frames must have same numbers of frames. ( src = %zu "
"rec = %zu norm = %zu ) \n",
sources.getFrameCount(), reconstructs.getFrameCount(), normals.getFrameCount() );
exit( -1 );
}
for ( size_t i = 0; i < sources.getFrameCount(); i++ ) {
const PCCPointSet3& sourceOrg = sources[i];
const PCCPointSet3& reconstructOrg = reconstructs[i];
sourcePoints_.push_back( sourceOrg.getPointCount() );
reconstructPoints_.push_back( reconstructOrg.getPointCount() );
PCCPointSet3 source;
PCCPointSet3 reconstruct;
if ( params_.dropDuplicates_ != 0 ) {
sourceOrg.removeDuplicate( source, params_.dropDuplicates_ );
reconstructOrg.removeDuplicate( reconstruct, params_.dropDuplicates_ );
sourceDuplicates_.push_back( source.getPointCount() );
reconstructDuplicates_.push_back( reconstruct.getPointCount() );
compute( source, reconstruct, normals.getFrameCount() == 0 ? normalEmpty : normals[i] );
} else {
source = sourceOrg;
reconstruct = reconstructOrg;
sourceDuplicates_.push_back( 0 );
reconstructDuplicates_.push_back( 0 );
compute( source, reconstruct, normals.getFrameCount() == 0 ? normalEmpty : normals[i] );
}
}
}
void PCCMetrics::compute( PCCPointSet3& source, PCCPointSet3& reconstruct, const PCCPointSet3& normalSource ) {
if ( normalSource.getPointCount() > 0 ) {
source.copyNormals( normalSource );
reconstruct.scaleNormals( normalSource );
}
QualityMetrics q1;
QualityMetrics q2;
q1.setParameters( params_ );
q1.compute( source, reconstruct );
q2.setParameters( params_ );
q2.compute( reconstruct, source );
quality1_.push_back( q1 );
quality2_.push_back( q2 );
qualityF_.push_back( q1 + q2 );
}
void PCCMetrics::display() {
printf( "Metrics results \n" );
for ( size_t i = 0; i < qualityF_.size(); i++ ) {
printf( "WARNING: %zu points with same coordinates found\n", reconstructPoints_[i] - reconstructDuplicates_[i] );
std::cout << "Imported intrinsic resoluiton: " << params_.resolution_ << std::endl;
std::cout << "Peak distance for PSNR: " << params_.resolution_ << std::endl;
std::cout << "Point cloud sizes for org version, dec version, and the scaling ratio: " << sourcePoints_[i] << ", "
<< reconstructDuplicates_[i] << ", "
<< static_cast<float>( reconstructDuplicates_[i] ) / static_cast<float>( sourcePoints_[i] ) << std::endl;
quality1_[i].print( '1' );
quality2_[i].print( '2' );
qualityF_[i].print( 'F' );
}
}
| 42.414758 | 121 | 0.590857 | [
"vector"
] |
982e23462f2d963e5f1d4f7277ddd3579a1b6d10 | 29,160 | cpp | C++ | src-qt5/desktop-utils/lumina-mediaplayer/mainUI.cpp | orangecms/lumina-desktop | 603e57e5d0a473ea7f51bf4cf274bebe512ac159 | [
"BSD-3-Clause"
] | null | null | null | src-qt5/desktop-utils/lumina-mediaplayer/mainUI.cpp | orangecms/lumina-desktop | 603e57e5d0a473ea7f51bf4cf274bebe512ac159 | [
"BSD-3-Clause"
] | null | null | null | src-qt5/desktop-utils/lumina-mediaplayer/mainUI.cpp | orangecms/lumina-desktop | 603e57e5d0a473ea7f51bf4cf274bebe512ac159 | [
"BSD-3-Clause"
] | null | null | null | //===========================================
// Lumina-Desktop source code
// Copyright (c) 2017, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "mainUI.h"
#include "ui_mainUI.h"
#include <QDebug>
#include <LuminaXDG.h>
#include <LUtils.h>
#include <QDesktopServices>
#include <QUrl>
#include <QInputDialog>
#include <QFileDialog>
#include <QMessageBox>
//#include "VideoWidget.h"
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI()){
ui->setupUi(this);
SETTINGS = LUtils::openSettings("lumina-desktop","lumina-mediaplayer",this);
closing = false;
DISABLE_VIDEO = false; //add a toggle in the UI for this later
//Any special UI changes
QWidget *spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
ui->toolBar->insertWidget(ui->radio_local, spacer);
//Setup an action group for the various modes/streams
QActionGroup *grp = new QActionGroup(this);
grp->addAction(ui->radio_local);
grp->addAction(ui->radio_pandora);
grp->setExclusive(true);
//Load the previously-saved user settings
ui->action_closeToTray->setChecked( SETTINGS->value("CloseToTrayWhenActive",true).toBool() );
ui->action_showNotifications->setChecked( SETTINGS->value("ShowNotifications",true).toBool() );
ui->radio_local->setChecked(true); //default
setupPlayer();
setupPandora();
setupTrayIcon();
setupConnections();
setupIcons();
PlayerTypeChanged();
SYSTRAY->show();
checkPandoraSettings();
}
MainUI::~MainUI(){
}
void MainUI::loadArguments(QStringList args){
//Parse out the arguments
for(int i=0; i<args.length(); i++){
if(args.startsWith("--")){ continue; } //skip this one - not a file to try loading
loadFile(args[i]);
}
//
if( (PLAYLIST->mediaCount() <=0 || args.contains("--pandora")) && ui->radio_pandora->isEnabled()){
ui->radio_pandora->toggle();
}
}
// ==== PRIVATE ====
void MainUI::setupPlayer(){
PLAYER = new QMediaPlayer(this); //base multimedia object
VIDEO = new QVideoWidget(this); //output to this widget for video
PLAYLIST = new QMediaPlaylist(PLAYER); //pull from this playlist
ui->videoLayout->addWidget(VIDEO);
//Now setup the interfaces between all these objects
if(!DISABLE_VIDEO){ PLAYER->setVideoOutput(VIDEO); }
PLAYER->setPlaylist(PLAYLIST);
PLAYER->setVolume(100); //just maximize this - will be managed outside this app
//Setup the player connections
//connect(PLAYER, SIGNAL(audioAvailableChanged(bool)), this, SLOT(LocalAudioAvailable(bool)) );
connect(PLAYER, SIGNAL(currentMediaChanged(const QMediaContent&)), this, SLOT(LocalMediaChanged(const QMediaContent&)) );
connect(PLAYER, SIGNAL(durationChanged(qint64)), this, SLOT(LocalDurationChanged(qint64)) );
connect(PLAYER, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(LocalError(QMediaPlayer::Error)) );
connect(PLAYER, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), this, SLOT(LocalMediaStatusChanged(QMediaPlayer::MediaStatus)) );
connect(PLAYER, SIGNAL(mutedChanged(bool)), this, SLOT(LocalNowMuted(bool)) );
connect(PLAYER, SIGNAL(positionChanged(qint64)), this, SLOT(LocalPositionChanged(qint64)) );
connect(PLAYER, SIGNAL(seekableChanged(bool)), this, SLOT(LocalIsSeekable(bool)) );
connect(PLAYER, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(LocalStateChanged(QMediaPlayer::State)) );
connect(PLAYER, SIGNAL(videoAvailableChanged(bool)), this, SLOT(LocalVideoAvailable(bool)) );
connect(PLAYER, SIGNAL(volumeChanged(int)), this, SLOT(LocalVolumeChanged(int)) );
//Setup the playlist connections
connect(PLAYLIST, SIGNAL(currentIndexChanged(int)), this, SLOT(LocalListIndexChanged(int)) );
connect(PLAYLIST, SIGNAL(mediaChanged(int,int)), this, SLOT(LocalListMediaChanged(int,int)) );
connect(PLAYLIST, SIGNAL(mediaInserted(int,int)), this, SLOT(LocalListMediaInserted(int,int)) );
connect(PLAYLIST, SIGNAL(mediaRemoved(int,int)), this, SLOT(LocalListMediaRemoved(int,int)) );
}
void MainUI::setupPandora(){
PANDORA = new PianoBarProcess(this);
if(!LUtils::isValidBinary("pianobar")){
ui->radio_pandora->setEnabled(false);
ui->radio_local->setChecked(true);
ui->radio_pandora->setToolTip(tr("Please install the `pianobar` utility to enable this functionality"));
ui->radio_pandora->setStatusTip(ui->radio_pandora->toolTip());
return;
}
ui->radio_pandora->setToolTip(tr("Stream music from the Pandora online radio service"));
ui->radio_pandora->setStatusTip(ui->radio_pandora->toolTip());
connect(PANDORA, SIGNAL(currentStateChanged(PianoBarProcess::State)), this, SLOT(PandoraStateChanged(PianoBarProcess::State)) );
connect(PANDORA, SIGNAL(NewInformation(QString)), this, SLOT(NewPandoraInfo(QString)) );
connect(PANDORA, SIGNAL(NowPlayingStation(QString, QString)), this, SLOT(PandoraStationChanged(QString)) );
connect(PANDORA, SIGNAL(NowPlayingSong(bool, QString,QString,QString, QString, QString)), this, SLOT(PandoraSongChanged(bool, QString, QString, QString, QString, QString)) );
connect(PANDORA, SIGNAL(TimeUpdate(int, int)), this, SLOT(PandoraTimeUpdate(int,int)) );
connect(PANDORA, SIGNAL(NewQuestion(QString, QStringList)), this, SLOT(PandoraInteractivePrompt(QString, QStringList)) );
connect(PANDORA, SIGNAL(StationListChanged(QStringList)), this, SLOT(PandoraStationListChanged(QStringList)) );
connect(PANDORA, SIGNAL(showError(QString)), this, SLOT(PandoraError(QString)) );
//Setup a couple of the option lists
ui->combo_pandora_quality->clear();
ui->combo_pandora_quality->addItem(tr("Low"),"low");
ui->combo_pandora_quality->addItem(tr("Medium"), "medium");
ui->combo_pandora_quality->addItem(tr("High"),"high");
ui->combo_pandora_driver->clear();
ui->combo_pandora_driver->addItems( PANDORA->availableAudioDrivers() );
//Now load the current settings into the UI
int qual = ui->combo_pandora_quality->findData(PANDORA->audioQuality());
if(qual>=0){ ui->combo_pandora_quality->setCurrentIndex(qual); }
else{ ui->combo_pandora_quality->setCurrentIndex(1); } //medium quality by default
qual = ui->combo_pandora_driver->findText(PANDORA->currentAudioDriver());
if(qual>=0){ ui->combo_pandora_driver->setCurrentIndex(qual); }
else{ ui->combo_pandora_driver->setCurrentIndex(0); } //automatic (always first in list)
ui->line_pandora_email->setText( PANDORA->email() );
ui->line_pandora_pass->setText( PANDORA->password() );
ui->line_pandora_proxy->setText( PANDORA->proxy() );
ui->line_pandora_cproxy->setText( PANDORA->controlProxy() );
//Make sure the interface is enabled/disabled as needed
PandoraStateChanged(PANDORA->currentState());
ui->progress_pandora->setRange(0,1);
ui->progress_pandora->setValue(0);
//Setup the menu for new stations
QMenu *tmp = new QMenu(this);
tmp->addAction(ui->action_pandora_newstation_song);
tmp->addAction(ui->action_pandora_newstation_artist);
tmp->addSeparator();
tmp->addAction(ui->action_pandora_newstation_search);
ui->tool_pandora_stationadd->setMenu( tmp );
}
void MainUI::setupConnections(){
connect(ui->radio_local, SIGNAL(toggled(bool)), this, SLOT(PlayerTypeChanged(bool)) );
connect(ui->radio_pandora, SIGNAL(toggled(bool)), this, SLOT(PlayerTypeChanged(bool)) );
connect(ui->action_closeToTray, SIGNAL(toggled(bool)), this, SLOT(PlayerSettingsChanged()) );
connect(ui->action_showNotifications, SIGNAL(toggled(bool)), this, SLOT(PlayerSettingsChanged()) );
connect(ui->actionPlay, SIGNAL(triggered()), this, SLOT(playToggled()) );
connect(ui->actionPause, SIGNAL(triggered()), this, SLOT(pauseToggled()) );
connect(ui->actionStop, SIGNAL(triggered()), this, SLOT(stopToggled()) );
connect(ui->actionNext, SIGNAL(triggered()), this, SLOT(nextToggled()) );
connect(ui->actionBack, SIGNAL(triggered()), this, SLOT(backToggled()) );
connect(ui->actionVolUp, SIGNAL(triggered()), this, SLOT(volupToggled()) );
connect(ui->actionVolDown, SIGNAL(triggered()), this, SLOT(voldownToggled()) );
connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(closeApplication()) );
connect(ui->slider_local, SIGNAL(sliderMoved(int)), this, SLOT(setLocalPosition(int)) );
connect(ui->tool_local_addFiles, SIGNAL(clicked()), this, SLOT(addLocalMedia()) );
connect(ui->tool_local_rm, SIGNAL(clicked()), this, SLOT(rmLocalMedia()) );
connect(ui->tool_local_shuffle, SIGNAL(clicked()), PLAYLIST, SLOT(shuffle()) );
connect(ui->tool_local_repeat, SIGNAL(toggled(bool)), this, SLOT(localPlaybackSettingsChanged()) );
connect(ui->tool_local_moveup, SIGNAL(clicked()), this, SLOT(upLocalMedia()) );
connect(ui->tool_local_movedown, SIGNAL(clicked()), this, SLOT(downLocalMedia()) );
connect(ui->push_pandora_apply, SIGNAL(clicked()), this, SLOT(applyPandoraSettings()) );
connect(ui->combo_pandora_station, SIGNAL(activated(QString)), this, SLOT(changePandoraStation(QString)) );
connect(ui->combo_pandora_driver, SIGNAL(activated(QString)), this, SLOT(checkPandoraSettings()) );
connect(ui->tool_pandora_ban, SIGNAL(clicked()), PANDORA, SLOT(banSong()) );
connect(ui->tool_pandora_love, SIGNAL(clicked()), PANDORA, SLOT(loveSong()) );
connect(ui->tool_pandora_tired, SIGNAL(clicked()), PANDORA, SLOT(tiredSong()) );
connect(ui->tool_pandora_info, SIGNAL(clicked()), this, SLOT(showPandoraSongInfo()) );
connect(ui->tool_pandora_stationrm, SIGNAL(clicked()), PANDORA, SLOT(deleteCurrentStation()) );
connect(ui->action_pandora_newstation_artist, SIGNAL(triggered()), PANDORA, SLOT(createStationFromCurrentArtist()) );
connect(ui->action_pandora_newstation_song, SIGNAL(triggered()), PANDORA, SLOT(createStationFromCurrentSong()) );
connect(ui->action_pandora_newstation_search, SIGNAL(triggered()), this, SLOT(createPandoraStation()) );
connect(ui->line_pandora_email, SIGNAL(textChanged(QString)), this, SLOT(checkPandoraSettings()) );
connect(ui->line_pandora_pass, SIGNAL(textChanged(QString)), this, SLOT(checkPandoraSettings()) );
connect(ui->line_pandora_proxy, SIGNAL(textChanged(QString)), this, SLOT(checkPandoraSettings()) );
connect(ui->line_pandora_cproxy, SIGNAL(textChanged(QString)), this, SLOT(checkPandoraSettings()) );
connect(ui->combo_pandora_quality, SIGNAL(currentIndexChanged(int)), this, SLOT(checkPandoraSettings()) );
connect(SYSTRAY, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayClicked(QSystemTrayIcon::ActivationReason)) );
connect(SYSTRAY, SIGNAL(messageClicked()), this, SLOT(trayMessageClicked()) );
}
void MainUI::setupIcons(){
ui->radio_local->setIcon( LXDG::findIcon("media-playlist-audio","audio-x-generic") );
ui->radio_pandora->setIcon( LXDG::findIcon("pandora",":pandora") );
ui->actionClose->setIcon( LXDG::findIcon("application-close","dialog-close") );
ui->actionPlay->setIcon( LXDG::findIcon("media-playback-start","") );
ui->actionPause->setIcon( LXDG::findIcon("media-playback-pause","") );
ui->actionStop->setIcon( LXDG::findIcon("media-playback-stop","") );
ui->actionNext->setIcon( LXDG::findIcon("media-skip-forward","") );
ui->actionBack->setIcon( LXDG::findIcon("media-skip-backward","") );
ui->actionVolUp->setIcon( LXDG::findIcon("audio-volume-high","") );
ui->actionVolDown->setIcon( LXDG::findIcon("audio-volume-low","") );
//Local Player Pages
ui->tool_local_addFiles->setIcon( LXDG::findIcon("list-add","") );
ui->tool_local_rm->setIcon( LXDG::findIcon("list-remove","") );
ui->tool_local_shuffle->setIcon( LXDG::findIcon("media-playlist-shuffle","") );
ui->tool_local_repeat->setIcon( LXDG::findIcon("media-playlist-repeat","") );
ui->tool_local_moveup->setIcon( LXDG::findIcon("go-up", "arrow-up") );
ui->tool_local_movedown->setIcon( LXDG::findIcon("go-down", "arrow-down") );
//Pandora Pages
ui->push_pandora_apply->setIcon( LXDG::findIcon("dialog-ok-apply","dialog-ok") );
ui->tool_pandora_ban->setIcon( LXDG::findIcon("dialog-warning","") );
ui->tool_pandora_info->setIcon( LXDG::findIcon("dialog-information","") );
ui->tool_pandora_love->setIcon( LXDG::findIcon("emblem-favorite","") );
ui->tool_pandora_tired->setIcon( LXDG::findIcon("media-playlist-close","flag") );
ui->tool_pandora_stationrm->setIcon( LXDG::findIcon("list-remove","") );
ui->tool_pandora_stationadd->setIcon( LXDG::findIcon("list-add","") );
ui->action_pandora_newstation_artist->setIcon( LXDG::findIcon("preferences-desktop-user","") );
ui->action_pandora_newstation_song->setIcon( LXDG::findIcon("bookmark-audio","media-playlist-audio") );
ui->action_pandora_newstation_search->setIcon( LXDG::findIcon("edit-find", "document-find") );
}
void MainUI::setupTrayIcon(){
SYSTRAY = new QSystemTrayIcon(this);
QMenu *tmp = new QMenu(this);
SYSTRAY->setContextMenu(tmp);
tmp->addAction(ui->actionPlay);
tmp->addAction(ui->actionPause);
tmp->addAction(ui->actionStop);
tmp->addAction(ui->actionBack);
tmp->addAction(ui->actionNext);
tmp->addSeparator();
tmp->addAction(ui->actionClose);
}
void MainUI::closeTrayIcon(){
}
void MainUI::loadFile(QString file){
//See if the file is a known playlist first
//Load the file as-is
PLAYLIST->addMedia( QUrl::fromLocalFile(file));
}
// ==== PRIVATE SLOTS ====
void MainUI::closeApplication(){
closing = true;
if(PANDORA->currentState()!= PianoBarProcess::Stopped){
PANDORA->closePianoBar();
this->hide();
QTimer::singleShot(500, this, SLOT(close()) );
}else{
this->close();
}
}
void MainUI::PlayerTypeChanged(bool active){
if(!active){ return; } //this gets rid of the "extra" signals from the radio button functionality (1 signal from each button on change)
if(ui->radio_pandora->isChecked()){
ui->stackedWidget->setCurrentWidget(ui->page_pandora);
PandoraStateChanged(PANDORA->currentState());
QIcon ico = LXDG::findIcon("pandora",":pandora");
SYSTRAY->setIcon( ico );
this->setWindowIcon( ico );
this->setWindowTitle( tr("Pandora Radio") );
//Now hide/deactivate any toolbar buttons which are not used
ui->actionBack->setVisible(!ui->radio_pandora->isChecked());
}else{
ui->stackedWidget->setCurrentWidget(ui->page_local);
LocalStateChanged(QMediaPlayer::StoppedState);
QIcon ico = LXDG::findIcon("media-playlist-audio","audio-x-generic");
SYSTRAY->setIcon( ico );
this->setWindowIcon( ico );
this->setWindowTitle( tr("Media Player") );
localPlaybackSettingsChanged();
}
//Now close down any currently running streams as needed
if(!ui->radio_pandora->isChecked() && PANDORA->currentState()!=PianoBarProcess::Stopped){ PANDORA->closePianoBar(); }
else if(!ui->radio_local->isChecked() && PLAYER->state()!=QMediaPlayer::StoppedState){ PLAYER->stop(); }
}
void MainUI::PlayerSettingsChanged(){
SETTINGS->setValue("CloseToTrayWhenActive", ui->action_closeToTray->isChecked() );
SETTINGS->setValue("ShowNotifications", ui->action_showNotifications->isChecked() );
}
//Toolbar actions
void MainUI::playToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->play();
}else{
if( ui->list_local->selectedItems().count()==1){
PLAYLIST->setCurrentIndex( ui->list_local->row(ui->list_local->selectedItems().first()) );
}
PLAYER->play();
}
}
void MainUI::pauseToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->pause();
} else{
PLAYER->pause();
}
}
void MainUI::stopToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->closePianoBar();
}else{
PLAYER->stop();
}
}
void MainUI::nextToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->skipSong();
}else{
PLAYLIST->next();
}
}
void MainUI::backToggled(){
if(ui->radio_pandora->isChecked()){ return; }
else{
PLAYLIST->previous();
}
}
void MainUI::volupToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->volumeUp();
}
}
void MainUI::voldownToggled(){
if(ui->radio_pandora->isChecked()){
PANDORA->volumeDown();
}
}
//Player Options/Feedback
void MainUI::addLocalMedia(){
QStringList paths = QFileDialog::getOpenFileNames(this, tr("Open Multimedia Files"), QDir::homePath() );
for(int i=0; i<paths.length(); i++){
loadFile(paths[i]);
//PLAYLIST->addMedia( QUrl::fromLocalFile(paths[i]) );
}
}
void MainUI::rmLocalMedia(){
QList<QListWidgetItem*> sel = ui->list_local->selectedItems();
for(int i=0; i<sel.length(); i++){
PLAYLIST->removeMedia( ui->list_local->row(sel[i]) );
}
}
void MainUI::upLocalMedia(){
//NOTE: Only a single selection is possible at the present time
QList<QListWidgetItem*> sel = ui->list_local->selectedItems();
for(int i=0; i<sel.length(); i++){
int row = ui->list_local->row(sel[i]);
PLAYLIST->moveMedia(row, row-1 );
QApplication::processEvents(); //this runs the inserted/removed functions
ui->list_local->setCurrentRow(row-1);
}
}
void MainUI::downLocalMedia(){
//NOTE: Only a single selection is possible at the present time
QList<QListWidgetItem*> sel = ui->list_local->selectedItems();
for(int i=0; i<sel.length(); i++){
int row = ui->list_local->row(sel[i]);
PLAYLIST->moveMedia(row, row+1 );
QApplication::processEvents(); //this runs the inserted/removed functions
ui->list_local->setCurrentRow(row+1);
}
}
void MainUI::localPlaybackSettingsChanged(){
if(ui->tool_local_shuffle->isChecked()){ PLAYLIST->setPlaybackMode(QMediaPlaylist::Random); }
else if(ui->tool_local_repeat->isChecked()){ PLAYLIST->setPlaybackMode(QMediaPlaylist::Loop); }
else{ PLAYLIST->setPlaybackMode(QMediaPlaylist::Sequential); }
}
//Local Playlist Feedback
void MainUI::LocalListIndexChanged(int current){
for(int i=0; i<ui->list_local->count(); i++){
if(i==current){
ui->list_local->item(i)->setIcon( LXDG::findIcon("media-playback-start","") );
ui->list_local->scrollToItem(ui->list_local->item(i));
ui->label_player_novideo->setText( tr("Now Playing:")+"\n\n"+ui->list_local->item(i)->text() );
}else if(!ui->list_local->item(i)->icon().isNull()){
ui->list_local->item(i)->setIcon( LXDG::findIcon("","") );
}
}
}
void MainUI::LocalListMediaChanged(int start, int end){
//qDebug() << "List Media Changed";
QList<QListWidgetItem*> sel = ui->list_local->selectedItems();
QString selItem;
if(!sel.isEmpty()){ sel.first()->text(); }
for(int i=start; i<end+1; i++){
QUrl url = PLAYLIST->media(i).canonicalUrl();
ui->list_local->item(i)->setText(url.toLocalFile().section("/",-1).simplified());
if(ui->list_local->item(i)->text()==selItem){
ui->list_local->setCurrentItem(ui->list_local->item(i));
}
}
}
void MainUI::LocalListMediaInserted(int start, int end){
// qDebug() << "Media Inserted";
for(int i=start; i<end+1; i++){
QUrl url = PLAYLIST->media(i).canonicalUrl();
ui->list_local->insertItem(i, url.toLocalFile().section("/",-1).simplified());
}
}
void MainUI::LocalListMediaRemoved(int start, int end){
//qDebug() << "Media Removed";
for(int i=end; i>=start; i--){
delete ui->list_local->takeItem(i);
}
}
/*void MainUI::LocalAudioAvailable(bool avail){
//qDebug() << "Local Audio Available:" << avail;
if(!avail && PLAYER->state()!=QMediaPlayer::StoppedState){
qDebug() << "WARNING: No Audio Output Available!!";
}
}*/
void MainUI::LocalVideoAvailable(bool avail){
qDebug() << "Local VideoAvailable:" << avail;
if(DISABLE_VIDEO){ avail = false; } //TEMPORARY DISABLE while working out gstreamer issues when video widget is hidden
//if(ui->tabWidget_local->currentWidget()==ui->tab_local_playing && avail){
VIDEO->setVisible(avail);
//}
ui->label_player_novideo->setVisible(!avail);
}
void MainUI::LocalIsSeekable(bool avail){
ui->slider_local->setEnabled(avail);
}
void MainUI::LocalNowMuted(bool mute){
qDebug() << "Local Player Muted:" << mute;
}
void MainUI::LocalError(QMediaPlayer::Error err){
if(err == QMediaPlayer::NoError){ return; };
QString errtext = QString(tr("[PLAYBACK ERROR]\n%1")).arg(PLAYER->errorString());
qDebug() << "Local Player Error:" << err << errtext;
ui->label_player_novideo->setText(errtext);
VIDEO->setVisible(false);
ui->label_player_novideo->setVisible(true);
}
void MainUI::LocalMediaChanged(const QMediaContent&){
//qDebug() << "Local Media Changed:" << content;
}
void MainUI::LocalMediaStatusChanged(QMediaPlayer::MediaStatus stat){
//qDebug() << "Local Media Status Changed:" << stat;
QString txt;
switch(stat){
case QMediaPlayer::LoadingMedia:
txt = tr("Media Loading..."); break;
case QMediaPlayer::StalledMedia:
txt = tr("Media Stalled..."); break;
case QMediaPlayer::BufferingMedia:
txt = tr("Media Buffering..."); break;
default:
txt.clear();
}
if(txt.isEmpty()){ ui->statusbar->clearMessage(); }
else{ ui->statusbar->showMessage(txt, 1500); }
}
void MainUI::LocalStateChanged(QMediaPlayer::State state){
//qDebug() << "Local Player State Changed:" << state;
ui->actionPlay->setVisible(state != QMediaPlayer::PlayingState);
ui->actionStop->setVisible(state != QMediaPlayer::StoppedState);
ui->actionPause->setVisible(state == QMediaPlayer::PlayingState);
ui->actionNext->setVisible(state == QMediaPlayer::PlayingState);
ui->actionBack->setVisible(state == QMediaPlayer::PlayingState);
if(state == QMediaPlayer::StoppedState){
ui->tabWidget_local->setCurrentWidget(ui->tab_local_playlist);
ui->tabWidget_local->setTabEnabled(0,false);
}else if(state == QMediaPlayer::PlayingState && !ui->tabWidget_local->isTabEnabled(0)){
ui->tabWidget_local->setTabEnabled(0,true);
ui->tabWidget_local->setCurrentWidget(ui->tab_local_playing);
}else if(!DISABLE_VIDEO && (PLAYER->mediaStatus()== QMediaPlayer::BufferingMedia || PLAYER->mediaStatus()==QMediaPlayer::BufferedMedia) ){
if(VIDEO->isVisible() != PLAYER->isVideoAvailable()){ VIDEO->setVisible(PLAYER->isVideoAvailable()); }
}
}
void MainUI::LocalDurationChanged(qint64 tot){
ui->slider_local->setRange(0,tot);
tot = qRound(tot/1000.0); //convert from ms to seconds
QString time = QTime(0, tot/60, tot%60,0).toString("m:ss") ;
//qDebug() << "Duration Update:" << tot << time;
ui->slider_local->setWhatsThis(time);
}
void MainUI::LocalPositionChanged(qint64 val){
ui->slider_local->setValue(val);
val = qRound(val/1000.0); //convert from ms to seconds
QString time = QTime(0, val/60, val%60,0).toString("m:ss");
//qDebug() << "Time Update:" << val << time;
ui->label_local_runstats->setText(time+ "/" + ui->slider_local->whatsThis());
}
void MainUI::LocalVolumeChanged(int vol){
qDebug() << "Local Volume Changed:" << vol;
}
//Pandora Options
void MainUI::showPandoraSongInfo(){
QDesktopServices::openUrl( QUrl(ui->tool_pandora_info->whatsThis()) );
}
void MainUI::changePandoraStation(QString station){
if(station == PANDORA->currentStation()){ return; }
//qDebug() << "[CHANGE STATION]" << station << "from:" << PANDORA->currentStation();
PANDORA->setCurrentStation(station);
}
void MainUI::checkPandoraSettings(){
bool changes = (PANDORA->email() != ui->line_pandora_email->text())
|| (PANDORA->password() != ui->line_pandora_pass->text())
|| (PANDORA->audioQuality() != ui->combo_pandora_quality->currentData().toString())
|| (PANDORA->proxy() != ui->line_pandora_proxy->text())
|| (PANDORA->controlProxy() != ui->line_pandora_cproxy->text())
|| (PANDORA->currentAudioDriver() != ui->combo_pandora_driver->currentText());
ui->push_pandora_apply->setEnabled(changes);
}
void MainUI::applyPandoraSettings(){
PANDORA->setLogin(ui->line_pandora_email->text(), ui->line_pandora_pass->text());
PANDORA->setAudioQuality(ui->combo_pandora_quality->currentData().toString());
PANDORA->setProxy(ui->line_pandora_proxy->text());
PANDORA->setControlProxy(ui->line_pandora_cproxy->text());
PANDORA->setAudioDriver(ui->combo_pandora_driver->currentText());
if(PANDORA->isSetup()){
//Go ahead and (re)start the Pandora process so it is aware of the new changes
if(PANDORA->currentState()!=PianoBarProcess::Stopped){ PANDORA->closePianoBar(); }
QTimer::singleShot(500, PANDORA, SLOT(play()) ); //give it a moment for the file to get written first
}
}
void MainUI::createPandoraStation(){
//Prompt for a search string
QString srch = QInputDialog::getText(this, tr("Pandora: Create Station"),"", QLineEdit::Normal, tr("Search Term"));
if(srch.isEmpty()){ return; } //cancelled
PANDORA->createNewStation(srch);
}
//Pandora Process Feedback
void MainUI::PandoraStateChanged(PianoBarProcess::State state){
//qDebug() << "[STATE CHANGE]" << state;
ui->actionPlay->setVisible(state != PianoBarProcess::Running);
ui->actionPause->setVisible(state == PianoBarProcess::Running);
ui->actionStop->setVisible(state != PianoBarProcess::Stopped);
ui->actionBack->setVisible(false); //never available for Pandora streams
ui->actionNext->setVisible(state!=PianoBarProcess::Stopped);
ui->tabWidget_pandora->setTabEnabled(0, state !=PianoBarProcess::Stopped);
if(!ui->tabWidget_pandora->isTabEnabled(0) && ui->tabWidget_pandora->currentIndex()==0){
ui->tabWidget_pandora->setCurrentWidget(ui->tab_pandora_settings);
}else if(state == PianoBarProcess::Running){
ui->tabWidget_pandora->setCurrentWidget(ui->tab_pandora_playing);
}
ui->actionVolUp->setVisible(false);//state != PianoBarProcess::Stopped);
ui->actionVolDown->setVisible(false); //state != PianoBarProcess::Stopped);
}
void MainUI::NewPandoraInfo(QString info){
//qDebug() << "[INFO]" << info;
ui->statusbar->showMessage(info, 2000);
}
void MainUI::PandoraStationChanged(QString station){
//qDebug() << "[STATION CHANGE]" << station;
int index = ui->combo_pandora_station->findText( station );
if(index>=0){
//qDebug() <<" [FOUND]" << ui->combo_pandora_station->itemText(index);
ui->combo_pandora_station->setCurrentIndex(index);
}else{
//Could not find the station in the current list - need to update that first
//qDebug() <<" [NOT FOUND]";
PandoraStationListChanged(PANDORA->stations());
}
}
void MainUI::PandoraSongChanged(bool isLoved, QString title, QString artist, QString album, QString detailsURL, QString){ // fromStation){
//qDebug() << "[SONG CHANGE]" << isLoved << title << artist << album << detailsURL << fromStation;
ui->tool_pandora_info->setWhatsThis(detailsURL);
ui->tool_pandora_love->setChecked(isLoved);
ui->tool_pandora_love->setEnabled(!isLoved); //pianobar cannot "unlove" a song
ui->label_pandora_album->setText(album);
ui->label_pandora_artist->setText(artist);
ui->label_pandora_title->setText(title);
ui->progress_pandora->setRange(0,1);
ui->progress_pandora->setValue(0);
ui->progress_pandora->setFormat("");
QString msg = QString("%1\n%2\n%3").arg(title, artist, album);
SYSTRAY->setToolTip(msg);
if(ui->action_showNotifications->isChecked()){
SYSTRAY->showMessage(tr("Now Playing"), msg, QSystemTrayIcon::NoIcon, 2000); //2 seconds
}
}
void MainUI::PandoraTimeUpdate(int curS, int totS){
//qDebug() << "[TIME UPDATE]" << curS << "/" << totS;
ui->progress_pandora->setRange(0, totS);
ui->progress_pandora->setValue(curS);
QString time = QTime(0, curS/60, curS%60,0).toString("m:ss") + "/" + QTime(0, totS/60, totS%60,0).toString("m:ss");
ui->progress_pandora->setFormat(time);
}
void MainUI::PandoraStationListChanged(QStringList list){
//qDebug() << "[STATION LIST]" << list;
ui->combo_pandora_station->clear();
if(list.isEmpty()){ return; }
ui->combo_pandora_station->addItems(list);
int index = ui->combo_pandora_station->findText( PANDORA->currentStation() );
//qDebug() << "[CURRENT STATION]" << PANDORA->currentStation() << index;
if(index>=0){ ui->combo_pandora_station->setCurrentIndex(index); }
}
void MainUI::PandoraInteractivePrompt(QString text, QStringList list){
QString sel = QInputDialog::getItem(this, tr("Pandora Question"), text, list, false);
PANDORA->answerQuestion( list.indexOf(sel) );
}
void MainUI::PandoraError(QString err){
QMessageBox::warning(this, tr("Pandora Error"), err);
}
//System Tray interactions
void MainUI::toggleVisibility(){
if(this->isVisible()){ this->hide(); }
else{ this->showNormal(); }
}
void MainUI::trayMessageClicked(){
this->showNormal();
this->activateWindow();
this->raise();
}
void MainUI::trayClicked(QSystemTrayIcon::ActivationReason rsn){
if(rsn == QSystemTrayIcon::Context){
SYSTRAY->contextMenu()->popup(QCursor::pos());
}else{
toggleVisibility();
}
}
void MainUI::closeEvent(QCloseEvent *ev){
if(!closing){
//Check if we have audio playing to determine if we should just minimize instead
if(ui->action_closeToTray->isChecked()){
closing = (PANDORA->currentState()!=PianoBarProcess::Running);
}else if(PANDORA->currentState()!=PianoBarProcess::Stopped){
//Make sure we close the stream down first
PANDORA->closePianoBar();
QTimer::singleShot(500, this, SLOT(close()) ); //try again in a moment
}else{
closing = true;
}
}
if(closing){ QMainWindow::closeEvent(ev); } //normal close procedure
else{
ev->ignore();
this->hide();
}
}
| 41.597718 | 176 | 0.708333 | [
"object"
] |
982e6a64d5e681343d279ccd28da83cdd178265f | 5,241 | cc | C++ | HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToKxMuMuBuilder.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | 2 | 2020-01-21T11:23:39.000Z | 2020-01-21T11:23:42.000Z | HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToKxMuMuBuilder.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | null | null | null | HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToKxMuMuBuilder.cc | AFJohan92/cmssw | c5b36f05986c35998ddd4c873dc6812646579744 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | /*
* See header file for a description of this class.
*
* \author Paolo Ronchese INFN Padova
*
*/
//-----------------------
// This Class' Header --
//-----------------------
#include "HeavyFlavorAnalysis/SpecificDecay/interface/BPHBdToKxMuMuBuilder.h"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoBuilder.h"
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHPlusMinusCandidate.h"
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoCandidate.h"
#include "HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSelect.h"
#include "HeavyFlavorAnalysis/SpecificDecay/interface/BPHChi2Select.h"
#include "HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassFitSelect.h"
#include "HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleMasses.h"
//---------------
// C++ Headers --
//---------------
using namespace std;
//-------------------
// Initializations --
//-------------------
//----------------
// Constructors --
//----------------
BPHBdToKxMuMuBuilder::BPHBdToKxMuMuBuilder(const edm::EventSetup& es,
const std::vector<BPHPlusMinusConstCandPtr>& oniaCollection,
const std::vector<BPHPlusMinusConstCandPtr>& kx0Collection)
: oniaName("Onia"), kx0Name("Kx0"), evSetup(&es), jCollection(&oniaCollection), kCollection(&kx0Collection) {
oniaSel = new BPHMassSelect(1.00, 12.00);
mkx0Sel = new BPHMassSelect(0.80, 1.00);
massSel = new BPHMassSelect(3.50, 8.00);
chi2Sel = new BPHChi2Select(0.02);
mFitSel = new BPHMassFitSelect(4.00, 7.00);
massConstr = true;
minPDiff = 1.0e-4;
updated = false;
}
//--------------
// Destructor --
//--------------
BPHBdToKxMuMuBuilder::~BPHBdToKxMuMuBuilder() {
delete oniaSel;
delete mkx0Sel;
delete massSel;
delete chi2Sel;
delete mFitSel;
}
//--------------
// Operations --
//--------------
vector<BPHRecoConstCandPtr> BPHBdToKxMuMuBuilder::build() {
if (updated)
return bdList;
bdList.clear();
BPHRecoBuilder bBd(*evSetup);
bBd.setMinPDiffererence(minPDiff);
bBd.add(oniaName, *jCollection);
bBd.add(kx0Name, *kCollection);
bBd.filter(oniaName, *oniaSel);
bBd.filter(kx0Name, *mkx0Sel);
bBd.filter(*massSel);
if (chi2Sel != nullptr)
bBd.filter(*chi2Sel);
if (massConstr)
bBd.filter(*mFitSel);
bdList = BPHRecoCandidate::build(bBd);
//
// Apply kinematic constraint on the onia mass.
// The operation is already performed when apply the mass selection,
// so it's not repeated. The following code is left as example
// for similar operations
//
// int iBd;
// int nBd = ( massConstr ? bdList.size() : 0 );
// for ( iBd = 0; iBd < nBd; ++iBd ) {
// BPHRecoCandidate* cptr = const_cast<BPHRecoCandidate*>(
// bdList[iBd].get() );
// BPHRecoConstCandPtr onia = cptr->getComp( oniaName );
// double oMass = onia->constrMass();
// if ( oMass < 0 ) continue;
// double sigma = onia->constrSigma();
// cptr->kinematicTree( oniaName, oMass, sigma );
// }
updated = true;
return bdList;
}
/// set cuts
void BPHBdToKxMuMuBuilder::setOniaMassMin(double m) {
updated = false;
oniaSel->setMassMin(m);
return;
}
void BPHBdToKxMuMuBuilder::setOniaMassMax(double m) {
updated = false;
oniaSel->setMassMax(m);
return;
}
void BPHBdToKxMuMuBuilder::setKxMassMin(double m) {
updated = false;
mkx0Sel->setMassMin(m);
return;
}
void BPHBdToKxMuMuBuilder::setKxMassMax(double m) {
updated = false;
mkx0Sel->setMassMax(m);
return;
}
void BPHBdToKxMuMuBuilder::setMassMin(double m) {
updated = false;
massSel->setMassMin(m);
return;
}
void BPHBdToKxMuMuBuilder::setMassMax(double m) {
updated = false;
massSel->setMassMax(m);
return;
}
void BPHBdToKxMuMuBuilder::setProbMin(double p) {
updated = false;
delete chi2Sel;
chi2Sel = (p < 0.0 ? nullptr : new BPHChi2Select(p));
return;
}
void BPHBdToKxMuMuBuilder::setMassFitMin(double m) {
updated = false;
mFitSel->setMassMin(m);
return;
}
void BPHBdToKxMuMuBuilder::setMassFitMax(double m) {
updated = false;
mFitSel->setMassMax(m);
return;
}
void BPHBdToKxMuMuBuilder::setConstr(bool flag) {
updated = false;
massConstr = flag;
return;
}
/// get current cuts
double BPHBdToKxMuMuBuilder::getOniaMassMin() const { return oniaSel->getMassMin(); }
double BPHBdToKxMuMuBuilder::getOniaMassMax() const { return oniaSel->getMassMax(); }
double BPHBdToKxMuMuBuilder::getKxMassMin() const { return mkx0Sel->getMassMin(); }
double BPHBdToKxMuMuBuilder::getKxMassMax() const { return mkx0Sel->getMassMax(); }
double BPHBdToKxMuMuBuilder::getMassMin() const { return massSel->getMassMin(); }
double BPHBdToKxMuMuBuilder::getMassMax() const { return massSel->getMassMax(); }
double BPHBdToKxMuMuBuilder::getProbMin() const { return (chi2Sel == nullptr ? -1.0 : chi2Sel->getProbMin()); }
double BPHBdToKxMuMuBuilder::getMassFitMin() const { return mFitSel->getMassMin(); }
double BPHBdToKxMuMuBuilder::getMassFitMax() const { return mFitSel->getMassMax(); }
bool BPHBdToKxMuMuBuilder::getConstr() const { return massConstr; }
| 27.87766 | 113 | 0.666094 | [
"vector"
] |
982eecdbb9c203bedde41d491e3c6d1a2901914f | 6,958 | cpp | C++ | client.cpp | s25g5d4/netproghw2 | 05739f27eaae0a4436f753f6b03fc52d217118e4 | [
"MIT"
] | null | null | null | client.cpp | s25g5d4/netproghw2 | 05739f27eaae0a4436f753f6b03fc52d217118e4 | [
"MIT"
] | null | null | null | client.cpp | s25g5d4/netproghw2 | 05739f27eaae0a4436f753f6b03fc52d217118e4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "commons.hpp"
#include "my_huffman.hpp"
extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <netdb.h>
#include <errno.h>
#include <libgen.h>
#include "my_send_recv.h"
}
int sockfd = 0;
/**
* Descrption: Clean exit when SIGINT received.
*/
static void sigint_safe_exit(int sig);
/**
* Descrption: Connect and login to server.
* Return: 0 if succeed, or -1 if fail.
*/
static int login(const char *addr, const char *port);
/**
* Descrption: Check and parse user input and run login command.
* Return: 0 if succeed, or -1 if fail.
*/
static int run_login(std::vector<std::string> &cmd);
/**
* Descrption: Check and parse user input and send file to server.
* Return: 0 if succeed, or -1 if fail.
*/
static int run_send(std::vector<std::string> &cmd, std::string &orig_cmd);
int main()
{
// Handle SIGINT
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_handler = sigint_safe_exit;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
using namespace std;
// Prompt for user command
while (true) {
cout << "> " << flush;
string orig_cmd;
getline(cin, orig_cmd);
vector<string> cmd = parse_command(orig_cmd);
if (cmd.size() == 0) {
continue;
}
// Run command
if (cmd[0] == "login") {
run_login(cmd);
}
else if (cmd[0] == "send") {
if (run_send(cmd, orig_cmd) < 0) {
break;
}
}
else if (cmd[0] == "logout" || cmd[0] == "exit") {
break;
}
else {
cout << "Invalid command." << endl;
}
}
// Clean exit
if (sockfd > 2) {
close(sockfd);
}
cout << "Goodbye." << endl;
return 0;
}
static void sigint_safe_exit(int sig)
{
if (sockfd > 2) {
close(sockfd);
}
fprintf(stderr, "Interrupt.\n");
exit(1);
}
static int login(const char *addr, const char *port)
{
// Resolve hostname and connect
struct addrinfo hints = {};
struct addrinfo *res;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(addr, port, &hints, &res);
if (status != 0) {
std::cerr << gai_strerror(status) << std::endl;
return -1;
}
struct addrinfo *p;
for (p = res; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sockfd > 0) {
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == 0) {
break;
}
perror("connect");
close(sockfd);
sockfd = 0;
continue;
}
perror("socket");
}
freeaddrinfo(res);
if (p == NULL) {
return -1;
}
// Read welcome message
char welcome_msg[64] = {};
int msglen = (int) sizeof (welcome_msg);
status = my_recv_cmd(sockfd, welcome_msg, &msglen);
if (status < 0) {
perror("my_recv_cmd");
return -1;
}
else if (status > 0) {
std::cout << "Invalid command received." << std::endl;
return -1;
}
welcome_msg[msglen - 1] = '\0';
std::cout << welcome_msg << std::endl;
return 0;
}
static int run_login(std::vector<std::string> &cmd)
{
if (cmd.size() < 3) {
std::cout << "Invalid command.";
return -1;
}
if (sockfd > 2) {
std::cout << "The connection has been established already." << std::endl;
return -1;
}
std::cout << "Connecting to " << cmd[1] << ":" << cmd[2] << std::endl;
if (login(cmd[1].c_str(), cmd[2].c_str()) < 0) {
std::cout << "Fail to login." << std::endl;
return -1;
}
return 0;
}
static int run_send(std::vector<std::string> &cmd, std::string &orig_cmd)
{
using namespace std;
if (sockfd <= 2) {
cout << "You are not logged in yet." << endl;
return 1;
}
if (cmd.size() < 2) {
cout << "Please provide file name." << endl;
return 1;
}
// Get file path
string::size_type n = orig_cmd.find(cmd[1]);
if (n == string::npos) {
cout << "Command error." << endl;
return 1;
}
string pathname(orig_cmd.begin() + n, orig_cmd.end());
ifstream file(pathname, fstream::in | fstream::binary);
if (!file.is_open()) {
cout << "Failed to open file." << endl;
return 1;
}
// Get filename
// Both dirname() and basename() may modify the contents of path, so it
// may be desirable to pass a copy when calling one of these functions.
char *pathname_c_str = new char[pathname.size() + 1];
memcpy(pathname_c_str, pathname.c_str(), pathname.size() + 1);
string filename = basename(pathname_c_str);
delete pathname_c_str;
// Encode with Huffman Coding
my_huffman::huffman_encode encoded_file(file);
uint8_t *buf;
int buflen;
file.seekg(0);
encoded_file.write(file, &buf, &buflen);
// Send command to server
string send_cmd = "send " + to_string(buflen) + " " + filename + "\n";
int sendlen = static_cast<int>(send_cmd.size());
int status = my_send(sockfd, send_cmd.c_str(), &sendlen);
if (status < 0) {
perror("my_send");
cout << "Send failed. Terminate conneciton." << endl;
return -1;
}
// Send file to server
status = my_send(sockfd, buf, &buflen);
if (status < 0) {
perror("my_send");
cout << "Send failed. Terminate conneciton." << endl;
return -1;
}
file.clear();
file.seekg(0, file.end);
cout << "Original file size: " << file.tellg() << "bytes, compressed size: " << buflen << " bytes." << endl;
cout.precision(2);
cout.setf(ios::fixed);
cout << "Compression ratio: " << static_cast<double>(buflen)*100.0 / static_cast<double>(file.tellg()) << "%." << endl;
// Get response
char msg[MAX_CMD];
int msglen = MAX_CMD - 1;
status = my_recv_cmd(sockfd, msg, &msglen);
if (status > 0) {
cout << "Invalid response. Terminate conneciton." << endl;
return -1;
}
else if (status < 0) {
perror("my_recv_cmd");
cout << "Invalid response. Terminate conneciton." << endl;
return -1;
}
vector<string> res = parse_command(msg);
if (res.size() < 2 || res[0] != "OK") {
cout << "Invalid response. Terminate conneciton." << endl;
return -1;
}
int sent;
try {
sent = stoi(res[1]);
}
catch (exception &e) {
cout << "Invalid response. Terminate conneciton." << endl;
return -1;
}
cout << "OK " << sent << " bytes sent." << endl;
return 0;
}
| 23.828767 | 123 | 0.553464 | [
"vector"
] |
98313ae9e9e4cf024a0c04db9d758a32bf5c4e5e | 325 | hh | C++ | include/ftk/io/mpas_stream.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 19 | 2018-11-01T02:15:17.000Z | 2022-03-28T16:55:00.000Z | include/ftk/io/mpas_stream.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 12 | 2019-04-14T12:49:41.000Z | 2021-10-20T03:59:21.000Z | include/ftk/io/mpas_stream.hh | hguo/FTT | f1d5387d6353cf2bd165c51fc717eb5d6b2675ef | [
"MIT"
] | 9 | 2019-02-08T19:40:46.000Z | 2021-06-15T00:31:09.000Z | #ifndef _FTK_MPAS_STREAM_HH
#define _FTK_MPAS_STREAM_HH
#include <ftk/object.hh>
#include <ftk/ndarray.hh>
#include <ftk/ndarray/ndarray_group.hh>
namespace ftk {
using nlohmann::json;
struct mpas_stream : public object {
mpas_stream(const std::string& path, diy::mpi::communicator comm=MPI_COMM_WORLD);
};
}
#endif
| 16.25 | 83 | 0.76 | [
"object"
] |
9839f37cb06cce890ed5b35ab5b8c033811ae328 | 14,163 | cpp | C++ | pennylane_lightning/src/benchmarks/Bench_LinearAlgebra.cpp | AmintorDusko/pennylane-lightning | 9554a95842de9d7759ce96bfa75857e0c9ca756b | [
"Apache-2.0"
] | null | null | null | pennylane_lightning/src/benchmarks/Bench_LinearAlgebra.cpp | AmintorDusko/pennylane-lightning | 9554a95842de9d7759ce96bfa75857e0c9ca756b | [
"Apache-2.0"
] | null | null | null | pennylane_lightning/src/benchmarks/Bench_LinearAlgebra.cpp | AmintorDusko/pennylane-lightning | 9554a95842de9d7759ce96bfa75857e0c9ca756b | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Xanadu Quantum Technologies Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <limits>
#include <random>
#include <LinearAlgebra.hpp>
#include <benchmark/benchmark.h>
/**
* @brief Benchmark generating a vector of random complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T>
static void create_random_cmplx_vector(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
for (auto _ : state) {
std::vector<std::complex<T>> vec;
for (size_t i = 0; i < sz; i++) {
vec.push_back({distr(eng), distr(eng)});
}
benchmark::DoNotOptimize(vec.size());
}
}
BENCHMARK(create_random_cmplx_vector<float>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(create_random_cmplx_vector<double>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
//***********************************************************************//
// Inner Product
//***********************************************************************//
/**
* @brief Benchmark std::inner_product for two vectors of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T> static void std_innerProd_cmplx(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> vec1;
for (size_t i = 0; i < sz; i++)
vec1.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> vec2;
for (size_t i = 0; i < sz; i++)
vec2.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::complex<T> res = std::inner_product(
vec1.data(), vec1.data() + sz, vec2.data(), std::complex<T>(),
Pennylane::Util::ConstSum<T>,
static_cast<std::complex<T> (*)(std::complex<T>, std::complex<T>)>(
&Pennylane::Util::ConstMult<T>));
benchmark::DoNotOptimize(res);
}
}
BENCHMARK(std_innerProd_cmplx<float>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(std_innerProd_cmplx<double>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
/**
* @brief Benchmark Pennylane::Util::omp_innerProd for two vectors of complex
* numbers.
*
* @tparam T Floating point precision type.
*/
template <class T> static void omp_innerProd_cmplx(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> vec1;
for (size_t i = 0; i < sz; i++)
vec1.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> vec2;
for (size_t i = 0; i < sz; i++)
vec2.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::complex<T> res(.0, .0);
Pennylane::Util::omp_innerProd(vec1.data(), vec2.data(), res, sz);
benchmark::DoNotOptimize(res);
}
}
BENCHMARK(omp_innerProd_cmplx<float>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(omp_innerProd_cmplx<double>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
#if __has_include(<cblas.h>) && defined _ENABLE_BLAS
/**
* @brief Benchmark cblas_cdotc_sub and cblas_zdotc_sub for two vectors of
* complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T> static void blas_innerProd_cmplx(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> vec1;
for (size_t i = 0; i < sz; i++)
vec1.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> vec2;
for (size_t i = 0; i < sz; i++)
vec2.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::complex<T> res(.0, .0);
if constexpr (std::is_same_v<T, float>) {
cblas_cdotc_sub(sz, vec1.data(), 1, vec2.data(), 1, &res);
} else if constexpr (std::is_same_v<T, double>) {
cblas_zdotc_sub(sz, vec1.data(), 1, vec2.data(), 1, &res);
}
benchmark::DoNotOptimize(res);
}
}
BENCHMARK(blas_innerProd_cmplx<float>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(blas_innerProd_cmplx<double>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
#endif
//***********************************************************************//
// Matrix Transpose
//***********************************************************************//
/**
* @brief Benchmark naive matrix transpose for a randomly generated matrix
* of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T> static void naive_transpose_cmplx(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> mat1;
for (size_t i = 0; i < sz * sz; i++)
mat1.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::vector<std::complex<T>> mat2(sz * sz);
for (size_t r = 0; r < sz; r++) {
for (size_t s = 0; s < sz; s++) {
mat2[s * sz + r] = mat1[r * sz + s];
}
}
benchmark::DoNotOptimize(mat2[sz * sz - 1]);
}
}
BENCHMARK(naive_transpose_cmplx<float>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(naive_transpose_cmplx<double>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
/**
* @brief Benchmark Pennylane::Util::CFTranspose for a randomly generated matrix
* of complex numbers.
*
* @tparam T Floating point precision type.
* @tparam BLOCKSIZE Size of submatrices in the blocking technique.
*/
template <class T, size_t BLOCKSIZE>
static void cf_transpose_cmplx(benchmark::State &state) {
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> mat1;
for (size_t i = 0; i < sz * sz; i++)
mat1.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::vector<std::complex<T>> mat2(sz * sz);
Pennylane::Util::CFTranspose<T, BLOCKSIZE>(mat1.data(), mat2.data(), sz,
sz, 0, sz, 0, sz);
benchmark::DoNotOptimize(mat2[sz * sz - 1]);
}
}
BENCHMARK(cf_transpose_cmplx<float, 16>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(cf_transpose_cmplx<double, 16>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(cf_transpose_cmplx<float, 32>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
BENCHMARK(cf_transpose_cmplx<double, 32>)
->RangeMultiplier(1l << 3)
->Range(1l << 5, 1l << 10);
//***********************************************************************//
// Matrix-Vector Product
//***********************************************************************//
/**
* @brief Benchmark PennyLane::Util::omp_matrixVecProd for a randomly generated
* matrix and vector of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T>
static void omp_matrixVecProd_cmplx(benchmark::State &state) {
using Pennylane::Util::Trans;
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> mat;
for (size_t i = 0; i < sz * sz; i++)
mat.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> vec1;
for (size_t i = 0; i < sz; i++)
vec1.push_back({distr(eng), distr(eng)});
for (auto _ : state) {
std::vector<std::complex<T>> vec2(sz);
Pennylane::Util::omp_matrixVecProd(mat.data(), vec1.data(), vec2.data(),
sz, sz, Trans::NoTranspose);
benchmark::DoNotOptimize(vec2[sz - 1]);
}
}
BENCHMARK(omp_matrixVecProd_cmplx<float>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
BENCHMARK(omp_matrixVecProd_cmplx<double>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
#if __has_include(<cblas.h>) && defined _ENABLE_BLAS
/**
* @brief Benchmark cblas_cgemv and cblas_zgemv for a randomly generated
* matrix and vector of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T>
static void blas_matrixVecProd_cmplx(benchmark::State &state) {
using Pennylane::Util::Trans;
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> mat;
for (size_t i = 0; i < sz * sz; i++)
mat.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> vec1;
for (size_t i = 0; i < sz; i++)
vec1.push_back({distr(eng), distr(eng)});
const auto tr = static_cast<CBLAS_TRANSPOSE>(Trans::NoTranspose);
constexpr std::complex<T> co{1, 0};
constexpr std::complex<T> cz{0, 0};
for (auto _ : state) {
std::vector<std::complex<T>> vec2(sz);
if constexpr (std::is_same_v<T, float>) {
cblas_cgemv(CblasRowMajor, tr, sz, sz, &co, mat.data(), sz,
vec1.data(), 1, &cz, vec2.data(), 1);
} else if constexpr (std::is_same_v<T, double>) {
cblas_zgemv(CblasRowMajor, tr, sz, sz, &co, mat.data(), sz,
vec1.data(), 1, &cz, vec2.data(), 1);
}
benchmark::DoNotOptimize(vec2[sz - 1]);
}
}
BENCHMARK(blas_matrixVecProd_cmplx<float>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
BENCHMARK(blas_matrixVecProd_cmplx<double>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
#endif
//***********************************************************************//
// Matrix-Matrix Product
//***********************************************************************//
/**
* @brief Benchmark Pennylane::Util::omp_matrixMatProd for two randomly
* generated matrices of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T>
static void omp_matrixMatProd_cmplx(benchmark::State &state) {
using Pennylane::Util::Trans;
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> m_left;
for (size_t i = 0; i < sz * sz; i++)
m_left.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> m_right;
for (size_t i = 0; i < sz * sz; i++)
m_right.push_back({distr(eng), distr(eng)});
const auto m_right_tr = Pennylane::Util::Transpose(m_right, sz, sz);
for (auto _ : state) {
std::vector<std::complex<T>> m_out(sz * sz);
Pennylane::Util::omp_matrixMatProd(m_left.data(), m_right_tr.data(),
m_out.data(), sz, sz, sz,
Trans::Transpose);
benchmark::DoNotOptimize(m_out[sz * sz - 1]);
}
}
BENCHMARK(omp_matrixMatProd_cmplx<float>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
BENCHMARK(omp_matrixMatProd_cmplx<double>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
#if __has_include(<cblas.h>) && defined _ENABLE_BLAS
/**
* @brief Benchmark cblas_cgemm and cblas_zgemm for two randomly
* generated matrices of complex numbers.
*
* @tparam T Floating point precision type.
*/
template <class T>
static void blas_matrixMatProd_cmplx(benchmark::State &state) {
using Pennylane::Util::Trans;
std::random_device rd;
std::mt19937_64 eng(rd());
std::uniform_real_distribution<T> distr;
const auto sz = static_cast<size_t>(state.range(0));
std::vector<std::complex<T>> m_left;
for (size_t i = 0; i < sz * sz; i++)
m_left.push_back({distr(eng), distr(eng)});
std::vector<std::complex<T>> m_right;
for (size_t i = 0; i < sz * sz; i++)
m_right.push_back({distr(eng), distr(eng)});
const auto tr = static_cast<CBLAS_TRANSPOSE>(Trans::NoTranspose);
constexpr std::complex<T> co{1, 0};
constexpr std::complex<T> cz{0, 0};
for (auto _ : state) {
std::vector<std::complex<T>> m_out(sz * sz);
if constexpr (std::is_same_v<T, float>) {
cblas_cgemm(CblasRowMajor, CblasNoTrans, tr, sz, sz, sz, &co,
m_left.data(), sz, m_right.data(), sz, &cz,
m_out.data(), sz);
} else if constexpr (std::is_same_v<T, double>) {
cblas_zgemm(CblasRowMajor, CblasNoTrans, tr, sz, sz, sz, &co,
m_left.data(), sz, m_right.data(), sz, &cz,
m_out.data(), sz);
}
benchmark::DoNotOptimize(m_out[sz * sz - 1]);
}
}
BENCHMARK(blas_matrixMatProd_cmplx<float>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
BENCHMARK(blas_matrixMatProd_cmplx<double>)
->RangeMultiplier(1l << 2)
->Range(1l << 4, 1l << 8);
#endif
| 32.483945 | 80 | 0.583492 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.