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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
da8c28984bc6d475be17819091daef1d5557b6f7 | 1,641 | cpp | C++ | Spoj/A_Needle_in_the_Haystack.cpp | ANONYMOUS609/Competitive-Programming | d3753eeee24a660963f1d8911bf887c8f41f5677 | [
"MIT"
] | 2 | 2019-01-30T12:45:18.000Z | 2021-05-06T19:02:51.000Z | Spoj/A_Needle_in_the_Haystack.cpp | ANONYMOUS609/Competitive-Programming | d3753eeee24a660963f1d8911bf887c8f41f5677 | [
"MIT"
] | null | null | null | Spoj/A_Needle_in_the_Haystack.cpp | ANONYMOUS609/Competitive-Programming | d3753eeee24a660963f1d8911bf887c8f41f5677 | [
"MIT"
] | 3 | 2020-10-02T15:42:04.000Z | 2022-03-27T15:14:16.000Z | #include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(false);cin.tie(0)
#define pb push_back
#define digit(x) floor(log10(x))+1
#define mod 1000000007
#define endl "\n"
typedef long long ll;
typedef long double ld;
typedef vector<vector<ll> > matrix;
typedef vector<ll> arr;
typedef vector<string> vs;
typedef vector<pair<ll,ll> > pv;
#define in1(x) scanf("%lld",&x)
#define in2(x,y) scanf("%lld %lld",&x,&y)
#define in3(x,y,z) scanf("%lld %lld %lld",&x,&y,&z)
#define all(x) x.begin(),x.end()
#define debug(x) cerr << #x << " is " << x << endl;
int bx[]={0,0,1,-1,1,-1,-1,1};
int by[]={1,-1,0,0,1,-1,1,-1};
int table[1000000] = {0};
//preprocessing Reset Table
void processTable(string p) {
int j = 0, i = 1;
int lp = p.length();
while(i<lp) {
while(j>0 and p[i]!=p[j]) {
j = table[j-1];
}
if(p[i]==p[j]) {
table[i] = j+1;
i++;
j++;
} else {
i++;
}
}
}
void KMP(string text, string p) {
processTable(p);
int i = 0;
int j = 0;
int ltext = text.length();
while(i<ltext) {
while(j>0 and text[i] != p[j]) {
j = table[j-1];
}
if(text[i] == p[j]) {
i++,
j++;
} else {
i++;
}
//pattern found
if(j == p.length()) {
cout<<i-j<<endl;
j = table[j-1];
}
}
}
int main(){
fast;
int n;
while(cin>>n) {
string text;
string p;
cin>>p>>text;
KMP(text,p);
cout<<endl;
}
return 0;
} | 20.259259 | 51 | 0.470445 | [
"vector"
] |
da8ca9ed581699da1a6938be6c34056c2d68afee | 17,864 | cc | C++ | mash/wm/bridge/wm_window_mus.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | mash/wm/bridge/wm_window_mus.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | mash/wm/bridge/wm_window_mus.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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 "mash/wm/bridge/wm_window_mus.h"
#include "ash/wm/common/container_finder.h"
#include "ash/wm/common/window_state.h"
#include "ash/wm/common/wm_layout_manager.h"
#include "ash/wm/common/wm_window_observer.h"
#include "ash/wm/common/wm_window_property.h"
#include "components/mus/public/cpp/window.h"
#include "components/mus/public/cpp/window_property.h"
#include "components/mus/public/cpp/window_tree_connection.h"
#include "mash/wm/bridge/mus_layout_manager_adapter.h"
#include "mash/wm/bridge/wm_globals_mus.h"
#include "mash/wm/bridge/wm_root_window_controller_mus.h"
#include "mash/wm/property_util.h"
#include "ui/aura/mus/mus_util.h"
#include "ui/base/hit_test.h"
#include "ui/display/display.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
MUS_DECLARE_WINDOW_PROPERTY_TYPE(mash::wm::WmWindowMus*);
// TODO(sky): fully implement this. Making DVLOG as too spammy to be useful.
#undef NOTIMPLEMENTED
#define NOTIMPLEMENTED() DVLOG(1) << "notimplemented"
namespace mash {
namespace wm {
MUS_DEFINE_OWNED_WINDOW_PROPERTY_KEY(mash::wm::WmWindowMus,
kWmWindowKey,
nullptr);
namespace {
// This classes is used so that the WindowState constructor can be made
// protected. GetWindowState() is the only place that should be creating
// WindowState.
class WindowStateMus : public ash::wm::WindowState {
public:
explicit WindowStateMus(ash::wm::WmWindow* window)
: ash::wm::WindowState(window) {}
~WindowStateMus() override {}
private:
DISALLOW_COPY_AND_ASSIGN(WindowStateMus);
};
ui::WindowShowState UIWindowShowStateFromMojom(mus::mojom::ShowState state) {
switch (state) {
case mus::mojom::ShowState::DEFAULT:
return ui::SHOW_STATE_DEFAULT;
case mus::mojom::ShowState::NORMAL:
return ui::SHOW_STATE_NORMAL;
case mus::mojom::ShowState::MINIMIZED:
return ui::SHOW_STATE_MINIMIZED;
case mus::mojom::ShowState::MAXIMIZED:
return ui::SHOW_STATE_MAXIMIZED;
case mus::mojom::ShowState::INACTIVE:
return ui::SHOW_STATE_INACTIVE;
case mus::mojom::ShowState::FULLSCREEN:
return ui::SHOW_STATE_FULLSCREEN;
case mus::mojom::ShowState::DOCKED:
return ui::SHOW_STATE_DOCKED;
default:
break;
}
return ui::SHOW_STATE_DEFAULT;
}
mus::mojom::ShowState MojomWindowShowStateFromUI(ui::WindowShowState state) {
switch (state) {
case ui::SHOW_STATE_DEFAULT:
return mus::mojom::ShowState::DEFAULT;
case ui::SHOW_STATE_NORMAL:
return mus::mojom::ShowState::NORMAL;
case ui::SHOW_STATE_MINIMIZED:
return mus::mojom::ShowState::MINIMIZED;
case ui::SHOW_STATE_MAXIMIZED:
return mus::mojom::ShowState::MAXIMIZED;
case ui::SHOW_STATE_INACTIVE:
return mus::mojom::ShowState::INACTIVE;
case ui::SHOW_STATE_FULLSCREEN:
return mus::mojom::ShowState::FULLSCREEN;
case ui::SHOW_STATE_DOCKED:
return mus::mojom::ShowState::DOCKED;
default:
break;
}
return mus::mojom::ShowState::DEFAULT;
}
} // namespace
WmWindowMus::WmWindowMus(mus::Window* window)
: window_(window),
// Matches aura, see aura::Window for details.
observers_(
base::ObserverList<ash::wm::WmWindowObserver>::NOTIFY_EXISTING_ONLY) {
window_->AddObserver(this);
window_->SetLocalProperty(kWmWindowKey, this);
window_state_.reset(new WindowStateMus(this));
}
WmWindowMus::~WmWindowMus() {
window_->RemoveObserver(this);
}
// static
WmWindowMus* WmWindowMus::Get(mus::Window* window) {
if (!window)
return nullptr;
wm::WmWindowMus* wm_window = window->GetLocalProperty(kWmWindowKey);
if (wm_window)
return wm_window;
// WmWindowMus is owned by the mus::Window.
return new WmWindowMus(window);
}
// static
WmWindowMus* WmWindowMus::Get(views::Widget* widget) {
return WmWindowMus::Get(aura::GetMusWindow(widget->GetNativeView()));
}
// static
const mus::Window* WmWindowMus::GetMusWindow(
const ash::wm::WmWindow* wm_window) {
return static_cast<const WmWindowMus*>(wm_window)->mus_window();
}
// static
std::vector<ash::wm::WmWindow*> WmWindowMus::FromMusWindows(
const std::vector<mus::Window*>& mus_windows) {
std::vector<ash::wm::WmWindow*> result(mus_windows.size());
for (size_t i = 0; i < mus_windows.size(); ++i)
result[i] = Get(mus_windows[i]);
return result;
}
const WmRootWindowControllerMus* WmWindowMus::GetRootWindowControllerMus()
const {
return WmRootWindowControllerMus::Get(window_->GetRoot());
}
const ash::wm::WmWindow* WmWindowMus::GetRootWindow() const {
return Get(window_->GetRoot());
}
ash::wm::WmRootWindowController* WmWindowMus::GetRootWindowController() {
return GetRootWindowControllerMus();
}
ash::wm::WmGlobals* WmWindowMus::GetGlobals() const {
return WmGlobalsMus::Get();
}
void WmWindowMus::SetShellWindowId(int id) {
shell_window_id_ = id;
}
int WmWindowMus::GetShellWindowId() const {
return shell_window_id_;
}
ui::wm::WindowType WmWindowMus::GetType() const {
return GetWmWindowType(window_);
}
ui::Layer* WmWindowMus::GetLayer() {
// TODO(sky): this function should be nuked entirely.
NOTIMPLEMENTED();
return widget_ ? widget_->GetLayer() : nullptr;
}
display::Display WmWindowMus::GetDisplayNearestWindow() {
// TODO(sky): deal with null rwc.
return GetRootWindowControllerMus()->GetDisplay();
}
bool WmWindowMus::HasNonClientArea() {
return widget_ ? true : false;
}
int WmWindowMus::GetNonClientComponent(const gfx::Point& location) {
return widget_ ? widget_->GetNonClientComponent(location) : HTNOWHERE;
}
gfx::Point WmWindowMus::ConvertPointToTarget(const WmWindow* target,
const gfx::Point& point) const {
const mus::Window* target_window = GetMusWindow(target);
if (target_window->Contains(window_)) {
gfx::Point result(point);
const mus::Window* window = window_;
while (window != target_window) {
result += window->bounds().origin().OffsetFromOrigin();
window = window->parent();
}
return result;
}
if (window_->Contains(target_window)) {
gfx::Point result(point);
result -=
target->ConvertPointToTarget(this, gfx::Point()).OffsetFromOrigin();
return result;
}
// Different roots.
gfx::Point point_in_screen =
GetRootWindowControllerMus()->ConvertPointToScreen(this, point);
return AsWmWindowMus(target)
->GetRootWindowControllerMus()
->ConvertPointFromScreen(AsWmWindowMus(target), point_in_screen);
}
gfx::Point WmWindowMus::ConvertPointToScreen(const gfx::Point& point) const {
return GetRootWindowControllerMus()->ConvertPointToScreen(this, point);
}
gfx::Point WmWindowMus::ConvertPointFromScreen(const gfx::Point& point) const {
return GetRootWindowControllerMus()->ConvertPointFromScreen(this, point);
}
gfx::Rect WmWindowMus::ConvertRectToScreen(const gfx::Rect& rect) const {
return gfx::Rect(ConvertPointToScreen(rect.origin()), rect.size());
}
gfx::Rect WmWindowMus::ConvertRectFromScreen(const gfx::Rect& rect) const {
return gfx::Rect(ConvertPointFromScreen(rect.origin()), rect.size());
}
gfx::Size WmWindowMus::GetMinimumSize() const {
return widget_ ? widget_->GetMinimumSize() : gfx::Size();
}
gfx::Size WmWindowMus::GetMaximumSize() const {
return widget_ ? widget_->GetMaximumSize() : gfx::Size();
}
bool WmWindowMus::GetTargetVisibility() const {
NOTIMPLEMENTED();
return window_->visible();
}
bool WmWindowMus::IsVisible() const {
return window_->visible();
}
bool WmWindowMus::IsSystemModal() const {
NOTIMPLEMENTED();
return false;
}
bool WmWindowMus::GetBoolProperty(ash::wm::WmWindowProperty key) {
switch (key) {
case ash::wm::WmWindowProperty::SNAP_CHILDREN_TO_PIXEL_BOUDARY:
NOTIMPLEMENTED();
return true;
case ash::wm::WmWindowProperty::ALWAYS_ON_TOP:
return IsAlwaysOnTop();
default:
NOTREACHED();
break;
}
NOTREACHED();
return false;
}
int WmWindowMus::GetIntProperty(ash::wm::WmWindowProperty key) {
if (key == ash::wm::WmWindowProperty::SHELF_ID) {
NOTIMPLEMENTED();
return 0;
}
NOTREACHED();
return 0;
}
const ash::wm::WindowState* WmWindowMus::GetWindowState() const {
return window_state_.get();
}
ash::wm::WmWindow* WmWindowMus::GetToplevelWindow() {
return WmGlobalsMus::GetToplevelAncestor(window_);
}
void WmWindowMus::SetParentUsingContext(WmWindow* context,
const gfx::Rect& screen_bounds) {
GetDefaultParent(context, this, screen_bounds)->AddChild(this);
}
void WmWindowMus::AddChild(WmWindow* window) {
window_->AddChild(GetMusWindow(window));
}
ash::wm::WmWindow* WmWindowMus::GetParent() {
return Get(window_->parent());
}
const ash::wm::WmWindow* WmWindowMus::GetTransientParent() const {
return Get(window_->transient_parent());
}
std::vector<ash::wm::WmWindow*> WmWindowMus::GetTransientChildren() {
return FromMusWindows(window_->transient_children());
}
void WmWindowMus::SetLayoutManager(
std::unique_ptr<ash::wm::WmLayoutManager> layout_manager) {
if (layout_manager) {
layout_manager_adapter_.reset(
new MusLayoutManagerAdapter(window_, std::move(layout_manager)));
} else {
layout_manager_adapter_.reset();
}
}
ash::wm::WmLayoutManager* WmWindowMus::GetLayoutManager() {
return layout_manager_adapter_ ? layout_manager_adapter_->layout_manager()
: nullptr;
}
void WmWindowMus::SetVisibilityAnimationType(int type) {
NOTIMPLEMENTED();
}
void WmWindowMus::SetVisibilityAnimationDuration(base::TimeDelta delta) {
NOTIMPLEMENTED();
}
void WmWindowMus::Animate(::wm::WindowAnimationType type) {
NOTIMPLEMENTED();
}
void WmWindowMus::SetBounds(const gfx::Rect& bounds) {
if (window_->parent()) {
WmWindowMus* parent = WmWindowMus::Get(window_->parent());
if (parent->layout_manager_adapter_) {
parent->layout_manager_adapter_->layout_manager()->SetChildBounds(this,
bounds);
return;
}
}
SetBoundsDirect(bounds);
}
void WmWindowMus::SetBoundsWithTransitionDelay(const gfx::Rect& bounds,
base::TimeDelta delta) {
NOTIMPLEMENTED();
SetBounds(bounds);
}
void WmWindowMus::SetBoundsDirect(const gfx::Rect& bounds) {
window_->SetBounds(bounds);
SnapToPixelBoundaryIfNecessary();
}
void WmWindowMus::SetBoundsDirectAnimated(const gfx::Rect& bounds) {
NOTIMPLEMENTED();
SetBoundsDirect(bounds);
}
void WmWindowMus::SetBoundsDirectCrossFade(const gfx::Rect& bounds) {
NOTIMPLEMENTED();
SetBoundsDirect(bounds);
}
void WmWindowMus::SetBoundsInScreen(const gfx::Rect& bounds_in_screen,
const display::Display& dst_display) {
// TODO(sky): need to find WmRootWindowControllerMus for dst_display and
// convert.
NOTIMPLEMENTED();
SetBounds(ConvertRectFromScreen(bounds_in_screen));
}
gfx::Rect WmWindowMus::GetBoundsInScreen() const {
return ConvertRectToScreen(gfx::Rect(window_->bounds().size()));
}
const gfx::Rect& WmWindowMus::GetBounds() const {
return window_->bounds();
}
gfx::Rect WmWindowMus::GetTargetBounds() {
NOTIMPLEMENTED();
return window_->bounds();
}
void WmWindowMus::ClearRestoreBounds() {
restore_bounds_in_screen_.reset();
}
void WmWindowMus::SetRestoreBoundsInScreen(const gfx::Rect& bounds) {
restore_bounds_in_screen_.reset(new gfx::Rect(bounds));
}
gfx::Rect WmWindowMus::GetRestoreBoundsInScreen() const {
return *restore_bounds_in_screen_;
}
bool WmWindowMus::Contains(const ash::wm::WmWindow* other) const {
return other
? window_->Contains(
static_cast<const WmWindowMus*>(other)->window_)
: false;
}
void WmWindowMus::SetShowState(ui::WindowShowState show_state) {
SetWindowShowState(window_, MojomWindowShowStateFromUI(show_state));
}
ui::WindowShowState WmWindowMus::GetShowState() const {
return UIWindowShowStateFromMojom(GetWindowShowState(window_));
}
void WmWindowMus::SetRestoreShowState(ui::WindowShowState show_state) {
restore_show_state_ = show_state;
}
void WmWindowMus::SetLockedToRoot(bool value) {
// TODO(sky): there is no getter for this. Investigate where used.
NOTIMPLEMENTED();
}
void WmWindowMus::SetCapture() {
window_->SetCapture();
}
bool WmWindowMus::HasCapture() {
return window_->HasCapture();
}
void WmWindowMus::ReleaseCapture() {
window_->ReleaseCapture();
}
bool WmWindowMus::HasRestoreBounds() const {
return restore_bounds_in_screen_.get() != nullptr;
}
bool WmWindowMus::CanMaximize() const {
return widget_ ? widget_->widget_delegate()->CanMaximize() : false;
}
bool WmWindowMus::CanMinimize() const {
return widget_ ? widget_->widget_delegate()->CanMinimize() : false;
}
bool WmWindowMus::CanResize() const {
return widget_ ? widget_->widget_delegate()->CanResize() : false;
}
bool WmWindowMus::CanActivate() const {
// TODO(sky): this isn't quite right. Should key off CanFocus(), which is not
// replicated.
return widget_ != nullptr;
}
void WmWindowMus::StackChildAtTop(ash::wm::WmWindow* child) {
GetMusWindow(child)->MoveToFront();
}
void WmWindowMus::StackChildAtBottom(ash::wm::WmWindow* child) {
GetMusWindow(child)->MoveToBack();
}
void WmWindowMus::StackChildAbove(ash::wm::WmWindow* child,
ash::wm::WmWindow* target) {
GetMusWindow(child)->Reorder(GetMusWindow(target),
mus::mojom::OrderDirection::ABOVE);
}
void WmWindowMus::StackChildBelow(WmWindow* child, WmWindow* target) {
GetMusWindow(child)->Reorder(GetMusWindow(target),
mus::mojom::OrderDirection::BELOW);
}
void WmWindowMus::SetAlwaysOnTop(bool value) {
mash::wm::SetAlwaysOnTop(window_, value);
}
bool WmWindowMus::IsAlwaysOnTop() const {
return mash::wm::IsAlwaysOnTop(window_);
}
void WmWindowMus::Hide() {
window_->SetVisible(false);
}
void WmWindowMus::Show() {
window_->SetVisible(true);
}
bool WmWindowMus::IsFocused() const {
return window_->HasFocus();
}
bool WmWindowMus::IsActive() const {
mus::Window* focused = window_->connection()->GetFocusedWindow();
return focused && window_->Contains(focused);
}
void WmWindowMus::Activate() {
window_->SetFocus();
ash::wm::WmWindow* top_level = GetToplevelWindow();
if (!top_level)
return;
// TODO(sky): mus should do this too.
GetMusWindow(top_level)->MoveToFront();
}
void WmWindowMus::Deactivate() {
if (IsActive())
window_->connection()->ClearFocus();
}
void WmWindowMus::SetFullscreen() {
SetWindowShowState(window_, mus::mojom::ShowState::FULLSCREEN);
}
void WmWindowMus::Maximize() {
SetWindowShowState(window_, mus::mojom::ShowState::MAXIMIZED);
}
void WmWindowMus::Minimize() {
SetWindowShowState(window_, mus::mojom::ShowState::MINIMIZED);
}
void WmWindowMus::Unminimize() {
SetWindowShowState(window_, MojomWindowShowStateFromUI(restore_show_state_));
restore_show_state_ = ui::SHOW_STATE_DEFAULT;
}
std::vector<ash::wm::WmWindow*> WmWindowMus::GetChildren() {
return FromMusWindows(window_->children());
}
ash::wm::WmWindow* WmWindowMus::GetChildByShellWindowId(int id) {
if (id == shell_window_id_)
return this;
for (mus::Window* child : window_->children()) {
ash::wm::WmWindow* result = Get(child)->GetChildByShellWindowId(id);
if (result)
return result;
}
return nullptr;
}
void WmWindowMus::SnapToPixelBoundaryIfNecessary() {
NOTIMPLEMENTED();
}
void WmWindowMus::AddObserver(ash::wm::WmWindowObserver* observer) {
observers_.AddObserver(observer);
}
void WmWindowMus::RemoveObserver(ash::wm::WmWindowObserver* observer) {
observers_.RemoveObserver(observer);
}
void WmWindowMus::OnTreeChanged(const TreeChangeParams& params) {
ash::wm::WmWindowObserver::TreeChangeParams wm_params;
wm_params.target = Get(params.target);
wm_params.new_parent = Get(params.new_parent);
wm_params.old_parent = Get(params.old_parent);
FOR_EACH_OBSERVER(ash::wm::WmWindowObserver, observers_,
OnWindowTreeChanged(this, wm_params));
}
void WmWindowMus::OnWindowReordered(mus::Window* window,
mus::Window* relative_window,
mus::mojom::OrderDirection direction) {
FOR_EACH_OBSERVER(ash::wm::WmWindowObserver, observers_,
OnWindowStackingChanged(this));
}
void WmWindowMus::OnWindowSharedPropertyChanged(
mus::Window* window,
const std::string& name,
const std::vector<uint8_t>* old_data,
const std::vector<uint8_t>* new_data) {
if (name == mus::mojom::WindowManager::kShowState_Property) {
GetWindowState()->OnWindowShowStateChanged();
}
if (name == mus::mojom::WindowManager::kAlwaysOnTop_Property) {
FOR_EACH_OBSERVER(ash::wm::WmWindowObserver, observers_,
OnWindowPropertyChanged(
this, ash::wm::WmWindowProperty::ALWAYS_ON_TOP, 0u));
return;
}
// Deal with snap to pixel.
NOTIMPLEMENTED();
}
void WmWindowMus::OnWindowBoundsChanged(mus::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
FOR_EACH_OBSERVER(ash::wm::WmWindowObserver, observers_,
OnWindowBoundsChanged(this, old_bounds, new_bounds));
}
void WmWindowMus::OnWindowDestroying(mus::Window* window) {
FOR_EACH_OBSERVER(ash::wm::WmWindowObserver, observers_,
OnWindowDestroying(this));
}
} // namespace wm
} // namespace mash
| 29 | 80 | 0.704266 | [
"vector"
] |
da8feca8fbce7724e1fcd8314d05b800f7562425 | 19,921 | cpp | C++ | wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 6 | 2017-05-26T21:19:41.000Z | 2021-09-03T14:17:29.000Z | wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 5 | 2016-02-18T12:39:58.000Z | 2016-03-13T12:57:45.000Z | wbsModels/LaricobiusNigrinus/LaricobiusNigrinusModel.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 1 | 2019-06-16T02:49:20.000Z | 2019-06-16T02:49:20.000Z | //***********************************************************
// 07/03/2019 1.0.0 Rémi Saint-Amant Creation
//***********************************************************
#include "LaricobiusNigrinusModel.h"
#include "ModelBase/EntryPoint.h"
#include "Basic\DegreeDays.h"
#include <boost/math/distributions/weibull.hpp>
#include <boost/math/distributions/beta.hpp>
#include <boost/math/distributions/Rayleigh.hpp>
#include <boost/math/distributions/logistic.hpp>
#include <boost/math/distributions/exponential.hpp>
using namespace WBSF::HOURLY_DATA;
using namespace WBSF::LNF;
using namespace std;
//static const bool BEGIN_NOVEMBER = false;
//static const size_t FIRST_Y = BEGIN_NOVEMBER ? 1 : 0;
namespace WBSF
{
static const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::MODIFIED_ALLEN_WAVE;
enum { ACTUAL_CDD, DATE_DD717, DIFF_DAY, NB_OUTPUTS };
//this line link this model with the EntryPoint of the DLL
static const bool bRegistred =
CModelFactory::RegisterModel(CLaricobiusNigrinusModel::CreateObject);
CLaricobiusNigrinusModel::CLaricobiusNigrinusModel()
{
//NB_INPUT_PARAMETER is used to determine if the dll
//uses the same number of parameters than the model interface
NB_INPUT_PARAMETER = -1;
VERSION = "1.0.2 (2020)";
// m_start = CTRef(YEAR_NOT_INIT, JANUARY, DAY_01);
// m_threshold = 5.6;
//m_sumDD = 540;
m_bCumul = false;
for (size_t s = 0; s < NB_STAGES; s++)
{
for (size_t p = 0; p < NB_RDR_PARAMS; p++)
{
m_RDR[s][p] = CLaricobiusNigrinusEquations::RDR[s][p];
}
}
for (size_t p = 0; p < NB_OVP_PARAMS; p++)
m_OVP[p] = CLaricobiusNigrinusEquations::OVP[p];
for (size_t p = 0; p < NB_ADE_PARAMS; p++)
m_ADE[p] = CLaricobiusNigrinusEquations::ADE[p];
for (size_t p = 0; p < NB_EAS_PARAMS; p++)
m_EAS[p] = CLaricobiusNigrinusEquations::EAS[p];
}
CLaricobiusNigrinusModel::~CLaricobiusNigrinusModel()
{
}
//this method is call to load your parameter in your variable
ERMsg CLaricobiusNigrinusModel::ProcessParameters(const CParameterVector& parameters)
{
ERMsg msg;
size_t c = 0;
m_bCumul = parameters[c++].GetBool();
if (parameters.size() == 1 + NB_STAGES * NB_RDR_PARAMS + NB_OVP_PARAMS + NB_ADE_PARAMS + NB_EAS_PARAMS)
{
for (size_t s = 0; s < NB_STAGES; s++)
{
for (size_t p = 0; p < NB_RDR_PARAMS; p++)
{
m_RDR[s][p] = parameters[c++].GetFloat();
}
}
for (size_t p = 0; p < NB_OVP_PARAMS; p++)
m_OVP[p] = parameters[c++].GetFloat();
for (size_t p = 0; p < NB_ADE_PARAMS; p++)
m_ADE[p] = parameters[c++].GetFloat();
for (size_t p = 0; p < NB_EAS_PARAMS; p++)
m_EAS[p] = parameters[c++].GetFloat();
}
return msg;
}
/*ERMsg CLaricobiusNigrinusModel::OnExecuteAnnual()
{
_ASSERTE(m_weather.size() > 1);
ERMsg msg;
CTRef today = CTRef::GetCurrentTRef();
CTPeriod outputPeriod = m_weather.GetEntireTPeriod(CTM::ANNUAL);
m_output.Init(outputPeriod, NB_OUTPUTS);
for (size_t y = 0; y < m_weather.GetNbYears(); y++)
{
int year = m_weather[y].GetTRef().GetYear();
CTRef begin = CTRef(year, m_start.GetMonth(), m_start.GetDay());
CTRef end = CTRef(year, DECEMBER, DAY_31);
double CDD = 0;
CTRef day717;
double actualCDD = -999;
CDegreeDays DD(DD_METHOD, m_threshold);
for (CTRef d = begin; d < end; d++)
{
CDD += DD.GetDD(m_weather.GetDay(d));
if (CDD >= m_sumDD && !day717.IsInit())
day717 = d;
if (d.as(CTM(CTM::DAILY, CTM::OVERALL_YEARS)) == today.as(CTM(CTM::DAILY, CTM::OVERALL_YEARS)))
actualCDD = CDD;
}
m_output[y][ACTUAL_CDD] = actualCDD;
if (day717.IsInit())
{
m_output[y][DATE_DD717] = day717.GetRef();
m_output[y][DIFF_DAY] = (int)day717.GetJDay() - (int)today.GetJDay();
}
}
return msg;
}*/
//This method is called to compute the solution
ERMsg CLaricobiusNigrinusModel::OnExecuteDaily()
{
ERMsg msg;
/* if (m_weather.GetNbYears() < 2)
{
msg.ajoute("Laricobius nigrinus model need at least 2 years of data");
return msg;
}*/
if (!m_weather.IsHourly())
m_weather.ComputeHourlyVariables();
//This is where the model is actually executed
CTPeriod p = m_weather.GetEntireTPeriod(CTM(CTM::DAILY));
m_output.Init(p, NB_STATS, 0);
//we simulate 2 years at a time.
//we also manager the possibility to have only one year
for (size_t y = 0; y < m_weather.size(); y++)
{
ExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, m_output);
}
return msg;
}
void CLaricobiusNigrinusModel::ExecuteDaily(int year, const CWeatherYears& weather, CModelStatVector& output)
{
//Create stand
CLNFStand stand(this, m_OVP[Τᴴ¹], m_OVP[Τᴴ²]);
//Set parameters to equation
for (size_t s = 0; s < NB_STAGES; s++)
{
for (size_t p = 0; p < NB_RDR_PARAMS; p++)
{
stand.m_equations.m_RDR[s][p] = m_RDR[s][p];
}
}
for (size_t p = 0; p < NB_OVP_PARAMS; p++)
stand.m_equations.m_OVP[p] = m_OVP[p];
for (size_t p = 0; p < NB_ADE_PARAMS; p++)
stand.m_equations.m_ADE[p] = m_ADE[p];
for (size_t p = 0; p < NB_EAS_PARAMS; p++)
stand.m_equations.m_EAS[p] = m_EAS[p];
stand.init(year, weather);
//compute 30 days avg
//stand.ComputeTavg30(year, weather);
//Create host
CLNFHostPtr pHost(new CLNFHost(&stand));
pHost->m_nbMinObjects = 10;
pHost->m_nbMaxObjects = 1000;
pHost->Initialize<CLaricobiusNigrinus>(CInitialPopulation(CTRef(year, JANUARY, DAY_01), 0, 400, 100, -1));
//add host to stand
stand.m_host.push_front(pHost);
CTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));
//if have other year extend period to February
//ASSERT(weather[year].HavePrevious());
//if (BEGIN_NOVEMBER)
//{
// p.Begin() = CTRef(year - 1, NOVEMBER, DAY_01);
//}
//if have other year extend period to February
//if (weather[year].HavePrevious())
//p.Begin() = CTRef(year - 1, JULY, DAY_01);
//if have other year extend period to February
if (weather[year].HaveNext())
p.End() = CTRef(year + 1, JUNE, DAY_30);
for (CTRef d = p.Begin(); d <= p.End(); d++)
{
/*if (d == CTRef(year + 1, JANUARY, DAY_01))
{
int gg;
gg=0;
}*/
stand.Live(weather.GetDay(d));
if (output.IsInside(d))
stand.GetStat(d, output[d]);
stand.AdjustPopulation();
HxGridTestConnection();
}
if (m_bCumul)
{
//cumulative result
for (size_t s = S_EGG; s < S_ACTIVE_ADULT; s++)
{
CTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));
CStatistic stat = output.GetStat(s, p);
if (stat.IsInit() && stat[SUM] > 0)
{
output[0][s] = output[0][s] * 100 / stat[SUM];//when first day is not 0
for (CTRef d = p.Begin() + 1; d <= p.End(); d++)
{
output[d][s] = output[d - 1][s] + output[d][s] * 100 / stat[SUM];
_ASSERTE(!_isnan(output[d][s]));
}
}
}
/*for (size_t s = S_M_EGG; s <= S_M_DEAD_ADULT; s++)
{
CTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));
if (s >= S_M_ACTIVE_ADULT)
{
p.Begin() = CTRef(year, JULY, DAY_01);
if (weather[year].HaveNext())
p.End() = CTRef(year + 1, JUNE, DAY_30);
}
CStatistic stat = output.GetStat(s, p);
if (stat.IsInit() && stat[SUM] > 0)
{
for (CTRef d = p.Begin() + 1; d <= p.End(); d++)
{
if(output.IsInside(d))
output[d][s] = output[d - 1][s] + output[d][s] * 100 / stat[SUM];
_ASSERTE(!_isnan(output[d][s]));
}
}
}*/
}
}
void CLaricobiusNigrinusModel::AddDailyResult(const StringVector& header, const StringVector& data)
{
ASSERT(data.size() == 5);
CSAResult obs;
//if (data[0] != "BlacksburgLab" && data[0] != "VictoriaLab")
//if (data[0] != "VictoriaLab")
//{
CStatistic egg_creation_date;
obs.m_ref.FromFormatedString(data[1]);
obs.m_obs.resize(NB_INPUTS);
for (size_t i = 0; i < NB_INPUTS; i++)
{
obs.m_obs[i] = stod(data[i + 2]);
if (i == 0 && obs.m_obs[i] > -999)
m_egg_creation_date[data[0] + "_" + to_string(obs.m_ref.GetYear())] += obs.m_ref.GetJDay();
//if (i == 1 && obs.m_obs[i] <= -999 && stod(data[i + 5]) > -999)
//obs.m_obs[i] = stod(data[i + 5]);//second method
if (obs.m_obs[i] > -999)
{
m_nb_days[i] += obs.m_ref.GetJDay();
m_years[i].insert(obs.m_ref.GetYear());
}
}
m_SAResult.push_back(obs);
//}
}
double GetSimX(size_t s, CTRef TRefO, double obs, const CModelStatVector& output)
{
double x = -999;
if (obs > -999)
{
//if (obs > 0.01 && obs < 99.99)
if (obs >= 100)
obs = 99.99;//to avoid some problem of truncation
long index = output.GetFirstIndex(s, ">=", obs, 1, CTPeriod(TRefO.GetYear(), FIRST_MONTH, FIRST_DAY, TRefO.GetYear(), LAST_MONTH, LAST_DAY));
if (index >= 1)
{
double obsX1 = output.GetFirstTRef().GetJDay() + index;
double obsX2 = output.GetFirstTRef().GetJDay() + index + 1;
double obsY1 = output[index][s];
double obsY2 = output[index + 1][s];
if (obsY2 != obsY1)
{
double slope = (obsX2 - obsX1) / (obsY2 - obsY1);
double obsX = obsX1 + (obs - obsY1)*slope;
ASSERT(!_isnan(obsX) && _finite(obsX));
x = obsX;
}
}
}
return x;
}
bool CLaricobiusNigrinusModel::IsParamValid()const
{
if (m_OVP[Τᴴ¹] >= m_OVP[Τᴴ²])
return false;
bool bValid = true;
for (size_t s = 0; s <= NB_STAGES && bValid; s++)
{
if (s == EGG || s == LARVAE /*|| s == AESTIVAL_DIAPAUSE_ADULT*/)
{
CStatistic rL;
for (double Э = 0.01; Э < 0.5; Э += 0.01)
{
double r = 1.0 - log((pow(Э, m_RDR[s][Ϙ]) - 1.0) / (pow(0.5, m_RDR[s][Ϙ]) - 1.0)) / m_RDR[s][к];
if (r >= 0.4 && r <= 2.5)
rL += 1.0 / r;//reverse for comparison
}
CStatistic rH;
for (double Э = 0.51; Э < 1.0; Э += 0.01)
{
double r = 1.0 - log((pow(Э, m_RDR[s][Ϙ]) - 1.0) / (pow(0.5, m_RDR[s][Ϙ]) - 1.0)) / m_RDR[s][к];
if (r >= 0.4 && r <= 2.5)
rH += r;
}
if (rL.IsInit() && rH.IsInit())
bValid = fabs(rL[SUM] - rH[SUM]) < 5.3; //in Régnière (2012) obtain a max of 5.3
else
bValid = false;
}
}
return bValid;
}
void CLaricobiusNigrinusModel::CalibrateDiapauseEndTh(CStatisticXY& stat)
{
static const double DiapauseDuration[3][3] =
{
{128.1,127.9,134.0},
{156.7,162.2,166.2},
{194.8,203.7,-999}
};
static const double DiapauseDurationSD[3][3] =
{
{2.2,3, 3.8},
{4.1,4.4,5.4},
{4.2,3.4,10.8}
};
if (m_SAResult.size() != 8)
return;
for (size_t t = 0; t < 3; t++)
{
for (size_t dl = 0; dl < 3; dl++)
{
if (DiapauseDuration[t][dl] > -999)
{
//NbVal = 8 Bias = 0.00263 MAE = 0.95222 RMSE = 1.25691 CD = 0.99785 R² = 0.99786
//lam0 = 15.81011 { 15.80907, 15.81142} VM = { 0.00021, 0.00060 }
//lam1 = 2.50857 { 2.50779, 2.50943} VM = { 0.00021, 0.00073 }
//lam2 = 6.64395 { 6.63745, 6.64922} VM = { 0.00113, 0.00379 }
//lam3 = 7.81911 { 7.80857, 7.82666} VM = { 0.00183, 0.00492 }
//lam_a = 0.16346 { 0.16328, 0.16369} VM = { 0.00006, 0.00019 }
//lam_b = 0.26484 { 0.26458, 0.26499} VM = { 0.00007, 0.00020 }
double T = 10 + 5 * t;
double DL = 8 + dl * 4;
double DD = 120.0 + (215.0 - 120.0) * 1 / (1 + exp(-(T - m_ADE[ʎ0]) / m_ADE[ʎ1]));
double f = exp(-m_ADE[ʎa] + m_ADE[ʎb] * 1 / (1 + exp(-(DL - m_ADE[ʎ2]) / m_ADE[ʎ3])));
stat.Add(DiapauseDuration[t][dl], DD * f);
}
}
}
}
static const int ROUND_VAL = 4;
CTRef CLaricobiusNigrinusModel::GetDiapauseEnd(const CWeatherYear& weather)
{
CTPeriod p = weather.GetEntireTPeriod(CTM(CTM::DAILY));
//return p.Begin() + 253;
double sumDD = 0;
//for (CTRef TRef = p.Begin()+172; TRef <= p.End()&& TRef<= p.Begin() + int(m_ADE[ʎ0]); TRef++)
for (CTRef TRef = p.Begin() + int(m_ADE[ʎ0]-1); TRef <= p.End() && TRef <= p.Begin() + int(m_ADE[ʎ1]-1); TRef++)
{
//size_t ii = TRef - p.Begin();
const CWeatherDay& wday = m_weather.GetDay(TRef);
double T = wday[H_TNTX][MEAN];
T = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);
//T = Round(max(m_ADE[ʎa], T), ROUND_VAL);
double DD = min(0.0, T - m_ADE[ʎb]);//DD is negative
sumDD += DD;
}
//boost::math::weibull_distribution<double> begin_dist(-m_ADE[ʎ2], m_ADE[ʎ3]);
// int begin = (int)Round(m_ADE[ʎ0] + m_ADE[ʎa] * cdf(begin_dist, -sumDD), 0);
boost::math::logistic_distribution<double> begin_dist(m_ADE[ʎ2], m_ADE[ʎ3]);
int begin = (int)Round(m_ADE[ʎ1] + m_ADE[ʎa] * cdf(begin_dist, sumDD), 0);
return p.Begin() + begin;
}
void CLaricobiusNigrinusModel::CalibrateDiapauseEnd(const bitset<3>& test, CStatisticXY& stat)
{
for (size_t EVALUATE_STAGE = 0; EVALUATE_STAGE < NB_INPUTS; EVALUATE_STAGE++)
//for (size_t j = 0; j < NB_INPUTS; j++)
{
if (test[EVALUATE_STAGE])
{
if (m_OVP[Τᴴ¹] >= m_OVP[Τᴴ²])
return;
if (m_SAResult.empty())
return;
if (!m_weather.IsHourly())
m_weather.ComputeHourlyVariables();
for (size_t y = 0; y < m_weather.GetNbYears(); y++)
{
int year = m_weather[y].GetTRef().GetYear();
if (m_years[EVALUATE_STAGE].find(year) == m_years[EVALUATE_STAGE].end())
continue;
double sumDD = 0;
vector<double> CDD;
CTPeriod p;
if (EVALUATE_STAGE == I_EMERGED_ADULT)
{
p = m_weather[year].GetEntireTPeriod(CTM(CTM::DAILY));
CDD.resize(p.size(), 0);
CTRef diapauseEnd = GetDiapauseEnd(m_weather[year]);
for (CTRef TRef = diapauseEnd; TRef <= p.End(); TRef++)
{
const CWeatherDay& wday = m_weather.GetDay(TRef);
double T = wday[H_TNTX][MEAN];
T = CLaricobiusNigrinus::AdjustTLab(wday.GetWeatherStation()->m_name, NOT_INIT, wday.GetTRef(), T);
//double DD = max(0.0, T - 4.0);//DD is negative
//T = min(T, m_OVP[Τᴴ²]);
double DD = max(0.0, T - m_EAS[Τᴴ]);//DD is positive
sumDD += DD;
size_t ii = TRef - p.Begin();
CDD[ii] = sumDD;
}
}
else
{
p = m_weather[year].GetEntireTPeriod(CTM(CTM::DAILY));
//p.Begin() = GetDiapauseEnd(m_weather[year - 1]);
CDD.resize(p.size(), 0);
CDegreeDays DDModel(CDegreeDays::MODIFIED_ALLEN_WAVE, m_OVP[Τᴴ¹], m_OVP[Τᴴ²]);
for (CTRef TRef = p.Begin(); TRef <= p.End(); TRef++)
{
const CWeatherDay& wday = m_weather.GetDay(TRef);
size_t ii = TRef - p.Begin();
sumDD += DDModel.GetDD(wday);
CDD[ii] = sumDD;
}
}
for (size_t i = 0; i < m_SAResult.size(); i++)
{
size_t ii = m_SAResult[i].m_ref - p.Begin();
if (m_SAResult[i].m_ref.GetYear() == year && ii < CDD.size())
{
double obs_y = m_SAResult[i].m_obs[EVALUATE_STAGE];
if (obs_y > -999)
{
double sim_y = 0;
if (EVALUATE_STAGE == I_EMERGED_ADULT)
{
boost::math::logistic_distribution<double> emerged_dist(m_EAS[μ], m_EAS[ѕ]);
//boost::math::weibull_distribution<double> emerged_dist(m_EAS[μ], m_EAS[ѕ]);
sim_y = Round(cdf(emerged_dist, CDD[ii]) * 100, ROUND_VAL);
}
else
{
boost::math::logistic_distribution<double> create_dist(m_OVP[μ], m_OVP[ѕ]);
//boost::math::weibull_distribution<double> create_dist(m_OVP[μ], m_OVP[ѕ]);
sim_y = Round(cdf(create_dist, CDD[ii]) * 100, ROUND_VAL);
}
if (sim_y < 0.1)
sim_y = 0;
if (sim_y > 99.9)
sim_y = 100;
stat.Add(obs_y, sim_y);
}
}
}
}//for all years
}//if
}//for
return;
}
void CLaricobiusNigrinusModel::CalibrateOviposition(CStatisticXY& stat)
{
if (m_SAResult.empty())
return;
for (size_t y = 0; y < m_weather.GetNbYears(); y++)
{
int year = m_weather[y].GetTRef().GetYear();
string key = m_info.m_loc.m_ID + "_" + to_string(year);
if (m_egg_creation_date.find(key) == m_egg_creation_date.end())
continue;
//CTRef emergingBegin = GetDiapauseEnd(m_weather[year-1]);
ASSERT(m_weather[year].HavePrevious());
if (m_weather[year].HavePrevious())
{
CStatistic Tmin;
Tmin += m_weather[year - 1][NOVEMBER][H_TMIN];
Tmin += m_weather[year - 1][DECEMBER][H_TMIN];
Tmin += m_weather[year][JANUARY][H_TMIN];
Tmin += m_weather[year][FEBRUARY][H_TMIN];
CStatistic Tmean;
Tmean += m_weather[year - 1][NOVEMBER][H_TNTX];
Tmean += m_weather[year - 1][DECEMBER][H_TNTX];
Tmean += m_weather[year][JANUARY][H_TNTX];
Tmean += m_weather[year][FEBRUARY][H_TNTX];
double obs = m_egg_creation_date.at(key);
double sim = m_ADE[ʎa] - m_ADE[ʎb] * 1 / (1 + exp(-(Tmean[MEAN] - m_ADE[ʎ2]) / m_ADE[ʎ3]));
if (sim < 0.1)
sim = 0;
if (sim > 99.9)
sim = 100;
stat.Add(obs, sim);
}
}
return;
}
void CLaricobiusNigrinusModel::GetFValueDaily(CStatisticXY& stat)
{
bitset<3> test;
test.reset();
//test.set(I_EGGS);
//test.set(I_LARVAE);
test.set(I_EMERGED_ADULT);
//return CalibrateDiapauseEndTh(stat);
return CalibrateDiapauseEnd(test, stat);
//return CalibrateOviposition(stat);
if (!m_SAResult.empty())
{
if (!m_bCumul)
m_bCumul = true;//SA always cumulative
if (!m_weather.IsHourly())
m_weather.ComputeHourlyVariables();
//low and hi relative development rate must be approximatively the same
//if (!IsParamValid())
//return;
for (size_t y = 0; y < m_weather.GetNbYears(); y++)
{
int year = m_weather[y].GetTRef().GetYear();
if ((test[0] && m_years[I_EGGS].find(year) != m_years[I_EGGS].end()) ||
(test[1] && m_years[I_LARVAE].find(year) != m_years[I_LARVAE].end()) ||
(test[2] && m_years[I_EMERGED_ADULT].find(year) != m_years[I_EMERGED_ADULT].end()))
{
CModelStatVector output;
CTPeriod p = m_weather[y].GetEntireTPeriod(CTM(CTM::DAILY));
//not possible to add a second year without having problem in evaluation....
//if (m_weather[y].HaveNext())
//p.End() = m_weather[y + 1].GetEntireTPeriod(CTM(CTM::DAILY)).End();
output.Init(p, NB_STATS, 0);
ExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, output);
static const size_t STAT_STAGE[3] = { S_EGG, S_LARVAE, S_ACTIVE_ADULT };
for (size_t i = 0; i < m_SAResult.size(); i++)
{
if (output.IsInside(m_SAResult[i].m_ref))
{
for (size_t j = 0; j < NB_INPUTS; j++)
{
if (test[j])
{
double obs_y = Round(m_SAResult[i].m_obs[j], ROUND_VAL);
double sim_y = Round(output[m_SAResult[i].m_ref][STAT_STAGE[j]], ROUND_VAL);
if (obs_y > -999)
{
stat.Add(obs_y, sim_y);
double obs_x = m_SAResult[i].m_ref.GetJDay();
double sim_x = GetSimX(STAT_STAGE[j], m_SAResult[i].m_ref, obs_y, output);
/*if (sim_x > -999)
{
obs_x = Round(100 * (obs_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);
sim_x = Round(100 * (sim_x - m_nb_days[j][LOWEST]) / m_nb_days[j][RANGE],ROUND_VAL);
stat.Add(obs_x, sim_x);
}*/
}
}
}
}
}//for all results
}//have data
}
}
}
}
| 26.561333 | 145 | 0.57472 | [
"vector",
"model"
] |
da9db09aee33d5de9077420cf1f23ed1ac937820 | 14,078 | cpp | C++ | ThreadManager/mainwindow.cpp | gusenov/task-manager-qt | 373df4371222d09a73752668a14e785e4109e2c4 | [
"MIT"
] | 3 | 2020-07-21T14:46:13.000Z | 2021-12-25T22:05:33.000Z | ThreadManager/mainwindow.cpp | gusenov/task-manager-qt | 373df4371222d09a73752668a14e785e4109e2c4 | [
"MIT"
] | null | null | null | ThreadManager/mainwindow.cpp | gusenov/task-manager-qt | 373df4371222d09a73752668a14e785e4109e2c4 | [
"MIT"
] | 1 | 2021-05-22T14:59:17.000Z | 2021-05-22T14:59:17.000Z | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
// Конструктор:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), // вызов родительского конструктора.
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Отключение кнопки для разворачивания окна
// и возможности менять размеры окна:
setFixedSize(width(), height());
// Создание модели данных для таблицы с процессами:
processesTableModel = new ProcessesTableModel();
// Настройка таблицы с процессами:
setupTable(ui->processesTableView, processesTableModel);
// Обработка события выделения строки в таблице процессов:
connect(
ui->processesTableView->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(processSelectionChangedSlot(const QItemSelection&, const QItemSelection&))
);
// Создание модели данных для таблицы с потоками:
threadsTableModel = new ThreadsTableModel();
threadsProxyModel = new PidFilterProxyModel();
threadsProxyModel->setSourceModel(threadsTableModel);
// Настройка таблицы с потоками:
setupTable(ui->threadsTableView, threadsProxyModel);
// Обработка события выделения строки в таблице потоков:
connect(
ui->threadsTableView->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(threadSelectionChangedSlot(const QItemSelection&, const QItemSelection&))
);
// Настройка статусной строки:
statusBarContainer = new QWidget();
statusBarLayout = new QHBoxLayout();
// Текстовая метка "Время ядра ЦП: # с":
cpuKernelTime = new QLabel();
statusBarLayout->addWidget(cpuKernelTime);
statusBarLayout->addSpacing(10);
// Текстовая метка "Время пользователя ЦП: # с":
cpuUserTime = new QLabel();
statusBarLayout->addWidget(cpuUserTime);
statusBarLayout->addSpacing(10);
statusBarLayout->setContentsMargins(0, 0, 0, 0);
statusBarContainer->setLayout(this->statusBarLayout);
ui->statusBar->addWidget(this->statusBarContainer);
createProcessesChart();
processesChartView->setChart(processesChart);
createThreadsChart();
threadsChartView->setChart(threadsChart);
if (ui->processesTableView->model()->rowCount() > 0)
ui->processesTableView->selectRow(0);
InitializeCriticalSection(&CrSectionUpd);
QObject::connect(&updater, SIGNAL(tick()),
this, SLOT(on_actionRefresh_triggered()));
updater.startUpdater();
}
// Метод для настройки внешнего вида таблиц процессов и потоков:
void MainWindow::setupTable(QTableView *tableView, QAbstractItemModel *tableModel)
{
// Установка модели данных для таблицы:
tableView->setModel(tableModel);
// Выделять целиком всю строку, а не отдельные ячейки:
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
// Подогнать ширину столбцов:
autosizeTable(tableView);
// Не выделять строку с заголовками при выделении строки с данными:
tableView->horizontalHeader()->setHighlightSections(false);
// Убрать синее выделение строки и пунктирное выделение ячейки:
tableView->setFocusPolicy(Qt::NoFocus);
// Сделать возможным выделение только одной строки, а не многих:
tableView->setSelectionMode(QAbstractItemView::SingleSelection);
}
// Подогнать ширину столбцов:
void MainWindow::autosizeTable(QTableView *tableView)
{
tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}
// Деструктор:
MainWindow::~MainWindow()
{
// Удаление из памяти пользовательского интерфейса:
delete ui;
// Удаление из памяти фильтрующей модели данных для таблицы потоков:
delete threadsProxyModel;
// Удаление из памяти модели данных для таблицы потоков:
delete threadsTableModel;
// Удаление из памяти модели данных для таблицы процессов:
delete processesTableModel;
destroyProcessesChart();
DeleteCriticalSection(&CrSectionUpd);
}
// Метод, который вызывается при выделении строки в таблице с процессами:
void MainWindow::processSelectionChangedSlot(const QItemSelection &newSelection, const QItemSelection &oldSelection)
{
Q_UNUSED(oldSelection);
QModelIndexList rowIndexes = newSelection.indexes();
if (rowIndexes.size() > 0)
{
// Индекс выделенной строки в таблице процессов:
int rowIndex = rowIndexes.first().row();
// ИД процесса:
lastSelectedPid = processesTableModel->getPidByRowIndex(rowIndex);
// Отображаем в таблице потоков только потоки принадлежащие выделенному процессу:
threadsProxyModel->setPidFilter(QString("%1").arg(lastSelectedPid));
for (int i = 0; i < threadsProxyModel->rowCount(); i++)
{
if (lastSelectedTid == threadsProxyModel->data(threadsProxyModel->index(i, 1)).toInt())
{
ui->threadsTableView->selectRow(i);
break;
}
}
foreach (QAbstractSeries* item, processesChart->series())
{
processesChart->removeSeries(item);
}
QtCharts::QLineSeries *series = processesTableModel->getMemSeriesForPid(lastSelectedPid);
// foreach (QAbstractAxis* item, processesChart->axes())
// {
// series->detachAxis(item);
// }
processesChart->addSeries(series);
series->attachAxis(processesAxisTime);
series->attachAxis(processesAxisMemory);
series = processesTableModel->getThreadCountSeriesForPid(lastSelectedPid);
// foreach (QAbstractAxis* item, processesChart->axes())
// {
// series->detachAxis(item);
// }
processesChart->addSeries(series);
series->attachAxis(processesAxisTime);
series->attachAxis(processesAxisThreadsCount);
processesAxisTime->setRange(processesTableModel->getMinTimeForPid(lastSelectedPid), QDateTime::currentDateTime());
processesAxisMemory->setRange(0, processesTableModel->getMaxMemForPid(lastSelectedPid) * 2);
processesAxisThreadsCount->setRange(0, processesTableModel->getMaxThreadCountForPid(lastSelectedPid) * 1.1);
processesChartView->invalidateScene();
foreach (QAbstractSeries* item, threadsChart->series())
threadsChart->removeSeries(item);
QStackedBarSeries* threadsSeries = threadsTableModel->getStackedBarSeriesForPid(lastSelectedPid);
threadsChart->addSeries(threadsSeries);
threadsAxisX->clear();
threadsAxisX->append(*threadsTableModel->getCategoriesForPid(lastSelectedPid));
// foreach (QAbstractAxis* item, threadsChart->axes())
// threadsChart->removeAxis(item);
threadsChart->removeAxis(threadsChart->axisX());
threadsChart->setAxisX(threadsAxisX, threadsSeries);
threadsAxisCPU->setMax(threadsTableModel->getMaxCpuTimeForPid(lastSelectedPid));
}
// Очистка статусной строки:
cpuKernelTime->setText("");
cpuUserTime->setText("");
}
// Пункт меню Файл -> Завершение диспетчера:
void MainWindow::on_actionExit_triggered()
{
QApplication::quit();
}
// Пункт меню Вид -> Обновить (F5):
void MainWindow::on_actionRefresh_triggered()
{
int processesTableViewVertical = ui->processesTableView->verticalScrollBar()->value();
EnterCriticalSection(&CrSectionUpd);
// Обновляем модель данных для таблицы процессов:
processesTableModel->refreshData();
// Обновляем модель данных для таблицы потоков:
threadsTableModel->refreshData();
// Очищаем фильтрацию:
threadsProxyModel->setPidFilter("");
// Очистка статусной строки:
cpuKernelTime->setText("");
cpuUserTime->setText("");
for (int i = 0; i < processesTableModel->rowCount(); i++)
{
if (lastSelectedPid == processesTableModel->data(processesTableModel->index(i, 1)).toInt())
{
ui->processesTableView->selectRow(i);
break;
}
}
ui->processesTableView->verticalScrollBar()->setValue(processesTableViewVertical);
LeaveCriticalSection(&CrSectionUpd);
}
// Метод, который вызывается при выделении строки в таблице с потоками:
void MainWindow::threadSelectionChangedSlot(const QItemSelection &newSelection, const QItemSelection &oldSelection)
{
// Неиспользуемая переменная:
Q_UNUSED(oldSelection);
QModelIndexList rowIndexes = newSelection.indexes();
if (rowIndexes.size() > 0)
{
// Индекс выделенной строки в таблице потоков:
int rowIndex = rowIndexes.first().row();
// ИД потока:
lastSelectedTid = threadsProxyModel->data(threadsProxyModel->index(rowIndex, 1)).toInt();
//qDebug() << "TID =" << tid;
// Время проведенноё потоком в режиме ядра:
double kernelTime = threadsTableModel->getKernelTimeByTid(lastSelectedTid);
QString kernelTimeStr = QString::number(kernelTime);
cpuKernelTime->setText(QString("Время ядра ЦП: %1 с").arg(kernelTimeStr));
// Время проведенноё потоком в режиме пользователя:
double userTime = threadsTableModel->getUserTimeByTid(lastSelectedTid);
QString userTimeStr = QString::number(userTime);
cpuUserTime->setText(QString("Время пользователя ЦП: %1 с").arg(userTimeStr));
}
}
// Освободить память выделенную под диаграмму процессов:
void MainWindow::destroyProcessesChart()
{
if (processesChart)
{
foreach (QAbstractSeries* series, processesChart->series())
{
foreach (QAbstractAxis* axis, series->attachedAxes())
{
series->detachAxis(axis);
}
processesChart->removeSeries(series);
}
}
if (processesAxisTime)
{
delete processesAxisTime;
processesAxisTime = nullptr;
}
if (processesAxisMemory)
{
delete processesAxisMemory;
processesAxisMemory = nullptr;
}
if (processesAxisThreadsCount)
{
delete processesAxisThreadsCount;
processesAxisThreadsCount = nullptr;
}
if (processesChart)
{
delete processesChart;
processesChart = nullptr;
}
if (processesChartView)
{
processesChartView->setParent(nullptr);
delete processesChartView;
processesChartView = nullptr;
}
}
// Создать диаграмму процессов:
void MainWindow::createProcessesChart()
{
processesChart = new QtCharts::QChart();
processesChart->legend()->hide();
processesAxisMemory = new QValueAxis;
processesAxisMemory->setLabelFormat("%i");
processesAxisMemory->setTitleText("Память (КБ)");
processesAxisMemory->setMin(0);
processesAxisMemory->setMax(1);
processesAxisMemory->setRange(0, 1);
processesChart->addAxis(processesAxisMemory, Qt::AlignLeft);
processesAxisThreadsCount = new QValueAxis;
processesAxisThreadsCount->setLabelFormat("%i");
processesAxisThreadsCount->setTitleText("Счетчик потоков");
processesAxisThreadsCount->setMin(0);
processesAxisThreadsCount->setMax(1);
processesAxisThreadsCount->setRange(0, 1);
processesChart->addAxis(processesAxisThreadsCount, Qt::AlignRight);
processesAxisTime = new QDateTimeAxis;
processesAxisTime->setTickCount(1);
processesAxisTime->setFormat("HH:mm:ss");
processesAxisTime->setTitleText("Время в формате HH : mm : ss");
QDateTime momentInTime = QDateTime::currentDateTime();
processesAxisTime->setMin(momentInTime.addSecs(-1));
processesAxisTime->setMax(momentInTime);
processesChart->addAxis(processesAxisTime, Qt::AlignBottom);
processesChartView = new QChartView(ui->processesWidget);
//processesChartView->move(510, 50);
processesChartView->resize(500, 250);
processesChartView->setRenderHint(QPainter::Antialiasing);
processesChartView->show();
}
// Освободить память выделенную под диаграмму потоков:
void MainWindow::destroyThreadsChart()
{
if (threadsChart)
{
foreach (QAbstractSeries* series, threadsChart->series())
{
foreach (QAbstractAxis* axis, series->attachedAxes())
{
series->detachAxis(axis);
}
threadsChart->removeSeries(series);
}
}
if (threadsAxisX)
{
delete threadsAxisX;
threadsAxisX = nullptr;
}
if (threadsAxisCPU)
{
delete threadsAxisCPU;
threadsAxisCPU = nullptr;
}
if (threadsChart)
{
delete threadsChart;
threadsChart = nullptr;
}
if (threadsChartView)
{
threadsChartView->setParent(nullptr);
delete threadsChartView;
threadsChartView = nullptr;
}
}
// Создать диаграмму потоков:
void MainWindow::createThreadsChart()
{
threadsChart = new QtCharts::QChart();
threadsChart->createDefaultAxes();
threadsChart->legend()->hide();
//threadsChart->legend()->setVisible(true);
//threadsChart->legend()->setAlignment(Qt::AlignBottom);
threadsAxisX = new QBarCategoryAxis();
threadsAxisX->setLabelsAngle(-90);
threadsAxisX->setTitleText("ИД потока (TID)");
threadsAxisCPU = new QValueAxis;
threadsAxisCPU->setLabelFormat("%i");
threadsAxisCPU->setTitleText("Время ЦП (с)");
threadsAxisCPU->setMin(0);
threadsAxisCPU->setMax(1);
threadsAxisCPU->setRange(0, 1);
threadsChart->addAxis(threadsAxisCPU, Qt::AlignLeft);
threadsChartView = new QChartView(ui->threadsWidget);
threadsChartView->resize(500, 250);
threadsChartView->setRenderHint(QPainter::Antialiasing);
threadsChartView->show();
}
| 33.124706 | 123 | 0.669768 | [
"model"
] |
daa1c449fe6f1d376384b46dc22952d2baa435e7 | 4,540 | hpp | C++ | Source/AllProjects/CoreTech/CQCIR/CQCIR_BlasterPersistData.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CoreTech/CQCIR/CQCIR_BlasterPersistData.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CoreTech/CQCIR/CQCIR_BlasterPersistData.hpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCIR_BlasterPersistData.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/12/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header file for the CQCIR_PersistData.cpp file. This file
// implements the TIRBlasterPerData class. The blaster drivers don't actually
// store fully device models, which would be dumb. They just store a list
// of models that they've been configured to load, and then reload those
// models when they are loaded up by CQCServer.
//
// Some blasters may derive from this and add some more info, but this is
// what most will use.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TIRBlasterPerData
// PREFIX: orbs
// ---------------------------------------------------------------------------
class CQCIREXPORT TIRBlasterPerData : public TObject, public MStreamable
{
public :
// -------------------------------------------------------------------
// Class types
// -------------------------------------------------------------------
typedef TIRBlasterCfg::TModelCursor TBlasterCursor;
typedef TVector<TString> TModelList;
typedef TModelList::TCursor TModelCursor;
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TIRBlasterPerData();
TIRBlasterPerData
(
const TString& strMoniker
);
TIRBlasterPerData(const TIRBlasterPerData&) = default;
TIRBlasterPerData(TIRBlasterPerData&&) = default;
~TIRBlasterPerData();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TIRBlasterPerData& operator=(const TIRBlasterPerData&) = default;
TIRBlasterPerData& operator=(TIRBlasterPerData&&) = default;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid AddModel
(
const TString& strToAdd
);
TModelCursor cursModels() const;
tCIDLib::TVoid RemoveModel
(
const TString& strToRemove
);
const TString& strMoniker() const;
tCIDLib::TVoid SetModels
(
TBlasterCursor cursModels
);
protected :
// -------------------------------------------------------------------
// Protected, inherited methods
// -------------------------------------------------------------------
tCIDLib::TVoid StreamFrom
(
TBinInStream& strmToReadFrom
) final;
tCIDLib::TVoid StreamTo
(
TBinOutStream& strmToWriteTo
) const final;
private :
// -------------------------------------------------------------------
// Private data members
//
// m_colModels
// This is a list of the device models that we've been configured
// to load up. We just have to store the device model names, since
// we can use that to query these model's files from the data
// server.
//
// m_strMoniker
// The moniker of the driver which saved us. The file name is
// actual based on the driver moniker, but this is just a sanity
// check that can be checked after the file is loaded.
// -------------------------------------------------------------------
TModelList m_colModels;
TString m_strMoniker;
// -------------------------------------------------------------------
// Magic macros
// -------------------------------------------------------------------
RTTIDefs(TIRBlasterPerData,TObject)
};
#pragma CIDLIB_POPPACK
| 31.971831 | 79 | 0.432159 | [
"model"
] |
daa6081552642afc69895bc58d7192f4d8387b27 | 547 | cpp | C++ | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.cpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.cpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.cpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | #include "./Workload.hpp"
#include "EnergyManager/Utility/Exceptions/Exception.hpp"
namespace EnergyManager {
namespace Benchmarking {
namespace Workloads {
void Workload::onRun() {
for(const auto& operation : operations_) {
operation->run();
}
}
Workload::Workload(std::vector<std::shared_ptr<Operations::Operation>> operations) : operations_(std::move(operations)) {
}
void Workload::addOperation(const std::shared_ptr<Operations::Operation>& operation) {
operations_.emplace_back(operation);
}
}
}
} | 24.863636 | 124 | 0.705667 | [
"vector"
] |
dab0a0cf490b7d1a3986bb9d9a06d5a8992a6cb3 | 5,492 | hpp | C++ | fon9/crypto/CryptoTools.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 21 | 2019-01-29T14:41:46.000Z | 2022-03-11T00:22:56.000Z | fon9/crypto/CryptoTools.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | null | null | null | fon9/crypto/CryptoTools.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 9 | 2019-01-27T14:19:33.000Z | 2022-03-11T06:18:24.000Z | /// \file fon9/crypto/CryptoTools.hpp
///
/// 您應該使用 OpenSSL or Windows Bcrypt.dll
/// 這裡僅提供一些簡單的包裝, 並降低相依姓.
///
/// \author fonwinz@gmail.com
#ifndef __fon9_crypto_CryptoTools_hpp__
#define __fon9_crypto_CryptoTools_hpp__
#include "fon9/Utility.hpp"
#include "fon9/Endian.hpp"
#include "fon9/buffer/MemBlock.hpp"
namespace fon9 { namespace crypto {
template <class AlgContext>
inline void CalcHash(const void* data, size_t len, byte output[AlgContext::kOutputSize]) {
AlgContext alg;
alg.Init();
alg.Update(data, len);
alg.Final(output);
}
template <class AlgContext>
inline void HashBlockUpdate(AlgContext& alg, const void* data, size_t len) {
if (len <= 0)
return;
uint32_t bufferUsed = static_cast<uint32_t>(alg.Count_ & (alg.kBlockSize - 1));
alg.Count_ += len;
if (bufferUsed) {
uint32_t bufferFill = static_cast<uint32_t>(alg.kBlockSize - bufferUsed);
if (len >= bufferFill) {
memcpy(alg.Buffer_ + bufferUsed, data, bufferFill);
alg.Transform(alg.State_, alg.Buffer_);
if ((len -= bufferFill) <= 0)
return;
bufferUsed = 0;
data = reinterpret_cast<const byte*>(data) + bufferFill;
}
}
while (len >= alg.kBlockSize) {
alg.Transform(alg.State_, reinterpret_cast<const byte*>(data));
data = reinterpret_cast<const byte*>(data) + alg.kBlockSize;
len -= alg.kBlockSize;
}
if (len > 0)
memcpy(alg.Buffer_ + bufferUsed, data, len);
}
template <class AlgContext>
inline void HashBlockFinal(AlgContext& alg, byte output[AlgContext::kOutputSize]) {
static const byte kFinalPadding[alg.kBlockSize] = {0x80};
auto bitCount = alg.Count_ << 3;
uint32_t bufferUsed = static_cast<uint32_t>(alg.Count_ & (alg.kBlockSize - 1));
constexpr uint32_t kExpLastSize = alg.kBlockSize - sizeof(bitCount);
uint32_t padCount = static_cast<uint32_t>((bufferUsed < kExpLastSize)
? (kExpLastSize - bufferUsed)
: (alg.kBlockSize + kExpLastSize - bufferUsed));
alg.Update(kFinalPadding, padCount);
PutBigEndian(alg.Buffer_ + kExpLastSize, bitCount);
alg.Transform(alg.State_, alg.Buffer_);
for (size_t L = 0; L < alg.kStateSize; ++L) {
PutBigEndian(output, alg.State_[L]);
output += sizeof(alg.State_[L]);
}
}
//--------------------------------------------------------------------------//
template <class AlgContext>
class HmacContext {
AlgContext Alg_;
byte OuterPad_[AlgContext::kBlockSize];
public:
static_assert(AlgContext::kOutputSize <= AlgContext::kBlockSize, "HmacContext: Unsupport alg.");
enum : size_t {
kOutputSize = AlgContext::kOutputSize,
kBlockSize = AlgContext::kBlockSize,
};
void Init(const void* key, size_t keyLen) {
byte ipad[AlgContext::kBlockSize];
if (keyLen > AlgContext::kBlockSize) {
this->Alg_.Init();
this->Alg_.Update(key, keyLen);
this->Alg_.Final(ipad);
keyLen = AlgContext::kOutputSize;
}
else {
memcpy(ipad, key, keyLen);
memset(ipad + keyLen, 0x36, sizeof(ipad) - keyLen);
memcpy(this->OuterPad_, key, keyLen);
memset(this->OuterPad_ + keyLen, 0x5c, sizeof(this->OuterPad_) - keyLen);
}
for (size_t i = 0; i < keyLen; i++) {
ipad[i] ^= 0x36;
this->OuterPad_[i] ^= 0x5c;
}
this->Alg_.Init();
this->Alg_.Update(ipad, AlgContext::kBlockSize);
}
void Update(const void* data, size_t len) {
this->Alg_.Update(data, len);
}
void Final(byte output[kOutputSize]) {
this->Alg_.Final(output);
this->Alg_.Init();
this->Alg_.Update(this->OuterPad_, AlgContext::kBlockSize);
this->Alg_.Update(output, AlgContext::kOutputSize);
this->Alg_.Final(output);
}
};
template <class AlgContext>
void CalcHmac(const void *text, size_t textLen,
const void *key, size_t keyLen,
byte output[AlgContext::kOutputSize])
{
HmacContext<AlgContext> context;
context.Init(key, keyLen);
context.Update(text, textLen);
context.Final(output);
}
template <class AlgContext>
bool CalcPbkdf2(const void* pass, size_t passLen,
const void* salt, size_t saltLen,
size_t iter,
size_t outLen, void* out)
{
using Context = HmacContext<AlgContext>;
uint32_t iBlk = 1;
Context preKeyCtx;
preKeyCtx.Init(pass, passLen);
MemBlock mem{static_cast<MemBlockSize>(saltLen + sizeof(iBlk))};
byte* pFirstUpdate = mem.begin();
if (!pFirstUpdate)
return false;
memcpy(pFirstUpdate, salt, saltLen);
while (outLen > 0) {
PutBigEndian(pFirstUpdate + saltLen, iBlk);
Context hmacCtx{preKeyCtx};
hmacCtx.Update(pFirstUpdate, saltLen + sizeof(iBlk));
byte digtmp[1024];
hmacCtx.Final(digtmp);
size_t cplen = (outLen > AlgContext::kOutputSize ? AlgContext::kOutputSize : outLen);
memcpy(out, digtmp, cplen);
for (size_t i = 1; i < iter; ++i) {
hmacCtx = preKeyCtx;
hmacCtx.Update(digtmp, AlgContext::kOutputSize);
hmacCtx.Final(digtmp);
for (size_t k = 0; k < cplen; ++k)
reinterpret_cast<byte*>(out)[k] ^= digtmp[k];
}
++iBlk;
outLen -= cplen;
out = reinterpret_cast<byte*>(out) + cplen;
}
return true;
}
} } // namespaces
#endif//__fon9_crypto_CryptoTools_hpp__
| 32.497041 | 99 | 0.624181 | [
"transform"
] |
dab380b8b913f4451827b2f5391f81c300e6ec36 | 5,326 | tpp | C++ | core/src/quadrature/tensor_product.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | core/src/quadrature/tensor_product.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | core/src/quadrature/tensor_product.tpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #include "quadrature/tensor_product.h"
#include "utility/math_utility.h"
namespace Quadrature
{
template<unsigned int D, typename Quadrature>
constexpr int TensorProductBase<D,Quadrature>::
numberEvaluations()
{
// compile-time power function
return MathUtility::powConst(Quadrature::numberEvaluations(),D);
}
// 1D sampling points
template<typename Quadrature>
std::array<std::array<double,1>,TensorProductBase<1,Quadrature>::numberEvaluations()> TensorProduct<1,Quadrature>::
samplingPoints()
{
std::array<std::array<double,1>,TensorProductBase<1,Quadrature>::numberEvaluations()> samplingPoints;
std::array<double, Quadrature::numberEvaluations()> samplingPoints1D = Quadrature::samplingPoints();
for (int x=0; x<Quadrature::numberEvaluations(); x++)
{
samplingPoints[x][0] = samplingPoints1D[x];
}
return samplingPoints;
}
// 2D sampling points
template<typename Quadrature>
std::array<Vec2,TensorProductBase<2,Quadrature>::numberEvaluations()> TensorProduct<2,Quadrature>::
samplingPoints()
{
std::array<Vec2,TensorProductBase<2,Quadrature>::numberEvaluations()> samplingPoints;
std::array<double, Quadrature::numberEvaluations()> samplingPoints1D = Quadrature::samplingPoints();
int samplingPointNo = 0;
for (int j = 0; j < Quadrature::numberEvaluations(); j++)
{
for (int i = 0; i < Quadrature::numberEvaluations(); i++, samplingPointNo++)
{
samplingPoints[samplingPointNo] = {samplingPoints1D[i], samplingPoints1D[j]}; // x y
}
}
return samplingPoints;
}
// 3D sampling points
template<typename Quadrature>
std::array<Vec3,TensorProductBase<3,Quadrature>::numberEvaluations()> TensorProduct<3,Quadrature>::
samplingPoints()
{
std::array<Vec3,TensorProductBase<3,Quadrature>::numberEvaluations()> samplingPoints;
std::array<double, Quadrature::numberEvaluations()> samplingPoints1D = Quadrature::samplingPoints();
int samplingPointNo = 0;
for (int k = 0; k < Quadrature::numberEvaluations(); k++)
{
for (int j = 0; j < Quadrature::numberEvaluations(); j++)
{
for (int i = 0; i < Quadrature::numberEvaluations(); i++, samplingPointNo++)
{
samplingPoints[samplingPointNo] = {samplingPoints1D[i], samplingPoints1D[j], samplingPoints1D[k]}; // x y z
}
}
}
return samplingPoints;
}
// 1D integration
template<typename Quadrature>
template<typename ValueType>
ValueType TensorProduct<1,Quadrature>::
computeIntegral(const std::array<ValueType, TensorProductBase<1,Quadrature>::numberEvaluations()> &evaluations)
{
return Quadrature::computeIntegral(evaluations);
}
// 2D tensor product integration
template<typename Quadrature>
template<typename ValueType>
ValueType TensorProduct<2,Quadrature>::
computeIntegral(const std::array<ValueType, TensorProductBase<2,Quadrature>::numberEvaluations()> &evaluations)
{
const std::array<double,Quadrature::numberEvaluations()> weights = Quadrature::quadratureWeights();
ValueType result{};
for (int j = 0; j < Quadrature::numberEvaluations(); j++)
{
for (int i = 0; i < Quadrature::numberEvaluations(); i++)
{
const int index = j*Quadrature::numberEvaluations() + i;
result += weights[j]*weights[i] * evaluations[index];
}
}
return result;
/*
// integrate by calling Quadrature in each direction
std::array<ValueType, Quadrature::numberEvaluations()> evaluationsY;
for (int y = 0; y < Quadrature::numberEvaluations(); y++)
{
// index of first evaluation that belongs to the list for the current y
size_t offset = y*Quadrature::numberEvaluations();
evaluationsY[y] = Quadrature::template computeIntegral<ValueType>(evaluations.begin()+offset);
}
return Quadrature::computeIntegral(evaluationsY);
*/
}
// 3D tensor product integration
template<typename Quadrature>
template<typename ValueType>
ValueType TensorProduct<3,Quadrature>::
computeIntegral(const std::array<ValueType, TensorProductBase<3,Quadrature>::numberEvaluations()> &evaluations)
{
const std::array<double,Quadrature::numberEvaluations()> weights = Quadrature::quadratureWeights();
ValueType result{};
for (int k = 0; k < Quadrature::numberEvaluations(); k++)
{
for (int j = 0; j < Quadrature::numberEvaluations(); j++)
{
for (int i = 0; i < Quadrature::numberEvaluations(); i++)
{
const int index = k*Quadrature::numberEvaluations()*Quadrature::numberEvaluations() + j*Quadrature::numberEvaluations() + i;
result += weights[k]*weights[j]*weights[i] * evaluations[index];
}
}
}
return result;
/*
// integrate by calling Quadrature in each direction
std::array<ValueType, Quadrature::numberEvaluations()> evaluationsZ;
for (int z=0; z<Quadrature::numberEvaluations(); z++)
{
std::array<ValueType, Quadrature::numberEvaluations()> evaluationsY;
for (int y=0; y<Quadrature::numberEvaluations(); y++)
{
// index of first evaluation that belongs to the list for the current y
size_t offset = y*Quadrature::numberEvaluations() + z*Quadrature::numberEvaluations()*Quadrature::numberEvaluations();
evaluationsY[y] = Quadrature::template computeIntegral<ValueType>(evaluations.begin()+offset);
}
evaluationsZ[z] = Quadrature::computeIntegral(evaluationsY);
}
return Quadrature::computeIntegral(evaluationsZ);
*/
}
} // namespace
| 34.810458 | 132 | 0.721179 | [
"3d"
] |
dab74df410eea3dc38bf095246eb830a235bd381 | 17,992 | cpp | C++ | udp_discovery_peer.cpp | truvorskameikin/udp-discovery-cpp | 9423117dbf30d4297e7601e7169e7d1ffd84f8b7 | [
"MIT"
] | 29 | 2017-01-18T14:13:16.000Z | 2022-01-19T13:08:28.000Z | udp_discovery_peer.cpp | truvorskameikin/udp-discovery-cpp | 9423117dbf30d4297e7601e7169e7d1ffd84f8b7 | [
"MIT"
] | 20 | 2017-02-16T12:40:31.000Z | 2021-11-27T20:24:43.000Z | udp_discovery_peer.cpp | truvorskameikin/udp-discovery-cpp | 9423117dbf30d4297e7601e7169e7d1ffd84f8b7 | [
"MIT"
] | 11 | 2017-04-02T01:51:11.000Z | 2021-09-02T02:46:23.000Z | #include "udp_discovery_peer.hpp"
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#include "udp_discovery_protocol.hpp"
// sockets
#if defined(_WIN32)
#define NOMINMAX
#include <winsock2.h>
#include <ws2tcpip.h>
typedef SOCKET SocketType;
typedef int AddressLenType;
const SocketType kInvalidSocket = INVALID_SOCKET;
#else
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
typedef int SocketType;
typedef socklen_t AddressLenType;
const SocketType kInvalidSocket = -1;
#endif
// time
#if defined(__APPLE__)
#include <mach/mach_time.h>
#include <stdint.h>
#endif
#if !defined(_WIN32)
#include <sys/time.h>
#endif
#include <time.h>
// threads
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <pthread.h>
#include <stdlib.h>
#endif
static void InitSockets() {
#if defined(_WIN32)
WSADATA wsa_data;
WSAStartup(MAKEWORD(2, 2), &wsa_data);
#endif
}
static void SetSocketTimeout(SocketType sock, int param, int timeout_ms) {
#if defined(_WIN32)
setsockopt(sock, SOL_SOCKET, param, (const char*)&timeout_ms,
sizeof(timeout_ms));
#else
struct timeval timeout;
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = 1000 * (timeout_ms % 1000);
setsockopt(sock, SOL_SOCKET, param, (const char*)&timeout, sizeof(timeout));
#endif
}
static void CloseSocket(SocketType sock) {
#if defined(_WIN32)
closesocket(sock);
#else
close(sock);
#endif
}
static bool IsRightTime(long last_action_time, long now_time, long timeout,
long& time_to_wait_out) {
if (last_action_time == 0) {
time_to_wait_out = timeout;
return true;
}
long time_passed = now_time - last_action_time;
if (time_passed >= timeout) {
time_to_wait_out = timeout - (time_passed - timeout);
return true;
}
time_to_wait_out = timeout - time_passed;
return false;
}
static uint32_t MakeRandomId() {
srand((unsigned int)time(0));
return (uint32_t)rand();
}
namespace udpdiscovery {
namespace impl {
long NowTime() {
#if defined(_WIN32)
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq)) {
return 0;
}
LARGE_INTEGER cur;
QueryPerformanceCounter(&cur);
return (long)(cur.QuadPart * 1000 / freq.QuadPart);
#elif defined(__APPLE__)
mach_timebase_info_data_t time_info;
mach_timebase_info(&time_info);
uint64_t cur = mach_absolute_time();
return (long)((cur / (time_info.denom * 1000000)) * time_info.numer);
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (long)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
#endif
return 0;
}
void SleepFor(long time_ms) {
#if defined(_WIN32)
Sleep((DWORD)time_ms);
#else
usleep((useconds_t)(time_ms * 1000));
#endif
}
class MinimalisticMutex {
public:
MinimalisticMutex() {
#if defined(_WIN32)
InitializeCriticalSection(&critical_section_);
#else
pthread_mutex_init(&mutex_, 0);
#endif
}
~MinimalisticMutex() {
#if defined(_WIN32)
DeleteCriticalSection(&critical_section_);
#else
pthread_mutex_destroy(&mutex_);
#endif
}
void Lock() {
#if defined(_WIN32)
EnterCriticalSection(&critical_section_);
#else
pthread_mutex_lock(&mutex_);
#endif
}
void Unlock() {
#if defined(_WIN32)
LeaveCriticalSection(&critical_section_);
#else
pthread_mutex_unlock(&mutex_);
#endif
}
private:
#if defined(_WIN32)
CRITICAL_SECTION critical_section_;
#else
pthread_mutex_t mutex_;
#endif
};
class MinimalisticThread : public MinimalisticThreadInterface {
public:
#if defined(_WIN32)
MinimalisticThread(LPTHREAD_START_ROUTINE f, void* env) : detached_(false) {
thread_ = CreateThread(NULL, 0, f, env, 0, NULL);
}
#else
MinimalisticThread(void* (*f)(void*), void* env) : detached_(false) {
pthread_create(&thread_, 0, f, env);
}
#endif
~MinimalisticThread() { detach(); }
void Detach() { detach(); }
void Join() {
if (detached_) return;
#if defined(_WIN32)
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
#else
pthread_join(thread_, 0);
#endif
detached_ = true;
}
private:
void detach() {
if (detached_) return;
#if defined(_WIN32)
CloseHandle(thread_);
#else
pthread_detach(thread_);
#endif
detached_ = true;
}
bool detached_;
#if defined(_WIN32)
HANDLE thread_;
#else
pthread_t thread_;
#endif
};
class PeerEnv : public PeerEnvInterface {
public:
PeerEnv()
: binding_sock_(kInvalidSocket),
sock_(kInvalidSocket),
packet_index_(0),
ref_count_(0),
exit_(false) {}
~PeerEnv() {
if (binding_sock_ != kInvalidSocket) {
CloseSocket(binding_sock_);
}
if (sock_ != kInvalidSocket) {
CloseSocket(sock_);
}
}
bool Start(const PeerParameters& parameters, const std::string& user_data) {
parameters_ = parameters;
user_data_ = user_data;
if (!parameters_.can_use_broadcast() && !parameters_.can_use_multicast()) {
std::cerr
<< "udpdiscovery::Peer can't use broadcast and can't use multicast."
<< std::endl;
return false;
}
if (!parameters_.can_discover() && !parameters_.can_be_discovered()) {
std::cerr << "udpdiscovery::Peer can't discover and can't be discovered."
<< std::endl;
return false;
}
InitSockets();
peer_id_ = MakeRandomId();
sock_ = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_ == kInvalidSocket) {
std::cerr << "udpdiscovery::Peer can't create socket." << std::endl;
return false;
}
{
int value = 1;
setsockopt(sock_, SOL_SOCKET, SO_BROADCAST, (const char*)&value,
sizeof(value));
}
if (parameters_.can_discover()) {
binding_sock_ = socket(AF_INET, SOCK_DGRAM, 0);
if (binding_sock_ == kInvalidSocket) {
std::cerr << "udpdiscovery::Peer can't create binding socket."
<< std::endl;
CloseSocket(sock_);
sock_ = kInvalidSocket;
}
{
int reuse_addr = 1;
setsockopt(binding_sock_, SOL_SOCKET, SO_REUSEADDR,
(const char*)&reuse_addr, sizeof(reuse_addr));
#ifdef SO_REUSEPORT
int reuse_port = 1;
setsockopt(binding_sock_, SOL_SOCKET, SO_REUSEPORT,
(const char*)&reuse_port, sizeof(reuse_port));
#endif
}
if (parameters_.can_use_multicast()) {
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr =
htonl(parameters_.multicast_group_address());
mreq.imr_interface.s_addr = INADDR_ANY;
setsockopt(binding_sock_, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(const char*)&mreq, sizeof(mreq));
}
sockaddr_in addr;
memset((char*)&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(parameters_.port());
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(binding_sock_, (struct sockaddr*)&addr, sizeof(sockaddr_in)) <
0) {
CloseSocket(binding_sock_);
binding_sock_ = kInvalidSocket;
CloseSocket(sock_);
sock_ = kInvalidSocket;
std::cerr << "udpdiscovery::Peer can't bind socket." << std::endl;
return false;
}
// TODO: Implement the way to unblock recvfrom without timeouting.
SetSocketTimeout(binding_sock_, SO_RCVTIMEO, 1000);
}
buffer_.resize(kMaxPacketSize);
return true;
}
void SetUserData(const std::string& user_data) {
lock_.Lock();
user_data_ = user_data;
lock_.Unlock();
}
std::list<DiscoveredPeer> ListDiscovered() {
std::list<DiscoveredPeer> result;
lock_.Lock();
result = discovered_peers_;
lock_.Unlock();
return result;
}
void Exit() {
lock_.Lock();
exit_ = true;
lock_.Unlock();
}
void SendingThreadFunc() {
lock_.Lock();
++ref_count_;
lock_.Unlock();
long last_send_time_ms = 0;
long last_delete_idle_ms = 0;
while (true) {
lock_.Lock();
if (exit_) {
send(/* under_lock= */ true, kPacketIAmOutOfHere);
decreaseRefCountAndMaybeDestroySelfAndUnlock();
return;
}
lock_.Unlock();
long cur_time_ms = NowTime();
long to_sleep_ms = 0;
if (parameters_.can_be_discovered()) {
if (IsRightTime(last_send_time_ms, cur_time_ms,
parameters_.send_timeout_ms(), to_sleep_ms)) {
send(/* under_lock= */ false, kPacketIAmHere);
last_send_time_ms = cur_time_ms;
}
}
if (parameters_.can_discover()) {
long to_sleep_until_next_delete_idle = 0;
if (IsRightTime(last_delete_idle_ms, cur_time_ms,
parameters_.discovered_peer_ttl_ms(),
to_sleep_until_next_delete_idle)) {
deleteIdle(cur_time_ms);
last_delete_idle_ms = cur_time_ms;
}
if (to_sleep_ms > to_sleep_until_next_delete_idle) {
to_sleep_ms = to_sleep_until_next_delete_idle;
}
}
SleepFor(to_sleep_ms);
}
}
void ReceivingThreadFunc() {
lock_.Lock();
++ref_count_;
lock_.Unlock();
while (true) {
sockaddr_in from_addr;
AddressLenType addr_length = sizeof(sockaddr_in);
int length = (int)recvfrom(binding_sock_, &buffer_[0], buffer_.size(), 0,
(struct sockaddr*)&from_addr, &addr_length);
lock_.Lock();
if (exit_) {
decreaseRefCountAndMaybeDestroySelfAndUnlock();
return;
}
lock_.Unlock();
if (length <= 0) {
continue;
}
IpPort from;
from.set_port(ntohs(from_addr.sin_port));
from.set_ip(ntohl(from_addr.sin_addr.s_addr));
processReceivedBuffer(NowTime(), from, length);
}
}
private:
void decreaseRefCountAndMaybeDestroySelfAndUnlock() {
--ref_count_;
int cur_ref_count = ref_count_;
// This method is performed when the mutex is locked.
lock_.Unlock();
if (cur_ref_count <= 0) {
if (cur_ref_count < 0) {
// Shouldn't be there.
std::cerr << "Strangly ref count is less than 0." << std::endl;
}
delete this;
}
}
void processReceivedBuffer(long cur_time_ms, const IpPort& from,
int packet_length) {
if (packet_length >= sizeof(PacketHeader)) {
PacketHeader header;
std::string user_data;
if (ParsePacket(buffer_.data(), packet_length, header, user_data)) {
bool accept_packet = false;
if (parameters_.application_id() == header.application_id) {
if (!parameters_.discover_self()) {
if (header.peer_id != peer_id_) {
accept_packet = true;
}
} else {
accept_packet = true;
}
}
if (accept_packet) {
lock_.Lock();
std::list<DiscoveredPeer>::iterator find_it = discovered_peers_.end();
for (std::list<DiscoveredPeer>::iterator it =
discovered_peers_.begin();
it != discovered_peers_.end(); ++it) {
if (Same(parameters_.same_peer_mode(), (*it).ip_port(), from)) {
find_it = it;
break;
}
}
if (header.packet_type == kPacketIAmHere) {
if (find_it == discovered_peers_.end()) {
discovered_peers_.push_back(DiscoveredPeer());
discovered_peers_.back().set_ip_port(from);
discovered_peers_.back().SetUserData(user_data,
header.packet_index);
discovered_peers_.back().set_last_updated(cur_time_ms);
} else {
bool update_user_data =
((*find_it).last_received_packet() < header.packet_index);
if (update_user_data) {
(*find_it).SetUserData(user_data, header.packet_index);
}
(*find_it).set_last_updated(cur_time_ms);
}
} else if (header.packet_type == kPacketIAmOutOfHere) {
if (find_it != discovered_peers_.end()) {
discovered_peers_.erase(find_it);
}
}
lock_.Unlock();
}
}
}
}
void deleteIdle(long cur_time_ms) {
lock_.Lock();
std::vector<std::list<DiscoveredPeer>::iterator> to_delete;
for (std::list<DiscoveredPeer>::iterator it = discovered_peers_.begin();
it != discovered_peers_.end(); ++it) {
if (cur_time_ms - (*it).last_updated() >
parameters_.discovered_peer_ttl_ms())
to_delete.push_back(it);
}
for (size_t i = 0; i < to_delete.size(); ++i)
discovered_peers_.erase(to_delete[i]);
lock_.Unlock();
}
void send(bool under_lock, PacketType packet_type) {
if (!under_lock) {
lock_.Lock();
}
std::string user_data = user_data_;
if (!under_lock) {
lock_.Unlock();
}
PacketHeader header;
header.packet_type = packet_type;
header.application_id = parameters_.application_id();
header.peer_id = peer_id_;
header.packet_index = packet_index_;
++packet_index_;
std::string packet_data;
if (MakePacket(header, user_data, packet_data)) {
sockaddr_in addr;
memset((char*)&addr, 0, sizeof(sockaddr_in));
if (parameters_.can_use_broadcast()) {
addr.sin_family = AF_INET;
addr.sin_port = htons(parameters_.port());
addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
}
if (parameters_.can_use_multicast()) {
addr.sin_family = AF_INET;
addr.sin_port = htons(parameters_.port());
addr.sin_addr.s_addr = htonl(parameters_.multicast_group_address());
}
sendto(sock_, &packet_data[0], packet_data.size(), 0,
(struct sockaddr*)&addr, sizeof(sockaddr_in));
}
}
private:
PeerParameters parameters_;
uint32_t peer_id_;
std::vector<char> buffer_;
SocketType binding_sock_;
SocketType sock_;
PacketIndex packet_index_;
MinimalisticMutex lock_;
int ref_count_;
bool exit_;
std::string user_data_;
std::list<DiscoveredPeer> discovered_peers_;
};
#if defined(_WIN32)
DWORD WINAPI SendingThreadFunc(void* env_typeless) {
PeerEnv* env = (PeerEnv*)env_typeless;
env->SendingThreadFunc();
return 0;
}
#else
void* SendingThreadFunc(void* env_typeless) {
PeerEnv* env = (PeerEnv*)env_typeless;
env->SendingThreadFunc();
return 0;
}
#endif
#if defined(_WIN32)
DWORD WINAPI ReceivingThreadFunc(void* env_typeless) {
PeerEnv* env = (PeerEnv*)env_typeless;
env->ReceivingThreadFunc();
return 0;
}
#else
void* ReceivingThreadFunc(void* env_typeless) {
PeerEnv* env = (PeerEnv*)env_typeless;
env->ReceivingThreadFunc();
return 0;
}
#endif
}; // namespace impl
Peer::Peer() : env_(0), sending_thread_(0), receiving_thread_(0) {}
Peer::~Peer() { Stop(false); }
bool Peer::Start(const PeerParameters& parameters,
const std::string& user_data) {
Stop(false);
impl::PeerEnv* env = new impl::PeerEnv();
if (!env->Start(parameters, user_data)) {
delete env;
env = 0;
return false;
}
env_ = env;
sending_thread_ = new impl::MinimalisticThread(impl::SendingThreadFunc, env_);
if (parameters.can_discover()) {
receiving_thread_ =
new impl::MinimalisticThread(impl::ReceivingThreadFunc, env_);
}
return true;
}
void Peer::SetUserData(const std::string& user_data) {
if (env_) {
env_->SetUserData(user_data);
}
}
std::list<DiscoveredPeer> Peer::ListDiscovered() const {
std::list<DiscoveredPeer> result;
if (env_) {
result = env_->ListDiscovered();
}
return result;
}
void Peer::Stop() { Stop(/* wait_for_threads= */ false); }
void Peer::StopAndWaitForThreads() { Stop(/* wait_for_threads= */ true); }
void Peer::Stop(bool wait_for_threads) {
if (!env_) {
return;
}
env_->Exit();
// Threads live longer than the object itself. So env will be deleted in one
// of the threads.
env_ = 0;
if (wait_for_threads) {
if (sending_thread_) {
sending_thread_->Join();
}
if (receiving_thread_) {
receiving_thread_->Join();
}
} else {
if (sending_thread_) {
sending_thread_->Detach();
}
if (receiving_thread_) {
receiving_thread_->Detach();
}
}
delete sending_thread_;
sending_thread_ = 0;
delete receiving_thread_;
receiving_thread_ = 0;
}
bool Same(PeerParameters::SamePeerMode mode, const IpPort& lhv,
const IpPort& rhv) {
switch (mode) {
case PeerParameters::kSamePeerIp:
return lhv.ip() == rhv.ip();
case PeerParameters::kSamePeerIpAndPort:
return (lhv.ip() == rhv.ip()) && (lhv.port() == rhv.port());
}
return false;
}
bool Same(PeerParameters::SamePeerMode mode,
const std::list<DiscoveredPeer>& lhv,
const std::list<DiscoveredPeer>& rhv) {
for (std::list<DiscoveredPeer>::const_iterator lhv_it = lhv.begin();
lhv_it != lhv.end(); ++lhv_it) {
std::list<DiscoveredPeer>::const_iterator in_rhv = rhv.end();
for (std::list<DiscoveredPeer>::const_iterator rhv_it = rhv.begin();
rhv_it != rhv.end(); ++rhv_it) {
if (Same(mode, (*lhv_it).ip_port(), (*rhv_it).ip_port())) {
in_rhv = rhv_it;
break;
}
}
if (in_rhv == rhv.end()) {
return false;
}
}
for (std::list<DiscoveredPeer>::const_iterator rhv_it = rhv.begin();
rhv_it != rhv.end(); ++rhv_it) {
std::list<DiscoveredPeer>::const_iterator in_lhv = lhv.end();
for (std::list<DiscoveredPeer>::const_iterator lhv_it = lhv.begin();
lhv_it != lhv.end(); ++lhv_it) {
if (Same(mode, (*rhv_it).ip_port(), (*lhv_it).ip_port())) {
in_lhv = lhv_it;
break;
}
}
if (in_lhv == lhv.end()) {
return false;
}
}
return true;
}
}; // namespace udpdiscovery
| 24.150336 | 80 | 0.630336 | [
"object",
"vector"
] |
dab9bae5e6ffa6fa6dfe7154779f03c1f092784d | 14,195 | cpp | C++ | src/input/parsers/xdmf/heavydata/griddata.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | 1 | 2021-09-16T10:15:50.000Z | 2021-09-16T10:15:50.000Z | src/input/parsers/xdmf/heavydata/griddata.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null | src/input/parsers/xdmf/heavydata/griddata.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null |
#include "griddata.h"
#include "basis/utilities/parser.h"
#include "wrappers/mpi/communication.h"
#include "esinfo/eslog.hpp"
#include "input/meshbuilder.h"
#include "input/parsers/mixedelementsparser.h"
#include "input/parsers/xdmf/lightdata/lightdata.h"
#include "input/parsers/xdmf/lightdata/xdmfdataitem.h"
#include "input/parsers/xdmf/lightdata/xdmfgrid.h"
#include "input/parsers/xdmf/lightdata/xdmfdomain.h"
#include "input/parsers/xdmf/lightdata/xdmfgeometry.h"
#include "input/parsers/xdmf/lightdata/xdmftopology.h"
#include "mesh/element.h"
#include "wrappers/hdf5/w.hdf5.h"
#include <vector>
#include <numeric>
using namespace mesio;
GridData::GridData(LightData &lightdata)
: _lightdata(lightdata)
{
}
void GridData::scan()
{
_lightdata.recurse([&] (XDMFElement *e, XDMFElement::EType type) {
switch (type) {
case XDMFElement::EType::Grid:
switch (dynamic_cast<XDMFGrid*>(e)->type) {
case XDMFGrid::Type::Collection: break;
case XDMFGrid::Type::Tree: break;
case XDMFGrid::Type::Uniform: _grids.push_back(_Grid{ dynamic_cast<XDMFGrid*>(e), NULL, NULL, NULL, NULL }); break;
case XDMFGrid::Type::Subset: break;
}
break;
case XDMFElement::EType::Geometry: _grids.back().geometry = dynamic_cast<XDMFGeometry*>(e); break;
case XDMFElement::EType::Topology: _grids.back().topology = dynamic_cast<XDMFTopology*>(e); break;
default: break;
}
});
auto xpath = [&] (XDMFDataItem *item) -> XDMFDataItem* {
if (item->reference.size()) {
if (StringCompare::caseInsensitiveEq(item->reference, "XML")) {
std::vector<std::string> path = Parser::split(item->data, "[]");
std::string name = Parser::split(path[1], "=")[1];
name = name.substr(1, name.size() - 2);
path = Parser::split(path[0], "/");
if (
path.size() == 4 &&
StringCompare::caseInsensitiveEq(path[0], "") &&
StringCompare::caseInsensitiveEq(path[1], "XDMF") &&
StringCompare::caseInsensitiveEq(path[2], "Domain") &&
StringCompare::caseInsensitiveEq(path[3], "DataItem")) {
XDMFElement *e = _lightdata.domain.front()->get(name);
if (dynamic_cast<XDMFDataItem*>(e)) {
return dynamic_cast<XDMFDataItem*>(e);
}
}
eslog::error("XDMF reader error: not supported DataItem reference.\n");
} else {
eslog::error("XDMF reader error: not supported reference type (only XML is supported).\n");
}
}
return item;
};
_geometry.reserve(_grids.size());
_topology.reserve(_grids.size());
for (auto it = _grids.begin(); it != _grids.end(); ++it) {
if (it->geometry->dataitem.size() != 1) {
eslog::error("XDMF parser error: Geometry element with exactly one DataItem is supported.\n");
}
if (it->topology->dataitem.size() != 1) {
eslog::error("XDMF parser error: Topology element with exactly one DataItem is supported.\n");
}
it->geometrydata = xpath(it->geometry->dataitem.front());
it->topologydata = xpath(it->topology->dataitem.front());
_geometry.push_back({ it->geometry, it->geometrydata });
_topology.push_back({ it->topology, it->topologydata });
}
}
void GridData::read()
{
if (_grids.size() == 0) {
return;
}
eslog::startln("HDF5: STARTED", "HDF5");
std::string hdffile = _lightdata.dir + "/" + Parser::split(_grids.front().geometrydata->data, ":")[0];
HDF5 hdf5(hdffile.c_str(), MPITools::subset->across, HDF5::MODE::READ);
eslog::checkpointln("HDF5: INITIALIZED");
for (size_t i = 0; i < _grids.size(); ++i) {
_geometry[i].read(hdf5);
_topology[i].read(hdf5);
}
eslog::checkpointln("HDF5: READ");
int reduction = MPITools::subset->within.size;
if (reduction > 1) { // scatter data to non-readers
std::vector<size_t> displacement(reduction + 1);
std::vector<char > sBuffer, rBuffer;
int writer = info::mpi::rank - MPITools::subset->within.rank;
size_t totalsize = 0;
for (size_t i = 0; i < _grids.size(); ++i) {
totalsize += _geometry[i].dimension * (_geometry[i].distribution[writer + reduction] - _geometry[i].distribution[writer]);
totalsize += _topology[i].esize * ( _topology[i].distribution[writer + reduction] - _topology[i].distribution[writer]);
}
for (int r = writer; r < writer + reduction; ++r) {
for (size_t i = 0; i < _grids.size(); ++i) {
{
size_t chunkoffset = _geometry[i].dimension * (_geometry[i].distribution[r] - _geometry[i].distribution[writer]);
size_t chunksize = _geometry[i].dimension * (_geometry[i].distribution[r + 1] - _geometry[i].distribution[r]);
displacement[r - writer + 1] += sizeof(float) * (chunkoffset + chunksize);
if (MPITools::subset->within.rank == 0 && chunksize) {
char* begin = reinterpret_cast<char*>(_geometry[i].data.data() + chunkoffset);
char* end = reinterpret_cast<char*>(_geometry[i].data.data() + chunkoffset + chunksize);
sBuffer.insert(sBuffer.end(), begin, end);
}
}
{
size_t chunkoffset = _topology[i].esize * ( _topology[i].distribution[r] - _topology[i].distribution[writer]);
size_t chunksize = _topology[i].esize * (_topology[i].distribution[r + 1] - _topology[i].distribution[r]);
displacement[r - writer + 1] += sizeof(esint) * (chunkoffset + chunksize);
if (MPITools::subset->within.rank == 0 && chunksize) {
char* begin = reinterpret_cast<char*>(_topology[i].data.data() + chunkoffset);
char* end = reinterpret_cast<char*>(_topology[i].data.data() + chunkoffset + chunksize);
sBuffer.insert(sBuffer.end(), begin, end);
}
}
}
}
Communication::scatterv(sBuffer, rBuffer, displacement, &MPITools::subset->within);
for (size_t i = 0, roffset = 0; i < _grids.size(); ++i) {
{
size_t chunksize = _geometry[i].dimension * (_geometry[i].distribution[info::mpi::rank + 1] - _geometry[i].distribution[info::mpi::rank]);
float* data = reinterpret_cast<float*>(rBuffer.data() + roffset);
_geometry[i].data.assign(data, data + chunksize);
roffset += sizeof(float) * chunksize;
}
{
size_t chunksize = _topology[i].esize * (_topology[i].distribution[info::mpi::rank + 1] - _topology[i].distribution[info::mpi::rank]);
esint* data = reinterpret_cast<esint*>(rBuffer.data() + roffset);
_topology[i].data.reserve(chunksize + TopologyData::align);
_topology[i].data.assign(data, data + chunksize);
roffset += sizeof(esint) * chunksize;
}
}
eslog::checkpointln("HDF5: DATA SCATTERED");
}
Communication::barrier();
eslog::checkpointln("HDF5: SYNCHRONIZED");
{ // align data
std::vector<esint, initless_allocator<esint> > sBuffer, rBuffer;
sBuffer.reserve(_topology.size() * TopologyData::align);
rBuffer.reserve(_topology.size() * TopologyData::align);
for (size_t i = 0; i < _topology.size(); ++i) {
sBuffer.insert(sBuffer.end(), _topology[i].data.begin(), _topology[i].data.begin() + TopologyData::align);
}
Communication::receiveUpper(sBuffer, rBuffer);
for (size_t i = 0; i < _topology.size(); ++i) {
if (info::mpi::rank + 1 != info::mpi::size) {
_topology[i].data.insert(_topology[i].data.end(), rBuffer.begin() + i * TopologyData::align, rBuffer.begin() + (i + 1) * TopologyData::align);
} else {
_topology[i].data.resize(_topology[i].data.size() + TopologyData::align, 0);
}
}
}
eslog::endln("HDF5: FINISHED");
}
static Element::CODE recognize(int id)
{
// some elements types are not supported by MESIO
switch (id) {
case 1: return Element::CODE::POINT1;
case 2: return Element::CODE::LINE2;
// case 3: return Element::CODE::HEXA8;
case 4: return Element::CODE::TRIANGLE3;
case 5: return Element::CODE::SQUARE4;
case 6: return Element::CODE::TETRA4;
case 7: return Element::CODE::PYRAMID5;
case 8: return Element::CODE::PRISMA6;
case 9: return Element::CODE::HEXA8;
// case 16: return Element::CODE::HEXA8;
case 34: return Element::CODE::LINE3;
// case 35: return Element::CODE::HEXA8;
case 36: return Element::CODE::TRIANGLE6;
case 37: return Element::CODE::SQUARE8;
case 38: return Element::CODE::TETRA10;
case 39: return Element::CODE::PYRAMID13;
case 40: return Element::CODE::PRISMA15;
// case 41: return Element::CODE::HEXA8;
case 48: return Element::CODE::HEXA20;
// case 49: return Element::CODE::HEXA8;
// case 50: return Element::CODE::HEXA8;
default:
return Element::CODE::SIZE;
}
}
void GridData::parse(MeshBuilder &mesh)
{
auto enodes = [] (size_t index, esint id) {
switch (id) {
case 1: return 2;
case 2: return 3;
// case 3: return 0;
case 4: return 3;
case 5: return 4;
case 6: return 4;
case 7: return 5;
case 8: return 6;
case 9: return 8;
// case 16: return 8;
case 34: return 3;
// case 35: return 8;
case 36: return 6;
case 37: return 8;
case 38: return 10;
case 39: return 13;
case 40: return 15;
// case 41: return 8;
case 48: return 20;
// case 49: return 8;
// case 50: return 8;
}
return 0;
};
std::vector<int> d(_topology.size()), dim(_topology.size());
for (size_t i = 0; i < _topology.size(); ++i) {
if (_topology[i].distribution[info::mpi::rank] == 0 && _topology[i].distribution[info::mpi::rank + 1] != 0) {
d[i] = _topology[i].data.front();
}
}
Communication::allReduce(d.data(), dim.data(), _topology.size(), MPI_INT, MPI_MAX);
MixedElementsParser mixedparser;
for (size_t i = 0; i < _topology.size(); ++i) {
if (_topology[i].etype == (int)Element::CODE::SIZE) {
mixedparser.add(_topology[i].data.data(), _topology[i].data.size() - TopologyData::align);
}
}
mixedparser.parse(enodes);
for (size_t i = 0, j = 0; i < _topology.size(); ++i) {
if (_topology[i].etype == (int)Element::CODE::SIZE) {
if (mixedparser.invalid[j++] != info::mpi::size) {
eslog::warning("XDMF parser: synchronization of region '%s'.\n", _grids[i].grid->name.c_str());
}
}
}
size_t csize = 0;
for (size_t i = 0; i < _geometry.size(); ++i) {
csize += _geometry[i].distribution[info::mpi::rank + 1] - _geometry[i].distribution[info::mpi::rank];
}
mesh.coordinates.reserve(csize);
for (size_t i = 0, nodes = 0; i < _geometry.size(); ++i) {
esint ncoordinates = _geometry[i].distribution[info::mpi::rank + 1] - _geometry[i].distribution[info::mpi::rank];
if (_geometry[i].dimension == 3) {
for (esint n = 0; n < ncoordinates; ++n) {
mesh.coordinates.push_back(Point(_geometry[i].data[3 * n + 0], _geometry[i].data[3 * n + 1], _geometry[i].data[3 * n + 2]));
}
} else {
for (esint n = 0; n < ncoordinates; ++n) {
mesh.coordinates.push_back(Point(_geometry[i].data[2 * n + 0], _geometry[i].data[2 * n + 1], 0));
}
}
for (esint n = 0; n < ncoordinates; ++n) {
mesh.nIDs.push_back(nodes + _geometry[i].distribution[info::mpi::rank] + n);
}
nodes += _geometry[i].distribution.back();
}
size_t esize = 0;
for (size_t i = 0; i < _topology.size(); ++i) {
if (_topology[i].etype == (int)Element::CODE::SIZE) {
esize += _topology[i].data.size() / 2;
} else {
if (_topology[i].esize != 1) {
esize += _topology[i].distribution[info::mpi::rank + 1] - _topology[i].distribution[info::mpi::rank];
}
}
}
mesh.esize.reserve(esize);
mesh.etype.reserve(esize);
mesh.eIDs.reserve(esize);
mesh.enodes.reserve(esize);
for (size_t i = 0, j = 0, nodes = 0, elements = 0; i < _topology.size(); ++i) {
if (_topology[i].etype == (int)Element::CODE::SIZE) {
std::vector<esint> ids;
for (size_t n = mixedparser.first[j]; n + TopologyData::align < _topology[i].data.size(); ++n) {
Element::CODE code = recognize(_topology[i].data[n]);
if (code == Element::CODE::POINT1) {
ids.push_back(nodes + _topology[i].data[n + 2]);
n += 2;
} else if (code == Element::CODE::LINE2) { // XDMF has POLYLINE (we assume pattern 2 2 id id, ...)
mesh.etype.push_back((int)Element::CODE::LINE2);
mesh.esize.push_back(2);
++n;
for (int nn = 0; nn < 2; ++nn, ++n) {
mesh.enodes.push_back(_topology[i].data[n + 1] + nodes);
}
ids.push_back(elements + mixedparser.offset[j]++);
} else {
mesh.etype.push_back((int)code);
mesh.esize.push_back(enodes(i, _topology[i].data[n]));
for (int nn = 0; nn < mesh.esize.back(); ++nn, ++n) {
mesh.enodes.push_back(_topology[i].data[n + 1] + nodes);
}
ids.push_back(elements + mixedparser.offset[j]++);
}
}
if (dim[i] == 1) {
mesh.nregions[_grids[i].grid->name] = ids;
} else {
mesh.eIDs.insert(mesh.eIDs.end(), ids.begin(), ids.end());
mesh.eregions[_grids[i].grid->name].swap(ids);
elements += mixedparser.nelements[j];
}
++j;
} else {
if (_topology[i].esize == 1) {
std::vector<esint> ids;
ids.reserve(_topology[i].data.size() - TopologyData::align);
for (size_t n = 0; n < _topology[i].data.size() - TopologyData::align; ++n) {
ids.push_back(nodes + _topology[i].data[n]);
}
mesh.nregions[_grids[i].grid->name].swap(ids);
} else {
size_t start = mesh.enodes.size();
size_t offset = _topology[i].distribution[info::mpi::rank];
size_t size = _topology[i].distribution[info::mpi::rank + 1] - _topology[i].distribution[info::mpi::rank];
mesh.eregions[_grids[i].grid->name].resize(size);
std::iota(mesh.eregions[_grids[i].grid->name].begin(), mesh.eregions[_grids[i].grid->name].end(), elements + offset);
mesh.eIDs.insert(mesh.eIDs.end(), mesh.eregions[_grids[i].grid->name].begin(), mesh.eregions[_grids[i].grid->name].end());
mesh.etype.resize(mesh.etype.size() + size, _topology[i].etype);
if (_topology[i].etype == (int)Element::CODE::LINE2) {
mesh.esize.resize(mesh.esize.size() + size, 2);
for (size_t n = 0; n + TopologyData::align < _topology[i].data.size();) {
n++; // nnodes
mesh.enodes.push_back(_topology[i].data[n++]);
mesh.enodes.push_back(_topology[i].data[n++]);
}
} else {
mesh.esize.resize(mesh.esize.size() + size, _topology[i].esize);
mesh.enodes.insert(mesh.enodes.end(), _topology[i].data.begin(), _topology[i].data.end() - TopologyData::align);
}
elements += _topology[i].distribution.back();
for (size_t n = start; n < mesh.enodes.size(); ++n) {
mesh.enodes[n] += nodes;
}
}
}
nodes += _geometry[i].distribution.back();
}
}
| 36.966146 | 146 | 0.644241 | [
"mesh",
"geometry",
"vector"
] |
dac8ee510bb5a6506dcae0b161d978953c754c3f | 2,440 | cc | C++ | emr/src/model/GetAuditLogsResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | emr/src/model/GetAuditLogsResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | emr/src/model/GetAuditLogsResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/emr/model/GetAuditLogsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Emr;
using namespace AlibabaCloud::Emr::Model;
GetAuditLogsResult::GetAuditLogsResult() :
ServiceResult()
{}
GetAuditLogsResult::GetAuditLogsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetAuditLogsResult::~GetAuditLogsResult()
{}
void GetAuditLogsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allItemsNode = value["Items"]["Item"];
for (auto valueItemsItem : allItemsNode)
{
Item itemsObject;
if(!valueItemsItem["Ts"].isNull())
itemsObject.ts = std::stol(valueItemsItem["Ts"].asString());
if(!valueItemsItem["UserId"].isNull())
itemsObject.userId = valueItemsItem["UserId"].asString();
if(!valueItemsItem["EntityId"].isNull())
itemsObject.entityId = valueItemsItem["EntityId"].asString();
if(!valueItemsItem["Operation"].isNull())
itemsObject.operation = valueItemsItem["Operation"].asString();
if(!valueItemsItem["Content"].isNull())
itemsObject.content = valueItemsItem["Content"].asString();
items_.push_back(itemsObject);
}
if(!value["PageNumber"].isNull())
pageNumber_ = std::stoi(value["PageNumber"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["TotalCount"].isNull())
totalCount_ = std::stoi(value["TotalCount"].asString());
}
int GetAuditLogsResult::getTotalCount()const
{
return totalCount_;
}
int GetAuditLogsResult::getPageSize()const
{
return pageSize_;
}
int GetAuditLogsResult::getPageNumber()const
{
return pageNumber_;
}
std::vector<GetAuditLogsResult::Item> GetAuditLogsResult::getItems()const
{
return items_;
}
| 28.045977 | 75 | 0.735656 | [
"vector",
"model"
] |
dadb407394cef503db2efc32903b329da21795f6 | 33,235 | cpp | C++ | controller/src/beerocks/master/wfa_ca.cpp | marcos-mxl/prplMesh | de16b3f74cf90d5d269e4b6f43723a34bc065917 | [
"BSD-2-Clause-Patent"
] | null | null | null | controller/src/beerocks/master/wfa_ca.cpp | marcos-mxl/prplMesh | de16b3f74cf90d5d269e4b6f43723a34bc065917 | [
"BSD-2-Clause-Patent"
] | null | null | null | controller/src/beerocks/master/wfa_ca.cpp | marcos-mxl/prplMesh | de16b3f74cf90d5d269e4b6f43723a34bc065917 | [
"BSD-2-Clause-Patent"
] | null | null | null |
#include "wfa_ca.h"
#include "son_actions.h"
#include <beerocks/bcl/beerocks_string_utils.h>
#include <beerocks/bcl/network/network_utils.h>
#include <beerocks/tlvf/beerocks_message.h>
#include <beerocks/tlvf/beerocks_message_bml.h>
#include <tlvf/wfa_map/eTlvTypeMap.h>
#include <tlvf/wfa_map/tlvChannelPreference.h>
#include <tlvf/wfa_map/tlvTransmitPowerLimit.h>
#include <easylogging++.h>
#include <algorithm>
#define FORBIDDEN_CHARS "$#&*()[];/\\<>?|`~=+"
using namespace beerocks;
static uint16_t g_mid = UINT16_MAX / 2 + 1;
/* Common Error Messages */
static const std::string err_internal = "Internal error";
/**
* @brief Checks for forbidden characters inside WFA-CA command
*
* @param[in] str WFA-CA command.
* @return String containing all the forbidden characters the have been found.
*/
static std::string check_forbidden_chars(const std::string &str)
{
std::string forbidden_chars_found;
auto found = str.find_first_of(FORBIDDEN_CHARS);
while (found != std::string::npos) {
forbidden_chars_found += str[found];
found = str.find_first_of(FORBIDDEN_CHARS, found + 1);
}
return forbidden_chars_found;
}
/**
* @brief Checks that the given string is in a hex notation
*
* @param[in] str String to check hex notation.
* @param[in] expected_octets Number of expected octets (Optional).
* @return true if string is valid hex notation, else false.
*/
static bool validate_hex_notation(const std::string &str, uint8_t expected_octets = 0)
{
// Each value must start with 0x
if (str.substr(0, 2) != "0x") {
return false;
}
// The number of digits must be even
if (str.size() % 2 != 0) {
return false;
}
// Expected octets validation
// "str.size() - 2" ignore "0x" prefix.
// division by 2 because 2 chars are equal to one octet
if (expected_octets != 0 && (str.size() - 2) / 2 != expected_octets) {
return false;
}
// Check if string has non-hex character
if (str.find_first_not_of("0123456789abcdefABCDEF", 2) != std::string::npos) {
return false;
}
return true;
}
/**
* @brief Parse bss_info string into bss_info_conf_struct.
*
* @param[in] bss_info_str String containing bss info configuration.
* @param[out] bss_info_conf Controller database struct filled with configuration.
* @param[out] err_string Contains an error description if the function fails.
* @return al_mac on success, empty string if not.
*/
static std::string parse_bss_info(const std::string &bss_info_str,
db::bss_info_conf_t &bss_info_conf, std::string &err_string)
{
auto confs = string_utils::str_split(bss_info_str, ' ');
/*
The Control API specification defines 8 parameters except for the case of
clearing the BSS info stored for a specific operating class, define only
two parameters: ALID and operating class.
*/
if ((confs.size() != 8) && (confs.size() != 2)) {
err_string = "missing configuration";
return std::string();
}
// Alid
std::string al_mac(confs[0]);
if (!net::network_utils::is_valid_mac(al_mac)) {
err_string = "invalid al_mac";
return std::string();
}
bss_info_conf = {};
// Operating class
auto &operating_class_str = confs[1];
if (operating_class_str == "8x") {
bss_info_conf.operating_class = {81, 83, 84};
} else if (operating_class_str == "11x") {
bss_info_conf.operating_class = {115, 116};
} else if (operating_class_str == "12x") {
bss_info_conf.operating_class = {124, 125, 126};
} else {
err_string = "invalid operating class " + operating_class_str;
return std::string();
}
if (confs.size() == 2) {
return al_mac;
}
// SSID
bss_info_conf.ssid = confs[2];
if (bss_info_conf.ssid.size() > WSC::eWscLengths::WSC_MAX_SSID_LENGTH) {
err_string = "ssid is too long";
return std::string();
}
// Authentication type
auto &authentication_type_str = confs[3];
if (!validate_hex_notation(authentication_type_str, 2)) {
err_string = "invalid authentication type format";
return std::string();
}
uint16_t authentication_type = std::stoi(authentication_type_str, nullptr, 16);
if (!WSC::eWscAuthValidate::check(authentication_type)) {
err_string = "invalid authentication type value";
return std::string();
}
bss_info_conf.authentication_type = static_cast<WSC::eWscAuth>(authentication_type);
// Encryption type
auto &encryption_type_str = confs[4];
if (!validate_hex_notation(encryption_type_str, 2)) {
err_string = "invalid encryption type format";
return std::string();
}
uint16_t encryption_type = std::stoi(encryption_type_str, nullptr, 16);
if (!WSC::eWscEncrValidate::check(encryption_type)) {
err_string = "invalid encryption type value";
return std::string();
}
bss_info_conf.encryption_type = static_cast<WSC::eWscEncr>(encryption_type);
// Network key
bss_info_conf.network_key = confs[5];
if (bss_info_conf.network_key.size() > WSC::eWscLengths::WSC_MAX_NETWORK_KEY_LENGTH) {
err_string = "network key is too long";
return std::string();
}
// Bit 6 of Multi-AP IE's extention attribute, aka "Backhaul BSS"
auto &bit_6_str = confs[6];
if (bit_6_str != "0" && bit_6_str != "1") {
err_string = "invalid bit 6 of Multi-AP IE's extention attribute";
return std::string();
}
uint8_t bss_type = (bit_6_str == "1" ? WSC::eWscVendorExtSubelementBssType::BACKHAUL_BSS : 0);
// Bit 5 of Multi-AP IE's extention attribute, aka "Fronthaul BSS"
auto &bit_5_str = confs[7];
if (bit_5_str != "0" && bit_5_str != "1") {
err_string = "invalid bit 5 of Multi-AP IE's extention attribute";
return std::string();
}
bss_type |= (bit_5_str == "1" ? WSC::eWscVendorExtSubelementBssType::FRONTHAUL_BSS : 0);
// Update Bits 6 and 5
bss_info_conf.bss_type = static_cast<WSC::eWscVendorExtSubelementBssType>(bss_type);
return al_mac;
}
/**
* @brief Convert enum of WFA-CA status to string.
*
* @param[in] status Enum of WFA-CA status.
* @return Status as string.
*/
const std::string wfa_ca::wfa_ca_status_to_string(eWfaCaStatus status)
{
switch (status) {
case eWfaCaStatus::RUNNING:
return "RUNNING";
case eWfaCaStatus::INVALID:
return "INVALID";
case eWfaCaStatus::ERROR:
return "ERROR";
case eWfaCaStatus::COMPLETE:
return "COMPLETE";
default:
LOG(ERROR) << "Status argument doesn't have an enum";
break;
}
return std::string();
}
/**
* @brief Convert string of WFA-CA command into enum
*
* @param[in] command String of WFA-CA command.
* @return Command enum. If command is not recognized returns eWfaCaCommand::WFA_CA_COMMAND_MAX.
*/
wfa_ca::eWfaCaCommand wfa_ca::wfa_ca_command_from_string(std::string command)
{
std::transform(command.begin(), command.end(), command.begin(), ::toupper);
if (command == "CA_GET_VERSION") {
return eWfaCaCommand::CA_GET_VERSION;
} else if (command == "DEVICE_GET_INFO") {
return eWfaCaCommand::DEVICE_GET_INFO;
} else if (command == "DEV_RESET_DEFAULT") {
return eWfaCaCommand::DEV_RESET_DEFAULT;
} else if (command == "DEV_SEND_1905") {
return eWfaCaCommand::DEV_SEND_1905;
} else if (command == "DEV_SET_CONFIG") {
return eWfaCaCommand::DEV_SET_CONFIG;
} else if (command == "DEV_GET_PARAMETER") {
return eWfaCaCommand::DEV_GET_PARAMETER;
}
return eWfaCaCommand::WFA_CA_COMMAND_MAX;
}
/**
* @brief Generate WFA-CA reply message and send it.
*
* @param[in] sd Socket to send the reply to.
* @param[in] cmdu_tx CmduTx message object to create the message with.
* @param[in] status Status of the reply.
* @param[in] description Optional, Description to add to the reply.
* @return true if successful, false if not.
*/
bool wfa_ca::reply(Socket *sd, ieee1905_1::CmduMessageTx &cmdu_tx, eWfaCaStatus status,
const std::string &description)
{
std::string reply_string = "status," + wfa_ca_status_to_string(status);
if (!description.empty()) {
reply_string += ",";
if (status == eWfaCaStatus::INVALID || status == eWfaCaStatus::ERROR) {
reply_string += "errorCode,";
}
reply_string += description;
}
auto response =
message_com::create_vs_message<beerocks_message::cACTION_BML_WFA_CA_CONTROLLER_RESPONSE>(
cmdu_tx);
if (!response) {
LOG(ERROR) << "Failed building cACTION_BML_WFA_CA_CONTROLLER_RESPONSE message!";
return false;
}
if (!response->set_reply(reply_string)) {
LOG(ERROR) << "setting reply has failed!";
return false;
}
return message_com::send_cmdu(sd, cmdu_tx);
}
/**
* @brief Parse the strings vector which containing parameter names, and values into unordered map
* which will contain the parameter name as a map key, and paramaeter value as map value.
* The function receives as an input unordered map of parameters that are mandatory, which will
* include non-mandatory parameters as output.
*
* @param[in] command_tokens A vector containing commands parameters name and values.
* @param[in,out] params An unordered map containing mandatory parameters on input, and parsed
* command as output.
* @param[out] err_string Contains an error description if the function fails.
* @return true if successful, false if not.
*/
bool wfa_ca::parse_params(const std::vector<std::string> &command_tokens,
std::unordered_map<std::string, std::string> ¶ms,
std::string &err_string)
{
// create a copy of all mandatory param names
std::list<std::string> mandatory_params;
for (const auto ¶m_name : params) {
mandatory_params.push_back(param_name.first);
}
size_t mandatory_params_cnt = 0;
for (auto it = std::next(command_tokens.begin()); it != command_tokens.end(); it++) {
std::string param_name = *it;
std::transform(param_name.begin(), param_name.end(), param_name.begin(), ::tolower);
if (params.find(param_name) != params.end()) {
mandatory_params_cnt++;
}
if (std::next(it) == command_tokens.end()) {
err_string = "missing param value for param '" + param_name + "'";
return false;
}
params[param_name] = *std::next(it);
it++;
}
if (mandatory_params_cnt == mandatory_params.size()) {
return true;
}
// Generate an err string if missing mandatory param
err_string = "missing mandatory params: ";
for (const std::string ¶m_name : mandatory_params) {
if ((params.find(param_name))->second.empty()) {
err_string += param_name + ", ";
}
}
// Remove last comma and space
err_string.pop_back();
err_string.pop_back();
return false;
}
/**
* @brief Receives WFA-CA command, preform it and returns a reply to the sender.
*
* @param[in] sd Socket of the sender.
* @param[in] beerocks_header Beerocks message header.
* @param[in] cmdu_rx CmduRx Message object, containing the command request.
* @param[in] cmdu_tx CmduTx Message object of the controller, to be used when replying.
* @param[in] database Controllers database
* @param[in] tasks Controlles tasks pool.
*/
void wfa_ca::handle_wfa_ca_message(
Socket *sd, std::shared_ptr<beerocks_message::cACTION_HEADER> beerocks_header,
ieee1905_1::CmduMessageRx &cmdu_rx, ieee1905_1::CmduMessageTx &cmdu_tx, db &database,
task_pool &tasks)
{
auto request = cmdu_rx.addClass<beerocks_message::cACTION_BML_WFA_CA_CONTROLLER_REQUEST>();
if (!request) {
LOG(ERROR) << "addClass cACTION_BML_WFA_CA_CONTROLLER_REQUEST failed";
return;
}
std::string command_str(request->command());
LOG(DEBUG) << "Received ACTION_BML_WFA_CA_CONTROLLER_REQUEST, command=\"" << command_str
<< "\"";
std::string err_string;
auto forbidden_chars = check_forbidden_chars(command_str);
if (!forbidden_chars.empty()) {
err_string = "command contain illegal chars";
LOG(ERROR) << err_string << ": " << forbidden_chars;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
return;
}
auto cmd_tokens_vec = string_utils::str_split(command_str, ',');
if (cmd_tokens_vec.empty()) {
err_string = "empty command";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
return;
}
auto &command_type_str = *cmd_tokens_vec.begin();
auto command_type = wfa_ca_command_from_string(command_type_str);
switch (command_type) {
case eWfaCaCommand::CA_GET_VERSION: {
// send back first reply
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
// Send back second reply
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE, std::string("version,") + BEEROCKS_VERSION);
break;
}
case eWfaCaCommand::DEVICE_GET_INFO: {
// send back first reply
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
// Send back second reply
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE,
std::string("vendor,") + database.settings_vendor() + std::string(",model,") +
database.settings_model() + std::string(",version,") + BEEROCKS_VERSION);
break;
}
case eWfaCaCommand::DEV_GET_PARAMETER: {
// For controller certification, the following command is received to get the ALid:
// DUT (127.0.0.1:5000) ---> dev_get_parameter,program,map,parameter,ALid
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
std::string alid;
if (!net::network_utils::linux_iface_get_mac("br-lan", alid))
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, "FAIL");
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE, std::string("aLid,") + alid);
break;
}
case eWfaCaCommand::DEV_RESET_DEFAULT: {
// NOTE: Note sure this parameters are actually needed. There is a controversial
// between TestPlan and CAPI specification regarding if these params are required.
std::unordered_map<std::string, std::string> params{
// {"name", std::string()},
// {"program", std::string()},
// {"devrole", std::string()},
// {"type", std::string()}
};
if (!parse_params(cmd_tokens_vec, params, err_string)) {
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
// Input check
if (params.find("devrole") != params.end()) {
if (params["devrole"] != "controller" && params["devrole"] != "agent") {
err_string = "invalid param value '" + params["devrole"] +
"' for param name 'devrole', accepted values can be only 'controller'"
" or 'agent";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
}
if (params.find("program") != params.end()) {
if (params["program"] != "map") {
err_string = "invalid param value '" + params["map"] +
"' for param name 'program', accepted value can be only 'map'";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
}
if (params.find("type") != params.end()) {
if (params["type"] != "test bed" && params["type"] != "DUT") {
err_string = "invalid param value '" + params["type"] +
"' for param name 'type', accepted values can be only 'test bed' or"
" 'dut'";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
}
// TODO: Find out what to do with value of param "name".
// send back first reply
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
database.clear_bss_info_configuration();
// Send back second reply
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE);
break;
}
case eWfaCaCommand::DEV_SEND_1905: {
std::unordered_map<std::string, std::string> params{{"destalid", std::string()},
{"messagetypevalue", std::string()}};
if (!parse_params(cmd_tokens_vec, params, err_string)) {
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
// Input check
auto &dest_alid = params["destalid"];
std::transform(dest_alid.begin(), dest_alid.end(), dest_alid.begin(), ::tolower);
Socket *agent_sd = database.get_node_socket(dest_alid);
if (agent_sd == nullptr) {
err_string = "invalid param value '" + params["destalid"] +
"' for param name 'DestALID', agent not found";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
auto &message_type_str = params["messagetypevalue"];
auto message_type = (uint16_t)(std::stoul(message_type_str, nullptr, 16));
if (!ieee1905_1::eMessageTypeValidate::check(message_type)) {
err_string = "invalid param value '0x" + message_type_str +
"' for param name 'MessageTypeValue', message type not found";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
// TLV check
std::list<tlv_hex_t> tlv_hex_list;
if (!get_send_1905_1_tlv_hex_list(tlv_hex_list, params, err_string)) {
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
// Send back first reply
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
// Check if CMDU message type has preprepared CMDU which can be loaded
auto certification_tx_buffer = database.get_certification_tx_buffer();
if (!certification_tx_buffer) {
LOG(ERROR) << "certification_tx_buffer is not allocated";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_internal);
break;
}
ieee1905_1::CmduMessageTx external_cmdu_tx(
certification_tx_buffer.get() + sizeof(beerocks::message::sUdsHeader),
message::MESSAGE_BUFFER_LENGTH - sizeof(beerocks::message::sUdsHeader));
if (create_cmdu(external_cmdu_tx, ieee1905_1::eMessageType(message_type), database,
err_string)) {
// Success
if (!son_actions::send_cmdu_to_agent(agent_sd, external_cmdu_tx)) {
LOG(ERROR) << "Failed to send CMDU";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_internal);
break;
}
} else if (!err_string.empty()) {
// Failure
LOG(ERROR) << "cmdu creation of type 0x" << message_type_str << ", has failed";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_string);
break;
} else {
// CMDU was not loaded from preprepared buffer, and need to be created manually, and
// use TLV data from the command (if exists)
if (!cmdu_tx.create(g_mid, ieee1905_1::eMessageType(message_type))) {
LOG(ERROR) << "cmdu creation of type 0x" << message_type_str << ", has failed";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_internal);
break;
}
// We need to fill in CmduMessage's class vector. However, we really don't care about
// the classes, and we don't want any swapping to be done. Still, we need something
// to make sure the length of the tlvs is taken into account.
// Therefore, use the tlvPrefilledData class, which can update the end pointer.
auto tlvs = cmdu_tx.addClass<tlvPrefilledData>();
if (!tlvs) {
LOG(ERROR) << "addClass tlvPrefilledData has failed";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_internal);
break;
}
if (!tlvs->add_tlvs_from_list(tlv_hex_list, err_string)) {
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_string);
break;
}
LOG(INFO) << "Send TLV CMDU " << message_type << " with " << tlv_hex_list.size()
<< " TLVs, length " << cmdu_tx.getMessageLength();
if (!son_actions::send_cmdu_to_agent(agent_sd, cmdu_tx)) {
LOG(ERROR) << "Failed to send CMDU";
reply(sd, cmdu_tx, eWfaCaStatus::ERROR, err_internal);
break;
}
}
std::string description = "mid,0x" + string_utils::int_to_hex_string(g_mid++, 4);
// Send back second reply
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE, description);
break;
}
case eWfaCaCommand::DEV_SET_CONFIG: {
// NOTE: Note sure this parameters are actually needed. There is a controversial
// between TestPlan and CAPI specification regarding if these params are required.
std::unordered_map<std::string, std::string> params{
// {"name", std::string()},
// {"program", std::string()},
};
if (!parse_params(cmd_tokens_vec, params, err_string)) {
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
// Input check
if (params.find("program") != params.end()) {
if (params["program"] != "map") {
err_string = "invalid param value '" + params["map"] +
"' for param name 'program', accepted value can be only 'map'";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
}
if (params.find("backhaul") != params.end()) {
err_string = "parameter 'backhaul' is relevant only on an agent";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
break;
}
for (uint8_t bss_info_idx = 1; bss_info_idx < UINT8_MAX; bss_info_idx++) {
std::string key("bss_info");
key += std::to_string(bss_info_idx);
if (params.find(key) == params.end()) {
if (bss_info_idx == 1) {
err_string = "command has no bss_info configuration";
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
return;
}
break;
}
db::bss_info_conf_t bss_info_conf;
auto al_mac = parse_bss_info(params[key], bss_info_conf, err_string);
if (al_mac.empty()) {
err_string += (" on " + key);
LOG(ERROR) << err_string;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_string);
return;
}
database.add_bss_info_configuration(al_mac, bss_info_conf);
}
// Send back first reply
if (!reply(sd, cmdu_tx, eWfaCaStatus::RUNNING)) {
LOG(ERROR) << "failed to send reply";
break;
}
// Send back second reply
reply(sd, cmdu_tx, eWfaCaStatus::COMPLETE);
break;
}
default: {
auto err_description = "Invalid WFA-CA command type: '" + command_type_str + "'";
LOG(ERROR) << err_description;
reply(sd, cmdu_tx, eWfaCaStatus::INVALID, err_description);
break;
}
}
}
/**
* @brief Create CMDU manually by loading CMDU from preperared buffer, or getting the data to fill
* TLVs from the database.
* If the function fails but err_string string is empty, then it means that the CMDU was not handled
* by this function, and the caller will need to create the CMDU by itself.
*
* @param[in,out] cmdu_tx CmduTx message object created from certification_tx_buffer.
* @param[in] message_type CMDU message type to create.
* @param[in] database Controllers database.
* @param[out] err_string Contains an error description if the function fails.
* @return true if CMDU was successfully loaded, false with empty err_string if CMDU was not loaded,
* but didn't fail, false with non-empty err_string on failure.
*/
bool wfa_ca::create_cmdu(ieee1905_1::CmduMessageTx &cmdu_tx, ieee1905_1::eMessageType message_type,
db &database, std::string &err_string)
{
std::shared_ptr<ieee1905_1::cCmduHeader> cmdu_header;
int tlv_type;
switch (message_type) {
case ieee1905_1::eMessageType::CHANNEL_SELECTION_REQUEST_MESSAGE: {
cmdu_header = cmdu_tx.load();
if (!cmdu_header) {
LOG(ERROR) << "load cmdu has failed";
return false;
}
tlv_type = cmdu_tx.getNextTlvType();
while (tlv_type != int(ieee1905_1::eTlvType::TLV_END_OF_MESSAGE)) {
if (tlv_type == int(wfa_map::eTlvTypeMap::TLV_CHANNEL_PREFERENCE)) {
if (!cmdu_tx.addClass<wfa_map::tlvChannelPreference>()) {
LOG(ERROR) << "addClass tlvChannelPreference has failed";
err_string = err_internal;
return false;
}
} else if (tlv_type == int(wfa_map::eTlvTypeMap::TLV_TRANSMIT_POWER_LIMIT)) {
if (!cmdu_tx.addClass<wfa_map::tlvTransmitPowerLimit>()) {
LOG(ERROR) << "addClass tlvTransmitPowerLimit has failed";
err_string = err_internal;
return false;
}
}
tlv_type = cmdu_tx.getNextTlvType();
}
break;
}
default:
// If message type handler is not implemented, then return false with empty error, so the
// caller would know that it was not handled.
err_string = std::string();
return false;
}
if (!cmdu_header) {
err_string = err_internal;
return false;
}
// Force mid
cmdu_header->message_id() = g_mid;
return true;
}
/**
* @brief Parse command "DEV_SEND_1905" TLVs parameters into an ordered list of TLV structure
* "tlv_hex_t", and does data validation.
*
* @param[in,out] tlv_hex_list An ordered list of TLVs of type "tlv_hex_t".
* @param[in] params An unordered map containing parsed parameters of a CAPI command.
* @param[out] err_string Contains an error description if the function fails.
* @return true if successful, false if not.
*/
bool wfa_ca::get_send_1905_1_tlv_hex_list(std::list<tlv_hex_t> &tlv_hex_list,
std::unordered_map<std::string, std::string> ¶ms,
std::string &err_string)
{
static const int max_tlv = 256; // Magic number
size_t tlv_idx = 0;
bool skip = false;
bool finish = false;
static const std::vector<std::string> tlv_members = {"tlv_type", "tlv_length", "tlv_value"};
do {
tlv_hex_t tlv_hex;
for (size_t tlv_member_idx = 0; tlv_member_idx < tlv_members.size(); tlv_member_idx++) {
std::string lookup_str =
tlv_members[tlv_member_idx] + (tlv_idx > 0 ? std::to_string(tlv_idx) : "");
auto it = params.find(lookup_str);
if (it == params.end()) {
if (tlv_idx == 0 && tlv_member_idx == 0) {
// Skipping TLV with no index (index 0), checking TLV index 1
skip = true;
break;
} else if (tlv_idx > 0 && tlv_member_idx == 0) {
// No indexed TLVs found, finish
finish = true;
break;
} else {
err_string = "missing param name '" + lookup_str + "'";
return false;
}
}
// Type
if (tlv_member_idx == 0) {
tlv_hex.type = &it->second;
if (!validate_hex_notation(*tlv_hex.type, 1)) {
err_string = "param name '" + lookup_str + "' has invalid hex notation value";
return false;
}
// Length
} else if (tlv_member_idx == 1) {
tlv_hex.length = &it->second;
if (!validate_hex_notation(*tlv_hex.length, 2)) {
err_string = "param name '" + lookup_str + "' has invalid hex notation value";
return false;
}
// Value
} else if (tlv_member_idx == 2) {
// The hex values contains '{' and '}' delimiters, but we don't care about them.
it->second.erase(std::remove(it->second.begin(), it->second.end(), '{'),
it->second.end());
it->second.erase(std::remove(it->second.begin(), it->second.end(), '}'),
it->second.end());
tlv_hex.value = &it->second;
// Validate hex notation on list of values separated by space
auto values = string_utils::str_split(it->second, ' ');
for (const auto &value : values) {
if (!validate_hex_notation(value)) {
err_string =
"param name '" + lookup_str + "' has invalid hex notation value";
return false;
}
}
} else {
LOG(ERROR) << "Illegal tlv_member_idx value: " << int(tlv_member_idx);
err_string = err_internal;
return false;
}
}
if (finish) {
return true;
}
tlv_idx++;
if (skip) {
skip = false;
continue;
}
tlv_hex_list.push_back(tlv_hex);
} while (tlv_idx < max_tlv);
LOG(ERROR) << "Reached stop condition";
err_string = err_internal;
return false;
}
/**
* @brief Writes TLVs from TLVs list 'tlv_hex_list' into the class buffer.
*
* @param[in] tlv_hex_list An ordered list of TLVs of type "tlv_hex_t".
* @param[out] err_string Contains an error description if the function fails.
* @return true if successful, false if not.
*/
bool tlvPrefilledData::add_tlvs_from_list(std::list<wfa_ca::tlv_hex_t> &tlv_hex_list,
std::string &err_string)
{
for (const auto &tlv : tlv_hex_list) {
uint8_t type = std::stoi(*tlv.type, nullptr, 16);
uint16_t length = std::stoi(*tlv.length, nullptr, 16);
// "+3" = size of type and length fields
if (getBuffRemainingBytes() < unsigned(length + 3)) {
err_string = "not enough space on buffer";
return false;
}
*m_buff_ptr__ = type;
m_buff_ptr__++;
*m_buff_ptr__ = uint8_t(length >> 8);
m_buff_ptr__++;
*m_buff_ptr__ = uint8_t(length);
m_buff_ptr__++;
auto values = string_utils::str_split(*tlv.value, ' ');
for (auto value : values) {
// iterate every to chars (1 octet) and write it to buffer
// start with char_idx = 2 to skip "0x"
for (size_t char_idx = 2; char_idx < value.size(); char_idx += 2) {
if (length == 0) {
err_string = "length smaller than data";
return false;
}
*m_buff_ptr__ = std::stoi(value.substr(char_idx, 2), nullptr, 16);
m_buff_ptr__++;
length--;
}
}
if (length != 0) {
err_string = "data smaller than length";
return false;
}
}
return true;
}
| 36.602423 | 100 | 0.58634 | [
"object",
"vector",
"model",
"transform"
] |
dadc674ca3014e18b1e2eddcda34f9b251627d81 | 519 | hpp | C++ | src/ui/focusable.hpp | ArthurSonzogni/beagle-config | 8283226adb5dd6844f8b0c24b18da20aab74e043 | [
"MIT"
] | null | null | null | src/ui/focusable.hpp | ArthurSonzogni/beagle-config | 8283226adb5dd6844f8b0c24b18da20aab74e043 | [
"MIT"
] | null | null | null | src/ui/focusable.hpp | ArthurSonzogni/beagle-config | 8283226adb5dd6844f8b0c24b18da20aab74e043 | [
"MIT"
] | null | null | null | #ifndef BEAGLE_CONFIG_UI_PANEL_FOCUSABLE
#define BEAGLE_CONFIG_UI_PANEL_FOCUSABLE
namespace ui {
using namespace ftxui;
// A simple text highlighted when focused.
class Focusable : public ftxui::ComponentBase {
public:
Focusable(const std::wstring& title) : title_(title) {}
Element Render() final {
auto style = Focused() ? inverted : nothing;
return text(title_) | style;
}
private:
std::wstring title_;
};
} // namespace ui
#endif /* end of include guard: BEAGLE_CONFIG_UI_PANEL_FOCUSABLE */
| 22.565217 | 67 | 0.734104 | [
"render"
] |
dadcd58425cd07ae82356d4f5a35cfebbd64467c | 3,423 | cpp | C++ | training/POJ/3281.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | 68 | 2017-10-08T04:44:23.000Z | 2019-08-06T20:15:02.000Z | training/POJ/3281.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | null | null | null | training/POJ/3281.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | 18 | 2017-05-31T02:52:23.000Z | 2019-07-05T09:18:34.000Z | // written at 17:27 on 20 Jan 2017
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <complex>
#include <deque>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <utility>
#include <bitset>
#define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr);
// #define __DEBUG__
#ifdef __DEBUG__
#define DEBUG(...) printf(__VA_ARGS__)
#else
#define DEBUG(...)
#endif
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout);
#define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans");
#define rep(i, j, k) for (int i = j; i < k; ++i)
#define irep(i, j, k) for (int i = j - 1; i >= k; --i)
using namespace std;
template <typename T>
inline T sqr(T a) { return a * a;};
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const ll LLINF = LLONG_MAX;
const int MAX_V = 1e3 + 10;
struct edge {int to, cap, rev; };
vector<edge> G[MAX_V];
int V, iter[MAX_V], level[MAX_V];
int F, D, N;
void add_edge(int from, int to, int cap) {
G[from].push_back(edge{to, cap, (int)G[to].size()});
G[to].push_back(edge{from, 0, (int)G[from].size() - 1});
}
void bfs(int s) {
memset(level, -1, sizeof level);
queue<int> que;
level[s] = 0; que.push(s);
while (!que.empty()) {
int v = que.front(); que.pop();
rep(i, 0, G[v].size()) {
edge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dfs(int v, int t, int f) {
if (v == t) return f;
for (int &i = iter[v]; i < G[v].size(); ++i) {
edge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
for(;;) {
bfs(s);
if (level[t] < 0) return flow;
memset(iter, 0, sizeof iter);
int f;
while ((f = dfs(s, t, INF)) > 0)
flow += f;
}
return flow;
}
int main(int argc, char const *argv[])
{
while (~scanf("%d%d%d", &N, &F, &D)) {
// 0 ~ N - 1 left cow
// N ~ 2N - 1 right cow
// 2N ~ 2N + F - 1 food
// 2N + F ~ 2N + F + D - 1 drink
int s = F + D + 2 * N, t = s + 1;
rep(v, 0, t + 1) G[v].clear();
int n, m, a;
rep(j, 0, F) add_edge(s, j + 2 * N, 1);
rep(j, 0, D) add_edge(j + 2 * N + F, t, 1);
rep(i, 0, N) {
scanf("%d%d", &n, &m);
rep(j, 0, n) {
scanf("%d", &a); --a;
add_edge(a + 2 * N, i, 1);
}
rep(j, 0, m) {
scanf("%d", &a); --a;
add_edge(i + N, a + 2 * N + F, 1);
}
add_edge(i, i + N, 1);
}
printf("%d\n", max_flow(s, t));
}
return 0;
} | 26.129771 | 118 | 0.488168 | [
"vector"
] |
daefab9fa12fc4a8ff1fbc0f609939a6982e2281 | 21,334 | cpp | C++ | engine/src/physics/DeformableBody.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | 1 | 2019-07-14T11:32:30.000Z | 2019-07-14T11:32:30.000Z | engine/src/physics/DeformableBody.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | engine/src/physics/DeformableBody.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | #include "DeformableBody.h"
#include <easylogging++.h>
#ifndef ABS
#define ABS(x) ((x) < 0 ? -(x) : (x))
#endif
namespace engine {
namespace physics {
SparseMatrix<double> DeformableBody::calculateMaterialMatrix() const {
SparseMatrix<double> materialMat(6, 6);
materialMat.reserve(12);
materialMat.insert(0, 0) = 1 - this->poissonsRatio;
materialMat.insert(0, 1) = this->poissonsRatio;
materialMat.insert(0, 2) = this->poissonsRatio;
materialMat.insert(1, 0) = this->poissonsRatio;
materialMat.insert(1, 1) = 1 - this->poissonsRatio;
materialMat.insert(1, 2) = this->poissonsRatio;
materialMat.insert(2, 0) = this->poissonsRatio;
materialMat.insert(2, 1) = this->poissonsRatio;
materialMat.insert(2, 2) = 1 - this->poissonsRatio;
materialMat.insert(3, 3) = 1 - 2*this->poissonsRatio;
materialMat.insert(4, 4) = 1 - 2*this->poissonsRatio;
materialMat.insert(5, 5) = 1 - 2*this->poissonsRatio;
return (this->youngsModulus / ((1+this->poissonsRatio)*(1-2*this->poissonsRatio)))
* materialMat;
}
std::pair<SparseMatrix<double>, MatrixXd> DeformableBody::calculateStiffnessAndStressMatrixForTetrahedron(size_t index) const {
MatrixXd A_inv(4, 4);
auto tetrahedron = this->getRestTetrahedron(index);
A_inv << tetrahedron.cast<double>(), MatrixXd::Ones(1, 4);
auto A = A_inv.inverse();
SparseMatrix<double> B(6, 12);
B.reserve(36);
for(int i = 0; i < 4; ++i) {
auto baseInd = i * 3;
B.insert(0, baseInd + 0) = A(i, 0);
B.insert(1, baseInd + 1) = A(i, 1);
B.insert(2, baseInd + 2) = A(i, 2);
B.insert(3, baseInd + 0) = 0.5 * A(i, 1);
B.insert(3, baseInd + 1) = 0.5 * A(i, 0);
B.insert(4, baseInd + 1) = 0.5 * A(i, 2);
B.insert(4, baseInd + 2) = 0.5 * A(i, 1);
B.insert(5, baseInd + 0) = 0.5 * A(i, 2);
B.insert(5, baseInd + 2) = 0.5 * A(i, 0);
}
SparseMatrix<double> stressMatrix = this->calculateMaterialMatrix() * B;
float volume = abs(
(static_cast<Vector3f>(tetrahedron.col(1) - tetrahedron.col(0)))
.cross
(static_cast<Vector3f>(tetrahedron.col(2) - tetrahedron.col(0)))
.dot(static_cast<Vector3f>(tetrahedron.col(3) - tetrahedron.col(0)))
) / 6;
return std::make_pair(volume * B.transpose() * stressMatrix, MatrixXd(stressMatrix));
}
void DeformableBody::combineBlock(int blockRows, int blockCols, SparseMatrix<double>& target, int targetRow, int targetCol, const SparseMatrix<double>& source, int sourceRow, int sourceCol) const {
for(int dimensionIndexRow = 0; dimensionIndexRow < blockRows; ++dimensionIndexRow) {
for(int dimensionIndexCol = 0; dimensionIndexCol < blockCols; ++dimensionIndexCol) {
auto coeff = source.coeff(sourceRow + dimensionIndexRow, sourceCol + dimensionIndexCol);
if(coeff != double(0)) {
target.coeffRef(targetRow + dimensionIndexRow, targetCol + dimensionIndexCol) += coeff;
}
}
}
}
void DeformableBody::combineBlock(int blockRows, int blockCols, SparseMatrix<double>& target, int targetRow, int targetCol, const MatrixXd& source, int sourceRow, int sourceCol) const {
for(int dimensionIndexRow = 0; dimensionIndexRow < blockRows; ++dimensionIndexRow) {
for(int dimensionIndexCol = 0; dimensionIndexCol < blockCols; ++dimensionIndexCol) {
auto coeff = source(sourceRow + dimensionIndexRow, sourceCol + dimensionIndexCol);
if(coeff != double(0)) {
target.coeffRef(targetRow + dimensionIndexRow, targetCol + dimensionIndexCol) += coeff;
}
}
}
}
void DeformableBody::combineStiffnessMatrices(SparseMatrix<double>& target, const SparseMatrix<double>& source, size_t tetraIndex) const {
for(int tetraRowIndex = 0; tetraRowIndex < 4; ++tetraRowIndex) {
auto rowVertexIndex = this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, tetraRowIndex) * 3;
for(int tetraColIndex = 0; tetraColIndex < 4; ++tetraColIndex) {
auto colVertexIndex = this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, tetraColIndex) * 3;
this->combineBlock(3, 3, target, rowVertexIndex, colVertexIndex, source, tetraRowIndex * 3, tetraColIndex * 3);
}
}
}
std::pair<SparseMatrix<double>, SparseMatrix<double>> DeformableBody::calculateStiffnessAndStressMatrix() const {
SparseMatrix<double> stiffnessMatrix(this->mesh.getSimulationMesh().rows(), this->mesh.getSimulationMesh().rows());
stiffnessMatrix.reserve(12 * 12 + 63 * (this->mesh.getNumberOfTetrahedron()-1));
SparseMatrix<double> stressMatrix(this->mesh.getNumberOfTetrahedron(), this->mesh.getSimulationMesh().rows());
if(this->isBreakingEnabled()) {
// TODO: Reserve on stressMatrix
}
for(size_t tetraIndex = 0; tetraIndex < this->mesh.getNumberOfTetrahedron(); ++tetraIndex) {
auto tetraMatrices = this->calculateStiffnessAndStressMatrixForTetrahedron(tetraIndex);
this->combineStiffnessMatrices(stiffnessMatrix, tetraMatrices.first, tetraIndex);
if(this->isBreakingEnabled()) {
auto tetraStress = tetraMatrices.second.colwise().sum();
for(int tetraColIndex = 0; tetraColIndex < 4; ++tetraColIndex) {
auto rowIndex = tetraIndex;
auto colVertexIndex = this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, tetraColIndex) * 3;
this->combineBlock(1, 3, stressMatrix, rowIndex, colVertexIndex, tetraStress, 0, tetraColIndex * 3);
}
}
}
stiffnessMatrix.makeCompressed();
stressMatrix.makeCompressed();
LOG(INFO) << "big stress " << stressMatrix.rows() << "x" << stressMatrix.cols();
return std::make_pair(stiffnessMatrix, stressMatrix);
}
SparseMatrix<double> DeformableBody::calculateDampeningMatrix() const {
SparseMatrix<double> dampening(this->mesh.getSimulationMesh().rows(), this->mesh.getSimulationMesh().rows());
dampening.setIdentity();
return this->dampening * dampening;
}
SparseMatrix<double> DeformableBody::calculateMassMatrix() const {
SparseMatrix<double> mass(this->mesh.getSimulationMesh().rows(), this->mesh.getSimulationMesh().rows());
for(int i = 0; i < this->mesh.getSimulationMesh().rows(); ++i) {
mass.insert(i, i) = static_cast<double>(this->mesh.getProperties().massPerVertex[i / 3]);
}
mass.makeCompressed();
return mass;
}
SparseMatrix<double, ColMajor> DeformableBody::calculateStepMatrix(float h) const {
SparseMatrix<double, ColMajor> mat = this->calculateMassMatrix() + h * h * this->stiffnessMatrix + h * this->dampeningMatrix;
mat.makeCompressed();
return mat;
}
void DeformableBody::prepareStepMatrixSolver() {
this->stepMatrixSolver.compute(this->stepMatrix);
}
void DeformableBody::updateStepMatrix(float h) {
TIMED_FUNC(timerCalcStiffnessMat);
this->stepMatrix = this->calculateStepMatrix(h);
this->prepareStepMatrixSolver();
this->stepSizeOnMatrixCalculation = h;
}
void DeformableBody::updateStepMatrixIfNecessary(float h) {
float deviation = ABS(this->stepSizeOnMatrixCalculation - h) / (float)this->stepSizeOnMatrixCalculation;
if(this->stepSizeOnMatrixCalculation == 0
|| deviation >= this->stepSizeDeviationPercentage) {
if(this->stepSizeOnMatrixCalculation != 0) {
LOG(WARNING) << "Recalculating step matrix. Time delta deviation: " << deviation << " %";
}
this->updateStepMatrix(h);
}
}
VectorXd DeformableBody::calculateCurrentDifferenceFromRestPosition() const {
return (this->mesh.getSimulationMesh() - this->restPosition).cast<double>();
}
VectorXd DeformableBody::calculateVelocities(float h, const VectorXf& forces) const {
return this->lastVelocities +
(
this->stepMatrixSolver.solve(
h * (
forces.cast<double>()
- this->stiffnessMatrix * this->calculateCurrentDifferenceFromRestPosition()
- this->dampeningMatrix * this->lastVelocities
- this->stiffnessMatrix * h * this->lastVelocities
)
)
);
}
void DeformableBody::calculateAndSetInitialState(float targetStepSize) {
LOG(INFO) << "Setting up deformable body matrices...";
this->restPosition = this->mesh.getSimulationMesh();
this->lastVelocities = VectorXd::Zero(this->mesh.getSimulationMesh().rows());
this->vertexFreezer = VectorXd::Ones(this->mesh.getSimulationMesh().rows());
this->dampeningMatrix = this->calculateDampeningMatrix();
auto materialbasedMatrices = this->calculateStiffnessAndStressMatrix();
this->stiffnessMatrix = materialbasedMatrices.first;
if(this->isBreakingEnabled()) {
this->stressMatrix = materialbasedMatrices.second;
}
this->updateStepMatrix(targetStepSize);
LOG(INFO) << "Done. Size of K: " << this->stiffnessMatrix.rows() << "x" << this->stiffnessMatrix.cols();
}
void DeformableBody::step(float deltaT, Force& force) {
auto forces = force.getForceOnVertices(this->mesh.getProperties());
if(forces.rows() > 0) {
this->step(deltaT, forces);
}
}
void DeformableBody::step(float deltaT, const VectorXf& forces) {
TIMED_FUNC_IF(timerSimulationStep, VLOG_IS_ON(1));
this->updateStepMatrixIfNecessary(deltaT);
this->lastVelocities = this->calculateVelocities(deltaT, forces);
// LOG(INFO) << "Error: " << this->stepMatrixSolver.error();
this->lastVelocities = this->lastVelocities.cwiseProduct(this->vertexFreezer);
this->mesh.updateMeshFromPlanarVector(this->mesh.getSimulationMesh() + (deltaT * this->lastVelocities).cast<float>());
if(this->isBreakingEnabled()) {
this->breakOnHighStress();
}
}
VectorXd DeformableBody::calculateStressPerTetrahedron(const VectorXd& deformation) {
return (this->stressMatrix * deformation).cwiseAbs();
}
void DeformableBody::breakOnHighStress() {
VectorXd stress = this->calculateStressPerTetrahedron(this->calculateCurrentDifferenceFromRestPosition());
LOG(INFO) << "Avg stress:" << stress.sum() / stress.rows();
Set<size_t> breakingTetrahedra;
breakingTetrahedra.set_empty_key(SIZE_MAX);
vector<std::pair<size_t, size_t>> breakingEdges;
for(int tetraIndex = 0; tetraIndex < stress.rows(); ++tetraIndex) {
if(stress[tetraIndex] > this->stressThresholdSqForBreaking) {
auto breakingEdge = this->findBreakingEdgeOfTetrahedron(tetraIndex);
if(this->deletedEdges.find(breakingEdge) == this->deletedEdges.end()) {
breakingEdges.push_back(breakingEdge);
this->deletedEdges.insert(breakingEdge);
this->deletedEdges.insert(std::make_pair(breakingEdge.second, breakingEdge.first));
auto tetrahedra = this->findTetrahedraAdjacentToEdge(breakingEdge);
breakingTetrahedra.insert(tetrahedra.begin(), tetrahedra.end());
}
}
}
if(breakingEdges.size() > 0) {
this->mesh.deleteEdges(breakingEdges);
for(auto index : breakingTetrahedra) {
this->deleteTetrahedronFromStiffnessAndStress(index);
}
this->prepareStepMatrixSolver();
// batch-remove all 0es
this->stressMatrix.prune([](auto row, auto col, auto val) { return abs(val) > 1e-16; });
}
}
vector<size_t> DeformableBody::findTetrahedraAdjacentToEdge(const std::pair<size_t, size_t>& edge) const {
vector<size_t> tetrahedra;
const auto& indices = this->mesh.getTetrahedronIndices();
for(size_t tetraIndex = 0; tetraIndex < indices.size() / 4; ++tetraIndex) {
if(this->deletedTetrahedra.find(tetraIndex) != this->deletedTetrahedra.end()) {
continue;
}
if(
(indices[tetraIndex * 4 + 0] == edge.first && indices[tetraIndex * 4 + 1] == edge.second)
|| (indices[tetraIndex * 4 + 0] == edge.first && indices[tetraIndex * 4 + 2] == edge.second)
|| (indices[tetraIndex * 4 + 0] == edge.first && indices[tetraIndex * 4 + 3] == edge.second)
|| (indices[tetraIndex * 4 + 1] == edge.first && indices[tetraIndex * 4 + 2] == edge.second)
|| (indices[tetraIndex * 4 + 1] == edge.first && indices[tetraIndex * 4 + 3] == edge.second)
|| (indices[tetraIndex * 4 + 2] == edge.first && indices[tetraIndex * 4 + 3] == edge.second)
|| (indices[tetraIndex * 4 + 0] == edge.second && indices[tetraIndex * 4 + 1] == edge.first)
|| (indices[tetraIndex * 4 + 0] == edge.second && indices[tetraIndex * 4 + 2] == edge.first)
|| (indices[tetraIndex * 4 + 0] == edge.second && indices[tetraIndex * 4 + 3] == edge.first)
|| (indices[tetraIndex * 4 + 1] == edge.second && indices[tetraIndex * 4 + 2] == edge.first)
|| (indices[tetraIndex * 4 + 1] == edge.second && indices[tetraIndex * 4 + 3] == edge.first)
|| (indices[tetraIndex * 4 + 2] == edge.second && indices[tetraIndex * 4 + 3] == edge.first)
) {
tetrahedra.push_back(tetraIndex);
}
}
return tetrahedra;
}
std::pair<size_t, size_t> DeformableBody::findBreakingEdgeOfTetrahedron(size_t tetraIndex) const {
MatrixXf currentTetrahedron = this->mesh.getTetrahedron(tetraIndex);
MatrixXf restTetrahedron = this->getRestTetrahedron(tetraIndex);
engine::util::Array<std::pair<size_t, size_t>> edges = {
{0, 1},
{0, 2},
{0, 3},
{1, 2},
{1, 3},
{2, 3}
};
MatrixXf restFrom(3, 6);
restFrom << restTetrahedron.col(0), restTetrahedron.col(0), restTetrahedron.col(0), restTetrahedron.col(1), restTetrahedron.col(1), restTetrahedron.col(2);
MatrixXf restTo(3, 6);
restTo << restTetrahedron.col(1), restTetrahedron.col(2), restTetrahedron.col(3), restTetrahedron.col(2), restTetrahedron.col(3), restTetrahedron.col(3);
MatrixXf currentFrom(3, 6);
currentFrom << currentTetrahedron.col(0), currentTetrahedron.col(0), currentTetrahedron.col(0), currentTetrahedron.col(1), currentTetrahedron.col(1), currentTetrahedron.col(2);
MatrixXf currentTo(3, 6);
currentTo << currentTetrahedron.col(1), currentTetrahedron.col(2), currentTetrahedron.col(3), currentTetrahedron.col(2), currentTetrahedron.col(3), currentTetrahedron.col(3);
VectorXf sqEdgeLengthDifferences = (
(restFrom - restTo).colwise().squaredNorm()
-(currentFrom - currentTo).colwise().squaredNorm()
).cwiseAbs().transpose();
std::pair<int, int> maxEdge = edges[0];
float maxDiff = sqEdgeLengthDifferences[0];
for(int i = 1; i < sqEdgeLengthDifferences.rows(); ++i) {
if(maxDiff < sqEdgeLengthDifferences[i]) {
maxDiff = sqEdgeLengthDifferences[i];
maxEdge = edges[i];
}
}
return std::make_pair(
this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, maxEdge.first),
this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, maxEdge.second)
);
}
void DeformableBody::deleteTetrahedronFromStiffnessAndStress(size_t tetraIndex) {
if(this->deletedTetrahedra.find(tetraIndex) != this->deletedTetrahedra.end()) {
return;
}
LOG(INFO) << "Deleted " << tetraIndex;
// Delete from stress
for(size_t row = tetraIndex; row < tetraIndex+1; ++row) {
for(int col = 0; col < this->stressMatrix.cols(); ++col) {
if(this->stressMatrix.coeff(row, col) != double(0)) {
this->stressMatrix.coeffRef(row, col) = 0;
}
}
}
this->combineStiffnessMatrices(this->stiffnessMatrix, -this->calculateStiffnessAndStressMatrixForTetrahedron(tetraIndex).first, tetraIndex);
this->deletedTetrahedra.insert(tetraIndex);
}
const ObjectProperties& DeformableBody::getProperties() const {
return this->mesh.getProperties();
}
VectorXd::Index DeformableBody::getExpectedForceVectorSize() const {
return this->mesh.getSimulationMesh().rows();
}
const VectorXf& DeformableBody::getCurrentPosition() const {
return this->mesh.getSimulationMesh();
}
Vector3f DeformableBody::getVertexOfRestPosition(int index) const {
return this->restPosition.segment<3>(index * 3);
}
MatrixXf DeformableBody::getRestTetrahedron(int tetraIndex) const {
MatrixXf tetrahedron(3, 4);
tetrahedron.col(0) = this->getVertexOfRestPosition(this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, 0));
tetrahedron.col(1) = this->getVertexOfRestPosition(this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, 1));
tetrahedron.col(2) = this->getVertexOfRestPosition(this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, 2));
tetrahedron.col(3) = this->getVertexOfRestPosition(this->mesh.getIndexOfVertexInTetrahedron(tetraIndex, 3));
return tetrahedron;
}
void DeformableBody::freezeVertex(size_t index) {
this->vertexFreezer.segment<3>(index * 3) = Vector3d::Zero();
}
void DeformableBody::freezeVertices(const engine::util::Array<size_t>& indices) {
for(auto index : indices) {
this->vertexFreezer.segment<3>(index * 3) = Vector3d::Zero();
}
}
void DeformableBody::unfreezeVertex(size_t index) {
this->vertexFreezer.segment<3>(index * 3) = Vector3d::Ones();
}
void DeformableBody::unfreezeVertices(const engine::util::Array<size_t>& indices) {
for(auto index : indices) {
this->vertexFreezer.segment<3>(index * 3) = Vector3d::Ones();
}
}
void DeformableBody::unfreezeAllVertices() {
this->vertexFreezer = VectorXd::Ones(this->vertexFreezer.rows());
}
bool DeformableBody::isBreakingEnabled() const {
return this->stressThresholdSqForBreaking > 0;
}
void DeformableBody::resetSimulation() {
this->lastVelocities = VectorXd::Zero(this->lastVelocities.rows());
this->mesh.updateMeshFromPlanarVector(this->restPosition);
}
}
}
| 51.781553 | 205 | 0.562154 | [
"mesh",
"vector"
] |
8ccc223c7085019fcfb9df22c0ca4120dabb789f | 331 | cpp | C++ | zadanie8/zadanie8.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | 1 | 2020-05-19T09:31:06.000Z | 2020-05-19T09:31:06.000Z | zadanie8/zadanie8.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | 2 | 2020-05-22T22:01:52.000Z | 2020-05-30T09:24:42.000Z | zadanie8/zadanie8.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
std::vector<int> foo(int count, int sequence) {
std::vector<int> vec(count);
for (size_t i = 0 ; i < count ; ++i) {
vec[i] = sequence * (i + 1);
}
return vec;
}
// int main() {
// for (const int element : foo(10, 5))
// std::cout << element << " | ";
// return 0;
// }
| 17.421053 | 47 | 0.528701 | [
"vector"
] |
8cda53a8a22b8d34b0428305e5ae23d6c900946e | 3,275 | hpp | C++ | redis/commands-set.hpp | cblauvelt/redis-client | e7e587f47f32adf2ad5c317138f58f128644f809 | [
"MIT"
] | null | null | null | redis/commands-set.hpp | cblauvelt/redis-client | e7e587f47f32adf2ad5c317138f58f128644f809 | [
"MIT"
] | 3 | 2022-02-02T04:29:21.000Z | 2022-03-17T02:30:12.000Z | redis/commands-set.hpp | cblauvelt/redis-client | e7e587f47f32adf2ad5c317138f58f128644f809 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <vector>
#include "redis/command.hpp"
#include "redis/types.hpp"
#include "redis/value.hpp"
namespace redis {
template <typename... Args> command sadd(std::string key, Args... members) {
auto commandStrings = std::vector<std::string>{"SADD", key};
(commandStrings.push_back(std::forward<Args>(members)), ...);
return command(commandStrings);
}
inline command sadd(std::string key, strings members) {
auto commandStrings = std::vector<std::string>{"SADD", key};
for (auto& member : members) {
commandStrings.push_back(std::move(member));
}
return command(commandStrings);
}
template <typename... Args> command sdiff(Args... keys) {
auto commandStrings = std::vector<std::string>{"SDIFF"};
(commandStrings.push_back(std::forward<Args>(keys)), ...);
return command(commandStrings);
}
inline command sdiff(strings keys) {
auto commandStrings = std::vector<std::string>{"SDIFF"};
for (auto& key : keys) {
commandStrings.push_back(std::move(key));
}
return command(commandStrings);
}
template <typename... Args> command sinter(Args... keys) {
auto commandStrings = std::vector<std::string>{"SINTER"};
(commandStrings.push_back(std::forward<Args>(keys)), ...);
return command(commandStrings);
}
inline command sinter(strings keys) {
auto commandStrings = std::vector<std::string>{"SINTER"};
for (auto& key : keys) {
commandStrings.push_back(std::move(key));
}
return command(commandStrings);
}
inline command sismember(std::string key, std::string member) {
return command(std::vector<std::string>{"SISMEMBER", key, member});
}
inline command sismember(std::string key, strings members) {
auto commandStrings = std::vector<std::string>{"SISMEMBER", key};
for (auto& member : members) {
commandStrings.push_back(std::move(member));
}
return command(commandStrings);
}
inline command smembers(std::string key) {
return command(std::vector<std::string>{"SMEMBERS", key});
}
inline command spop(std::string key, int num_pop = 1) {
if (num_pop == 1) {
return command(std::vector<std::string>{"SPOP", key});
}
return command(
std::vector<std::string>{"SPOP", key, std::to_string(num_pop)});
}
template <typename... Args> command srem(std::string key, Args... members) {
auto commandStrings = std::vector<std::string>{"SREM", key};
(commandStrings.push_back(std::forward<Args>(members)), ...);
return command(commandStrings);
}
inline command srem(std::string key, strings members) {
auto commandStrings = std::vector<std::string>{"SREM", key};
for (auto& member : members) {
commandStrings.push_back(std::move(member));
}
return command(commandStrings);
}
template <typename... Args> command sunion(Args... keys) {
auto commandStrings = std::vector<std::string>{"SUNION"};
(commandStrings.push_back(std::forward<Args>(keys)), ...);
return command(commandStrings);
}
inline command sunion(strings keys) {
auto commandStrings = std::vector<std::string>{"SUNION"};
for (auto& key : keys) {
commandStrings.push_back(std::move(key));
}
return command(commandStrings);
}
} // namespace redis
| 28.72807 | 76 | 0.665954 | [
"vector"
] |
8ce195cee3d33d53bbc5c58f8fe397d2731d2c47 | 2,021 | cpp | C++ | Lepus3D/Source/Transform/Transform.cpp | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | null | null | null | Lepus3D/Source/Transform/Transform.cpp | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | 22 | 2017-08-25T23:27:54.000Z | 2019-12-02T13:35:40.000Z | Lepus3D/Source/Transform/Transform.cpp | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | null | null | null | #include "../Transform.h"
using namespace LepusEngine::Lepus3D;
Transform::Transform(Vector3 p, Vector3 r, Vector3 s) : Transform::Transform()
{
m_Pos = glm::vec4(p.x, p.y, p.z, 1.f);
m_Rot = glm::vec4(r.x, r.y, r.z, 1.f);
m_Scale = glm::vec4(s.x, s.y, s.z, 1.f);
}
glm::mat4 Transform::GetMatrix()
{
glm::mat4 ret = glm::mat4(1.0);
ret = glm::translate(ret, m_Pos);
// Check if there is any rotation
// otherwise it would fill the matrix with NaN for some reason
if (m_Rot != Vector3(0.f, 0.f, 0.f).vec3())
ret = glm::rotate(ret, toRadians(m_RotAngle), m_Rot);
ret = glm::scale(ret, m_Scale);
return ret;
}
void Transform::SetPosition(Vector3 p)
{
m_Pos = p.vec3();
}
void Transform::SetRotation(Vector3 r)
{
float maxAngle = 0.f;
if (r.x >= r.y && r.x >= r.z)
maxAngle = r.x;
else if (r.y >= r.x && r.y >= r.z)
maxAngle = r.y;
else if (r.z >= r.x && r.z >= r.y)
maxAngle = r.z;
if (maxAngle != 0.f)
{
m_Rot = { r.x / maxAngle, r.y / maxAngle, r.z / maxAngle };
m_RotAngle = maxAngle;
}
}
void Transform::SetScale(Vector3 s)
{
m_Scale = s.vec3();
}
void Transform::SetScale(float s)
{
SetScale(Vector3(s, s, s));
}
void Transform::Move(Vector3 translation)
{
m_Pos.x += translation.x;
m_Pos.y += translation.y;
m_Pos.z += translation.z;
}
void Transform::Rotate(Vector3 rotation)
{
rotation.x += m_Rot.x;
rotation.y += m_Rot.y;
rotation.z += m_Rot.z;
SetRotation(rotation);
}
Vector3 Transform::GetPosition()
{
auto ret = Vector3::Create(m_Pos.x, m_Pos.y, m_Pos.z);
return ret;
}
Vector3 Transform::GetRotation()
{
return Vector3::Create(m_Rot.x * m_RotAngle, m_Rot.y * m_RotAngle, m_Rot.z * m_RotAngle);
}
Vector3 Transform::GetScale()
{
return Vector3(m_Scale.x, m_Scale.y, m_Scale.z);
}
std::string Transform::ToString()
{
Vector3 p = this->GetPosition();
Vector3 r = this->GetRotation();
Vector3 s = this->GetScale();
std::string ret = "P ";
ret += p.ToString();
ret += ", R ";
ret += r.ToString();
ret += ", S ";
ret += s.ToString();
return ret;
} | 20.414141 | 90 | 0.636813 | [
"transform"
] |
8ce71cc64626857f4abfc6f6b444c6920fdd1875 | 596 | cc | C++ | leetcode/055-jump-game/can_jump_v2.cc | dantin/poj | 812859a982da666daecedbb1197afed21485a432 | [
"BSD-3-Clause"
] | null | null | null | leetcode/055-jump-game/can_jump_v2.cc | dantin/poj | 812859a982da666daecedbb1197afed21485a432 | [
"BSD-3-Clause"
] | null | null | null | leetcode/055-jump-game/can_jump_v2.cc | dantin/poj | 812859a982da666daecedbb1197afed21485a432 | [
"BSD-3-Clause"
] | null | null | null | // version 1.0 2018-05-14
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool canJump(vector<int> &nums)
{
int maxCover = 0;
for (int i = 0; i <= maxCover && i < nums.size(); ++i) {
if (nums[i] + i > maxCover) {
maxCover = nums[i] + i;
}
if (maxCover >= nums.size()-1) return true;
}
return false;
}
};
int main()
{
int n, num;
vector<int> nums;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> num;
nums.push_back(num);
}
Solution s;
cout << s.canJump(nums) << endl;
return 0;
}
| 14.536585 | 60 | 0.526846 | [
"vector"
] |
8ce9505955fedbc4baea7d07fe687b5c1bc2a786 | 5,337 | cpp | C++ | ArdUI.cpp | ivanseidel/ArdUI | 599fe2bcb7c8e7d496a640866d0f242cc30d5421 | [
"MIT"
] | 11 | 2015-02-03T22:24:16.000Z | 2021-08-07T17:49:37.000Z | ArdUI.cpp | ivanseidel/ArdUI | 599fe2bcb7c8e7d496a640866d0f242cc30d5421 | [
"MIT"
] | null | null | null | ArdUI.cpp | ivanseidel/ArdUI | 599fe2bcb7c8e7d496a640866d0f242cc30d5421 | [
"MIT"
] | null | null | null | #include "ArdUI.h"
#include "Graphics.h"
#include "View.h"
#include "ViewGroup.h"
#ifdef DEBUG
#pragma message("ArdUI DEBUG Mode is ON")
#endif
// Default Setup
callback ArdUI::onInvalidateView = NULL;
bool ArdUI::enabled = false;
UTFT* ArdUI::LCD = NULL;
View* ArdUI::rootView = 0; // NULL
ArdUI::TouchTriggerMode ArdUI::touchMode = ArdUI::INTERRUPT_TIMER;
ArdUI::TouchPerception ArdUI::touchPerception = ArdUI::NORMAL;
UTouch* ArdUI::touchObject = 0; // NULL
int ArdUI::touchInterrupt = -1;
long ArdUI::touchTimerPeriod = 70000; // 70ms is the default
DueTimer* ArdUI::touchTimer = 0; // NULL
void ArdUI::enableTouch(){
debug("ArdUI::enableTouch()");
enabled = true;
setup();
}
void ArdUI::disableTouch(){
debug("ArdUI::disableTouch()");
enabled = false;
setup();
}
void ArdUI::setup(){
debug("ArdUI::setup()");
if(enabled && touchMode != NONE){
if(touchMode == INTERRUPT_TIMER){
// Enable interrupt on Touch pin
#ifdef DEBUG
if(touchInterrupt < 0)
debug("$ ArdUI: You didn't setup touchInterrupt!");
#endif
detachInterrupt(touchInterrupt);
attachInterrupt(touchInterrupt, touchHandler, FALLING);
// Stop Timer
#ifdef DEBUG
if(!touchTimer)
debug("$ ArdUI: You didn't setup touchTimer!");
#endif
touchTimer->attachInterrupt(touchHandler);
touchTimer->setPeriod(touchTimerPeriod);
// touchTimer->stop(); // This will bug, if changes View and is touching
}else if(touchMode == INTERRUPT_ONLY){
// Enable interrupt on Touch pin
#ifdef DEBUG
if(touchInterrupt < 0)
debug("$ ArdUI: You didn't setup touchInterrupt!");
#endif
attachInterrupt(touchInterrupt, touchHandler, LOW);
// Stop Timer
if(touchTimer)
touchTimer->stop();
}else if(touchMode == TIMER_ONLY){
// Disable interrupt
if(touchInterrupt >= 0)
detachInterrupt(touchInterrupt);
// Enable Timer
#ifdef DEBUG
if(!touchTimer)
debug("$ ArdUI: You didn't setup touchTimer!");
#endif
touchTimer->attachInterrupt(touchHandler);
touchTimer->setPeriod(touchTimerPeriod);
touchTimer->start();
}else{
debug("$ ArdUI: _touchMode not configured! ", touchMode);
}
}else{
// Disable interrupt
if(touchInterrupt >= 0)
detachInterrupt(touchInterrupt);
// Stop Timer
if(touchTimer)
touchTimer->stop();
}
}
// Method that handles touch on screen and send Events
void ArdUI::touchHandler(){
debug("ArdUI::touchHandler");
static bool is_touching = false, same_spot = false;
static int lastRootViewID = 0, x, y;
static ActionEvent event; // Static to not spend memory
static View* currView = 0; // Current view being touched
static View* currRootView = 0; // Root of the views
if(touchMode == INTERRUPT_TIMER){
touchTimer->start();
detachInterrupt(touchInterrupt);
}
if(touchObject->dataAvailable()){
touchObject->read();
if (touchPerception==NORMAL){
x = touchObject->getX();
y = touchObject->getY();
}
if (touchPerception==INVERTED_X){
x = LCD->getDisplayXSize() - touchObject->getX();
y = touchObject->getY();
}
if (touchPerception==INVERTED_Y){
x = touchObject->getX();
y = LCD->getDisplayYSize() - touchObject->getY();
}
if (touchPerception==INVERTED_X_Y){
x = LCD->getDisplayXSize() - touchObject->getX();
y = LCD->getDisplayYSize() - touchObject->getY();
}
// Check if is the same spot touched
same_spot = false;
if(event.x == x && event.y == y)
same_spot = true;
//We copy, to avoid changing while processing
currRootView = rootView;
// Checks if there is a current activity
if(currRootView){
event.x = x;
event.y = y;
// hit test the same last view? (and is the same root View)
if( currRootView->ViewID == lastRootViewID
&& currView
&& currView->hitTest(event.x, event.y)){
// Did it moved?
if(!same_spot){
// Prepare event
event.type = ACTION_MOVE;
// Send callback
currView->onTouch(event);
}
}else if(!same_spot){
// Check if was over another object, if yes
// send a ACTION_HOVER_EXIT to it
if(currView){
event.type = ACTION_HOVER_EXIT;
currView->onTouch(event);
}
// This will return the first view on the Tree
// that has been hitted. Starting from currRootView
currView = currRootView->hitTest(event.x, event.y);
if(currView){
// If was touching, then is a Hover_enter,
// otherwise, it's a Down event
if(is_touching)
event.type = ACTION_HOVER_ENTER;
else
event.type = ACTION_DOWN;
// Send callback
currView->onTouch(event);
}
}
is_touching = true; // is touching screen
}
// Save this activity ID as last, so we can compare next time
lastRootViewID = (currRootView? currRootView->ViewID: 0);
}else{
// Checks if released button
// Was there a view being touched?
if(currView){
// is the same root view?
if(rootView->ViewID == lastRootViewID){
// Prepare event
event.type = ACTION_UP;
// Send callback
currView->onTouch(event);
}
}
// Reset flags
if(is_touching){
is_touching = false;
currView = NULL;
}
// If, trigger mode is INTERRUPT_TIMER:
// * Disable timer
// * Enable interrupt
if(touchMode == INTERRUPT_TIMER){
touchTimer->stop();
attachInterrupt(touchInterrupt, touchHandler, LOW);
}
}
} | 24.259091 | 75 | 0.66498 | [
"object"
] |
8ceeb59e4ab69589b1d5962038a50d52c23f76a4 | 9,165 | cpp | C++ | 1 course/math_lab_5/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 1 course/math_lab_5/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 1 course/math_lab_5/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <cmath>
#include <ctime>
#include <limits.h>
#include <vector>
#include <iomanip>
#include <fstream>
#include <windows.h>
using namespace std;
typedef vector<int> row;
typedef vector<row> graf;
void clean (graf &A)
{
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
A[i][j] = 0;
}
}
}
void create_empty_matrix (graf &A)
{
row Row(5,0);
for (int i=0; i<5; i++)
{
A.push_back(Row);
}
}
void hand_init_weight (graf &A, bool &alg)
{
int n = A.size();
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (j != i) {
cout << " Вес связи " << i+1 << "-" << j+1 << " [-10; 10]: ";
cin >> A[i][j];
while ((A[i][j] < -10) || (A[i][j] > 10))
{
cout << " Ошибка! Вы зашли за границы! Повторите ввод: ";
cin >> A[i][j];
}
if (A[i][j] < 0) { alg = false; }
}
}
}
}
void random_init_weight (graf &A, bool &alg)
{
int n = A.size();
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (j != i) {
//A[i][j] = -10 + rand()%22;
A[i][j] = rand()%11;
if (A[i][j] < 0) { alg = false; }
}
}
}
}
void diagramm_way (const graf &A)
{
ofstream out("graph.dot");
out << "digraph {\n";
int n = A.size();
for (int i=0; i<n; i++)
{
int c = 0;
for (int j=0; j<n; j++)
{
if (A[i][j] != 0)
{
out << i+1 << "->" << j+1 << "[label=\"" << A[i][j] << "\"];" << endl;
} else c++;
}
if (c == n) out << i+1 << endl;
}
out << "}\n";
out.close();
}
void print_graf (const graf &A)
{
int n = A.size();
cout << setw(3) << "\\" << setw(4) << "A" << setw(2) << "|" << endl;
cout << setw(4) << "\\" << setw(5) << "|" << endl;
cout << setw(2) << "A" << setw (3) << "\\" << setw(4) << "|";
for (int j=0; j<n; j++)
{
cout << "\t" << j+1;
}
cout << endl;
cout << setfill('-') << setw(60);
cout << "\n";
cout << setfill(' ');
for (int i=0; i<n; i++)
{
cout << i+1 << "\t" << "|";
for(int j=0; j<n; j++)
{
cout << "\t";
if (i != j && A[i][j] == 0) {
cout << "inf";
} else { cout << A[i][j]; }
}
cout << endl;
cout << setfill('-') << setw(60);
cout << "\n";
cout << setfill(' ');
}
}
void Deikstra(const graf &A, const int &st)
{
cout << "Промежуточные результаты работы алгоритма Дейкстры: " << endl;
cout << " i\td[1]\td[2]\td[3]\td[4]\td[5]" << endl; // шапка промежуточных выводов
int N = A.size();
vector<int> distance = A[st]; // вектор - длины путей у каждой вершины
for (int i = 0; i < N; i++)
{
if ((distance[i] == 0) && (st != i)) distance[i] = INT_MAX;
}
cout << " 1\t";
for (int i=0; i<N; i++) // вывожу первую строку по алгоритму
{
if (distance[i]!=INT_MAX) cout<<distance[i]<< "\t";
else cout<< "inf"<< "\t";
}
cout << endl;
vector<bool> visited(N, false); // вектор - проверена ли вершина
visited[st] = true; // исключаю источник из множества вершин T
for (int S=1; S< N-1; S++) // до N-1, так как последнюю вершину нет смысла рассматривать, так как все соседи уже проверены
{
int min=INT_MAX;
int j(0);
for (int i=0; i<N; i++)
{
if (!visited[i] && distance[i]<=min) // ищем ближайшую нерассмотренную вершину с минимальной длиной пути
{
min=distance[i];
j=i;
}
}
visited[j]=true; // когда нашли, помечаем ее как рассмотренную, так как сейчас будем ее проверять
for (int k=0; k<N; k++)
{
// если вершина j не рассмотрена, между текущей и j существует ребро,
// проверка дистанс на != INT_MAX на случай если источник - изолирован ото всех, тогда и нет смысла ничего проверять,
// если новый дистанс оказался меньше предыдущего
if (!visited[k] && A[j][k] && distance[j]!=INT_MAX && distance[j]+A[j][k]<distance[k])
distance[k]=distance[j]+A[j][k]; // тогда получаем новую длину пути (дистанс)
}
cout << " "<< S+1 << "\t";
for (int i=0; i<N; i++)
{
if (distance[i]!=INT_MAX) cout<<distance[i]<< "\t";
else cout<< "inf"<< "\t";
}
cout << endl;
}
int m=st+1;
cout<<"Стоимость пути из начальной вершины до остальных:\t\n";
for (int i=0; i<N; i++)
if (distance[i]!=INT_MAX)
cout<<m<<" > "<<i+1<<" = "<<distance[i]<<endl;
else if (st == i) cout<<m<<" > "<<i+1<<" = "<<"0"<<endl;
else
cout<<m<<" > "<<i+1<<" = "<<"маршрут недоступен"<<endl;
}
void Ford_Bellman (const graf &A, const int &st)
{
cout << "Промежуточные результаты работы алгоритма Дейкстры: " << endl;
cout << " i\td[1]\td[2]\td[3]\td[4]\td[5]" << endl; // шапка промежуточных выводов
int N = A.size();
vector<int> distance = A[st]; // вектор - длины путей у каждой вершины
for (int i = 0; i < N; i++)
{
if ((distance[i] == 0) && (st != i)) distance[i] = INT_MAX;
}
cout << " 1\t";
for (int i=0; i<N; i++) // вывожу первую строку по алгоритму
{
if (distance[i]!=INT_MAX) cout<<distance[i]<< "\t";
else cout<< "inf"<< "\t";
}
cout << endl;
for (int S=1; S< N-1; S++) // до N-1, так как последнюю вершину нет смысла рассматривать, так как все соседи уже проверены
{
vector<int> distance_old = distance;
for (int j=0; j<N; j++)
{
int min = distance_old[j];
for (int k = 0; k < N; k++)
{
// если вершина j не рассмотрена, между текущей и j существует ребро,
// проверка дистанс на != INT_MAX на случай если источник - изолирован ото всех, тогда и нет смысла ничего проверять,
// если новый дистанс оказался меньше предыдущего
if (A[k][j] && distance_old[k]!=INT_MAX && distance_old[k]+A[k][j]<min)
min=distance_old[k]+A[k][j]; // тогда получаем новую длину пути (дистанс)
}
distance[j] = min;
}
cout << " "<< S+1 << "\t";
for (int i=0; i<N; i++)
{
if (distance[i]!=INT_MAX) cout<<distance[i]<< "\t";
else cout<< "inf"<< "\t";
}
cout << endl;
if (distance == distance_old) S = N;
}
int m=st+1;
cout<<"Стоимость пути из начальной вершины до остальных:\t\n";
for (int i=0; i<N; i++)
if (distance[i]!=INT_MAX)
cout<<m<<" > "<<i+1<<" = "<<distance[i]<<endl;
else if (st == i) cout<<m<<" > "<<i+1<<" = "<<"0"<<endl;
else
cout<<m<<" > "<<i+1<<" = "<<"маршрут недоступен"<<endl;
}
int main()
{
srand(time(0));
system("chcp 1251 > nul");
int ch = 1;
while (ch == 1)
{
bool alg = true;
graf A;
create_empty_matrix(A);
int init;
int ok = 0;
while (ok != 2) {
clean(A);
cout << " Заполнения матрицы весов \n 1. С клавиатуры \n 2. Случайно" << endl;
do {
cout << " \nВвод: ";
cin >> init;
} while ((init < 1) || (init > 2));
if (init == 1) {
hand_init_weight(A, alg);
} else {
random_init_weight(A, alg);
}
cout << " Матрица весов: " << endl;
print_graf(A);
cout << " Пересгенерировать матрицу? \n 1. Да \n 2. Нет" << endl;
do {
cout << " \nВвод: ";
cin >> ok;
} while ((ok < 1) || (ok > 2));
}
cout << " Открываю диаграмму графа... " << endl;
diagramm_way(A);
system("graphics\\circo.exe -Tpng -O graph.dot");
system("graph.dot.png");
system("pause");
int st;
do {
cout << " Выберите вершину графа [1, 5]: ";
cin >> st;
} while ((st < 1) || (st > 5));
if (alg)
{
int met;
cout << " 1. Алгоритм Дейкстры. \n 2. Алгоритм Форда-Беллмана." << endl;
do {
cout << " \nВвод: ";
cin >> met;
} while ((met < 1) || (met > 2));
if (met == 1) {
Deikstra(A, st-1);
} else { Ford_Bellman(A, st-1); }
} else {
cout << " Доступен только алгоритм Форда-Беллмана, так как хотя бы одна дуга имеет отрицательный вес." << endl;
Ford_Bellman(A, st-1);
}
cout << " \n 0. Выход \n 1. Пересгенерировать" << endl;
do {
cout << " \nВвод: ";
cin >> ch;
} while ((ch < 0) || (ch > 1));
}
return 0;
}
| 29.469453 | 133 | 0.438953 | [
"vector"
] |
8cf498ba9f1f340d9ebd333c2bd7c7b6abece40b | 5,777 | cpp | C++ | cwp/src/v20180228/model/DescribeUndoVulCountsResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cwp/src/v20180228/model/DescribeUndoVulCountsResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cwp/src/v20180228/model/DescribeUndoVulCountsResponse.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* 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/cwp/v20180228/model/DescribeUndoVulCountsResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cwp::V20180228::Model;
using namespace std;
DescribeUndoVulCountsResponse::DescribeUndoVulCountsResponse() :
m_undoVulCountHasBeenSet(false),
m_undoHostCountHasBeenSet(false),
m_notProfessionCountHasBeenSet(false)
{
}
CoreInternalOutcome DescribeUndoVulCountsResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("UndoVulCount") && !rsp["UndoVulCount"].IsNull())
{
if (!rsp["UndoVulCount"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `UndoVulCount` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_undoVulCount = rsp["UndoVulCount"].GetUint64();
m_undoVulCountHasBeenSet = true;
}
if (rsp.HasMember("UndoHostCount") && !rsp["UndoHostCount"].IsNull())
{
if (!rsp["UndoHostCount"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `UndoHostCount` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_undoHostCount = rsp["UndoHostCount"].GetInt64();
m_undoHostCountHasBeenSet = true;
}
if (rsp.HasMember("NotProfessionCount") && !rsp["NotProfessionCount"].IsNull())
{
if (!rsp["NotProfessionCount"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `NotProfessionCount` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_notProfessionCount = rsp["NotProfessionCount"].GetUint64();
m_notProfessionCountHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeUndoVulCountsResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_undoVulCountHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UndoVulCount";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_undoVulCount, allocator);
}
if (m_undoHostCountHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "UndoHostCount";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_undoHostCount, allocator);
}
if (m_notProfessionCountHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NotProfessionCount";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_notProfessionCount, allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
uint64_t DescribeUndoVulCountsResponse::GetUndoVulCount() const
{
return m_undoVulCount;
}
bool DescribeUndoVulCountsResponse::UndoVulCountHasBeenSet() const
{
return m_undoVulCountHasBeenSet;
}
int64_t DescribeUndoVulCountsResponse::GetUndoHostCount() const
{
return m_undoHostCount;
}
bool DescribeUndoVulCountsResponse::UndoHostCountHasBeenSet() const
{
return m_undoHostCountHasBeenSet;
}
uint64_t DescribeUndoVulCountsResponse::GetNotProfessionCount() const
{
return m_notProfessionCount;
}
bool DescribeUndoVulCountsResponse::NotProfessionCountHasBeenSet() const
{
return m_notProfessionCountHasBeenSet;
}
| 33.201149 | 136 | 0.694478 | [
"object",
"model"
] |
8cf7e4c1d42b4e8c082f992ce58fd5eb44095041 | 90,143 | cpp | C++ | src/main.cpp | intesight/Panorama4GWM | 55571a1d22fae2257db4a968ee7c1776c9ad543a | [
"WTFPL"
] | null | null | null | src/main.cpp | intesight/Panorama4GWM | 55571a1d22fae2257db4a968ee7c1776c9ad543a | [
"WTFPL"
] | null | null | null | src/main.cpp | intesight/Panorama4GWM | 55571a1d22fae2257db4a968ee7c1776c9ad543a | [
"WTFPL"
] | 3 | 2021-01-16T13:53:41.000Z | 2021-01-28T10:48:30.000Z | /*****************************************************************************
*
* Freescale Confidential Proprietary
*
* Copyright (c) 2016 Freescale Semiconductor;
* All Rights Reserved
*
*****************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS 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 <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "ImageStitching.h"
#include "uart_to_mcu.h"
#include "uart_to_android.h"
#include "fb_helper.h"
#include "network.h"
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <errno.h>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#ifndef __STANDALONE__
#include <signal.h>
#include <termios.h>
#endif // #ifdef __STANDALONE__
#include <string.h>
#ifdef __STANDALONE__
#include "frame_output_dcu.h"
#define CHNL_CNT io::IO_DATA_CH3
#else // #ifdef __STANDALONE__
#include "frame_output_v234fb.h"
#define CHNL_CNT io::IO_DATA_CH3
#endif // else from #ifdef __STANDALONE__
#include "oal.h"
#include "vdb_log.h"
#include "sdi.hpp"
#include "max9286_96705_4_uyvy_c.h"
#include "vdb_log.h"
///////////////////////////////////new head files//////////////////////////////////////////////////////
//#include <stdio.h>
#include <fstream>
#include "CameraDevice.h"
#include "DrawScene.h"
#include "ImageBilt.h"
#include "FinalScene.h"
#include "keyboardInput.h"
#include "OGLEGL.h"
#include "PanoramaParam.h"
#include "Panorama3DScene.h"
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include "dump.h"
#include "utils/Timer.hpp"
//#include "json.hpp"
//using json = nlohmann::json;
bool fbo_on = false;
char path_pattern[256+1]={0};
int num_frames = 0;
using namespace keyboard_device; //ʹ�ñ������豸
//for gl end
//****************************************************************************//
using namespace cv;
extern unsigned int McuTimeData;
extern unsigned long long Mcu_tt;
unsigned long long Soc_tt;
BasicData *BasicData_Ptr;
CamData *CamData_Ptr;
ParkingPlace *ParkingPlace_Ptr;
McuSendDada *McuSendDada_Ptr;
LanelineData *LanelineData_Ptr;
ObstacleData *ObstacleData_Ptr;
PCWRITEDATA *PCWRITEDATA_Ptr;
extern volatile unsigned int CounterTick;
unsigned long long GetTime(void);
unsigned long long GetNowTimeUs(void);
extern int num;
extern int McuSendOffset[10*3];
extern unsigned int McuSendCounter[10];
extern int reset_status_changed_num;
extern int reset_new_value_cnt;
extern int reset_new_value_cnt_flag;
extern int reset_chang_flag;
extern SOCREADDATA AndroidSend_SocReadData;
extern SOCWRITEDATA AndroidReceive_SocWriteData;
vsdk::SMat frame_map[4];
//unsigned char* frameDataPtr[4];
vsdk::SMat frame_map_out;
unsigned char mem_tmp_T0[IMG_WIDTH*IMG_HEIGHT*2];
unsigned char mem_tmp_T1[IMG_WIDTH*IMG_HEIGHT*2];
unsigned char mem_tmp_T2[IMG_WIDTH*IMG_HEIGHT*2];
unsigned char mem_tmp_T3[IMG_WIDTH*IMG_HEIGHT*2];
void *VideoCaptureTask(void * ptr);
void *GLTask(void * ptr);
int Ipc_Create();
//int saveframe(char *str, void *p, int length, int is_oneframe);
/**********************************************************Parking Management***************************/
typedef struct parkplace{
float ParkPlace[4*2];
int x;
int y;
int z;
int park_confidence;
struct parkplace *next;
} LinkList; //定义车位链表节点
static int TimeCntTmp1;
LinkList *head; //定义头节点
ParkingPlace ParkingPlace_PtrCopy;
int disFront; //后轴中心点到环视前视野边缘距离
int disBack; //后轴中心点到环视后视野边缘距离
int disLF; //后轴中心点到环视左/右视野边缘距离
int validNode; //当前链表中在视野范围内的节点数(即车位数)
//#define Rear_Axle_Center_x 405
//#define Rear_Axle_Center_y 680
//#define Pixel_Ration 9.83
///////1200x1080 2D VIEW/////////////////////////////////////////////////
//车身坐标系:后轴中心点为原点,车头方向为X+,左侧为Y+
//屏幕坐标系,左上角为原点,水平为X,垂直为Y
int Rear_Axle_Center_x = 1320; //屏幕坐标系,后轴中心点X坐标
int Rear_Axle_Center_y = 700;//654+20; //屏幕坐标系,后轴中心点Y坐标
float Pixel_Ration_x = 9.448;//9.62; //屏幕坐标系,垂直方向
float Pixel_Ration_y = 8.667;//9.5; //屏幕坐标系,水平方向
///////720x900 2D VIEW/////////////////////////////////
int Rear_Axle_Center_x2 = 1560; //屏幕坐标系,后轴中心点X坐标
int Rear_Axle_Center_y2 = 583;//564;//600; //屏幕坐标系,后轴中心点Y坐标
float Pixel_Ration2_x = 9.448;//9.62; //屏幕坐标系,垂直方向
float Pixel_Ration2_y = 8.667;//9.5; //屏幕坐标系,水平方向
////////////////////////////////////////////////////////////////////////
int disLRCam;
int Mcu_Send_Parking_Data_Fag;
int Parking_Select_Num ; //parking place selected
int Total_Parking_Num ;
int Car_Parking_Status;
int Parking_Place_Mode_Select_OK;
int Car_Speed_Flag;
int parking_place_detected_flag;
int parking_place_detected_num;
extern TARGETPLACEDATA ToMcuTargetData;
int parking_in_scan_direction; //1 scan left 2 scan right
static void coord_pts2veh(short int curr_coords[3], short int prev_coords[3], float prev_pts[8], float pts2veh[8]);
static void coord_cc2oc(short int coords[3], float cc[8], float oc[8]);
void insert_trail(LinkList * list,LinkList * newnode);
void deleteNode(LinkList *list, int n) ;
void deleteLinklist(LinkList *list);
void ParkingManagemet();
/******************************************************************************/
//***************************************************************************
// Possible to set input resolution (must be supported by the DCU)
#define WIDTH 1280 ///< width of DDR buffer in pixels
#define HEIGHT 960 ///< height of DDR buffer in pixels
#define DDR_BUFFER_CNT 3 ///< number of DDR buffers per ISP stream
static uint8_t OutPutBufferUYVY[WIDTH*HEIGHT*2];
static uint8_t RGB24Buffer[WIDTH*HEIGHT*3];
//***************************************************************************
#define FRM_TIME_MSR 300 ///< number of frames to measure the time and fps
#ifdef __STANDALONE__
//extern SEQ_Buf_t producerless_buffer_1;
extern "C" {
unsigned long get_uptime_microS(void);
}
#define GETTIME(time) (*(time)=get_uptime_microS())
#else // ifdef __STANDALONE__
#define GETTIME(time) \
{ \
struct timeval lTime; gettimeofday(&lTime,0); \
*time=(lTime.tv_sec*1000000+lTime.tv_usec); \
}
#endif // else from #ifdef __STANDALONE__
/************************************************************************/
/** User defined call-back function for Sequencer event handling.
*
* \param aEventType defines Sequencer event type
* \param apUserVal pointer to any user defined object
************************************************************************/
void SeqEventCallBack(uint32_t aEventType, void* apUserVal);
#ifndef __STANDALONE__
/************************************************************************/
/** SIGINT handler.
*
* \param aSigNo
************************************************************************/
void SigintHandler(int);
/************************************************************************/
/** SIGINT handler.
*
* \param aSigNo
*
* \return SEQ_LIB_SUCCESS if all ok
* SEQ_LIB_FAILURE if failed
************************************************************************/
int32_t SigintSetup(void);
//***************************************************************************
static bool sStop = false; ///< to signal Ctrl+c from command line
#endif // #ifndef __STANDALONE__
/************************************************************************/
/** Allocates contiguous DDR buffers for one ISP stream.
*
* \param appFbsVirtual array of virtual buffer pointers to be filled
* \param apFbsPhysical array of buffer physical addresses to be filled
* \param aMemSize size of the array in bytes
* \param aBufferCnt number of buffers to be allocated
*
* \return 0 if all OK
* < 0 otherwise
************************************************************************/
int32_t DdrBuffersAlloc(void** appFbsVirtual, uint32_t* apFbsPhysical,
size_t aMemSize, uint32_t aBufferCnt);
/************************************************************************/
/** Frees DDR buffers for one ISP stream.
*
* \param appFbsVirtual array of virtual buffer pointers to be filled
* \param apFbsPhysical array of buffer physical addresses to be filled
* \param aBufferCnt number of buffers to be freed
************************************************************************/
void DdrBuffersFree(void** appFbsVirtual, uint32_t* apFbsPhysical,
uint32_t aBufferCnt);
static void TermNonBlockSet()
{
struct termios lTermState;
// get current state of the terminal
tcgetattr(STDIN_FILENO, &lTermState);
// disable canonical mode
lTermState.c_lflag &= ~ICANON;
// set minimum number of input characters to read
lTermState.c_cc[VMIN] = 1;
// set the terminal attributes
tcsetattr(STDIN_FILENO, TCSANOW, &lTermState);
} // TermNonBlockSet()
static int KeyDown()
{
struct timeval lTv;
fd_set lFdSet;
lTv.tv_sec = 0;
lTv.tv_usec = 50;
FD_ZERO(&lFdSet);
FD_SET(STDIN_FILENO, &lFdSet);
select(STDIN_FILENO + 1, &lFdSet, NULL, NULL, &lTv);
return FD_ISSET(STDIN_FILENO, &lFdSet);
} // KeyDown()
static int GetCharNonBlock()
{
int lChar = EOF;
usleep(1);
if(KeyDown())
{
lChar = fgetc(stdin);
} // if Key pressed
return lChar;
} // KeyDown()
static char GetChar()
{
#ifdef __STANDALONE__
return sci_0_testchar();
#else // #ifdef __STANDALONE__
int lChar = GetCharNonBlock();
return (char)((lChar < 0)? 0: lChar&0xff);
#endif // else from #ifdef __STANDALONE__
} // GetChar()
#if 1
//#define IMAGE_DEBUG_MODE
int main(int, char **)
{
int ret = 0;
pthread_t gltask,cltask,keytask,tertask,guitask,uartrxtask,uarttxtask,videotask,id1;
pthread_t net_staus_thread,tr_thread,rv_thread, uartandroidrxtask, uartandroidtxtask;
Ipc_Create();
//OpenglInit();
#ifndef IMAGE_DEBUG_MODE
pthread_create(&videotask, NULL, VideoCaptureTask,NULL);
#endif
sleep(1);
printf("start GLTask\n");
#ifdef IMAGE_DEBUG_MODE
ret = pthread_create(&gltask, NULL, GLTask,NULL);
#endif
if(ret)
{
printf("Create GL Task error!\n");
return 1;
}
//ret = pthread_create(&cltask, NULL, CLTask,NULL);
if(ret)
{
printf("Create CLTask error!\n");
return 1;
}
ret = pthread_create(&keytask, NULL, KeyTask,NULL);
if(ret)
{
printf("Create keytask error!\n");
return 1;
}
//ret = pthread_create(&tertask, NULL, TerminalTask,NULL);
if(ret)
{
printf("Create TerminalTask error!\n");
return 1;
}
//ret = pthread_create(&guitask, NULL, Gui_meg_thread,NULL);
//pthread_create(&id1, NULL, Gui_draw_thread,NULL);
/// if(ret)
/// {
/// printf("Create Gui_meg_thread error!\n");
/// return 1;
/// }
#ifndef IMAGE_DEBUG_MODE
ret = pthread_create(&uartrxtask, NULL, Uart_meg_thread,NULL);
if(ret)
{
printf("Create Uart_meg_thread error!\n");
return 1;
}
ret = pthread_create(&uarttxtask, NULL, Uart_TX_thread,NULL);
if(ret)
{
printf("Create Uart_TX_thread error!\n");
return 1;
}
ret = pthread_create(&tr_thread, NULL, net_tr_thread, NULL);
if(ret)
{
printf("Create net_tr_thread error!\n");
return 1;
}
ret = pthread_create(&uartandroidrxtask, NULL, Uart_to_Android_RX_thread,NULL);
if(ret)
{
printf("Create Uart_to_Android_RX_thread error!\n");
return 1;
}
ret = pthread_create(&uartandroidtxtask, NULL, Uart_to_Android_TX_thread,NULL);
if(ret)
{
printf("Create Uart_to_Android_TX_thread error!\n");
return 1;
}
#endif
#ifndef IMAGE_DEBUG_MODE
pthread_join(videotask,NULL);
#else
pthread_join(gltask, NULL);
#endif
//pthread_join(cltask,NULL);
pthread_join(keytask,NULL);
//pthread_join(tertask,NULL);
//pthread_join(guitask,NULL);
pthread_join(uartrxtask,NULL);
pthread_join(uarttxtask,NULL);
pthread_join(tr_thread,NULL);
pthread_join(uartandroidrxtask,NULL);
pthread_join(uartandroidtxtask,NULL);
return 0;
}
#endif
void *VideoCaptureTask(void *ptr1)
{
LIB_RESULT lRet = LIB_SUCCESS;
LIB_RESULT lRes = LIB_SUCCESS;
char cam_cmd[12];
char cur_char;
//vsdk::SMat frame_map_UYVY;
OAL_Initialize();
//*** Init DCU Output ***
#ifdef __STANDALONE__
io::FrameOutputDCU
lDcuOutput(WIDTH,
HEIGHT,
io::IO_DATA_DEPTH_08,
io::IO_DATA_CH3,
DCU_BPP_YCbCr422
);
#else // #ifdef __STANDALONE__
// setup Ctrl+C handler
//if(SigintSetup() != SEQ_LIB_SUCCESS)
//{
// VDB_LOG_ERROR("Failed to register Ctrl+C signal handler.");
//return -1;
//}
//printf("Press Ctrl+C to terminate the demo.\n");
// *** set terminal to nonblock input ***
//TermNonBlockSet();
/*
io::FrameOutputV234Fb
lDcuOutput(1280,
720,
io::IO_DATA_DEPTH_08,
io::IO_DATA_CH3,
DCU_BPP_YCbCr422
);
*/
#endif // else from #ifdef __STANDALONE__
//printf("main.cpp line135\n");
//
// *** Initialize SDI ***
//
lRes = sdi::Initialize(0);
//printf("main.cpp line140\n");
// *** create grabber ***
sdi_grabber *lpGrabber = new(sdi_grabber);
lpGrabber->ProcessSet(gpGraph, &gGraphMetadata);
//printf("main.cpp line144\n");
// *** set user defined Sequencer event handler ***
int32_t lCallbackUserData = 12345;
lpGrabber->SeqEventCallBackInstall(&SeqEventCallBack, &lCallbackUserData);
// *** prepare IOs ***
sdi_FdmaIO *lpFdma = (sdi_FdmaIO*)lpGrabber->IoGet(SEQ_OTHRIX_FDMA);
// modify DDR frame geometry to fit display output
SDI_ImageDescriptor lFrmDesc = SDI_ImageDescriptor(WIDTH, HEIGHT, YUV422Stream_UYVY);
lpFdma->DdrBufferDescSet(0, lFrmDesc);
lFrmDesc = SDI_ImageDescriptor(WIDTH, HEIGHT, YUV422Stream_UYVY);
lpFdma->DdrBufferDescSet(1, lFrmDesc);
lFrmDesc = SDI_ImageDescriptor(WIDTH, HEIGHT, YUV422Stream_UYVY);
lpFdma->DdrBufferDescSet(2, lFrmDesc);
lFrmDesc = SDI_ImageDescriptor(WIDTH, HEIGHT, YUV422Stream_UYVY);
lpFdma->DdrBufferDescSet(3, lFrmDesc);
//*** allocate DDR buffers ***
lpFdma->DdrBuffersAlloc(DDR_BUFFER_CNT);
//printf("main.cpp line154\n");
TermNonBlockSet();
// *** prestart grabber ***
lpGrabber->PreStart();
//printf("main.cpp line157\n");
// fetched frame buffer storage
SDI_Frame lFrame[4];
// *** start grabbing ***
lpGrabber->Start();
//printf("main.cpp line163\n");
unsigned long lTimeStart = 0, lTimeEnd = 0, lTimeDiff = 0;
GETTIME(&lTimeStart);
uint32_t actualBufferIndex = 2;
uint32_t lFrmCnt = 0;
printf("Complete init done.\n");
uint8_t lLoop=0;
uint8_t num=0;
static int nn;
static int numCopy;
static int McuSendOffsetCopy[10*3];
static unsigned int McuSendCounterCopy[10];
int numtmp;
//frameDataPtr[0] = mem_tmp_T0;
//frameDataPtr[1] = mem_tmp_T1;
//frameDataPtr[2] = mem_tmp_T2;
//frameDataPtr[3] = mem_tmp_T3;
///////////////////////////////////////////////////////opengl init///////////////////
if(initialGL(1920,1080) != 0) //初始化opengl es环境
{
fprintf(stderr,"opengl init unsucess!\n");
//return -1;
}
printf("initialGL()::\n");
auto glVer = glGetString(GL_VERSION);
if (!glVer)
{
printf("glGetString failed: %d\n", glGetError());
}
else
{
printf("OpenGL version: %s\n", glGetString(GL_VERSION));
}
//if(getCameraDevice().initCamera() != 0) //初始化视频采集设备
{
printf("can not initialize the camera device!\n");
//return -1;
}
printf("getCameraDevice()::\n");
if(initPanoramaParam() != 0){
printf("can not initialize the camera param");
//return -1;
}
printf("initPanoramaParam() success!\n");
keyboard_device::initDevice(); //使用标准键盘设备
printf("keyboard_device::initDevice() sucess!\n");
CFinalScene scene;
scene.setBirdEyeViewport(0,
0,
810,
1080);
scene.setSingleViewport(0,
0,
1056,
1080);
scene.set3DViewport(810,
270,
1110,
810);
scene.onStart();
//std::cout << displaySetting << std::endl;
//Calib_2D_Init();
///////////////////////////////////////////////////////////////////////////////////////
while(1)
{
for (int i = 0;i < 4;i++)
{
lFrame[i] = lpGrabber->FramePop(i);
/*IFrame[0] -->T1 ,IFrame[1] -->T2 ,IFrame[2] -->T3 ,IFrame[3] -->T4 ****wyf added 2017.11.29**/
if(lFrame[i].mUMat.empty())
{
printf("Failed to grab image number %u\n", i);
//break;
} // if pop failed
}
//GETTIME(&lTimeEnd2);
//time_elapsed = (lTimeEnd2-lTimeStart2)/1000;
//GETTIME(&lTimeStart2);
#if 1
for (int i = 0;i < 4;i++)
{
frame_map[i] = lFrame[i].mUMat.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED);
}
//frame_map_out = lFrame[3].mUMat.getMat(vsdk::ACCESS_RW | OAL_USAGE_CACHED);
buf_camfront = (unsigned char *)frame_map[0].data;
buf_camback = (unsigned char *)frame_map[1].data;
buf_camleft = (unsigned char *)frame_map[2].data;
buf_camright = (unsigned char *)frame_map[3].data;
//memcpy(mem_tmp_T0, (unsigned char *)frame_map[0].data, 1280*720*2 );
//memcpy(mem_tmp_T1, (unsigned char *)frame_map[1].data, 1280*720*2 );
//memcpy(mem_tmp_T2, (unsigned char *)frame_map[2].data, 1280*720*2 );
//memcpy(mem_tmp_T3, (unsigned char *)frame_map[3].data, 1280*720*2 );
#endif
memcpy(CamData_Ptr->Mem_FrontCam, frame_map[0].data, 1280*960*2 );
memcpy(CamData_Ptr->Mem_BackCam, frame_map[1].data, 1280*960*2 );
memcpy(CamData_Ptr->Mem_LeftCam, frame_map[2].data, 1280*960*2 );
memcpy(CamData_Ptr->Mem_RightCam, frame_map[3].data, 1280*960*2 );
CounterTick = GetTime( ); //获取当前基准COUNTER值
unsigned char LA[4],LB[4],SA[4],SB[4];
float dT[8];
LA[0] = CamData_Ptr->Mem_FrontCam[9];
LB[0] = CamData_Ptr->Mem_FrontCam[8];
SA[0] = CamData_Ptr->Mem_FrontCam[11];
SB[0] = CamData_Ptr->Mem_FrontCam[10];
dT[0] = (LA[0]*256+LB[0])*42.708/1000;
dT[1] = (SA[0]*256+SB[0])*42.708/1000;
LA[1] = CamData_Ptr->Mem_BackCam[9];
LB[1] = CamData_Ptr->Mem_BackCam[8];
SA[1] = CamData_Ptr->Mem_BackCam[11];
SB[1] = CamData_Ptr->Mem_BackCam[10];
dT[2] = (LA[1]*256+LB[1])*42.708/1000;
dT[3] = (SA[1]*256+SB[1])*42.708/1000;
LA[2] = CamData_Ptr->Mem_LeftCam[9];
LB[2] = CamData_Ptr->Mem_LeftCam[8];
SA[2] = CamData_Ptr->Mem_LeftCam[11];
SB[2] = CamData_Ptr->Mem_LeftCam[10];
dT[4] = (LA[2]*256+LB[2])*42.708/1000;
dT[5] = (SA[2]*256+SB[2])*42.708/1000;
LA[3] = CamData_Ptr->Mem_RightCam[9];
LB[3] = CamData_Ptr->Mem_RightCam[8];
SA[3] = CamData_Ptr->Mem_RightCam[11];
SB[3] = CamData_Ptr->Mem_RightCam[10];
dT[6] = (LA[3]*256+LB[3])*42.708/1000;
dT[7] = (SA[3]*256+SB[3])*42.708/1000;
float dTmax = dT[0];
for(int i=0;i<8;i++)
{
if(dT[i]>dTmax)
dTmax = dT[i];
}
CamData_Ptr->TimeStamp = CounterTick-dTmax-10; //补偿摄像头的曝光时间
printf("TimeStamp==%d dTmax==%d\n",CamData_Ptr->TimeStamp,dTmax);
//printf("N7F %x,N8 %x\n",CamData_Ptr->Mem_FrontCam[6],CamData_Ptr->Mem_FrontCam[7]);
//printf("N7B %x,N8 %x\n",CamData_Ptr->Mem_BackCam[6],CamData_Ptr->Mem_BackCam[7]);
//printf("N7L %x,N8 %x\n",CamData_Ptr->Mem_LeftCam[6],CamData_Ptr->Mem_LeftCam[7]);
//printf("N7R %x,N8 %x\n",CamData_Ptr->Mem_RightCam[6],CamData_Ptr->Mem_RightCam[7]);
//printf("T0:%f,%f T1:%f,%f T2:%f,%f T3:%f,%f dTmax=%f\n", dT[0],dT[1], dT[2],dT[3], dT[4],dT[5], dT[6],dT[7],dTmax);
if(num >0)
{
numCopy = num-1;
}
else if(num == 0)
{
numCopy=9;
}
for(int j=0;j<10;j++)
{
McuSendOffsetCopy[j*3] = McuSendOffset[j*3];
McuSendOffsetCopy[j*3+1] = McuSendOffset[j*3+1];
McuSendOffsetCopy[j*3+2] = McuSendOffset[j*3+2];
McuSendCounterCopy[j] = McuSendCounter[j];
printf("McuSendCounterCopy[%d]=%u xyz:%d %d %d\n",j,McuSendCounterCopy[j],McuSendOffsetCopy[j*3],McuSendOffsetCopy[j*3+1],McuSendOffsetCopy[j*3+2]);
}
/////////////////////////////////////////////////////////////////////////////////////
int maxtimecnt = McuSendCounterCopy[0];
for(int i=0;i<10;i++)
{
if(maxtimecnt < McuSendCounterCopy[i])
maxtimecnt = McuSendCounterCopy[i];
}
for(int i=0;i<10;i++)
{
if(maxtimecnt == McuSendCounterCopy[i])
{
numCopy = i;
printf("Max numCopy==%d\n",numCopy);
}
}
for(int j=0;j<10;j++) //找到缓冲数组中距离补偿过的Counter值最近的序号
{
if(j<9)
{
if( CamData_Ptr->TimeStamp >= McuSendCounterCopy[j] && CamData_Ptr->TimeStamp<McuSendCounterCopy[j+1])
{
numCopy = j;
printf("ok1 numCopy=%d\n",j);
break;
}
}
else
{
if( CamData_Ptr->TimeStamp >= McuSendCounterCopy[9] && CamData_Ptr->TimeStamp<McuSendCounterCopy[0])
{
numCopy = j;
printf("ok2 numCopy=%d\n",j);
break;
}
}
}
if(numCopy>0)
{
numtmp = numCopy-1;
}
else if(numCopy ==0)
{
numtmp = 9;
}
printf("numCopy=%d numtmp=%d\n",numCopy,numtmp);
float deltaX = McuSendOffsetCopy[numCopy*3]-McuSendOffsetCopy[numtmp*3];
float deltaY = McuSendOffsetCopy[numCopy*3+1]-McuSendOffsetCopy[numtmp*3+1];
float deltaZ = McuSendOffsetCopy[numCopy*3+2]-McuSendOffsetCopy[numtmp*3+2];
float deltaCnt = McuSendCounterCopy[numCopy]-McuSendOffsetCopy[numtmp];
float deltaCntNow = CamData_Ptr->TimeStamp-McuSendCounterCopy[numCopy];
CamData_Ptr->x = deltaX/deltaCnt*deltaCntNow + McuSendOffsetCopy[numCopy*3];
CamData_Ptr->y = deltaY/deltaCnt*deltaCntNow + McuSendOffsetCopy[numCopy*3+1];
CamData_Ptr->z = deltaZ/deltaCnt*deltaCntNow + McuSendOffsetCopy[numCopy*3+2];
printf("CamData_Ptr->x:%d y:%d z:%d TimeStamp=%d\n",CamData_Ptr->x,CamData_Ptr->y,CamData_Ptr->z,CamData_Ptr->TimeStamp);//
//lDcuOutput.PutFrame(lFrame[0].mUMat);
for (int i = 0;i < 4;i++) //*******;************DY****************
{
if(lpGrabber->FramePush(lFrame[i]) != LIB_SUCCESS)
{
printf("lpGrabber->FramePush(lFrame[i]) %d\n", i);
break;
} // if push failed
}
scene.encoderData.x = CamData_Ptr->x;//关闭对应双线程
scene.encoderData.y = CamData_Ptr->y;//关闭对应双线程
scene.encoderData.theta = CamData_Ptr->z;//关闭对应双线程
scene.setSteeringAngleBySteeringWheel(McuSendDada_Ptr->actual_steering_wheel_angle);
scene.setGearStatus(McuSend_PcReadData.gear_status_actual);
// scene.clearObstacleFrames();
// scene.addObstacleFrame(const_value::FRONT_CAM,
// {
// cv::Point(100, 100),
// cv::Point(100, 200),
// cv::Point(200, 200),
// cv::Point(200, 100)
// });
// 雷达信号
scene.radarSignals[0] = McuSend_PcReadData.rader2_alarm_level * 20.0;
scene.radarSignals[1] = McuSend_PcReadData.rader3_alarm_level * 20.0;
scene.radarSignals[2] = McuSend_PcReadData.rader4_alarm_level * 20.0;
scene.radarSignals[3] = McuSend_PcReadData.rader5_alarm_level * 20.0;
scene.radarSignals[4] = McuSend_PcReadData.rader6_alarm_level * 20.0;
scene.radarSignals[5] = McuSend_PcReadData.rader7_alarm_level * 20.0;
scene.radarSignals[6] = McuSend_PcReadData.rader10_alarm_level * 20.0;
scene.radarSignals[7] = McuSend_PcReadData.rader11_alarm_level * 20.0;
scene.radarSignals[8] = McuSend_PcReadData.rader12_alarm_level * 20.0;
scene.radarSignals[9] = McuSend_PcReadData.rader13_alarm_level * 20.0;
scene.radarSignals[10] = McuSend_PcReadData.rader14_alarm_level * 20.0;
scene.radarSignals[11] = McuSend_PcReadData.rader15_alarm_level * 20.0;
scene.radarSignals[12] = McuSend_PcReadData.rader1_alarm_level * 20.0;
scene.radarSignals[13] = McuSend_PcReadData.rader16_alarm_level * 20.0;
scene.radarSignals[14] = McuSend_PcReadData.rader8_alarm_level * 20.0;
scene.radarSignals[15] = McuSend_PcReadData.rader9_alarm_level * 20.0;
// keyboard
int times = 0;
#if 1
readFromDevice();
#if 1
if((times = getKeyTimes(MY_KEY_UP)) > 0)
scene.onButtonUp(times);
else if((times = getKeyTimes(MY_KEY_DOWN)) > 0)
scene.onButtonDown(times);
else if((times = getKeyTimes(MY_KEY_LEFT)) > 0)
scene.onButtonLeft(times);
else if((times = getKeyTimes(MY_KEY_RIGHT)) > 0)
scene.onButtonRight(times);
// else if((times = getKeyTimes(MY_KEY_MENU)) > 0)
// scene.onButtonOK();
#else
if ((times = getKeyTimes('w')) > 0)
{
scene.onButtonMoveUp(times);
}
else if ((times = getKeyTimes('s')) > 0)
{
scene.onButtonMoveDown(times);
}
else if ((times = getKeyTimes('a')) > 0)
{
scene.onButtonMoveLeft(times);
}
else if ((times = getKeyTimes('d')) > 0)
{
scene.onButtonMoveRight(times);
}
#endif
else if ((times = getKeyTimes('n')) > 0)
{
scene.onButtonNextMode();
}
else if ((times = getKeyTimes('p')) > 0)
{
scene.onButtonPrevMode();
}
else if ((times = getKeyTimes('[')) > 0)
{
scene.onButtonTurnLeft(times);
}
else if ((times = getKeyTimes(']')) > 0)
{
scene.onButtonTurnRight(times);
}
else if((times = getKeyTimes(MY_KEY_RETURN)) > 0)
break;
for(int i = 0;i < 9;i++){
if(times = getKeyTimes('0' + i) > 0){
scene.onMessage('0' + i);
}
}
#endif
// start rendering
Timer<> timer;
timer.start();
static int lastFPS = 0;
scene.renderToSreen();
scene.renderTextBox(std::string(std::to_string(lastFPS) + " FPS").c_str(), 0, 0, 32);
flushToScreen();
timer.stop();
lastFPS = 1000.0 / timer.count();
std::cout << "rendering: " << timer.get() << std::endl;
// usleep(300000);
//printf("wwwwwww50\n");
ParkingManagemet();
//printf("&&&&&&&&&ParkPlaceNum =%d car_paring_status=%d\n",ParkingPlace_Ptr->ParkPlaceNum,McuSendDada_Ptr->car_paring_status);
}
} // main()
void *GLTask(void *ptr1)
{
#if 0
FILE* fp = fopen("config.txt", "r");
if (fp == NULL)
{
printf("could not found config.txt\n");
//return -1;
}
fscanf(fp, "path: %s\n", path_pattern);
fscanf(fp, "num_frames: %d\n", &num_frames);
fclose(fp);
printf("path = %s", path_pattern);
// load display settings
std::ifstream displaySettingFile("param/display.json");
json displaySetting;
displaySettingFile >> displaySetting;
#endif
//if(initialGL(displaySetting["screen"]["width"], displaySetting["screen"]["height"]) != 0) //初始化opengl es环境
if(initialGL(1920,1080) != 0) //初始化opengl es环境
{
fprintf(stderr,"opengl init unsucess!\n");
//return -1;
}
printf("initialGL()::\n");
auto glVer = glGetString(GL_VERSION);
if (!glVer)
{
printf("glGetString failed: %d\n", glGetError());
}
else
{
printf("OpenGL version: %s\n", glGetString(GL_VERSION));
}
//if(getCameraDevice().initCamera() != 0) //初始化视频采集设备
{
printf("can not initialize the camera device!\n");
//return -1;
}
printf("getCameraDevice()::\n");
if(initPanoramaParam() != 0){
printf("can not initialize the camera param");
//return -1;
}
printf("initPanoramaParam() success!\n");
keyboard_device::initDevice(); //使用标准键盘设备
printf("keyboard_device::initDevice() sucess!\n");
CFinalScene scene;
scene.setBirdEyeViewport(0,
0,
810,
1080);
scene.setSingleViewport(810,
270,
1110,
810);
scene.set3DViewport(810,
270,
1110,
810);
scene.onStart();
//std::cout << displaySetting << std::endl;
//Calib_2D_Init();
//Fbo_2D_Init();
while(1)
{
int times = 0;
#if 1
readFromDevice();
#if 1
if((times = getKeyTimes(MY_KEY_UP)) > 0)
scene.onButtonUp(times);
else if((times = getKeyTimes(MY_KEY_DOWN)) > 0)
scene.onButtonDown(times);
else if((times = getKeyTimes(MY_KEY_LEFT)) > 0)
scene.onButtonLeft(times);
else if((times = getKeyTimes(MY_KEY_RIGHT)) > 0)
scene.onButtonRight(times);
// else if((times = getKeyTimes(MY_KEY_MENU)) > 0)
// scene.onButtonOK();
#else
if ((times = getKeyTimes('w')) > 0)
{
scene.onButtonMoveUp(times);
}
else if ((times = getKeyTimes('s')) > 0)
{
scene.onButtonMoveDown(times);
}
else if ((times = getKeyTimes('a')) > 0)
{
scene.onButtonMoveLeft(times);
}
else if ((times = getKeyTimes('d')) > 0)
{
scene.onButtonMoveRight(times);
}
#endif
else if ((times = getKeyTimes('n')) > 0)
{
scene.onButtonNextMode();
}
else if ((times = getKeyTimes('p')) > 0)
{
scene.onButtonPrevMode();
}
else if ((times = getKeyTimes('[')) > 0)
{
scene.onButtonTurnLeft(times);
}
else if ((times = getKeyTimes(']')) > 0)
{
scene.onButtonTurnRight(times);
}
else if((times = getKeyTimes(MY_KEY_RETURN)) > 0)
break;
for(int i = 0;i < 9;i++){
if(times = getKeyTimes('0' + i) > 0){
scene.onMessage('0' + i);
}
}
#endif
//printf("scene.renderToSreen()\n");
Timer<> timer;
timer.start();
static int lastFPS = 0;
scene.renderToSreen();
scene.renderTextBox(std::string(std::to_string(lastFPS) + " FPS").c_str(), 0, 0, 32);
flushToScreen();
timer.stop();
lastFPS = 1000.0 / timer.count();
std::cout << "rendering: " << timer.get() << std::endl;
}
//程序执行完毕,做一些释放资源的操作
scene.onStop();
//getCameraDevice().deinitCamera();
//keyboard_device::deinitDevice();
deinitGL();
return 0;
#if 0
readParam();
if(initialGL() != 0) // //��ʼ��opengl es����
{
fprintf(stderr,"opengl init unsucess!\n");
return 0;
}
printf("initialGL()::\n");
//if(getCameraDevice().initCamera() != 0) //��ʼ����Ƶ�ɼ��豸
// {
// printf("can not initialize the camera device\n");
// return 0;
//}
//printf("getCameraDevice()::\n");
if(initPanoramaParam() != 0){
printf("can not initialize the camera param");
return 0;
}
printf("initPanoramaParam() success!\n");
//keyboard_device::initDevice(); //ʹ�ñ������豸
//printf("keyboard_device::initDevice() sucess!\n");
CFinalScene scene;
scene.onStart();
Calib_2D_Init();
while(1)
{
#if 0
int times = 0;
readFromDevice();
usleep(20000);
if((times = getKeyTimes(MY_KEY_UP)) > 0)
scene.onButtonUp(times);
if((times = getKeyTimes(MY_KEY_DOWN)) > 0)
scene.onButtonDown(times);
if((times = getKeyTimes(MY_KEY_LEFT)) > 0)
scene.onButtonLeft(times);
if((times = getKeyTimes(MY_KEY_RIGHT)) > 0)
scene.onButtonRight(times);
if((times = getKeyTimes(MY_KEY_MENU)) > 0)
scene.onButtonOK();
if((times = getKeyTimes(MY_KEY_RETURN)) > 0)
break;
for(int i = 0;i < 9;i++){
if(times = getKeyTimes('0' + i) > 0){
scene.onMessage('0' + i);
}
}
#endif
//printf("scene.renderToSreen()\n");
scene.renderToSreen();
flushToScreen();
}
//����ִ����ϣ���һЩ�ͷ���Դ�IJ���
scene.onStop();
getCameraDevice().deinitCamera();
keyboard_device::deinitDevice();
deinitGL();
return 0;
#endif
}
int32_t DdrBuffersAlloc(void** appFbsVirtual,
uint32_t* apFbsPhysical,
size_t aMemSize,
uint32_t aBufferCnt
)
{
int32_t lRet = 0;
// allocate buffers & get physical addresses
for(uint32_t i = 0; i < aBufferCnt; i++)
{
appFbsVirtual[i] = OAL_MemoryAllocFlag(
aMemSize,
OAL_MEMORY_FLAG_ALIGN(ALIGN2_CACHELINE)|
OAL_MEMORY_FLAG_CONTIGUOUS);
if( appFbsVirtual[i] == NULL)
{
lRet = -1;
break;
}
apFbsPhysical[i] = (uint32_t)(uintptr_t)OAL_MemoryReturnAddress(
appFbsVirtual[i],
ACCESS_PHY); // get physical address
memset(appFbsVirtual[i], 0x00, aMemSize);
#if defined(__STANDALONE__) && defined(__ARMV8)
//flush_dcache_range(appFbsVirtual[i], aMemSize);
#endif // #ifdef __STANDALONE__
} // for all framebuffers
if(lRet != 0)
{
DdrBuffersFree(appFbsVirtual, apFbsPhysical, aBufferCnt);
}
return lRet;
} // DdrBuffersAlloc()
//***************************************************************************
void DdrBuffersFree(void** appFbsVirtual,
uint32_t* apFbsPhysical,
uint32_t aBufferCnt
)
{
for(uint32_t i = 0; i < aBufferCnt; i++)
{
if(appFbsVirtual[i] != NULL)
{
OAL_MemoryFree(appFbsVirtual[i]);
} // if buffer allocated
appFbsVirtual[i] = NULL;
apFbsPhysical[i] = 0;
} // for all framebuffers
} // DdrBuffersFree()
//***************************************************************************
void SeqEventCallBack(uint32_t aEventType, void* apUserVal)
{
static uint32_t slFrmCnt = 0;
if(aEventType == SEQ_MSG_TYPE_FRAMEDONE)
{
//printf("Frame done message arrived #%u. User value %d\n",
// slFrmCnt++,
// *((int32_t*)apUserVal));
} // if frame done arrived
} // SeqEventCallBack()
//***************************************************************************
#ifndef __STANDALONE__
void SigintHandler(int)
{
sStop = true;
} // SigintHandler()
//***************************************************************************
int32_t SigintSetup()
{
int32_t lRet = SEQ_LIB_SUCCESS;
// prepare internal signal handler
struct sigaction lSa;
memset(&lSa, 0, sizeof(lSa));
lSa.sa_handler = SigintHandler;
if( sigaction(SIGINT, &lSa, NULL) != 0)
{
VDB_LOG_ERROR("Failed to register signal handler.\n");
lRet = SEQ_LIB_FAILURE;
} // if signal not registered
return lRet;
} // SigintSetup()
//***************************************************************************
#endif // #ifndef __STANDALONE__
int Ipc_Create()
{
int shmid1,shmid2,shmid3,shmid4,shmid5,shmid6,shmid7;
//���������ڎ� ���൱�ڎ��Č����Č���������
shmid1 = shmget(0x2234, sizeof(CamData), IPC_CREAT | 0666);
if (shmid1 == -1)
{
perror("shmget 1 err");
return errno;
}
printf("shmid1:%d \n", shmid1);
//�������ڎ�����ӵ����̵�ַ�Ռ�
CamData_Ptr =(CamData *)shmat(shmid1, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (CamData_Ptr == (void *)-1 )
{
perror("shmat 1 err");
return errno;
}
shmid2 = shmget(0x3234, sizeof(ParkingPlace), IPC_CREAT | 0666);
if (shmid2 == -1)
{
perror("shmget 2 err");
return errno;
}
printf("shmid2:%d \n", shmid2);
//�������ڎ�����ӵ����̵�ַ�Ռ�
ParkingPlace_Ptr =(ParkingPlace *)shmat(shmid2, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (ParkingPlace_Ptr == (void *)-1 )
{
perror("shmat 2 err");
return errno;
}
shmid3 = shmget(0x4234, sizeof(McuSendDada), IPC_CREAT | 0666);
if (shmid3 == -1)
{
perror("shmget 3 err");
return errno;
}
printf("shmid3:%d \n", shmid3);
//�������ڎ�����ӵ����̵�ַ�Ռ�
McuSendDada_Ptr =(McuSendDada *)shmat(shmid3, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (McuSendDada_Ptr == (void *)-1 )
{
perror("shmat 3 err");
return errno;
}
shmid4 = shmget(0x5234, sizeof(PCWRITEDATA), IPC_CREAT | 0666);
if (shmid4 == -1)
{
perror("shmget 4 err");
return errno;
}
printf("shmid4:%d \n", shmid4);
//�������ڎ�����ӵ����̵�ַ�Ռ�
PCWRITEDATA_Ptr =(PCWRITEDATA *)shmat(shmid4, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (PCWRITEDATA_Ptr == (void *)-1 )
{
perror("shmat 4 err");
return errno;
}
shmid5 = shmget(0x6234, sizeof(BasicData), IPC_CREAT | 0666);
if (shmid5 == -1)
{
perror("shmget 5 err");
return errno;
}
printf("shmid5:%d \n", shmid5);
//�������ڎ�����ӵ����̵�ַ�Ռ�
BasicData_Ptr =(BasicData *)shmat(shmid5, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (BasicData_Ptr == (void *)-1 )
{
perror("shmat 5 err");
return errno;
}
shmid6 = shmget(0x7234, sizeof(LanelineData), IPC_CREAT | 0666);
if (shmid6 == -1)
{
perror("shmget 6 err");
return errno;
}
printf("shmid6:%d \n", shmid6);
//�������ڎ�����ӵ����̵�ַ�Ռ�
LanelineData_Ptr =(LanelineData *)shmat(shmid6, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (LanelineData_Ptr == (void *)-1 )
{
perror("shmat 6 err");
return errno;
}
shmid7 = shmget(0x8234, sizeof(ObstacleData), IPC_CREAT | 0666);
if (shmid7 == -1)
{
perror("shmget 7 err");
return errno;
}
printf("shmid7:%d \n", shmid7);
//�������ڎ�����ӵ����̵�ַ�Ռ�
ObstacleData_Ptr =(ObstacleData *)shmat(shmid7, NULL, 0);//�ڶ�������shmaddrΪNULL�������Զ�ѡ��һ����ַ
if (ObstacleData_Ptr == (void *)-1 )
{
perror("shmat 7 err");
return errno;
}
}
unsigned long long GetTime(void)
{
Soc_tt=GetNowTimeUs();
Soc_tt=Soc_tt/1000;
return McuTimeData + (Soc_tt - Mcu_tt);
}
unsigned long long GetNowTimeUs(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (unsigned long long)tv.tv_sec * 1000000 + tv.tv_usec;
}
void ParkingManagemet()
{
//printf("parkingmanagemetn\n");
int ii;
static int ss,tt;
static int TimeCntTmp;
static float ParkPlaceCopy[10*4*2];
float prev_pts[8]; // 车位坐标 {(x1, y1), (x2, y2), (x3, y3), (x4, y4)}
short int prev_coords[3]; // 车位坐标对应车身位置 X,Y,Z
short int curr_coords[3]; // 当前车身位置 X,Y,Z
float pts2veh[8]; // 车位坐标相对当前车身坐标
/*****************************************************/
//////////////////////////////////////////////////////////////
//static GLint box_num; //2018.10.19
//static GLfloat Ver_Texture_Pos_Parking[10*4*2] = {0}; //2018.10.19
//static GLfloat Ver_Screen_Pos_Parking[10*4*2];
if(ToMcuTargetData.Dnn_Scan_Ok_Flag == 0)
{
if( (abs(ParkingPlace_Ptr->ParkPlace[0]) + abs(ParkingPlace_Ptr->ParkPlace[2]) )>0)
ToMcuTargetData.Dnn_Scan_Ok_Flag = 1;
}
if( (abs(McuSend_PcReadData.parking_rect_point0_x) + abs(McuSend_PcReadData.parking_rect_point1_x) )>0)
Mcu_Send_Parking_Data_Fag = 1;
else
Mcu_Send_Parking_Data_Fag = 0;
//printf("!!!!!!!!!!!!!Mcu_Send_Parking_Data_Fag=%d\n",Mcu_Send_Parking_Data_Fag);
static int vv;
if(vv == 0) //计算环视视野边界值 单位:mm
{
disFront = Rear_Axle_Center_y*Pixel_Ration_x;
disBack = (1080-Rear_Axle_Center_y)*Pixel_Ration_x;
disLF = Rear_Axle_Center_x*Pixel_Ration_y;
printf("disFront=%dmm\n",disFront);
printf("disBack=%dmm\n",disBack);
printf("disLF=%dmm\n",disLF);
vv = 1;
}
if( (Car_Parking_Status >= 4) || (Car_Parking_Status == 0)) //停止或异常,以及0初始状态下,清除相关标志位
{
//memset(&ToMcuTargetData,0,sizeof(TARGETPLACEDATA));
memset(ParkingPlace_Ptr,0,sizeof(ParkingPlace));
Parking_Place_Mode_Select_OK = 0;
Parking_Select_Num = 0;
ss = 0;
tt = 0;
Total_Parking_Num =0;
//box_num = 0;
if(ToMcuTargetData.Dnn_Scan_Ok_Flag == 1)
deleteLinklist(head);//删除链表
memset(&ToMcuTargetData,0,sizeof(TARGETPLACEDATA));
memset(PCWRITEDATA_Ptr,0,sizeof(PCWRITEDATA));
memset(&AndroidReceive_SocWriteData,0,sizeof(SOCWRITEDATA));
parking_place_detected_flag = 0;
}
if(Car_Parking_Status>0 && Car_Parking_Status<4)
{
float Parking_Rect_Point0_x;
float Parking_Rect_Point0_y;
float Parking_Rect_Point1_x;
float Parking_Rect_Point1_y;
float Parking_Rect_Point2_x;
float Parking_Rect_Point2_y;
float Parking_Rect_Point3_x;
float Parking_Rect_Point3_y;
//////////////////////////////////////////////////////////////////////////////
//printf("ParkingPlace_Ptr->TimeStamp=%d\n",ParkingPlace_Ptr->TimeStamp);
//printf("ParkingPlace_Ptr->ParkPlaceNum=%d\n",ParkingPlace_Ptr->ParkPlaceNum);
/////////////////////////////////////////////////////////////////////////////////////////
if(Car_Parking_Status == 1) //scan status
{
////////////////////////////////车位管理/////////////////////////////////////////////////
#if 1
memcpy(ParkingPlace_PtrCopy.ParkPlace,ParkingPlace_Ptr->ParkPlace,80*sizeof(float));
ParkingPlace_PtrCopy.ParkPlaceNum = ParkingPlace_Ptr->ParkPlaceNum;
ParkingPlace_PtrCopy.x = ParkingPlace_Ptr->x;
ParkingPlace_PtrCopy.y = ParkingPlace_Ptr->y;
ParkingPlace_PtrCopy.z = ParkingPlace_Ptr->z;
memcpy(ParkingPlace_PtrCopy.ParkConfidence,ParkingPlace_Ptr->ParkConfidence,10*sizeof(int));
ParkingPlace_PtrCopy.TimeStamp = ParkingPlace_Ptr->TimeStamp;
if(ToMcuTargetData.Dnn_Scan_Ok_Flag == 1) //DNN第一次扫描到车位
{
if(tt==0) //开始创建链表
{
LinkList *node, *end;//定义普通节点,尾部节点;
head = (LinkList*)malloc(sizeof(LinkList));//链表首地址
end = head; //若是空链表则头尾节点一样
printf("ParkingPlace_PtrCopy.ParkPlaceNum=%d\n",ParkingPlace_PtrCopy.ParkPlaceNum);
for (int i = 0; i < ParkingPlace_PtrCopy.ParkPlaceNum; i++) //根据扫描到的车位数,创建节点
{
node = (LinkList*)malloc(sizeof(LinkList));
for(int j=0;j<8;j++)
node->ParkPlace[j] = ParkingPlace_PtrCopy.ParkPlace[i*8+j];
node->x = ParkingPlace_PtrCopy.x;
node->y = ParkingPlace_PtrCopy.y;
node->z = ParkingPlace_PtrCopy.z;
node->park_confidence = ParkingPlace_PtrCopy.ParkConfidence[i];
end->next = node;
end = node;
}
end->next = NULL;//结束创建
//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
printf("creat link list success!\n");
//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
tt = 1;
TimeCntTmp1 = ParkingPlace_PtrCopy.TimeStamp;
}
}
#endif
#if 1
//printf("ParkingPlace_PtrCopy.ParkPlaceNum=%d\n",ParkingPlace_PtrCopy.ParkPlaceNum);
if(TimeCntTmp1 != ParkingPlace_PtrCopy.TimeStamp) //若DNN有新扫描到的车位,每个车位都和己有车位进行比对
{
for (int i = 0; i < ParkingPlace_PtrCopy.ParkPlaceNum; i++)
{
LinkList *h = head;
int listNum =0;
int listTotal = 0;
while (h->next != NULL)
{
listTotal++;
h = h->next;
prev_coords[0] = h->x;
prev_coords[1] = h->y;
prev_coords[2] = h->z;
curr_coords[0] = ParkingPlace_PtrCopy.x;
curr_coords[1] = ParkingPlace_PtrCopy.y;
curr_coords[2] = ParkingPlace_PtrCopy.z;
memcpy(prev_pts,h->ParkPlace,8*sizeof(float));
coord_pts2veh(curr_coords, prev_coords, prev_pts, pts2veh); //物理坐标到绝对坐标转换
//计算新车位和己有车位的中点距离,小于1200mm为重合车位,大于1200mm为新车位,创建新节点并加入链表
float new_mid_point_x; //新车位中点X坐标
float new_mid_point_y; //新车位中点y坐标
float old_mid_point_x; //已有车位中点X坐标
float old_mid_point_y; //已有车位中点y坐标
float mid_point_distance;//两个车位中点之间的距离
//***********计算新车位和己有车位的中点坐标
new_mid_point_x = (ParkingPlace_PtrCopy.ParkPlace[i*8]+ParkingPlace_PtrCopy.ParkPlace[i*8+2]+ParkingPlace_PtrCopy.ParkPlace[i*8+4]+ParkingPlace_PtrCopy.ParkPlace[i*8+6])/4;
new_mid_point_y = (ParkingPlace_PtrCopy.ParkPlace[i*8+1]+ParkingPlace_PtrCopy.ParkPlace[i*8+3]+ParkingPlace_PtrCopy.ParkPlace[i*8+5]+ParkingPlace_PtrCopy.ParkPlace[i*8+7])/4;
old_mid_point_x = (pts2veh[0]+pts2veh[2]+pts2veh[4]+pts2veh[6])/4;
old_mid_point_y = (pts2veh[1]+pts2veh[3]+pts2veh[5]+pts2veh[7])/4;
//**********计算两个中点之间的距离**********如果距离大于1200mm,则认为是新车位,否则是重合车位**************
mid_point_distance = sqrt( (new_mid_point_x-old_mid_point_x)*(new_mid_point_x-old_mid_point_x) +(new_mid_point_y-old_mid_point_y)*(new_mid_point_y-old_mid_point_y) );
//if( (abs(pts2veh[0]-ParkingPlace_PtrCopy.ParkPlace[i*8]) >= 500) || (abs(pts2veh[1]-ParkingPlace_PtrCopy.ParkPlace[i*8+1]) >= 500) ) //新车位
if(mid_point_distance>=1200)
{
listNum++;
}
else //是重合车位,比较哪个离左/右摄像头更近
{
//int disLRCam = 1930; //左、右后视镜摄像头到后轴中心X方向上的距离 mm
int deltOld = abs( ( h->ParkPlace[0] + h->ParkPlace[2] )/2 -disLRCam ); //计算当前车位P0x、P1x中点到后视镜摄像头距离
int deltNew = abs( (ParkingPlace_PtrCopy.ParkPlace[i*8] + ParkingPlace_PtrCopy.ParkPlace[i*8+2] )/2 -disLRCam); //计算新车位P0x、P1x中点到后视镜摄像头距离
//printf("deltOld =%d deltNew=%d \n",deltOld,deltNew);
if( deltOld > deltNew) //若新车位比旧车位距离更靠近后视镜,则更新车位信息,否则保持旧车位信息
{
for(int j=0;j<8;j++)
h->ParkPlace[j] = ParkingPlace_PtrCopy.ParkPlace[i*8+j];
h->x = ParkingPlace_PtrCopy.x;
h->y = ParkingPlace_PtrCopy.y;
h->z = ParkingPlace_PtrCopy.z;
h->park_confidence = ParkingPlace_PtrCopy.ParkConfidence[i];
//printf("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$new parkingplace replace\n");
}
}
}
printf("listTotal=%d listNum =%d\n,",listTotal,listNum);
if(listNum == listTotal) //若没有重合车位,则添加新车位
{
LinkList * newnode = (LinkList*)malloc(sizeof(LinkList));
for(int j=0;j<8;j++)
newnode->ParkPlace[j] = ParkingPlace_PtrCopy.ParkPlace[i*8+j];
newnode->x = ParkingPlace_PtrCopy.x;
newnode->y = ParkingPlace_PtrCopy.y;
newnode->z = ParkingPlace_PtrCopy.z;
newnode->park_confidence = ParkingPlace_PtrCopy.ParkConfidence[i];
newnode->next = NULL;
//printf("add new node start\n");
insert_trail(head,newnode);
//printf("add new node end\n");
}
}
TimeCntTmp1 = ParkingPlace_PtrCopy.TimeStamp;
}
#endif
/////////////////////////////////////////////////////////////////////////////////////////
if(Mcu_Send_Parking_Data_Fag ==1 && ToMcuTargetData.Dnn_Scan_Ok_Flag == 0) //DNN扫到车位之前。超声波先扫到车位,则先显示超声波扫到的车位
{
//memset(Ver_Pos_Parking,0,sizeof(GLfloat)*10*4*3);
//Parking_Select_Num = 1;
Total_Parking_Num =1;
//box_num = Total_Parking_Num;
validNode = 1;
//Parking_Rect_Point0_x = Rear_Axle_Center_x-(McuSend_PcReadData.parking_rect_point0_y/Pixel_Ration_y);
//Parking_Rect_Point0_y = Rear_Axle_Center_y-(McuSend_PcReadData.parking_rect_point0_x/Pixel_Ration_x);
//Parking_Rect_Point1_x = Rear_Axle_Center_x-(McuSend_PcReadData.parking_rect_point1_y/Pixel_Ration_y);
//Parking_Rect_Point1_y = Rear_Axle_Center_y-(McuSend_PcReadData.parking_rect_point1_x/Pixel_Ration_x);
//Parking_Rect_Point2_x = Rear_Axle_Center_x-(McuSend_PcReadData.parking_rect_point2_y/Pixel_Ration_y);
//Parking_Rect_Point2_y = Rear_Axle_Center_y-(McuSend_PcReadData.parking_rect_point2_x/Pixel_Ration_x);
//Parking_Rect_Point3_x = Rear_Axle_Center_x-(McuSend_PcReadData.parking_rect_point3_y/Pixel_Ration_y);
//Parking_Rect_Point3_y = Rear_Axle_Center_y-(McuSend_PcReadData.parking_rect_point3_x/Pixel_Ration_x);
pts2veh[0] = McuSend_PcReadData.parking_rect_point0_x;
pts2veh[1] = McuSend_PcReadData.parking_rect_point0_y;
pts2veh[2] = McuSend_PcReadData.parking_rect_point1_x;
pts2veh[3] = McuSend_PcReadData.parking_rect_point1_y;
pts2veh[4] = McuSend_PcReadData.parking_rect_point2_x;
pts2veh[5] = McuSend_PcReadData.parking_rect_point2_y;
pts2veh[6] = McuSend_PcReadData.parking_rect_point3_x;
pts2veh[7] = McuSend_PcReadData.parking_rect_point3_y;
printf("pts2veh:%f %f , %f %f, %f %f,%f %f\n",pts2veh[0],pts2veh[1],pts2veh[2],pts2veh[3],pts2veh[4],pts2veh[5],pts2veh[6],pts2veh[7]);
/////////////////////////////to screen display////////////////////////////////////////////////////
int validPoingFlag = 0; //车位坐标在视野范围内标志,1:在视野范围内,0:超出视野范围
for(int i=0;i<4;i++) //判断是否在视野范围内
{
if( (pts2veh[i*2]<disFront) && (pts2veh[i*2]> -disBack))
{
if (abs(pts2veh[i*2+1])<disLF)
validPoingFlag = 1;
}
}
if(validPoingFlag == 1) //在视野范围内,送显示
{
memcpy(ParkPlaceCopy,pts2veh,8*sizeof(float));
parking_place_detected_num = 1;
parking_place_detected_flag = 1;
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration_x);
printf("ParkPlaceCopy:%f %f , %f %f, %f %f,%f %f\n",ParkPlaceCopy[0],ParkPlaceCopy[1],ParkPlaceCopy[2],ParkPlaceCopy[3],ParkPlaceCopy[4],ParkPlaceCopy[5],ParkPlaceCopy[6],ParkPlaceCopy[7]);
printf("radar chewei 1 P0:%d %d \n",AndroidReceive_SocWriteData.parking_1_point0_x,AndroidReceive_SocWriteData.parking_1_point0_y);
printf("radar chewei 1 P1:%d %d \n",AndroidReceive_SocWriteData.parking_1_point1_x,AndroidReceive_SocWriteData.parking_1_point1_y);
printf("radar chewei 1 P2:%d %d \n",AndroidReceive_SocWriteData.parking_1_point2_x,AndroidReceive_SocWriteData.parking_1_point2_y);
printf("radar chewei 1 P3:%d %d \n",AndroidReceive_SocWriteData.parking_1_point3_x,AndroidReceive_SocWriteData.parking_1_point3_y);
/*
int k=0;
int disPoint01= (ParkPlaceCopy[0]-ParkPlaceCopy[2])*(ParkPlaceCopy[0]-ParkPlaceCopy[2])+(ParkPlaceCopy[1]-ParkPlaceCopy[3])*(ParkPlaceCopy[1]-ParkPlaceCopy[3]);
int disPoint03= (ParkPlaceCopy[0]-ParkPlaceCopy[6])*(ParkPlaceCopy[0]-ParkPlaceCopy[6])+(ParkPlaceCopy[1]-ParkPlaceCopy[7])*(ParkPlaceCopy[1]-ParkPlaceCopy[7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration_x);
}
else
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration_x);
}
*/
}
else //出视野,清除标志位
{
parking_place_detected_num = 0;
parking_place_detected_flag = 0;
}
if(Parking_Place_Mode_Select_OK == 1) //选择好车位,确定
{
ToMcuTargetData.Customer_Select_Ok_Flag = 1;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
}
else if(ToMcuTargetData.Dnn_Scan_Ok_Flag == 1) //若DNN扫到车位,则显示DNN扫到的车位
{
////////////////////////////检测链表中的车位在当前时刻是否在UI显示视野范围内//////////////////////////
#if 1
//printf("check Node\n");
LinkList *h1 = head;
int nodeTotal=0,rr=0;
int invalidNode[30]; //记录链表中超出视野范围的节点序号
//int validNode = 0; //当前链表中在视野范围内的节点数(即车位数)
memset(invalidNode,0,30*sizeof(int));
while (h1->next != NULL)
{
nodeTotal++;
h1 = h1->next;
prev_coords[0] = h1->x;
prev_coords[1] = h1->y;
prev_coords[2] = h1->z;
curr_coords[0] = McuSend_PcReadData.TimeStampex[0];
curr_coords[1] = McuSend_PcReadData.TimeStampex[1];
curr_coords[2] = McuSend_PcReadData.TimeStampex[2];
memcpy(prev_pts,h1->ParkPlace,8*sizeof(float));
coord_pts2veh(curr_coords, prev_coords, prev_pts, pts2veh); //物理坐标到绝对坐标转换
int validPoingFlag = 0; //车位坐标在视野范围内标志,1:在视野范围内,0:超出视野范围
for(int i=0;i<4;i++)
{
if( (pts2veh[i*2]<disFront) && (pts2veh[i*2]> -disBack))
{
if (abs(pts2veh[i*2+1])<disLF)
validPoingFlag = 1;
}
}
if( validPoingFlag == 0 ) //超出视野范围
{
invalidNode[rr]=nodeTotal;
rr++;
//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@111!!!!!!!!!!!!!!!rr=%d\n",rr);
}
//printf("\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n");
}
for(int i=0;i<rr;i++)
{
if(invalidNode[i]>0)
{
printf("invalidNode[%d]=%d\n",i,invalidNode[i]);
deleteNode(head,invalidNode[i]-i*1);
}
}
validNode = nodeTotal-rr; //链表中符合要求的车位数
printf("****Total valid parking place :%d\n",validNode);
#endif
///////////////////////////////////////////////////////////////////////////////
if(Car_Speed_Flag >0)
Parking_Select_Num = 0;
Total_Parking_Num = validNode;
//box_num = Total_Parking_Num;
TimeCntTmp = ParkingPlace_Ptr->TimeStamp;
LinkList *h2 = head;
int nn = 0;
int nn_left = 0;
int left_parking_id_record[10] = {0};
int nn_right = 0;
int right_parking_id_record[10] = {0};
memset(&ParkPlaceCopy,0,10*4*2*sizeof(float));
parking_place_detected_flag = 0;
while (h2->next != NULL)
{
nn++;
h2 = h2->next;
prev_coords[0] = h2->x;
prev_coords[1] = h2->y;
prev_coords[2] = h2->z;
curr_coords[0] = McuSend_PcReadData.TimeStampex[0];
curr_coords[1] = McuSend_PcReadData.TimeStampex[1];
curr_coords[2] = McuSend_PcReadData.TimeStampex[2];
if(nn<10) //目前显示最多支持9个车位,超过9个的不再显示
{
memcpy(prev_pts,h2->ParkPlace,8*sizeof(float));
coord_pts2veh(curr_coords, prev_coords, prev_pts, pts2veh); //物理坐标到绝对坐标转换
//memcpy(&ParkPlaceCopy[(nn-1)*8],pts2veh,8*sizeof(float));
//printf("pts2veh %f,%f, %f,%f, %f,%f, %f,%f\n",pts2veh[0],pts2veh[1],pts2veh[2],pts2veh[3],pts2veh[4],pts2veh[5],pts2veh[6],pts2veh[7]);
//parking_place_detected_flag = 1;
//parking_place_detected_num = nn;
//printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@parking_place_detected_num=%d\n",parking_place_detected_num);
/////////////////////////////////////left or right////////////////////////////////
///*
if(parking_in_scan_direction == 1)
{
if( pts2veh[1]>=900 && pts2veh[3]>=900 && pts2veh[5]>=900 && pts2veh[7]>=900) //是否左侧车位?
{
//int nn_left;
//int left_parking_id_record[10];
nn_left++;
memcpy(&ParkPlaceCopy[(nn_left-1)*8],pts2veh,8*sizeof(float));
left_parking_id_record[nn_left] = nn;
parking_place_detected_flag = 1;
}
}
else if(parking_in_scan_direction == 2)
{
if( pts2veh[1]<=-900 && pts2veh[3]<=-900 && pts2veh[5]<=-900 && pts2veh[7]<=-900) //是否右侧车位?
{
//int nn_right;
//int right_parking_id_record[10];
nn_right++;
memcpy(&ParkPlaceCopy[(nn_right-1)*8],pts2veh,8*sizeof(float));
right_parking_id_record[nn_right] = nn;
parking_place_detected_flag = 1;
}
}
//*/
/////////////////////////////////////////////////////////////////////////////////////
}
else
break;
}
///*
if(parking_place_detected_flag == 1)
{
if(parking_in_scan_direction == 1) //left scan
parking_place_detected_num = nn_left;
else if(parking_in_scan_direction == 2) //right scan
parking_place_detected_num = nn_right;
else
parking_place_detected_num = 0;
printf("direction=%d,parking_place_detected_num=%d\n",parking_in_scan_direction,parking_place_detected_num);
}
//*/
//printf("prev_pts %f,%f, %f,%f, %f,%f, %f,%f\n",prev_pts[0],prev_pts[1],prev_pts[2],prev_pts[3],prev_pts[4],prev_pts[5],prev_pts[6],prev_pts[7]);
int k=0;
int disPoint01= (ParkPlaceCopy[0]-ParkPlaceCopy[2])*(ParkPlaceCopy[0]-ParkPlaceCopy[2])+(ParkPlaceCopy[1]-ParkPlaceCopy[3])*(ParkPlaceCopy[1]-ParkPlaceCopy[3]);
int disPoint03= (ParkPlaceCopy[0]-ParkPlaceCopy[6])*(ParkPlaceCopy[0]-ParkPlaceCopy[6])+(ParkPlaceCopy[1]-ParkPlaceCopy[7])*(ParkPlaceCopy[1]-ParkPlaceCopy[7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration_x);
}
else
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration_x);
}
//printf("ParkPlaceCopy k=%d P0:%f,%f, P1: %f,%f,\n",k,ParkPlaceCopy[k+0],ParkPlaceCopy[k+1],ParkPlaceCopy[k+2],ParkPlaceCopy[k+3]);
//printf("ParkPlaceCopy k=%d P2:%f,%f, P3:%f,%f,\n",k,ParkPlaceCopy[k+4],ParkPlaceCopy[k+5],ParkPlaceCopy[k+6],ParkPlaceCopy[k+7]);
///*
k = 1*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_2_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
}
else
{
AndroidReceive_SocWriteData.parking_2_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_2_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_2_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
}
//printf("ParkPlaceCopy k=%d P0:%f,%f, P1: %f,%f,\n",k,ParkPlaceCopy[k+0],ParkPlaceCopy[k+1],ParkPlaceCopy[k+2],ParkPlaceCopy[k+3]);
//printf("ParkPlaceCopy k=%d P2:%f,%f, P3:%f,%f,\n",k,ParkPlaceCopy[k+4],ParkPlaceCopy[k+5],ParkPlaceCopy[k+6],ParkPlaceCopy[k+7]);
k = 2*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_3_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
}
else
{
AndroidReceive_SocWriteData.parking_3_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_3_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_3_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
}
//printf("ParkPlaceCopy k=%d P0:%f,%f, P1: %f,%f,\n",k,ParkPlaceCopy[k+0],ParkPlaceCopy[k+1],ParkPlaceCopy[k+2],ParkPlaceCopy[k+3]);
//printf("ParkPlaceCopy k=%d P2:%f,%f, P3:%f,%f,\n",k,ParkPlaceCopy[k+4],ParkPlaceCopy[k+5],ParkPlaceCopy[k+6],ParkPlaceCopy[k+7]);
k = 3*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_4_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
}
else
{
AndroidReceive_SocWriteData.parking_4_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration_x);
AndroidReceive_SocWriteData.parking_4_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration_y);
AndroidReceive_SocWriteData.parking_4_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration_x);
}
//printf("ParkPlaceCopy k=%d P0:%f,%f, P1: %f,%f,\n",k,ParkPlaceCopy[k+0],ParkPlaceCopy[k+1],ParkPlaceCopy[k+2],ParkPlaceCopy[k+3]);
//printf("ParkPlaceCopy k=%d P2:%f,%f, P3:%f,%f,\n",k,ParkPlaceCopy[k+4],ParkPlaceCopy[k+5],ParkPlaceCopy[k+6],ParkPlaceCopy[k+7]);
//*/
//printf("p0:%f,%f \n",ParkPlaceCopy[0],ParkPlaceCopy[1]);
//printf("p1:%f,%f \n",ParkPlaceCopy[8],ParkPlaceCopy[9]);
//printf("p2:%f,%f \n",ParkPlaceCopy[16],ParkPlaceCopy[17]);
//printf("p3:%f,%f \n",ParkPlaceCopy[24],ParkPlaceCopy[25]);
//for(ii=0;ii<box_num*8;ii=ii+2)
//{
// Ver_Screen_Pos_Parking[ii] = Rear_Axle_Center_x-(ParkPlaceCopy[ii+1]/Pixel_Ration);
// Ver_Screen_Pos_Parking[ii+1] = Rear_Axle_Center_y-(ParkPlaceCopy[ii]/Pixel_Ration);
//}
#if 1
if(Car_Speed_Flag==0) //停车静止状态下,按键选择目标车位,并下发MCU
{
if(Parking_Place_Mode_Select_OK == 1) //目标车位己确定,发送给MCU
{
//Parking_Select_Num=AndroidSend_SocReadData.auto_parking_in_stallID;
/////////////////////////////////////////////////////////////////////////////
///*
if(parking_in_scan_direction == 1)
Parking_Select_Num = left_parking_id_record[AndroidSend_SocReadData.auto_parking_in_stallID];
else if(parking_in_scan_direction == 2)
Parking_Select_Num = right_parking_id_record[AndroidSend_SocReadData.auto_parking_in_stallID];
// */
/////////////////////////////////////////////////////////////////////////////
if(Parking_Select_Num>0){
if(ss==0)
{
int n1=0;
LinkList *h3 = head;
while (h3->next != NULL)
{
n1++;
h3 = h3->next;
//Parking_Select_Num=AndroidSend_SocReadData.auto_parking_in_stallID;
printf("*******&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&***********************************selected %d parking********************\n",Parking_Select_Num);
printf("*******&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&7***********************************selected %d parking********************\n",Parking_Select_Num);
printf("*******&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&***********************************selected %d parking********************\n",Parking_Select_Num);
printf("*******&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&7***********************************selected %d parking********************\n",Parking_Select_Num);
//if(Parking_Select_Num>0){
if( n1== Parking_Select_Num) //选中车位
{
memcpy(ParkingPlace_Ptr->TargetPlace,h3->ParkPlace,8*sizeof(float));
ParkingPlace_Ptr->Targetx = h3->x;
ParkingPlace_Ptr->Targety = h3->y;
ParkingPlace_Ptr->Targetz = h3->z;
ParkingPlace_Ptr->TargetConfidence = h3->park_confidence;
ParkingPlace_Ptr->Target_TimeStamp = ParkingPlace_Ptr->TimeStamp;
ToMcuTargetData.Target_CarPark_P0Point[0] = ParkingPlace_Ptr->TargetPlace[0];
ToMcuTargetData.Target_CarPark_P0Point[1] = ParkingPlace_Ptr->TargetPlace[1];
ToMcuTargetData.Target_CarPark_P1Point[0] = ParkingPlace_Ptr->TargetPlace[2];
ToMcuTargetData.Target_CarPark_P1Point[1] = ParkingPlace_Ptr->TargetPlace[3];
ToMcuTargetData.Target_CarPark_P2Point[0] = ParkingPlace_Ptr->TargetPlace[4];
ToMcuTargetData.Target_CarPark_P2Point[1] = ParkingPlace_Ptr->TargetPlace[5];
ToMcuTargetData.Target_CarPark_P3Point[0] = ParkingPlace_Ptr->TargetPlace[6];
ToMcuTargetData.Target_CarPark_P3Point[1] = ParkingPlace_Ptr->TargetPlace[7];
ToMcuTargetData.TargetConfidence = ParkingPlace_Ptr->TargetConfidence;
ToMcuTargetData.Targetx = ParkingPlace_Ptr->Targetx;
ToMcuTargetData.Targety = ParkingPlace_Ptr->Targety;
ToMcuTargetData.Targetz = ParkingPlace_Ptr->Targetz;
ToMcuTargetData.Customer_Select_Ok_Flag = 1;
printf("Target_ParkingPlace_Ptr p0:%f %f \n",ParkingPlace_Ptr->TargetPlace[0],ParkingPlace_Ptr->TargetPlace[1]);
printf("Target_ParkingPlace_Ptr p1:%f %f \n",ParkingPlace_Ptr->TargetPlace[2],ParkingPlace_Ptr->TargetPlace[3]);
printf("Target_ParkingPlace_Ptr p2:%f %f \n",ParkingPlace_Ptr->TargetPlace[4],ParkingPlace_Ptr->TargetPlace[5]);
printf("Target_ParkingPlace_Ptr p3:%f %f \n",ParkingPlace_Ptr->TargetPlace[6],ParkingPlace_Ptr->TargetPlace[7]);
printf("ParkingPlace_Ptr->TimeStamp = %d\n",ParkingPlace_Ptr->TimeStamp);
printf("Target_ x:%d y:%d z:%d TimeStamp=%d\n",ParkingPlace_Ptr->Targetx,ParkingPlace_Ptr->Targety,ParkingPlace_Ptr->Targetz,ParkingPlace_Ptr->Target_TimeStamp);
break;
}
//}
}
ss = 1;
}
}
/*
ToMcuTargetData.Target_CarPark_P0Point[0] = ParkingPlace_Ptr->TargetPlace[0];
ToMcuTargetData.Target_CarPark_P0Point[1] = ParkingPlace_Ptr->TargetPlace[1];
ToMcuTargetData.Target_CarPark_P1Point[0] = ParkingPlace_Ptr->TargetPlace[2];
ToMcuTargetData.Target_CarPark_P1Point[1] = ParkingPlace_Ptr->TargetPlace[3];
ToMcuTargetData.Target_CarPark_P2Point[0] = ParkingPlace_Ptr->TargetPlace[4];
ToMcuTargetData.Target_CarPark_P2Point[1] = ParkingPlace_Ptr->TargetPlace[5];
ToMcuTargetData.Target_CarPark_P3Point[0] = ParkingPlace_Ptr->TargetPlace[6];
ToMcuTargetData.Target_CarPark_P3Point[1] = ParkingPlace_Ptr->TargetPlace[7];
ToMcuTargetData.TargetConfidence = ParkingPlace_Ptr->TargetConfidence;
ToMcuTargetData.Targetx = ParkingPlace_Ptr->Targetx;
ToMcuTargetData.Targety = ParkingPlace_Ptr->Targety;
ToMcuTargetData.Targetz = ParkingPlace_Ptr->Targetz;
ToMcuTargetData.Customer_Select_Ok_Flag = 1;
*/
}
}
#endif
}
}
else //进入 READY 和RUN status,实时显示MCU上传的车位信息
{
//memset(Ver_Pos_Parking,0,sizeof(GLfloat)*10*4*3);
//box_num = 1;
Parking_Select_Num = 1;
#if 0
Parking_Rect_Point0_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point0_y/Pixel_Ration2);
Parking_Rect_Point0_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point0_x/Pixel_Ration2);
Parking_Rect_Point1_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point1_y/Pixel_Ration2);
Parking_Rect_Point1_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point1_x/Pixel_Ration2);
Parking_Rect_Point2_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point2_y/Pixel_Ration2);
Parking_Rect_Point2_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point2_x/Pixel_Ration2);
Parking_Rect_Point3_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point3_y/Pixel_Ration2);
Parking_Rect_Point3_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point3_x/Pixel_Ration2);
#endif
AndroidReceive_SocWriteData.target_parking_point0_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point0_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.target_parking_point0_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point0_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.target_parking_point1_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point1_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.target_parking_point1_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point1_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.target_parking_point2_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point2_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.target_parking_point2_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point2_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.target_parking_point3_x = Rear_Axle_Center_x2-(McuSend_PcReadData.parking_rect_point3_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.target_parking_point3_y = Rear_Axle_Center_y2-(McuSend_PcReadData.parking_rect_point3_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.virtual_parking_point0_x = Rear_Axle_Center_x2-(McuSend_PcReadData.travel_parking_rect_point0_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.virtual_parking_point0_y = Rear_Axle_Center_y2-(McuSend_PcReadData.travel_parking_rect_point0_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.virtual_parking_point1_x = Rear_Axle_Center_x2-(McuSend_PcReadData.travel_parking_rect_point1_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.virtual_parking_point1_y = Rear_Axle_Center_y2-(McuSend_PcReadData.travel_parking_rect_point1_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.virtual_parking_point2_x = Rear_Axle_Center_x2-(McuSend_PcReadData.travel_parking_rect_point2_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.virtual_parking_point2_y = Rear_Axle_Center_y2-(McuSend_PcReadData.travel_parking_rect_point2_x/Pixel_Ration2_x);
AndroidReceive_SocWriteData.virtual_parking_point3_x = Rear_Axle_Center_x2-(McuSend_PcReadData.travel_parking_rect_point3_y/Pixel_Ration2_y);
AndroidReceive_SocWriteData.virtual_parking_point3_y = Rear_Axle_Center_y2-(McuSend_PcReadData.travel_parking_rect_point3_x/Pixel_Ration2_x);
printf("MCU PO:%d %d P1:%d %d P2:%d %d P3:%d %d\n",McuSend_PcReadData.parking_rect_point0_x,McuSend_PcReadData.parking_rect_point0_y,McuSend_PcReadData.parking_rect_point1_x,McuSend_PcReadData.parking_rect_point1_y,McuSend_PcReadData.parking_rect_point2_x,McuSend_PcReadData.parking_rect_point2_y,McuSend_PcReadData.parking_rect_point3_x,McuSend_PcReadData.parking_rect_point3_y);
printf("MCU XYZ:%d,%d,%d\n",McuSend_PcReadData.TimeStampex[0],McuSend_PcReadData.TimeStampex[1],McuSend_PcReadData.TimeStampex[2]);
#if 1
printf("ssssssssssssssssssssssssssssss^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
printf("MCU PO:%d %d P1:%d %d P2:%d %d P3:%d %d\n",McuSend_PcReadData.parking_rect_point0_x,McuSend_PcReadData.parking_rect_point0_y,McuSend_PcReadData.parking_rect_point1_x,McuSend_PcReadData.parking_rect_point1_y,McuSend_PcReadData.parking_rect_point2_x,McuSend_PcReadData.parking_rect_point2_y,McuSend_PcReadData.parking_rect_point3_x,McuSend_PcReadData.parking_rect_point3_y);
printf("travee: P0:%d %d \n",McuSend_PcReadData.travel_parking_rect_point0_x,McuSend_PcReadData.travel_parking_rect_point0_y);
printf("travee: P1:%d %d \n",McuSend_PcReadData.travel_parking_rect_point1_x,McuSend_PcReadData.travel_parking_rect_point1_y);
printf("travee: P2:%d %d \n",McuSend_PcReadData.travel_parking_rect_point2_x,McuSend_PcReadData.travel_parking_rect_point2_y);
printf("travee: P3:%d %d \n",McuSend_PcReadData.travel_parking_rect_point3_x,McuSend_PcReadData.travel_parking_rect_point3_y);
printf("to ANDROID: P0:%d %d \n",AndroidReceive_SocWriteData.target_parking_point0_x,AndroidReceive_SocWriteData.target_parking_point0_y);
printf("to ANDROID: P1:%d %d \n",AndroidReceive_SocWriteData.target_parking_point1_x,AndroidReceive_SocWriteData.target_parking_point1_y);
printf("to ANDROID: P2:%d %d \n",AndroidReceive_SocWriteData.target_parking_point2_x,AndroidReceive_SocWriteData.target_parking_point2_y);
printf("to ANDROID: P3:%d %d \n",AndroidReceive_SocWriteData.target_parking_point3_x,AndroidReceive_SocWriteData.target_parking_point3_y);
printf("to ANDROID xingcheng: P0:%d %d \n",AndroidReceive_SocWriteData.virtual_parking_point0_x,AndroidReceive_SocWriteData.virtual_parking_point0_y);
printf("to ANDROID xingcheng: P1:%d %d \n",AndroidReceive_SocWriteData.virtual_parking_point1_x,AndroidReceive_SocWriteData.virtual_parking_point1_y);
printf("to ANDROID xingcheng: P2:%d %d \n",AndroidReceive_SocWriteData.virtual_parking_point2_x,AndroidReceive_SocWriteData.virtual_parking_point2_y);
printf("to ANDROID xingcheng: P3:%d %d \n",AndroidReceive_SocWriteData.virtual_parking_point3_x,AndroidReceive_SocWriteData.virtual_parking_point3_y);
#endif
}
}
else
{
//memset(Ver_Pos_Parking,0,sizeof(GLfloat)*10*4*3);
}
///////////////////////////////////////////////////////////
#if 0
parking_place_detected_flag = 1;
ParkPlaceCopy[0]=6410;
ParkPlaceCopy[1]=1840;
ParkPlaceCopy[2]=4277;
ParkPlaceCopy[3]=1873;
ParkPlaceCopy[4]=4197;
ParkPlaceCopy[5]=6733;
ParkPlaceCopy[6]=6380;
ParkPlaceCopy[7]=6746;
//#endif
//#if 0
//ParkPlaceCopy[0]=6410;
//ParkPlaceCopy[1]=-1840;
//ParkPlaceCopy[2]=4277;
//ParkPlaceCopy[3]=-1873;
//ParkPlaceCopy[4]=4197;
//ParkPlaceCopy[5]=-6733;
//ParkPlaceCopy[6]=6380;
//ParkPlaceCopy[7]=-6746;
//#endif
ParkPlaceCopy[8+0]=6410;
ParkPlaceCopy[8+1]=-1840;
ParkPlaceCopy[8+2]=1277;
ParkPlaceCopy[8+3]=-1873;
ParkPlaceCopy[8+4]=1197;
ParkPlaceCopy[8+5]=-4733;
ParkPlaceCopy[8+6]=6380;
ParkPlaceCopy[8+7]=-4746;
ParkPlaceCopy[2*8+0]=-6410;
ParkPlaceCopy[2*8+1]=-1840;
ParkPlaceCopy[2*8+2]=-1277;
ParkPlaceCopy[2*8+3]=-1873;
ParkPlaceCopy[2*8+4]=-1197;
ParkPlaceCopy[2*8+5]=-4733;
ParkPlaceCopy[2*8+6]=-6380;
ParkPlaceCopy[2*8+7]=-4746;
ParkPlaceCopy[3*8+0]=6410;
ParkPlaceCopy[3*8+1]=-1840;
ParkPlaceCopy[3*8+2]=1277;
ParkPlaceCopy[3*8+3]=-1873;
ParkPlaceCopy[3*8+4]=1197;
ParkPlaceCopy[3*8+5]=-4733;
ParkPlaceCopy[3*8+6]=6380;
ParkPlaceCopy[3*8+7]=-4746;
int disPoint01= (ParkPlaceCopy[0]-ParkPlaceCopy[2])*(ParkPlaceCopy[0]-ParkPlaceCopy[2])+(ParkPlaceCopy[1]-ParkPlaceCopy[3])*(ParkPlaceCopy[1]-ParkPlaceCopy[3]);
int disPoint03= (ParkPlaceCopy[0]-ParkPlaceCopy[6])*(ParkPlaceCopy[0]-ParkPlaceCopy[6])+(ParkPlaceCopy[1]-ParkPlaceCopy[7])*(ParkPlaceCopy[1]-ParkPlaceCopy[7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration);
}
else
{
AndroidReceive_SocWriteData.parking_1_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[6]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_1_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[4]/Pixel_Ration);
}
int k = 1*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_2_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
}
else
{
AndroidReceive_SocWriteData.parking_2_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_2_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
}
k = 2*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_3_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
}
else
{
AndroidReceive_SocWriteData.parking_3_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_3_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
}
k = 3*8;
disPoint01= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+2])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+3]);
disPoint03= (ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])*(ParkPlaceCopy[k+0]-ParkPlaceCopy[k+6])+(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7])*(ParkPlaceCopy[k+1]-ParkPlaceCopy[k+7]);
if(disPoint01 <= disPoint03)
{
AndroidReceive_SocWriteData.parking_4_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
}
else
{
AndroidReceive_SocWriteData.parking_4_point0_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+7]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point0_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+6]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point1_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+1]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point1_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+0]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point2_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+3]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point2_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+2]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point3_x = Rear_Axle_Center_x-(ParkPlaceCopy[k+5]/Pixel_Ration);
AndroidReceive_SocWriteData.parking_4_point3_y = Rear_Axle_Center_y-(ParkPlaceCopy[k+4]/Pixel_Ration);
}
#endif
}
void insert_trail(LinkList * list,LinkList * newnode) //链表尾部添加节点
{
LinkList *h = list;
while (h->next != NULL)
{
h = h->next;
//printf("%d ", h->score);
}
h->next = newnode;
}
void deleteNode(LinkList *list, int n) //删除链表第n个节点
{
LinkList *t = list, *in;
int i = 0;
while (i < n && t != NULL)
{
in = t;
t = t->next;
i++;
}
if (t != NULL)
{
in->next = t->next;
free(t);
}
else
{
puts("节点不存在");
}
}
void deleteLinklist(LinkList *list) //删除整个链表,释放空间
{
LinkList * pNext;
LinkList * pHead = list;
while(pHead != NULL)
{
pNext = pHead->next;
free(pHead);
pHead = pNext;
}
}
static void coord_cc2oc(short int coords[3], float cc[8], float oc[8])
{
float radian = (float) coords[2] / 10000;
for (int i=0; i<4; i++)
{
//float x = cc[i * 2 + 1];
// float y = -cc[i * 2];
float y = cc[i * 2 + 1];
float x = cc[i * 2];
oc[i * 2] = x * cos(radian) - y * sin(radian) + coords[0];
oc[i * 2 + 1] = x * sin(radian) + y * cos(radian) + coords[1];
}
}
static void coord_pts2veh(short int curr_coords[3], short int prev_coords[3], float prev_pts[8], float pts2veh[8])
{
// convert CC to OC for previous points
float prev_oc[8];
coord_cc2oc(prev_coords, prev_pts, prev_oc);
// convert OC to coordinates relative to vehicle
float radian = (float) curr_coords[2] / 10000;
for (int i=0; i<4; i++)
{
float delta_x = curr_coords[0] - prev_oc[i * 2];
float delta_y = curr_coords[1] - prev_oc[i * 2+1];
pts2veh[i * 2] = -cos(radian) * delta_x - sin(radian) * delta_y;
pts2veh[i * 2+ 1] = sin(radian) * delta_x - cos(radian) * delta_y;
}
}
| 39.48445 | 388 | 0.668771 | [
"geometry",
"object"
] |
8cf80433b4337489f80350833cde15eec627275e | 20,959 | cpp | C++ | Source/main.cpp | harrymt/rasterizer | 7afd2fd9e8a0e25ecdd7fcde82f7e045cc8522c0 | [
"MIT"
] | 3 | 2020-02-15T12:45:02.000Z | 2021-09-13T17:00:17.000Z | Source/main.cpp | harrymt/rasterizer | 7afd2fd9e8a0e25ecdd7fcde82f7e045cc8522c0 | [
"MIT"
] | null | null | null | Source/main.cpp | harrymt/rasterizer | 7afd2fd9e8a0e25ecdd7fcde82f7e045cc8522c0 | [
"MIT"
] | null | null | null | #include "rasterizer.h"
#include "omp.h"
#define D2R(x) x * pi / 180
SDL_Surface* screen;
int t;
Triangle* triangles;
int num_triangles;
glm::vec3 cameraPos(0, 0, -FOCAL);
const float delta_displacement = 0.1f;
float rotationAngle = 0;
glm::vec3 lightPos(0, 0, -FOCAL_LIGHT);// (0, -FOCAL_LIGHT, 0);
glm::mat3 lightRot(1, 0, 0, 0, 1, 0, 0, 0, 1); //(1, 0, 0, 0, 0, -1, 0, 1, 0);
glm::vec3 lightPower = 16.f * glm::vec3(1, 1, 1);
glm::vec3 indirectLightPowerPerArea = 0.5f * glm::vec3(1, 1, 1);
glm::vec3 indirectIllumination(0.2f, 0.2f, 0.2f);
#ifdef OPEN_CL
ocl_t ocl;
#endif
framebuffer_t frame_buffer;
float light_buffer[LIGHT_HEIGHT][LIGHT_WIDTH];
const float theta = D2R(5);
glm::mat3 currentRot(1, 0, 0, 0, 1, 0, 0, 0, 1);
void updateRotation() {
float s = sin(rotationAngle);
currentRot[0][0] = currentRot[2][2] = cos(rotationAngle);
currentRot[0][2] = s;
currentRot[2][0] = -s;
}
void update()
{
// Compute frame time:
int t2 = SDL_GetTicks();
float dt = (float) (t2-t);
t = t2;
std::cout << "Render time: " << dt << " ms.\n";
// Need to compute these every update
glm::vec3 right(currentRot[0][0], currentRot[0][1], currentRot[0][2]);
glm::vec3 forward(currentRot[2][0], currentRot[2][1], currentRot[2][2]);
Uint8* keystate = SDL_GetKeyState(0);
if (keystate[SDLK_w])
{
cameraPos += theta * forward;
updateRotation();
}
if (keystate[SDLK_s])
{
cameraPos -= theta * forward;
updateRotation();
}
// Strafe
if (keystate[SDLK_d])
{
cameraPos += theta * right;
updateRotation();
}
if (keystate[SDLK_a])
{
cameraPos -= theta * right;
updateRotation();
}
if (keystate[SDLK_t])
{
cameraPos = cameraPos * glm::inverse(currentRot);
cameraPos[1] -= delta_displacement;
cameraPos = cameraPos * currentRot;
updateRotation();
}
if (keystate[SDLK_y])
{
cameraPos = cameraPos * glm::inverse(currentRot);
cameraPos[1] += delta_displacement;
cameraPos = cameraPos * currentRot;
updateRotation();
}
if (keystate[SDLK_q])
{
rotationAngle += theta;
updateRotation();
}
if (keystate[SDLK_e])
{
rotationAngle -= theta;
updateRotation();
}
if (keystate[SDLK_r])
{
cameraPos = {0, 0, -FOCAL};
lightPos = {0, -0.5, -0.7};
currentRot = glm::mat3(1, 0, 0, 0, 1, 0, 0, 0, 1);
rotationAngle = 0;
}
if (keystate[SDLK_UP])
{
lightPos[2] += delta_displacement;
}
if (keystate[SDLK_DOWN])
{
lightPos[2] -= delta_displacement;
}
if (keystate[SDLK_RIGHT])
{
lightPos[0] += delta_displacement;
}
if (keystate[SDLK_LEFT])
{
lightPos[0] -= delta_displacement;
}
if (keystate[SDLK_PAGEUP])
{
lightPos[1] -= delta_displacement;
}
if (keystate[SDLK_PAGEDOWN])
{
lightPos[1] += delta_displacement;
}
}
void vertexShader(const vertex_t& v, pixel_t& p)
{
glm::vec3 point = (v - cameraPos) * currentRot;
glm::vec3 lightRel = (v - lightPos) * lightRot;
float x = point.x;
float y = point.y;
float z = point.z;
p.pos3d = v;
p.zinv = 1/z;
p.x = (int) (FOCAL_LENGTH * x/z) + SCREEN_WIDTH / 2;
p.y = (int) (FOCAL_LENGTH * y/z) + SCREEN_HEIGHT / 2;
x = lightRel.x;
y = lightRel.y;
z = lightRel.z;
p.lzinv = 1 / z;
p.lx = (int)(FOCAL_LENGTH_LIGHT * x / z) + LIGHT_HEIGHT / 2;
p.ly = (int)(FOCAL_LENGTH_LIGHT * y / z) + LIGHT_WIDTH / 2;
}
/**
* The nearer the pixel.pos3d is to the lightPos, the brighter it should be.
*/
#ifndef OPEN_CL
#define NUM_SAMPLES 1
#define ADJUSTMENT 0.0185f
void pixelShader(const int x, const int y)
{
glm::vec3 illumination;
#if NUM_SAMPLES != 1
for (float i = -1.0f; i < 1.0f; i += 2.0f / NUM_SAMPLES)
{
for (float j = -1.0f; j < 1.0f; j += 2.0f / NUM_SAMPLES)
{
#else
float i = 0;
float j = 0;
#endif
float xl = frame_buffer.light_positions[y][x].x + j*ADJUSTMENT;
float yl = frame_buffer.light_positions[y][x].y + i*ADJUSTMENT;
float zl = frame_buffer.light_positions[y][x].z;
int ilx = (int)(FOCAL_LENGTH_LIGHT * xl / zl) + LIGHT_WIDTH / 2;
int ily = (int)(FOCAL_LENGTH_LIGHT * yl / zl) + LIGHT_HEIGHT / 2;
if (// If any of these are true, then the point is not lit by the light at all
ilx < 0 || ilx >= LIGHT_WIDTH || ily < 0 || ily >= LIGHT_HEIGHT || zl < 0
// If the above was false, then we are within the field, but if our depth isn't
// what the light_buffer tells us is the closest depth to the light, then we are
// obviously occluded
|| 1 / zl < light_buffer[ily][ilx] - 0.005f
)
{
// There is ambient lighting in the room
// TODO: We can make it so that cast shadows are slightly more bright than out of field shadows
illumination += indirectIllumination;
}
else
{
glm::vec3 surfaceToLight = lightPos - frame_buffer.positions[y][x];
float r = glm::length(surfaceToLight);
float ratio = glm::dot(glm::normalize(surfaceToLight), frame_buffer.normals[y][x]);
if (ratio < 0) ratio = 0;
glm::vec3 B = lightPower / (4.0f * pi * r * r);
glm::vec3 D = B * ratio;
illumination += D + indirectLightPowerPerArea;
}
#if NUM_SAMPLES != 1
}
}
#endif
illumination /= (NUM_SAMPLES * NUM_SAMPLES);
frame_buffer.colours[y][x] = illumination * frame_buffer.colours[y][x];
}
#endif
#ifdef OPEN_CL
void checkError(cl_int err, const char* op, const int line);
void initialiseCl();
void finaliseCl();
const cl_float2 u_texel = { 1.0f / SCREEN_WIDTH, 1.0f / SCREEN_HEIGHT };
#endif
void draw()
{
#ifdef OPEN_CL
cl_int err;
#endif
SDL_FillRect(screen, 0, 0);
if(SDL_MUSTLOCK(screen)) SDL_LockSurface(screen);
#pragma omp parallel for
for (int i = 0; i < SCREEN_HEIGHT; ++i)
{
for (int j = 0; j < SCREEN_WIDTH; ++j)
{
frame_buffer.depths[i][j] = 0;
frame_buffer.colours[i][j] = toFloat3(glm::vec3(0.0f, 0.0f, 0.0f));
if (i < LIGHT_HEIGHT && j < LIGHT_WIDTH)
{
light_buffer[i][j] = 0;
}
}
}
#pragma omp parallel for
for (int i = 0; i < num_triangles; i++)
{
drawPolygon(triangles[i]);
}
#ifdef OPEN_CL
err = clEnqueueWriteBuffer(ocl.queue, ocl.depths, CL_TRUE, 0, sizeof(cl_float) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.depths, 0, nullptr, nullptr);
checkError(err, "writing depth data", __LINE__);
err = clEnqueueWriteBuffer(ocl.queue, ocl.light_depths, CL_TRUE, 0, sizeof(cl_float) * LIGHT_WIDTH * LIGHT_HEIGHT, light_buffer, 0, nullptr, nullptr);
checkError(err, "writing light depth buffer data", __LINE__);
err = clEnqueueWriteBuffer(ocl.queue, ocl.normals, CL_TRUE, 0, sizeof(cl_float3) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.normals, 0, nullptr, nullptr);
checkError(err, "writing normal data", __LINE__);
err = clEnqueueWriteBuffer(ocl.queue, ocl.colours, CL_TRUE, 0, sizeof(cl_float3) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.colours, 0, nullptr, nullptr);
checkError(err, "writing colour data", __LINE__);
err = clEnqueueWriteBuffer(ocl.queue, ocl.positions, CL_TRUE, 0, sizeof(cl_float3) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.positions, 0, nullptr, nullptr);
checkError(err, "writing position data", __LINE__);
err = clEnqueueWriteBuffer(ocl.queue, ocl.light_positions, CL_TRUE, 0, sizeof(cl_float3) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.light_positions, 0, nullptr, nullptr);
checkError(err, "writing light position data", __LINE__);
cl_int width = SCREEN_WIDTH;
cl_int height = SCREEN_HEIGHT;
cl_int light_width = LIGHT_WIDTH;
cl_int light_height = LIGHT_HEIGHT;
cl_float3 light_pos = toFloat3(lightPos);
cl_float light_focal = FOCAL_LENGTH_LIGHT;
err = clSetKernelArg(ocl.pixelShader, 0, sizeof(cl_mem), &ocl.positions);
checkError(err, "setting pixelShader arg 0", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 1, sizeof(cl_mem), &ocl.normals);
checkError(err, "setting pixelShader arg 1", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 2, sizeof(cl_mem), &ocl.colours);
checkError(err, "setting pixelShader arg 2", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 3, sizeof(cl_mem), &ocl.light_depths);
checkError(err, "setting pixelShader arg 3", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 4, sizeof(cl_mem), &ocl.light_positions);
checkError(err, "setting pixelShader arg 4", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 5, sizeof(cl_float), &light_focal);
checkError(err, "setting pixelShader arg 5", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 6, sizeof(cl_int), &width);
checkError(err, "setting pixelShader arg 6", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 7, sizeof(cl_int), &height);
checkError(err, "setting pixelShader arg 7", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 8, sizeof(cl_int), &light_width);
checkError(err, "setting pixelShader arg 8", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 9, sizeof(cl_int), &light_height);
checkError(err, "setting pixelShader arg 9", __LINE__);
err = clSetKernelArg(ocl.pixelShader, 10, sizeof(cl_float3), &light_pos);
checkError(err, "setting pixelShader arg 10", __LINE__);
size_t global[2] = { width, height };
err = clEnqueueNDRangeKernel(ocl.queue, ocl.pixelShader, 2, nullptr, global, nullptr, 0, nullptr, nullptr);
checkError(err, "enqueueing pixelShader kernel", __LINE__);
clFinish(ocl.queue);
err = clSetKernelArg(ocl.fxaa, 0, sizeof(cl_mem), &ocl.colours);
checkError(err, "setting fxaa arg 0", __LINE__);
err = clSetKernelArg(ocl.fxaa, 1, sizeof(cl_mem), &ocl.fxaa_colours);
checkError(err, "setting fxaa arg 1", __LINE__);
err = clSetKernelArg(ocl.fxaa, 2, sizeof(cl_int), &width);
checkError(err, "setting fxaa arg 2", __LINE__);
err = clSetKernelArg(ocl.fxaa, 3, sizeof(cl_int), &height);
checkError(err, "setting fxaa arg 3", __LINE__);
err = clSetKernelArg(ocl.fxaa, 4, sizeof(cl_float2), &u_texel);
checkError(err, "setting fxaa arg 4", __LINE__);
err = clEnqueueNDRangeKernel(ocl.queue, ocl.fxaa, 2, nullptr, global, nullptr, 0, nullptr, nullptr);
checkError(err, "enqueueing fxaa kernel", __LINE__);
clFinish(ocl.queue);
err = clEnqueueReadBuffer(ocl.queue, ocl.fxaa_colours, CL_TRUE, 0, sizeof(cl_float3) * SCREEN_WIDTH * SCREEN_HEIGHT, frame_buffer.colours, 0, nullptr, nullptr);
checkError(err, "reading frame data", __LINE__);
#else
#pragma omp parallel for
for (int i = 0; i < SCREEN_HEIGHT; ++i)
{
for (int j = 0; j < SCREEN_WIDTH; ++j)
{
pixelShader(j, i);
}
}
#endif
#pragma omp parallel for
for (int i = 0; i < SCREEN_HEIGHT; ++i)
{
for (int j = 0; j < SCREEN_WIDTH; ++j)
{
#ifndef OPEN_CL
fxaa(j, i);
PutPixelSDL(screen, j, i, frame_buffer.fxaa_colours[i][j]);
#else
PutPixelSDL(screen, j, i, fromFloat3(&frame_buffer.colours[i][j]));
#endif
}
}
if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
#ifndef OPEN_CL
float reducemul = 1.0f/8.0f;
float reducemin = 1.0f/128.0f;
float u_strength = 2.5f;
glm::vec2 u_texel(1.0f/SCREEN_WIDTH, 1.0f/SCREEN_HEIGHT);
inline glm::vec3 texture2D(float x, float y)
{
return fromFloat3(&frame_buffer.colours[glm::clamp((int) (glm::clamp(y, 0.0f, 1.0f)*SCREEN_HEIGHT-1), 0, SCREEN_HEIGHT-1)]
[glm::clamp((int) (glm::clamp(x, 0.0f, 1.0f)*SCREEN_WIDTH-1), 0, SCREEN_WIDTH-1)]);
}
inline glm::vec3 texture2D(glm::vec2 coords)
{
return texture2D(coords.x, coords.y);
}
void fxaa(int x_, int y_)
{
glm::vec2 coords((float) x_/(float)SCREEN_WIDTH, (float) y_/(float)SCREEN_HEIGHT);
glm::vec3 centre = texture2D(coords);
glm::vec3 nw = texture2D(coords-u_texel);
glm::vec3 ne = texture2D(coords.x + u_texel.x, coords.y - u_texel.y);
glm::vec3 sw = texture2D(coords.x - u_texel.x, coords.y + u_texel.y);
glm::vec3 se = texture2D(coords+u_texel);
glm::vec3 gray(0.299f, 0.587f, 0.114f);
float mono_centre = glm::dot(centre, gray);
float mono_nw = glm::dot(nw, gray);
float mono_ne = glm::dot(ne, gray);
float mono_sw = glm::dot(sw, gray);
float mono_se = glm::dot(se, gray);
float mono_min = MIN(mono_centre, MIN(mono_nw, MIN(mono_ne, MIN(mono_sw, mono_se))));
float mono_max = MAX(mono_centre, MAX(mono_nw, MAX(mono_ne, MAX(mono_sw, mono_se))));
glm::vec2 dir(-((mono_nw + mono_ne) - (mono_sw + mono_se)), ((mono_nw + mono_sw) - (mono_ne + mono_se)));
float dir_reduce = MAX((mono_nw + mono_ne + mono_sw + mono_se) * reducemul * 0.25, reducemin);
float dir_min = 1.0f / (MIN(abs(dir.x), abs(dir.y)) + dir_reduce);
// This can be changed to use glm min and max I think
dir = glm::vec2(MIN(u_strength, MAX(-u_strength, dir.x * dir_min))*u_texel.x, MIN(u_strength, MAX(-u_strength, dir.y * dir_min))*u_texel.y);
glm::vec3 resultA = 0.5f * (texture2D(coords + (-0.166667f * dir)) + texture2D(coords + 0.166667f * dir));
glm::vec3 resultB = 0.5f * resultA + 0.25f * (texture2D(coords + (-0.5f*dir)) + texture2D(coords + 0.5f*dir));
float mono_b = glm::dot(resultB, gray);
frame_buffer.fxaa_colours[y_][x_] = toFloat3(mono_b < mono_min || mono_b > mono_max ? resultA : resultB);
}
#endif
int main()
{
#ifdef OPEN_CL
initialiseCl();
#endif
screen = InitializeSDL(SCREEN_WIDTH, SCREEN_HEIGHT);
t = SDL_GetTicks();
currentRot[1][1] = 1.0f;
// Fill triangles with test model
std::vector<Triangle> triangles_;
LoadTestModel(triangles_);
num_triangles = triangles_.size();
triangles = new Triangle[num_triangles];
for (size_t i = 0; i < num_triangles; ++i)
{
triangles[i] = triangles_[i];
}
while (NoQuitMessageSDL())
{
update();
draw();
}
delete[] triangles;
SDL_SaveBMP(screen, "screenshot.bmp");
#ifdef OPEN_CL
finaliseCl();
#endif
return 0;
}
#ifdef OPEN_CL
cl_device_id selectOpenCLDevice();
void die(const char* message, const int line, const char* file);
void initialiseCl()
{
cl_int err;
ocl.device = selectOpenCLDevice();
ocl.context = clCreateContext(nullptr, 1, &ocl.device, nullptr, nullptr, &err);
checkError(err, "creating context", __LINE__);
ocl.queue = clCreateCommandQueue(ocl.context, ocl.device, 0, &err);
checkError(err, "creating command queue", __LINE__);
std::ifstream fp;
fp.open("kernels.cl");
if (!fp.is_open())
{
char message[1024];
printf(message, "could not open OpenCL kernel file: kernels.cl");
die(message, __LINE__, __FILE__);
}
std::string file_contents = std::string(std::istreambuf_iterator<char>(fp), std::istreambuf_iterator<char>());
const char* ocl_src = file_contents.c_str();
ocl.program = clCreateProgramWithSource(ocl.context, 1, (const char**)&ocl_src, nullptr, &err);
checkError(err, "creating program", __LINE__);
ocl.work_group_size = GROUP_SIZE;
ocl.num_work_groups = (SCREEN_WIDTH * SCREEN_HEIGHT) / ocl.work_group_size;
std::stringstream flags;
flags << "-D NUM_GROUPS=" << ocl.work_group_size << " -D GROUP_SIZE=" << ocl.num_work_groups;
err = clBuildProgram(ocl.program, 1, &ocl.device, flags.str().c_str(), nullptr, nullptr);
if (err == CL_BUILD_PROGRAM_FAILURE)
{
size_t sz;
clGetProgramBuildInfo(ocl.program, ocl.device, CL_PROGRAM_BUILD_LOG, 0, nullptr, &sz);
char* buildlog = (char*)calloc(sz, sizeof(char));
clGetProgramBuildInfo(ocl.program, ocl.device, CL_PROGRAM_BUILD_LOG, sz, buildlog, nullptr);
std::cout << "\nOpenCL build log : \n\n" << buildlog << std::endl;
free(buildlog);
}
checkError(err, "building program", __LINE__);
ocl.pixelShader = clCreateKernel(ocl.program, "pixelShader", &err);
checkError(err, "creating pixelShader kernel", __LINE__);
ocl.fxaa = clCreateKernel(ocl.program, "fxaa", &err);
checkError(err, "creating fxaa kernel", __LINE__);
ocl.depths = clCreateBuffer(ocl.context, CL_MEM_READ_ONLY, sizeof(cl_float) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating depth buffer", __LINE__);
ocl.normals = clCreateBuffer(ocl.context, CL_MEM_READ_ONLY, sizeof(cl_float3) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating normal buffer", __LINE__);
ocl.colours = clCreateBuffer(ocl.context, CL_MEM_READ_WRITE, sizeof(cl_float3) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating colour buffer", __LINE__);
ocl.fxaa_colours = clCreateBuffer(ocl.context, CL_MEM_WRITE_ONLY, sizeof(cl_float3) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating fxaa colour buffer", __LINE__);
ocl.positions = clCreateBuffer(ocl.context, CL_MEM_READ_ONLY, sizeof(cl_float3) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating position buffer", __LINE__);
ocl.light_positions = clCreateBuffer(ocl.context, CL_MEM_READ_ONLY, sizeof(cl_float3) * SCREEN_HEIGHT * SCREEN_WIDTH, nullptr, &err);
checkError(err, "creating light position buffer", __LINE__);
ocl.light_depths = clCreateBuffer(ocl.context, CL_MEM_READ_ONLY, sizeof(cl_float) * LIGHT_HEIGHT * LIGHT_WIDTH, nullptr, &err);
checkError(err, "creating light depth buffer", __LINE__);
}
void finaliseCl()
{
clReleaseMemObject(ocl.depths);
clReleaseMemObject(ocl.normals);
clReleaseMemObject(ocl.colours);
clReleaseMemObject(ocl.fxaa_colours);
clReleaseMemObject(ocl.positions);
clReleaseMemObject(ocl.light_positions);
clReleaseMemObject(ocl.light_depths);
clReleaseKernel(ocl.pixelShader);
clReleaseKernel(ocl.fxaa);
clReleaseProgram(ocl.program);
clReleaseCommandQueue(ocl.queue);
clReleaseContext(ocl.context);
}
#define MAX_DEVICES 4
#define MAX_DEVICE_NAME 100
cl_device_id selectOpenCLDevice()
{
cl_int err;
cl_uint num_platforms = 0;
cl_uint total_devices = 0;
cl_platform_id platforms[8];
cl_device_id devices[MAX_DEVICES];
char name[MAX_DEVICE_NAME];
// Get list of platforms
err = clGetPlatformIDs(8, platforms, &num_platforms);
checkError(err, "getting platforms", __LINE__);
// Get list of devices
for (cl_uint p = 0; p < num_platforms; p++)
{
cl_uint num_devices = 0;
err = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, MAX_DEVICES - total_devices, devices + total_devices, &num_devices);
checkError(err, "getting device name", __LINE__);
total_devices += num_devices;
}
// Print list of devices
printf("\nAvailable OpenCL devices:\n");
for (cl_uint d = 0; d < total_devices; d++)
{
clGetDeviceInfo(devices[d], CL_DEVICE_NAME, MAX_DEVICE_NAME, name, nullptr);
printf("%2d: %s\n", d, name);
}
printf("\n");
// Use first device unless OCL_DEVICE environment variable used
cl_uint device_index = 0;
#ifdef _MSC_VER
char* dev_env = nullptr;
size_t sz = 0;
_dupenv_s(&dev_env, &sz, "OCL_DEVICE");
#else
char *dev_env = getenv("OCL_DEVICE");
#endif
if (dev_env)
{
char *end;
device_index = strtol(dev_env, &end, 10);
if (strlen(end)) die("invalid OCL_DEVICE variable", __LINE__, __FILE__);
}
if (device_index >= total_devices)
{
fprintf(stderr, "device index set to %d but only %d devices available\n", device_index, total_devices);
exit(1);
}
// Print OpenCL device name
clGetDeviceInfo(devices[device_index], CL_DEVICE_NAME, MAX_DEVICE_NAME, name, nullptr);
printf("Selected OpenCL device:\n-> %s (index=%d)\n\n", name, device_index);
return devices[device_index];
}
void checkError(cl_int err, const char *op, const int line)
{
if (err != CL_SUCCESS)
{
fprintf(stderr, "OpenCL error during '%s' on line %d: %d\n", op, line, err);
fflush(stderr);
//while (true);
exit(EXIT_FAILURE);
}
}
void die(const char* message, const int line, const char* file)
{
fprintf(stderr, "Error at line %d of file %s:\n", line, file);
fprintf(stderr, "%s\n", message);
fflush(stderr);
exit(EXIT_FAILURE);
}
#endif | 34.873544 | 176 | 0.642636 | [
"render",
"vector",
"model"
] |
ea0b251905a4dd19f4905ece462fb1568267647f | 22,214 | cpp | C++ | kdrive/src/access/core/KnxPort.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 34 | 2015-09-16T10:10:14.000Z | 2022-02-19T16:11:04.000Z | kdrive/src/access/core/KnxPort.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 17 | 2017-01-02T15:26:19.000Z | 2022-01-20T01:27:24.000Z | kdrive/src/access/core/KnxPort.cpp | weinzierl-engineering/baos | 306acc8e86da774fdeecec042dcf99734677fdc0 | [
"MIT"
] | 20 | 2016-12-12T22:18:08.000Z | 2022-03-15T16:20:20.000Z |
#include "pch/kdrive_pch.h"
#include "kdrive/access/core/KnxPort.h"
#include "kdrive/access/core/Exception.h"
#include "kdrive/access/ldm/LocalDeviceManager.h"
#include "kdrive/access/ldm/LinkLayerManagement.h"
#include "kdrive/access/core/KnxPacket.h"
#include "kdrive/access/core/TransportPacket.h"
#include "kdrive/access/core/Events.h"
#include "kdrive/access/core/API.h"
#include "kdrive/access/core/details/RfDomainAddressFilter.h"
#include "kdrive/knx/defines/KnxLayer.h"
#include "kdrive/knx/telegrams/cemi/Frame.h"
#include "kdrive/knx/defines/MaskVersion.h"
#include "kdrive/knx/defines/KnxProperty.h"
#include "kdrive/knx/telegrams/formatters/Telegram.h"
#include "kdrive/utility/Logger.h"
#include <Poco/Exception.h>
#include <Poco/Format.h>
#include <Poco/Logger.h>
#include <Poco/NumberFormatter.h>
#include <map>
using namespace kdrive::connector;using namespace kdrive::access;using kdrive::
utility::PropertyCollection;using kdrive::knx::ze127e0a511;using kdrive::knx::
zba36969226;using kdrive::knx::cemi::z5655d09358;using kdrive::knx::zb5ec3c9a78;
using kdrive::knx::cemi::z5b8ac31779;using kdrive::knx::z2a66522423;using kdrive
::knx::zc61eee6dc0;using Poco::Dynamic::Var;using Poco::Exception;using Poco::
FastMutex;using Poco::format;using Poco::NumberFormatter;using Poco::ScopedLock;
CLASS_LOGGER(
"\x6b\x6e\x78\x2e\x61\x63\x63\x65\x73\x73\x2e\x4b\x6e\x78\x50\x6f\x72\x74")
namespace{void za640e45333(PropertyCollection&z56fa974c3c,const std::string&key,
const Poco::Dynamic::Var&value,const std::string&description,bool isReadOnly=
false){z56fa974c3c.setProperty(key,value);}void zdd2e046b74(kdrive::utility::
PropertyCollection&z56fa974c3c){using PropertyWriteableMode=zea2d083c85::
PropertyWriteableMode;za640e45333(z56fa974c3c,zea2d083c85::PortType,zea2d083c85
::ConnectorTypeLabel,"\x50\x6f\x72\x74\x20\x54\x79\x70\x65",true);za640e45333(
z56fa974c3c,zea2d083c85::zb18866bb87,static_cast<unsigned int>(zea2d083c85::
z61d5be1f36),
"\x4c\x2d\x44\x61\x74\x61\x2e\x63\x6f\x6e\x20\x54\x69\x6d\x65\x6f\x75\x74\x20\x28\x6d\x73\x29"
);za640e45333(z56fa974c3c,zea2d083c85::z39ec4d1ae7,false,
"\x4c\x61\x7a\x79\x20\x43\x6f\x6e\x66\x69\x72\x6d");za640e45333(z56fa974c3c,
zea2d083c85::z0ad2fe7ad5,true,
"\x41\x75\x74\x6f\x20\x72\x65\x69\x6e\x69\x74\x69\x61\x6c\x69\x7a\x65\x20\x61\x66\x74\x65\x72\x20\x52\x65\x73\x65\x74\x2e\x69\x6e\x64"
);za640e45333(z56fa974c3c,zea2d083c85::ze2fc87d94b,true,
"\x46\x69\x6c\x74\x65\x72\x20\x52\x46\x20\x44\x6f\x6d\x61\x69\x6e\x20\x41\x64\x64\x72\x65\x73\x73"
);za640e45333(z56fa974c3c,zea2d083c85::z5b2ecda528,static_cast<unsigned int>(
zea2d083c85::z4e34b5d0f7::Unknown),
"\x4b\x4e\x58\x20\x42\x75\x73\x20\x53\x74\x61\x74\x65",true);za640e45333(
z56fa974c3c,zea2d083c85::za6f2fc65f0,false,
"\x53\x68\x6f\x77\x20\x54\x72\x61\x6e\x73\x70\x6f\x72\x74\x20\x46\x72\x61\x6d\x65\x73"
);}bool z171490f0fd(Packet::Ptr packet){bool z8877986cc8=false;try{KnxPacket::
Ptr zfd29354025=KnxPacket::convert(packet,false);if(zfd29354025){const std::
vector<unsigned char>&buffer=zfd29354025->getBuffer();z8877986cc8=(buffer.size()
==(0x7a+8877-0x2326))&&(buffer.at((0x1ba5+936-0x1f4d))==z5b8ac31779::z60a21285a4
);}}catch(...){}return z8877986cc8;}bool z6a86f9a0fc(Packet::Ptr packet){try{
z2a66522423 frame;frame.read(packet->getBuffer());if(frame.z6b11bcce77()==
z5b8ac31779::zcb37dec9d5){return true;}}catch(Exception&e){poco_warning_f1(
LOGGER(),
"\x45\x72\x72\x6f\x72\x20\x69\x6e\x20\x69\x73\x4c\x44\x61\x74\x61\x52\x65\x71\x20\x25\x73"
,e.displayText());}return false;}}const std::string zea2d083c85::
ConnectorTypeLabel="\x4b\x6e\x78\x50\x6f\x72\x74";const std::string zea2d083c85
::zb18866bb87=
"\x6b\x6e\x78\x2e\x6c\x5f\x64\x61\x74\x61\x5f\x63\x6f\x6e\x66\x69\x72\x6d\x5f\x74\x69\x6d\x65\x6f\x75\x74"
;const std::string zea2d083c85::z39ec4d1ae7=
"\x6b\x6e\x78\x2e\x6c\x61\x7a\x79\x5f\x63\x6f\x6e\x66\x69\x72\x6d";const std::
string zea2d083c85::z0ad2fe7ad5=
"\x6b\x6e\x78\x2e\x61\x75\x74\x6f\x5f\x72\x65\x69\x6e\x69\x74\x69\x61\x6c\x69\x7a\x65\x5f\x61\x66\x74\x65\x72\x5f\x72\x65\x73\x65\x74"
;const std::string zea2d083c85::ze2fc87d94b=
"\x6b\x6e\x78\x2e\x66\x69\x6c\x74\x65\x72\x5f\x72\x66\x5f\x64\x6f\x6d\x61\x69\x6e\x5f\x61\x64\x64\x72\x65\x73\x73"
;const std::string zea2d083c85::z8b957c5a25=
"\x6b\x6e\x78\x2e\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x5f\x70\x72\x6f\x74\x6f\x63\x6f\x6c\x73"
;const std::string zea2d083c85::za498009d76=
"\x6b\x6e\x78\x2e\x70\x72\x6f\x74\x6f\x63\x6f\x6c";const std::string zea2d083c85
::za6f43e69a4=
"\x6b\x6e\x78\x2e\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x5f\x6c\x61\x79\x65\x72\x73"
;const std::string zea2d083c85::z9884ee4d6b=
"\x6b\x6e\x78\x2e\x6c\x61\x79\x65\x72";const std::string zea2d083c85::
z74dda860c7=
"\x6b\x6e\x78\x2e\x69\x73\x5f\x74\x6c\x6c\x5f\x73\x75\x70\x70\x6f\x72\x74\x65\x64"
;const std::string zea2d083c85::zb5ec3c9a78=
"\x6b\x6e\x78\x2e\x6d\x61\x73\x6b\x5f\x76\x65\x72\x73\x69\x6f\x6e";const std::
string zea2d083c85::z2a66eed75d=
"\x6b\x6e\x78\x2e\x6d\x65\x64\x69\x61\x5f\x74\x79\x70\x65\x73";const std::string
zea2d083c85::z13c23c3849=
"\x6b\x6e\x78\x2e\x69\x6e\x64\x69\x76\x69\x64\x75\x61\x6c\x5f\x61\x64\x64\x72\x65\x73\x73"
;const std::string zea2d083c85::zc3e6a1886e=
"\x6b\x6e\x78\x2e\x70\x6c\x5f\x64\x6f\x6d\x61\x69\x6e\x5f\x61\x64\x64\x72\x65\x73\x73"
;const std::string zea2d083c85::zee467d54fc=
"\x6b\x6e\x78\x2e\x72\x66\x5f\x64\x6f\x6d\x61\x69\x6e\x5f\x61\x64\x64\x72\x65\x73\x73"
;const std::string zea2d083c85::SerialNumber=
"\x6b\x6e\x78\x2e\x73\x65\x72\x69\x61\x6c\x5f\x6e\x75\x6d\x62\x65\x72";const std
::string zea2d083c85::zdc8dff356e=
"\x6b\x6e\x78\x2e\x6d\x61\x6e\x75\x66\x61\x63\x74\x75\x72\x65\x72\x5f\x69\x64";
const std::string zea2d083c85::z1be699fe9f=
"\x6b\x6e\x78\x2e\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x5f\x6d\x6f\x64\x65"
;const std::string zea2d083c85::z5b2ecda528=
"\x6b\x6e\x78\x2e\x6b\x6e\x78\x5f\x62\x75\x73\x5f\x73\x74\x61\x74\x65";const std
::string zea2d083c85::z83d2649f20=
"\x6b\x6e\x78\x2e\x6d\x61\x78\x5f\x61\x70\x64\x75\x5f\x6c\x65\x6e\x67\x74\x68";
const std::string zea2d083c85::za6f2fc65f0=
"\x6b\x6e\x78\x2e\x72\x6f\x75\x74\x65\x5f\x74\x72\x61\x6e\x73\x70\x6f\x72\x74\x5f\x70\x61\x63\x6b\x65\x74"
;zea2d083c85::zea2d083c85():z58740d8fff(),z8a3623983b(*this),z7eae6471dd(
(0x1a62+2935-0x25d9)){zdd2e046b74(*this);z674533ad46();}zea2d083c85::~
zea2d083c85(){try{z3101dee849();}catch(...){}}void zea2d083c85::routeRx(Packet::
Ptr packet){KnxPacket::Ptr zfd29354025=KnxPacket::convert(packet,false);bool
zd47ebe7a90=true;const unsigned int z7827eb5079=getProperty(z2a66eed75d,
(0x3a6+6069-0x1b5b));const bool z3990f18c27=ze127e0a511::z0266f230d6(z7827eb5079
);if(zfd29354025&&z3990f18c27&&z605bfe297a()){std::vector<unsigned char>
zf92894300e;try{zf92894300e=getProperty(zee467d54fc).extract<std::vector<
unsigned char> >();}catch(...){}zd47ebe7a90=z2429a4bade::zd47ebe7a90(zfd29354025
,zf92894300e);}if(zd47ebe7a90){z58740d8fff::routeRx(packet);if(zfd29354025){
routeEvent(z11d7f1cf7b::zefe6385ec5);}}if(z171490f0fd(packet)){poco_warning(
LOGGER(),
"\x52\x65\x63\x65\x69\x76\x65\x64\x20\x61\x20\x52\x65\x73\x65\x74\x2e\x69\x6e\x64"
);routeEvent(z11d7f1cf7b::z00c580762c);}}void zea2d083c85::zb44d474e62(unsigned
int timeout){setProperty(zb18866bb87,timeout);}unsigned int zea2d083c85::
z0eb4f337db()const{return getProperty(zb18866bb87);}void zea2d083c85::
zbac9796807(bool enable){setProperty(z39ec4d1ae7,enable);}bool zea2d083c85::
z680ad25263()const{return getProperty(z39ec4d1ae7);}void zea2d083c85::
z367d96a272(bool enable){enable?z674533ad46():z3101dee849();setProperty(
z0ad2fe7ad5,enable);}bool zea2d083c85::zddad992be2()const{return getProperty(
z0ad2fe7ad5);}void zea2d083c85::z76d6965e85(bool enable){setProperty(ze2fc87d94b
,enable);}bool zea2d083c85::z605bfe297a()const{return getProperty(ze2fc87d94b);}
unsigned int zea2d083c85::z791c5fd335(){if(isEmpty(z8b957c5a25)){setProperty(
z8b957c5a25,zc1ee43d1f6());}return getProperty(z8b957c5a25);}void zea2d083c85::
setProtocol(unsigned int zd2b01bb0a4){if(!zdf6fe1862a(zd2b01bb0a4)){const
UnsupportedProtocolException e(NumberFormatter::format(zd2b01bb0a4));raiseError(
e);}z8a3623983b.setProtocol(zd2b01bb0a4);z81289a39cd(zd2b01bb0a4);const unsigned
int z5f793390e9=z93d917156c();if(z5f793390e9!=zd2b01bb0a4){const
ProtocolWriteValidationException e(format(
"\x77\x72\x69\x74\x65\x20\x25\x75\x2c\x20\x72\x65\x61\x64\x20\x25\x75",
zd2b01bb0a4,z5f793390e9));raiseError(e);}setProperty(za498009d76,zd2b01bb0a4);}
unsigned int zea2d083c85::z01a2f5d4b7(){if(isEmpty(za498009d76)){const unsigned
int zd2b01bb0a4=z93d917156c();zc7087b3e64().setProtocol(zd2b01bb0a4);setProperty
(za498009d76,zd2b01bb0a4);}return getProperty(za498009d76);}bool zea2d083c85::
zdf6fe1862a(unsigned int zd2b01bb0a4){const unsigned int z45fb7ed6f5=z791c5fd335
();return zdf6fe1862a(z45fb7ed6f5,zd2b01bb0a4);}bool zea2d083c85::zdf6fe1862a(
unsigned int zef30e92c56,unsigned int zd2b01bb0a4){if(zd2b01bb0a4==za498009d76::
Unknown){return false;}return((zef30e92c56&zd2b01bb0a4)==zd2b01bb0a4)?true:false
;}unsigned int zea2d083c85::z089addfe48(unsigned int zef30e92c56)const{unsigned
int zd2b01bb0a4=za498009d76::Unknown;if(zdf6fe1862a(zef30e92c56,za498009d76::
z1746fd28fd)){zd2b01bb0a4=za498009d76::z1746fd28fd;}return zd2b01bb0a4;}void
zea2d083c85::zd897a67e14(){const unsigned int zef30e92c56=z791c5fd335();const
unsigned int zef47cdc64c=z089addfe48(zef30e92c56);if(zef47cdc64c==za498009d76::
Unknown){const NoPreferredProtocolFoundException e(format(
"\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x20\x70\x72\x6f\x74\x6f\x63\x6f\x6c\x73\x20\x25\x75"
,zef30e92c56));raiseError(e);}setProtocol(zef47cdc64c);}unsigned int zea2d083c85
::z524baf8256(){if(isEmpty(za6f43e69a4)){setProperty(za6f43e69a4,z07a1de2360());
}return getProperty(za6f43e69a4);}void zea2d083c85::z7de2a5ac1c(unsigned int
z1166f2fdb4){if(!z4011fc21c2(z1166f2fdb4)){const UnsupportedLayerException e(
NumberFormatter::format(z1166f2fdb4));raiseError(e);}const unsigned int
z799b0099b5=!isEmpty(z9884ee4d6b)?z42de9bb630():static_cast<unsigned int>(
zba36969226::Unknown);try{setProperty(z9884ee4d6b,z1166f2fdb4);zd8cf4148d6(
z1166f2fdb4);}catch(Exception&e){setProperty(z9884ee4d6b,z799b0099b5);raiseError
(e);}}unsigned int zea2d083c85::z42de9bb630(){unsigned int z1166f2fdb4=
zba36969226::Unknown;if(isEmpty(z9884ee4d6b)){if(z01a2f5d4b7()==za498009d76::
z1746fd28fd){z1166f2fdb4=z6fe0401c37();setProperty(z9884ee4d6b,z1166f2fdb4);}}
else{z1166f2fdb4=getProperty(z9884ee4d6b);}return z1166f2fdb4;}bool zea2d083c85
::z4011fc21c2(unsigned int z1166f2fdb4){unsigned int z7b2ce21a17=z524baf8256();
return z4011fc21c2(z7b2ce21a17,z1166f2fdb4);}bool zea2d083c85::z4011fc21c2(
unsigned int z7ecdefe519,unsigned int z1166f2fdb4){if(z1166f2fdb4==zba36969226::
Unknown){return false;}return((z7ecdefe519&z1166f2fdb4)==z1166f2fdb4)?true:false
;}unsigned int zea2d083c85::z340f3e6eca(unsigned int z7ecdefe519)const{unsigned
int z1166f2fdb4=zba36969226::Unknown;if(z4011fc21c2(z7ecdefe519,zba36969226::
Link)){z1166f2fdb4=zba36969226::Link;}else if(z4011fc21c2(z7ecdefe519,
zba36969226::z1340d1c626)){z1166f2fdb4=zba36969226::z1340d1c626;}else if(
z4011fc21c2(z7ecdefe519,zba36969226::Raw)){z1166f2fdb4=zba36969226::Raw;}return
z1166f2fdb4;}void zea2d083c85::za8d5adfa57(){const unsigned int z7ecdefe519=
z524baf8256();const unsigned int zef47cdc64c=z340f3e6eca(z7ecdefe519);if(
zef47cdc64c==zba36969226::Unknown){const NoPreferredLayerFoundException error(
format(
"\x73\x75\x70\x70\x6f\x72\x74\x65\x64\x20\x6c\x61\x79\x65\x72\x73\x20\x25\x75",
z7ecdefe519));raiseError(error);}z7de2a5ac1c(zef47cdc64c);}bool zea2d083c85::
z19cee9e459(){if(isEmpty(z74dda860c7)){setProperty(z74dda860c7,z021857951d());}
return getProperty(z74dda860c7);}void zea2d083c85::z371132a440(bool enable){if(!
z19cee9e459()){const AccessPortException error(
"\x63\x45\x4d\x49\x20\x4c\x6f\x63\x61\x6c\x20\x54\x72\x61\x6e\x73\x70\x6f\x72\x74\x20\x4c\x61\x79\x65\x72\x20\x69\x73\x20\x6e\x6f\x74\x20\x73\x75\x70\x70\x6f\x72\x74\x65\x64"
,zfa668fdf8b::z1bcf406118);raiseError(error);}zbe0f21419f(enable);}unsigned int
zea2d083c85::z12ff055552(){if(isEmpty(zb5ec3c9a78)){setProperty(zb5ec3c9a78,
z1f86c15fd0());}return getProperty(zb5ec3c9a78);}std::string zea2d083c85::
z3251ee4772(){return zb5ec3c9a78::getDescription(z12ff055552());}unsigned short
zea2d083c85::z1bf089d014(){if(isEmpty(z2a66eed75d)){if(z01a2f5d4b7()==
za498009d76::z1746fd28fd){try{setProperty(z2a66eed75d,z716d13ecdd());}catch(
Exception&exception){LOGGER().log(exception);poco_warning(LOGGER(),
"\x67\x65\x74\x4d\x65\x64\x69\x61\x54\x79\x70\x65\x73\x20\x66\x61\x69\x6c\x65\x64\x2c\x20\x67\x65\x74\x74\x69\x6e\x67\x20\x6d\x65\x64\x69\x61\x20\x74\x79\x70\x65\x73\x20\x66\x72\x6f\x6d\x20\x74\x68\x65\x20\x6d\x61\x73\x6b\x20\x76\x65\x72\x73\x69\x6f\x6e"
);setProperty(z2a66eed75d,z21e0db8628());}}else{setProperty(z2a66eed75d,
z21e0db8628());}}return getProperty(z2a66eed75d);}std::string zea2d083c85::
zc3136dcdfa(){return ze127e0a511::zed9c5ebd97(z1bf089d014());}void zea2d083c85::
zf52767dc71(unsigned int z83744e1e92){zd0d51f5d95(z83744e1e92);setProperty(
z13c23c3849,z83744e1e92);}unsigned int zea2d083c85::zbe00e8c303(){if(isEmpty(
z13c23c3849)){setProperty(z13c23c3849,zfbca701d15());}return getProperty(
z13c23c3849);}void zea2d083c85::z22c631a890(unsigned int zf92894300e){
za08556178a(zf92894300e);setProperty(zc3e6a1886e,zf92894300e);}unsigned int
zea2d083c85::zbb04277d6f(){if(isEmpty(zc3e6a1886e)){setProperty(zc3e6a1886e,
z7bc42300fa());}return getProperty(zc3e6a1886e);}void zea2d083c85::z3a2f8fbb8f(
const std::vector<unsigned char>&zf92894300e){z57588f181e(zf92894300e);
setProperty(zee467d54fc,zf92894300e);}const std::vector<unsigned char>&
zea2d083c85::zafeaeec64f(){if(isEmpty(zee467d54fc)){std::vector<unsigned char>v;
zee1690ad9d(v);setProperty(zee467d54fc,v);}return extract<std::vector<unsigned
char> >(zee467d54fc);}void zea2d083c85::z5f5fd61d58(const std::vector<unsigned
char>&zd311e7ca26){za8e4013ca3(zd311e7ca26);setProperty(SerialNumber,zd311e7ca26
);}const std::vector<unsigned char>&zea2d083c85::getSerialNumber(){if(isEmpty(
SerialNumber)){std::vector<unsigned char>v;zc153fe5430(v);setProperty(
SerialNumber,v);}return extract<std::vector<unsigned char> >(SerialNumber);}void
zea2d083c85::z68349079eb(unsigned int zb9dc9070a1){zf52cc38da1(zb9dc9070a1);
setProperty(zdc8dff356e,zb9dc9070a1);}unsigned int zea2d083c85::z19770e1430(){if
(isEmpty(zdc8dff356e)){setProperty(zdc8dff356e,z29f4d6d6a3());}return
getProperty(zdc8dff356e);}void zea2d083c85::z64a5d004ba(bool enable){zeb33dc19f4
(enable);setProperty(z1be699fe9f,enable);}bool zea2d083c85::z2a654b4732(){const
bool z2772cce074=zf21c0140ae();setProperty(z1be699fe9f,z2772cce074);return
z2772cce074;}unsigned int zea2d083c85::z175c5f0532()const{return getProperty(
z5b2ecda528);}unsigned int zea2d083c85::zaff92585a2(){if(isEmpty(z83d2649f20)){
try{setProperty(z83d2649f20,z50193a49a9());}catch(
DeviceManagementAlreadyOpenException&e){poco_warning_f1(LOGGER(),
"\x52\x65\x61\x64\x69\x6e\x67\x20\x6d\x61\x78\x20\x41\x50\x44\x55\x20\x6c\x65\x6e\x67\x74\x68\x20\x66\x61\x69\x6c\x65\x64\x20\x28\x25\x73\x29\x2c\x20\x75\x73\x65\x20\x73\x74\x61\x6e\x64\x61\x72\x64\x20\x76\x61\x6c\x75\x65\x20\x28\x31\x35\x29"
,e.displayText());return z81eda64581;}}return getProperty(z83d2649f20);}void
zea2d083c85::z4fb044e67b(bool enable){setProperty(za6f2fc65f0,enable);}bool
zea2d083c85::z0be6f75ca1()const{return getProperty(za6f2fc65f0);}void
zea2d083c85::openImpl(){zd897a67e14();za8d5adfa57();removeProperty(zee467d54fc);
unsigned int z7827eb5079=z1bf089d014();const bool z0266f230d6=ze127e0a511::
z0266f230d6(z7827eb5079);if(z0266f230d6){zafeaeec64f();getSerialNumber();}
zaff92585a2();z19cee9e459();}void zea2d083c85::resetPropertiesImpl(){z58740d8fff
::resetPropertiesImpl();zdd2e046b74(*this);}void zea2d083c85::
setPreferredSettingsImpl(){zd897a67e14();za8d5adfa57();}bool zea2d083c85::
z021857951d(){return z4011fc21c2(zba36969226::za9068249eb);}void zea2d083c85::
zbe0f21419f(bool enable){if(enable){z7eae6471dd=z42de9bb630();z7de2a5ac1c(
zba36969226::za9068249eb);}else{z7de2a5ac1c(z7eae6471dd);}}unsigned int
zea2d083c85::z1f86c15fd0(){const unsigned int z65fc26404c=z4b4d92d5e8();
setProperty(zb5ec3c9a78,z65fc26404c);return z65fc26404c;}unsigned short
zea2d083c85::z716d13ecdd(){const unsigned short z7827eb5079=zf4cd0c79bd();
setProperty(z2a66eed75d,z7827eb5079);return z7827eb5079;}unsigned short
zea2d083c85::z21e0db8628(){const unsigned short z7827eb5079=z442e211ba0();
setProperty(z2a66eed75d,z7827eb5079);return z7827eb5079;}void zea2d083c85::
zd0d51f5d95(unsigned int z83744e1e92){z8a3623983b.z5392ddee85(z83744e1e92);
setProperty(z13c23c3849,z83744e1e92);}unsigned int zea2d083c85::zfbca701d15(){
const unsigned int z83744e1e92=z8a3623983b.zf670e5347d();setProperty(z13c23c3849
,z83744e1e92);return z83744e1e92;}void zea2d083c85::za08556178a(unsigned int
zf92894300e){z8a3623983b.z6c59c3156d(zf92894300e);setProperty(zc3e6a1886e,
zf92894300e);}unsigned int zea2d083c85::z7bc42300fa(){const unsigned int
zf92894300e=z8a3623983b.zfa42f5b322();setProperty(zc3e6a1886e,zf92894300e);
return zf92894300e;}void zea2d083c85::z57588f181e(const Var&zf92894300e){const
std::vector<unsigned char>address=zf92894300e.extract<std::vector<unsigned char>
>();z8a3623983b.zb488b9244d(address);setProperty(zee467d54fc,zf92894300e);}void
zea2d083c85::zee1690ad9d(std::vector<unsigned char>&zf92894300e){z8a3623983b.
z875dcf85de(zf92894300e);setProperty(zee467d54fc,zf92894300e);}void zea2d083c85
::za8e4013ca3(const Poco::Dynamic::Var&zd311e7ca26){const std::vector<unsigned
char>ze205a3dad4=zd311e7ca26.extract<std::vector<unsigned char> >();z8a3623983b.
z2853a8fc86(ze205a3dad4);setProperty(SerialNumber,ze205a3dad4);}void zea2d083c85
::zc153fe5430(std::vector<unsigned char>&zd311e7ca26){z8a3623983b.z8039b7bd80(
zd311e7ca26);setProperty(SerialNumber,zd311e7ca26);}void zea2d083c85::
zf52cc38da1(unsigned int zb9dc9070a1){z8a3623983b.z563fc10557(zb9dc9070a1);
setProperty(zdc8dff356e,zb9dc9070a1);}unsigned int zea2d083c85::z29f4d6d6a3(){
const unsigned int zb9dc9070a1=z8a3623983b.z7e6620eb94();setProperty(zdc8dff356e
,zb9dc9070a1);return zb9dc9070a1;}void zea2d083c85::zeb33dc19f4(bool enable){
zc7087b3e64().ze5acd8e45b(enable);setProperty(z1be699fe9f,enable);}bool
zea2d083c85::zf21c0140ae(){const bool z2772cce074=zc7087b3e64().ze59351aa9c();
setProperty(z1be699fe9f,z2772cce074);return z2772cce074;}unsigned int
zea2d083c85::z50193a49a9(){unsigned int zae41a04420=z81eda64581;try{zae41a04420=
zc7087b3e64().z2afe3965f8();if(zae41a04420<z81eda64581){zae41a04420=z81eda64581;
poco_warning_f1(LOGGER(),
"\x49\x6e\x74\x65\x72\x66\x61\x63\x65\x20\x72\x65\x74\x75\x72\x6e\x20\x61\x6e\x20\x69\x6e\x76\x61\x6c\x69\x64\x20\x6d\x61\x78\x20\x41\x50\x44\x55\x20\x6c\x65\x6e\x67\x74\x68\x20\x28\x25\x75\x29\x2c\x20\x75\x73\x65\x20\x73\x74\x61\x6e\x64\x61\x72\x64\x20\x76\x61\x6c\x75\x65"
,zae41a04420);}}catch(DeviceManagementAlreadyOpenException&){throw;}catch(
Exception&){poco_warning(LOGGER(),
"\x52\x65\x61\x64\x69\x6e\x67\x20\x6d\x61\x78\x20\x41\x50\x44\x55\x20\x6c\x65\x6e\x67\x74\x68\x20\x66\x61\x69\x6c\x65\x64\x2c\x20\x75\x73\x65\x20\x73\x74\x61\x6e\x64\x61\x72\x64\x20\x76\x61\x6c\x75\x65\x20\x28\x31\x35\x29"
);}return zae41a04420;}z11671f1e0a&zea2d083c85::zc7087b3e64(){return z8a3623983b
;}const z11671f1e0a&zea2d083c85::zc7087b3e64()const{return z8a3623983b;}
KnxPacket::Ptr zea2d083c85::zdc8ced637e(const KnxPacket::Ptr packet){return
packet;}KnxPacket::Ptr zea2d083c85::z4f92549f31(const KnxPacket::Ptr packet){
return packet;}void zea2d083c85::za117cd55de(ScopedQueueConnectorRxQueue&queue,
KnxPacket::Ptr packet){const unsigned int z00601023bd=z0eb4f337db();if(
z00601023bd&&z6a86f9a0fc(packet)){try{zaa4f795dda::z6eae11ab53(queue,z00601023bd
);routeEvent(z11d7f1cf7b::z294e2e57c8);}catch(Poco::TimeoutException&e){
routeEvent(z11d7f1cf7b::zc10d61ac8e);poco_warning_f1(LOGGER(),
"\x77\x61\x69\x74\x43\x6f\x6e\x66\x69\x72\x6d\x3a\x20\x25\x73",e.displayText());
if(!z680ad25263()){const LDataConfirmTimeoutException e("");raiseError(e);}}}}
void zea2d083c85::zd82f9ac44a(z4e34b5d0f7::State z7619915478){ScopedLock<
FastMutex>lock(zf31a9d5745);const int z57c0ade8ca=getProperty(z5b2ecda528);if(
z57c0ade8ca!=z7619915478){setProperty(z5b2ecda528,static_cast<unsigned int>(
z7619915478));if(z7619915478!=z4e34b5d0f7::Unknown){routeEvent(z7619915478==
z4e34b5d0f7::Connected?z11d7f1cf7b::za7b5aa463a:z11d7f1cf7b::z740394bba8);}}}
void zea2d083c85::zae0bb42f7a(TransportPacket::Ptr zfa61376f49){if(getProperty(
za6f2fc65f0)==true){routeRx(zfa61376f49);}}void zea2d083c85::z174ce8ab4d(
TransportPacket::Ptr zfa61376f49){if(getProperty(za6f2fc65f0)==true){routeTx(
zfa61376f49);}}void zea2d083c85::zd8cf4148d6(unsigned int z1166f2fdb4){
z8a3623983b.z766e2388b4(z1166f2fdb4);}unsigned int zea2d083c85::z6fe0401c37(){
return z8a3623983b.z6f5601a8cf();}unsigned int zea2d083c85::zf4cd0c79bd(){return
z8a3623983b.z5da113978e();}unsigned int zea2d083c85::z4b4d92d5e8(){return
z8a3623983b.z51177f5ce9();}unsigned short zea2d083c85::z442e211ba0(){const
unsigned int ze723c17414=zb5ec3c9a78::za2a7a09218(z12ff055552());unsigned short
z7827eb5079=(0xef4+5364-0x23e8);switch(ze723c17414){case zb5ec3c9a78::
z1f5ef68b4f:z7827eb5079=ze127e0a511::Medium::z1f5ef68b4f;break;case zb5ec3c9a78
::z6cb5bb14f9:z7827eb5079=ze127e0a511::Medium::z6cb5bb14f9;break;case
zb5ec3c9a78::z575b70b0f4:z7827eb5079=ze127e0a511::Medium::z575b70b0f4;break;case
zb5ec3c9a78::IP:z7827eb5079=ze127e0a511::Medium::IP;break;}return z7827eb5079;}
void zea2d083c85::z674533ad46(){EventSignal&signal=getEventSignal();
signalConnectionEvent_=signal.connect(std::bind(&zea2d083c85::onEvent,this,std::
placeholders::_1));}void zea2d083c85::z3101dee849(){signalConnectionEvent_.
disconnect();}void zea2d083c85::onEvent(unsigned long e){if((e==z11d7f1cf7b::
z00c580762c)&&zddad992be2()){poco_information(LOGGER(),
"\x54\x72\x79\x20\x74\x6f\x20\x72\x65\x69\x6e\x69\x74\x69\x61\x6c\x69\x7a\x65\x20\x6c\x61\x79\x65\x72\x20\x61\x66\x74\x65\x72\x20\x72\x65\x73\x65\x74"
);try{z7de2a5ac1c(z42de9bb630());}catch(Exception&e){poco_warning_f1(LOGGER(),
"\x52\x65\x69\x6e\x69\x74\x69\x61\x6c\x69\x7a\x65\x20\x66\x61\x69\x6c\x65\x64\x3a\x20\x25\x73"
,e.displayText());}}}
| 73.072368 | 274 | 0.802692 | [
"vector"
] |
ea0b9ed48a02b531a878da8761bfe262281b2532 | 1,180 | cpp | C++ | LeetCode/ThousandOne/0030-substr_with_concat_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0030-substr_with_concat_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0030-substr_with_concat_words.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 30. 串联所有单词的子串
给定一个字符串 s 和一些长度相同的单词 words。
找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例 1:
输入:
s = "barfoothefoobarman",
words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
输出:[]
*/
vector<int> findSubstring(string const& str, vector<string> const& words)
{
vector<int> ans;
if (str.empty() || words.empty()) return ans;
int s, slen = static_cast<int>(str.length());
int w, ws = static_cast<int>(words.size());
int wlen = static_cast<int>(words[0].length());
unordered_map<string, int> counts; // 每个单词的期望出现次数
unordered_map<string, int> seen; // 实际看到的每个单词的次数
for (string const& wd : words)
counts[wd]++;
slen -= (wlen * ws);
for (s = 0; s <= slen; s++)
{
seen.clear();
for (w = 0; w < ws; w++)
{
string wd = str.substr(s + w * wlen, wlen);
if (counts.find(wd) != counts.end())
{
seen[wd]++;
if (seen[wd] > counts[wd])
break;
}
else
break;
}
if (w == ws)
ans.push_back(s);
}
return ans;
}
int main()
{}
| 18.4375 | 73 | 0.613559 | [
"vector"
] |
ea18427928ed08c2be03a55f35f44f1e25986145 | 320 | cpp | C++ | 799-champagne-tower/799-champagne-tower.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 799-champagne-tower/799-champagne-tower.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 799-champagne-tower/799-champagne-tower.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | class Solution {
public:
double champagneTower(int poured, int query_row, int query_glass) {
vector<double> dp(101, 0); dp[0] = poured;
for(int row=1; row<=query_row; row++)
for(int i=row; i>=0; i--)
dp[i+1] += dp[i] = max(0.0, (dp[i]-1)/2);
return min(dp[query_glass], 1.0);
}
}; | 32 | 71 | 0.5625 | [
"vector"
] |
ea18aa42c4c2aa7a305e092080b521e9c140da99 | 3,132 | cpp | C++ | willow/src/aliasesmap.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/src/aliasesmap.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/src/aliasesmap.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2021 Graphcore Ltd. All rights reserved.
#include <popart/aliasesmap.hpp>
#include <poprithms/logging/timepartitionlogger.hpp>
namespace popart {
AliasesMap::AliasesMap() : ir{nullptr}, aliasesMap{} {}
AliasesMap::AliasesMap(const Ir *ir_) : ir{ir_}, aliasesMap{} { update(); }
AliasesMap::AliasesMap(const Graph &graph) : ir{&graph.getIr()}, aliasesMap{} {
update(graph);
}
void AliasesMap::setIr(const Ir *ir_) { ir = ir_; }
Aliases &AliasesMap::getAliases(const GraphId &graphId) {
return aliasesMap.at(graphId);
}
Aliases &AliasesMap::getAliases(Graph &graph) {
return aliasesMap.at(graph.id);
}
const Aliases &AliasesMap::getAliases(const GraphId &graphId) const {
return aliasesMap.at(graphId);
}
const Aliases &AliasesMap::getAliases(Graph &graph) const {
return aliasesMap.at(graph.id);
}
void AliasesMap::clear() { aliasesMap.clear(); }
void AliasesMap::update() {
if (!ir) {
throw internal_error("[AliasesMap] Ir not set.");
}
aliasesMap.clear();
for (auto &graph : ir->getGraphs()) {
update(*graph.second.get());
}
}
void AliasesMap::update(const GraphId &graphId) {
if (!ir) {
throw internal_error("[AliasesMap] Ir not set.");
}
Graph &graph = ir->getGraph(graphId);
update(graph);
}
void AliasesMap::update(const Graph &graph) {
auto &aliases = aliasesMap[graph.id];
aliases.clearAliases();
for (auto &op : graph.getOps()) {
update(op.second.get());
}
}
void AliasesMap::update(Op *op) {
if (!ir) {
throw internal_error("[AliasesMap] Ir not set.");
}
logging::trace("[updateAliases] Updating alias for Op {}", op->debugName());
auto scopedStopwatch =
ir->timePartitionLogger().scopedStopwatch("Tensors::updateAliases");
auto &aliases = aliasesMap[op->getGraph().id];
// for all of the inputs of op, t1 and all output, t2:
for (auto i1_t1 : op->input->tensorMap()) {
for (auto o1_t2 : op->output->tensorMap()) {
InIndex i1 = i1_t1.first;
Tensor *t1 = i1_t1.second;
InIndex o1 = o1_t2.first;
Tensor *t2 = o1_t2.second;
logging::trace("[updateAliases] In: {}-{} {}, Out: {}-{} {}",
i1,
t1->id,
t1->info.shape(),
o1,
t2->id,
t2->info.shape());
view::Regions inRegions = op->aliases(i1, o1);
if (std::all_of(inRegions.begin(), inRegions.end(), [](view::Region &r) {
return r.isEmpty();
})) {
continue;
}
auto fwdMap = op->fwdRegMap(i1, o1);
auto bwdMap = op->bwdRegMap(i1, o1);
aliases.updateAliases(t1,
t2,
inRegions,
fwdMap,
bwdMap,
"Fwd Link of " + op->debugName() + " " +
std::to_string(i1) + "->" + std::to_string(o1),
"Bwd Link of " + op->debugName() + " " +
std::to_string(i1) + "->" + std::to_string(o1));
}
}
}
} // namespace popart
| 27.234783 | 80 | 0.564176 | [
"shape"
] |
ea191fe84d1a87de06275152c25b69887d32d4cc | 12,506 | cpp | C++ | Source/rubikCube.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | Source/rubikCube.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | Source/rubikCube.cpp | rajatarora21/ComputerGraphics | 314288d3c7ed4cf1593327bd1ec03b2c5c6306da | [
"MIT"
] | null | null | null | #include "rubikCube.h"
using namespace glm;
using namespace std;
std::vector<RubikCube::Cube*> RubikCube::findCubesOfLayer(function<bool(glm::vec3)> pred)
{
std::vector<RubikCube::Cube*> layerOfCubes;
for (auto c:cubes)
{
mat4 m = c->rotation* c->translation;
vec3 center = m*vec4(0, 0, 0, 1);
if (pred(center))
{
layerOfCubes.push_back(c);
}
}
return layerOfCubes;
}
GLuint RubikCube::createCubeVAO()
{
// Cube model
glm::vec3 vertexArray[] = {
// position, texCoord normal
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(-1,0,0), //left
glm::vec3(-0.5f,-0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(-1,0,0),
glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(-1,0,0),
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(-1,0,0),
glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(-1,0,0),
glm::vec3(-0.5f, 0.5f,-0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(-1,0,0),
glm::vec3(0.5f, 0.5f,-0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,0,-1), // far
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,0,-1),
glm::vec3(-0.5f, 0.5f,-0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(0,0,-1),
glm::vec3(0.5f, 0.5f,-0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,0,-1),
glm::vec3(0.5f,-0.5f,-0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,0,-1),
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,0,-1),
glm::vec3(0.5f,-0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,-1,0), // bottom
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,-1,0),
glm::vec3(0.5f,-0.5f,-0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,-1,0),
glm::vec3(0.5f,-0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,-1,0),
glm::vec3(-0.5f,-0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(0,-1,0),
glm::vec3(-0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,-1,0),
glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(0,0,1), // near
glm::vec3(-0.5f,-0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,0,1),
glm::vec3(0.5f,-0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,0,1),
glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,0,1),
glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(0,0,1),
glm::vec3(0.5f,-0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,0,1),
glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(1,0,0), // right
glm::vec3(0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(1,0,0),
glm::vec3(0.5f, 0.5f,-0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(1,0,0),
glm::vec3(0.5f,-0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(1,0,0),
glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(1,0,0),
glm::vec3(0.5f,-0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(1,0,0),
glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,1,0), // top
glm::vec3(0.5f, 0.5f,-0.5f), glm::vec3(1.0f, 0.0f, 0.0f),glm::vec3(0,1,0),
glm::vec3(-0.5f, 0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,1,0),
glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 1.0f, 0.0f),glm::vec3(0,1,0),
glm::vec3(-0.5f, 0.5f,-0.5f), glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(0,1,0),
glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f),glm::vec3(0,1,0),
};
// Create a vertex array
GLuint vertexArrayObject;
glGenVertexArrays(1, &vertexArrayObject);
glBindVertexArray(vertexArrayObject);
// Upload Vertex Buffer to the GPU, keep a reference to it (vertexBufferObject)
GLuint vertexBufferObject;
glGenBuffers(1, &vertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexArray), vertexArray, GL_STATIC_DRAW);
glVertexAttribPointer(0, // attribute 0 matches aPos in Vertex Shader
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
3 * sizeof(vec3), // stride - each vertex contain 2 vec3 (position, color)
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, // attribute 1 matches aColor in Vertex Shader
3,
GL_FLOAT,
GL_FALSE,
3 * sizeof(vec3),
(void*)sizeof(vec3) // color is offseted a vec3 (comes after position)
);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, // attribute 1 matches aColor in Vertex Shader
3,
GL_FLOAT,
GL_FALSE,
3 * sizeof(vec3),
(void*)(sizeof(vec3) * 2) // color is offseted a vec3 (comes after position)
);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
glBindVertexArray(0);
return vertexArrayObject;
}
GLuint RubikCube::createFaceVAO(FaceDir faceDir, int tileX, int tileY)
{
float faceRatio = 0.9;
float sp = 0.51;
vec4 normal = vec4(0, 1, 0,0);
vec4 pos[] = {
vec4(-0.5*faceRatio,sp,-0.5*faceRatio,1),
vec4(0.5*faceRatio,sp,-0.5*faceRatio,1),
vec4(0.5*faceRatio,sp,0.5*faceRatio,1),
vec4(-0.5*faceRatio,sp,0.5*faceRatio,1),
};
float ts = 1 / 3.0;
vec3 uv[] = {
vec3(-0.5,-0.5,1),
vec3(0.5,-0.5,1),
vec3(0.5,0.5,1),
vec3(-0.5,0.5,1),
};
mat4 posNormM=mat4(1);
switch (faceDir)
{
case RubikCube::X:
posNormM = mat4(0,-1,0,0,1,0,0,0,0,0,1,0,0,0,0,1);
break;
case RubikCube::_X:
posNormM = mat4(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
break;
case RubikCube::Y:
break;
case RubikCube::_Y:
posNormM = mat4(-1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
break;
case RubikCube::Z:
posNormM = mat4(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1);
break;
case RubikCube::_Z:
posNormM = mat4(1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
break;
default:
break;
}
mat3 uvM=mat3(ts*faceRatio,0,0,0, ts*faceRatio,0,(tileX+0.5)*ts,(tileY+0.5)*ts,1);
// Cube model
glm::vec3 vertexArray[] = {
// position, texCoord normal
glm::vec3(posNormM*pos[0]), uvM*uv[0],glm::vec3(posNormM*normal), //left
glm::vec3(posNormM*pos[2]), uvM*uv[2],glm::vec3(posNormM*normal), //left
glm::vec3(posNormM*pos[1]), uvM*uv[1],glm::vec3(posNormM*normal), //left
glm::vec3(posNormM*pos[0]), uvM*uv[0],glm::vec3(posNormM*normal), //left
glm::vec3(posNormM*pos[3]), uvM*uv[3],glm::vec3(posNormM*normal), //left
glm::vec3(posNormM*pos[2]), uvM*uv[2],glm::vec3(posNormM*normal), //left
};
// Create a vertex array
GLuint vertexArrayObject;
glGenVertexArrays(1, &vertexArrayObject);
glBindVertexArray(vertexArrayObject);
// Upload Vertex Buffer to the GPU, keep a reference to it (vertexBufferObject)
GLuint vertexBufferObject;
glGenBuffers(1, &vertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexArray), vertexArray, GL_STATIC_DRAW);
glVertexAttribPointer(0, // attribute 0 matches aPos in Vertex Shader
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
3 * sizeof(vec3), // stride - each vertex contain 2 vec3 (position, color)
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, // attribute 1 matches aColor in Vertex Shader
3,
GL_FLOAT,
GL_FALSE,
3 * sizeof(vec3),
(void*)sizeof(vec3) // color is offseted a vec3 (comes after position)
);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, // attribute 1 matches aColor in Vertex Shader
3,
GL_FLOAT,
GL_FALSE,
3 * sizeof(vec3),
(void*)(sizeof(vec3) * 2) // color is offseted a vec3 (comes after position)
);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
glBindVertexArray(0);
return vertexArrayObject;
}
void RubikCube::update(float dt)
{
if (currentMove.valid)
{
currentMove.moveTime += dt;
if (currentMove.moveTime>moveTime)
{
currentMove.moveTime = moveTime;
currentMove.valid = false;
}
for (auto c: currentMove.moveCubes)
{
c->rotation = rotate(mat4(1), currentMove.moveTime/ moveTime*pi<float>()*0.5f,currentMove.rotateAxis) * c->originalRotation;
}
}
}
void RubikCube::makeMove(Move move, bool cw)
{
if (currentMove.valid)
{
return;
}
float dir = cw ? 1 : -1;
switch (move)
{
case RubikCube::_None:
return;
break;
case RubikCube::L:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.x - (-1)) < 0.5; });
currentMove.rotateAxis = vec3(1 * dir, 0, 0);
break;
case RubikCube::R:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.x - (1)) < 0.5; });
currentMove.rotateAxis = vec3(-1 * dir, 0, 0);
break;
case RubikCube::U:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.y - (1)) < 0.5; });
currentMove.rotateAxis = vec3(0, -1 * dir, 0);
break;
case RubikCube::D:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.y - (-1)) < 0.5; });
currentMove.rotateAxis = vec3(0, 1 * dir, 0);
break;
case RubikCube::F:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.z - (1)) < 0.5; });
currentMove.rotateAxis = vec3(0, 0, -1 * dir);
break;
case RubikCube::B:
currentMove.moveCubes = findCubesOfLayer([](vec3 p)->bool {return abs(p.z - (-1)) < 0.5; });
currentMove.rotateAxis = vec3(0, 0, 1 * dir);
break;
default:
break;
}
for (auto c:currentMove.moveCubes)
{
c->originalRotation = c->rotation;
}
currentMove.moveTime = 0;
currentMove.valid = true;
}
void RubikCube::reset()
{
currentMove.valid = false;
for (auto c : cubes)
{
c->rotation = c->originalRotation = mat4(1);
}
}
void RubikCube::initialize()
{
model = mat4(1);
auto cubeVAO = createCubeVAO();
for (int y = 0; y < 3; y++)
{
for (int z = 0; z < 3; z++)
{
for (int x = 0; x < 3; x++)
{
auto cube= new Cube();
cube->vao = cubeVAO;
cube->translation = translate(mat4(1), vec3(x - 1, y - 1, z - 1));
cube->rotation = mat4(1);
if (x == 0)
{
Face face;
face.faceDir = _X;
face.vao = createFaceVAO(face.faceDir, y, z);
cube->faces.push_back(face);
}
if (x == 2)
{
Face face;
face.faceDir = X;
face.vao = createFaceVAO(face.faceDir, 2-y, z);
cube->faces.push_back(face);
}
if (y == 0)
{
Face face;
face.faceDir = _Y;
face.vao = createFaceVAO(face.faceDir, 2-x, z);
cube->faces.push_back(face);
}
if (y == 2)
{
Face face;
face.faceDir = Y;
face.vao = createFaceVAO(face.faceDir, x, z);
cube->faces.push_back(face);
}
if (z == 0)
{
Face face;
face.faceDir = _Z;
face.vao = createFaceVAO(face.faceDir, x, y);
cube->faces.push_back(face);
}
if (z == 2)
{
Face face;
face.faceDir = Z;
face.vao = createFaceVAO(face.faceDir, x, 2-y);
cube->faces.push_back(face);
}
cubes.push_back(cube);
}
}
}
}
void RubikCube::render(GLuint shader, glm::mat4 worldMatrix)
{
int texLoc = glGetUniformLocation(shader, "tex");
int MLoc = glGetUniformLocation(shader, "worldMatrix");
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,cubeTexture);
glUniform1i(texLoc, 0);
for (auto c:cubes)
{
auto &cube = *c;
mat4 m = worldMatrix *model*cube.rotation*cube.translation;
glUniformMatrix4fv(MLoc, 1, GL_FALSE, &m[0][0]);
glBindVertexArray(cube.vao);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
}
for (auto c : cubes)
{
auto &cube = *c;
mat4 m = worldMatrix *model*cube.rotation*cube.translation;
for (auto &face:cube.faces)
{
glBindTexture(GL_TEXTURE_2D, faceTextures[face.faceDir]);
glUniformMatrix4fv(MLoc, 1, GL_FALSE, &m[0][0]);
glBindVertexArray(face.vao);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
}
}
}
void RubikCube::setFaceTexture(std::vector<GLuint> faceTex)
{
faceTextures = faceTex;
}
void RubikCube::setCubeTexture(GLuint cubeTex)
{
cubeTexture = cubeTex;
}
| 30.502439 | 128 | 0.592036 | [
"render",
"vector",
"model"
] |
ea1a730c0c7464c30df2a10f677453a98dba4e72 | 9,136 | hpp | C++ | Sources/Fonts/Text.hpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | Sources/Fonts/Text.hpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | Sources/Fonts/Text.hpp | liuping1997/Acid | 0b28d63d03ead41047d5881f08e3b693a4e6e63f | [
"MIT"
] | null | null | null | #pragma once
#include "Maths/Colour.hpp"
#include "Maths/Vector2.hpp"
#include "Maths/Visual/Driver.hpp"
#include "Models/Model.hpp"
#include "Models/VertexDefault.hpp"
#include "Graphics/Descriptors/DescriptorsHandler.hpp"
#include "Graphics/Buffers/UniformHandler.hpp"
#include "Graphics/Pipelines/PipelineGraphics.hpp"
#include "Uis/UiObject.hpp"
#include "FontType.hpp"
namespace acid
{
/**
* @brief Class that represents a text in a GUI.
*/
class ACID_EXPORT Text :
public UiObject
{
public:
/**
* @brief A enum that represents how the text will be justified.
*/
enum class Justify
{
Left, Centre, Right, Fully
};
/**
* Creates a new text object.
* @param parent The parent screen object.
* @param rectangle The rectangle that will represent the bounds of the ui object.
* @param fontSize The font size to be used in this text.
* @param text The string text the object will be created with.
* @param fontType The font type to be used in this text.
* @param justify How the text will justify.
* @param maxWidth The maximum length of a line of this text.
* @param textColour The colour of this text.
* @param kerning The kerning (type character spacing multiplier) of this text.
* @param leading The leading (vertical line spacing multiplier) of this text.
*/
Text(UiObject *parent, const UiBound &rectangle, const float &fontSize, std::string text, std::shared_ptr<FontType> fontType = FontType::Create("Fonts/ProximaNova", "Regular"),
const Justify &justify = Justify::Left, const float &maxWidth = 1.0f, const Colour &textColour = Colour::Black, const float &kerning = 0.0f, const float &leading = 0.0f);
void UpdateObject() override;
bool CmdRender(const CommandBuffer &commandBuffer, const PipelineGraphics &pipeline, UniformHandler &uniformScene);
/**
* Gets the text model, which contains all the vertex data for the quads on which the text will be rendered.
* @return The model of the text.
*/
const Model *GetModel() const { return m_model.get(); }
/**
* Gets the number of lines in this text.
* @return The number of lines.
*/
const uint32_t &GetNumberLines() const { return m_numberLines; }
/**
* Gets the string of text represented.
* @return The string of text.
*/
const std::string &GetString() const { return m_string; }
/**
* Changed the current string in this text.
* @param string The new text,
*/
void SetString(const std::string &string);
/**
* Gets how the text should justify.
* @return How the text should justify.
*/
const Justify &GetJustify() const { return m_justify; }
/**
* Gets the maximum length of a line of this text.
* @return The maximum length of a line.
*/
const float &GetMaxWidth() const { return m_maxWidth; }
/**
* Sets the maximum length of a line of this text.
* @param maxWidth The new maximum length.
*/
void SetMaxWidth(const float &maxWidth) { m_maxWidth = maxWidth; }
/**
* Gets the kerning (type character spacing multiplier) of this text.
* @return The type kerning.
*/
const float &GetKerning() const { return m_kerning; }
/**
* Sets the kerning (type character spacing multiplier) of this text.
* @param kerning The new kerning.
*/
void SetKerning(const float &kerning) { m_kerning = kerning; }
/**
* Gets the leading (vertical line spacing multiplier) of this text.
* @return The line leading.
*/
const float &GetLeading() const { return m_leading; }
/**
* Sets the leading (vertical line spacing multiplier) of this text.
* @param leading The new leading.
*/
void SetLeading(const float &leading) { m_leading = leading; }
/**
* Gets the font used by this text.
* @return The font used by this text.
*/
const std::shared_ptr<FontType> &GetFontType() const { return m_fontType; }
/**
* Gets the colour of the text.
* @return The colour of the text.
*/
const Colour &GetTextColour() const { return m_textColour; }
/**
* Sets the colour of the text.
* @param textColour The new colour of the text.
*/
void SetTextColour(const Colour &textColour) { m_textColour = textColour; }
/**
* Gets the border colour of the text. This is used with border and glow drivers.
* @return The border colour of the text.
*/
const Colour &GetBorderColour() const { return m_borderColour; }
/**
* Sets the border colour of the text. This is used with border and glow drivers.
* @param borderColour The new border colour of the text.
*/
void SetBorderColour(const Colour &borderColour) { m_borderColour = borderColour; }
Driver<float> *GetGlowDriver() const { return m_glowDriver.get(); }
/**
* Sets the glow driver, will disable solid borders.
* @param glowDriver The new glow driver.
*/
void SetGlowDriver(Driver<float> *glowDriver);
Driver<float> *GetBorderDriver() const { return m_borderDriver.get(); }
/**
* Sets the border driver, will disable glowing.
* @param borderDriver The new border driver.
*/
void SetBorderDriver(Driver<float> *borderDriver);
/**
* Disables both solid borders and glow borders.
*/
void RemoveBorder();
/**
* Gets the calculated border size.
* @return The border size.
*/
float GetTotalBorderSize() const;
/**
* Gets the size of the glow.
* @return The glow size.
*/
float GetGlowSize() const;
/**
* Gets the distance field edge before antialias.
* @return The distance field edge.
*/
float CalculateEdgeStart() const;
/**
* Gets the distance field antialias distance.
* @return The distance field antialias distance.
*/
float CalculateAntialiasSize() const;
/**
* Gets if the text has been loaded to a model.
* @return If the text has been loaded to a model.
*/
bool IsLoaded() const;
private:
friend class FontType;
/**
* During the loading of a text this represents one word in the text.
*/
class Word
{
public:
/**
* Creates a new text word.
*/
Word() :
m_width(0.0f)
{
}
/**
* Adds a character to the end of the current word and increases the screen-space width of the word.
* @param character The character to be added.
* @param kerning The character kerning.
*/
void AddCharacter(const FontMetafile::Character &character, const float &kerning)
{
m_characters.emplace_back(character);
m_width += kerning + character.m_advanceX;
}
std::vector<FontMetafile::Character> m_characters;
float m_width;
};
/**
* Represents a line of text during the loading of a text.
*/
class Line
{
public:
/**
* Creates a new text line.
* @param spaceWidth The screen-space width of a space character.
* @param maxLength The screen-space maximum length of a line.
*/
Line(const float &spaceWidth, const float &maxLength) :
m_maxLength(maxLength),
m_spaceSize(spaceWidth),
m_currentWordsLength(0.0f),
m_currentLineLength(0.0f)
{
}
/**
* Attempt to add a word to the line. If the line can fit the word in without reaching the maximum line length then the word is added and the line length increased.
* @param word The word to try to add.
* @return {@code true} if the word has successfully been added to the line.
*/
bool AddWord(const Word &word)
{
float additionalLength = word.m_width;
additionalLength += !m_words.empty() ? m_spaceSize : 0.0f;
if (m_currentLineLength + additionalLength <= m_maxLength)
{
m_words.emplace_back(word);
m_currentWordsLength += word.m_width;
m_currentLineLength += additionalLength;
return true;
}
return false;
}
float m_maxLength;
float m_spaceSize;
std::vector<Word> m_words;
float m_currentWordsLength;
float m_currentLineLength;
};
/**
* Takes in an unloaded text and calculate all of the vertices for the quads on which this text will be rendered.
* The vertex positions and texture coords and calculated based on the information from the font file.
* Then takes the information about the vertices of all the quads and stores it in a model.
*/
void LoadText();
std::vector<Line> CreateStructure() const;
void CompleteStructure(std::vector<Line> &lines, Line ¤tLine, const Word ¤tWord) const;
std::vector<VertexDefault> CreateQuad(const std::vector<Line> &lines);
static void AddVerticesForCharacter(const float &cursorX, const float &cursorY, const FontMetafile::Character &character, std::vector<VertexDefault> &vertices);
static void AddVertex(const float &vx, const float &vy, const float &tx, const float &ty, std::vector<VertexDefault> &vertices);
void NormalizeQuad(Vector2f &bounding, std::vector<VertexDefault> &vertices) const;
DescriptorsHandler m_descriptorSet;
UniformHandler m_uniformObject;
std::unique_ptr<Model> m_model;
uint32_t m_numberLines;
std::string m_string;
std::optional<std::string> m_newString;
Justify m_justify;
std::shared_ptr<FontType> m_fontType;
float m_maxWidth;
float m_kerning;
float m_leading;
Colour m_textColour;
Colour m_borderColour;
bool m_solidBorder;
bool m_glowBorder;
std::unique_ptr<Driver<float>> m_glowDriver;
float m_glowSize;
std::unique_ptr<Driver<float>> m_borderDriver;
float m_borderSize;
};
}
| 28.197531 | 177 | 0.709829 | [
"object",
"vector",
"model",
"solid"
] |
ea315a10b595438a779c0043680113c0b5152603 | 9,914 | cc | C++ | src/application/AppCli_m.cc | badriciobq/rogue-drone | d982bd4cdad6d90b22465b4fbae258061aa59295 | [
"MIT"
] | null | null | null | src/application/AppCli_m.cc | badriciobq/rogue-drone | d982bd4cdad6d90b22465b4fbae258061aa59295 | [
"MIT"
] | null | null | null | src/application/AppCli_m.cc | badriciobq/rogue-drone | d982bd4cdad6d90b22465b4fbae258061aa59295 | [
"MIT"
] | null | null | null | //
// Generated file, do not edit! Created by nedtool 4.6 from application/AppCli.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#include <iostream>
#include <sstream>
#include "AppCli_m.h"
USING_NAMESPACE
// Another default rule (prevents compiler from choosing base class' doPacking())
template<typename T>
void doPacking(cCommBuffer *, T& t) {
throw cRuntimeError("Parsim error: no doPacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t)));
}
template<typename T>
void doUnpacking(cCommBuffer *, T& t) {
throw cRuntimeError("Parsim error: no doUnpacking() function for type %s or its base class (check .msg and _m.cc/h files!)",opp_typename(typeid(t)));
}
// Template rule for outputting std::vector<T> types
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
Register_Class(EtherAppPct);
EtherAppPct::EtherAppPct(const char *name, int kind) : ::cPacket(name,kind)
{
this->key_var = 0;
this->nodeId_var = 0;
this->macAddress_var = 0;
}
EtherAppPct::EtherAppPct(const EtherAppPct& other) : ::cPacket(other)
{
copy(other);
}
EtherAppPct::~EtherAppPct()
{
}
EtherAppPct& EtherAppPct::operator=(const EtherAppPct& other)
{
if (this==&other) return *this;
::cPacket::operator=(other);
copy(other);
return *this;
}
void EtherAppPct::copy(const EtherAppPct& other)
{
this->key_var = other.key_var;
this->nodeId_var = other.nodeId_var;
this->macAddress_var = other.macAddress_var;
}
void EtherAppPct::parsimPack(cCommBuffer *b)
{
::cPacket::parsimPack(b);
doPacking(b,this->key_var);
doPacking(b,this->nodeId_var);
doPacking(b,this->macAddress_var);
}
void EtherAppPct::parsimUnpack(cCommBuffer *b)
{
::cPacket::parsimUnpack(b);
doUnpacking(b,this->key_var);
doUnpacking(b,this->nodeId_var);
doUnpacking(b,this->macAddress_var);
}
const char * EtherAppPct::getKey() const
{
return key_var.c_str();
}
void EtherAppPct::setKey(const char * key)
{
this->key_var = key;
}
int EtherAppPct::getNodeId() const
{
return nodeId_var;
}
void EtherAppPct::setNodeId(int nodeId)
{
this->nodeId_var = nodeId;
}
const char * EtherAppPct::getMacAddress() const
{
return macAddress_var.c_str();
}
void EtherAppPct::setMacAddress(const char * macAddress)
{
this->macAddress_var = macAddress;
}
class EtherAppPctDescriptor : public cClassDescriptor
{
public:
EtherAppPctDescriptor();
virtual ~EtherAppPctDescriptor();
virtual bool doesSupport(cObject *obj) const;
virtual const char *getProperty(const char *propertyname) const;
virtual int getFieldCount(void *object) const;
virtual const char *getFieldName(void *object, int field) const;
virtual int findField(void *object, const char *fieldName) const;
virtual unsigned int getFieldTypeFlags(void *object, int field) const;
virtual const char *getFieldTypeString(void *object, int field) const;
virtual const char *getFieldProperty(void *object, int field, const char *propertyname) const;
virtual int getArraySize(void *object, int field) const;
virtual std::string getFieldAsString(void *object, int field, int i) const;
virtual bool setFieldAsString(void *object, int field, int i, const char *value) const;
virtual const char *getFieldStructName(void *object, int field) const;
virtual void *getFieldStructPointer(void *object, int field, int i) const;
};
Register_ClassDescriptor(EtherAppPctDescriptor);
EtherAppPctDescriptor::EtherAppPctDescriptor() : cClassDescriptor("EtherAppPct", "cPacket")
{
}
EtherAppPctDescriptor::~EtherAppPctDescriptor()
{
}
bool EtherAppPctDescriptor::doesSupport(cObject *obj) const
{
return dynamic_cast<EtherAppPct *>(obj)!=NULL;
}
const char *EtherAppPctDescriptor::getProperty(const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : NULL;
}
int EtherAppPctDescriptor::getFieldCount(void *object) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount(object) : 3;
}
unsigned int EtherAppPctDescriptor::getFieldTypeFlags(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeFlags(object, field);
field -= basedesc->getFieldCount(object);
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *EtherAppPctDescriptor::getFieldName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldName(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldNames[] = {
"key",
"nodeId",
"macAddress",
};
return (field>=0 && field<3) ? fieldNames[field] : NULL;
}
int EtherAppPctDescriptor::findField(void *object, const char *fieldName) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount(object) : 0;
if (fieldName[0]=='k' && strcmp(fieldName, "key")==0) return base+0;
if (fieldName[0]=='n' && strcmp(fieldName, "nodeId")==0) return base+1;
if (fieldName[0]=='m' && strcmp(fieldName, "macAddress")==0) return base+2;
return basedesc ? basedesc->findField(object, fieldName) : -1;
}
const char *EtherAppPctDescriptor::getFieldTypeString(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldTypeString(object, field);
field -= basedesc->getFieldCount(object);
}
static const char *fieldTypeStrings[] = {
"string",
"int",
"string",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : NULL;
}
const char *EtherAppPctDescriptor::getFieldProperty(void *object, int field, const char *propertyname) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldProperty(object, field, propertyname);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
}
}
int EtherAppPctDescriptor::getArraySize(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getArraySize(object, field);
field -= basedesc->getFieldCount(object);
}
EtherAppPct *pp = (EtherAppPct *)object; (void)pp;
switch (field) {
default: return 0;
}
}
std::string EtherAppPctDescriptor::getFieldAsString(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldAsString(object,field,i);
field -= basedesc->getFieldCount(object);
}
EtherAppPct *pp = (EtherAppPct *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getKey());
case 1: return long2string(pp->getNodeId());
case 2: return oppstring2string(pp->getMacAddress());
default: return "";
}
}
bool EtherAppPctDescriptor::setFieldAsString(void *object, int field, int i, const char *value) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->setFieldAsString(object,field,i,value);
field -= basedesc->getFieldCount(object);
}
EtherAppPct *pp = (EtherAppPct *)object; (void)pp;
switch (field) {
case 0: pp->setKey((value)); return true;
case 1: pp->setNodeId(string2long(value)); return true;
case 2: pp->setMacAddress((value)); return true;
default: return false;
}
}
const char *EtherAppPctDescriptor::getFieldStructName(void *object, int field) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructName(object, field);
field -= basedesc->getFieldCount(object);
}
switch (field) {
default: return NULL;
};
}
void *EtherAppPctDescriptor::getFieldStructPointer(void *object, int field, int i) const
{
cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount(object))
return basedesc->getFieldStructPointer(object, field, i);
field -= basedesc->getFieldCount(object);
}
EtherAppPct *pp = (EtherAppPct *)object; (void)pp;
switch (field) {
default: return NULL;
}
}
| 29.861446 | 153 | 0.679342 | [
"object",
"vector"
] |
ea38f2b5c2d8e285015f7dbd074220630e293563 | 3,078 | cpp | C++ | compute_samples/core/ocl_utils/test/ocl_utils_integration_tests.cpp | maximd33/compute-samples | b16a666b76b43c2a7bd1671edc563b45e978f1a7 | [
"MIT"
] | 75 | 2018-03-19T16:06:11.000Z | 2022-02-10T11:10:17.000Z | compute_samples/core/ocl_utils/test/ocl_utils_integration_tests.cpp | maximd33/compute-samples | b16a666b76b43c2a7bd1671edc563b45e978f1a7 | [
"MIT"
] | 10 | 2019-04-17T04:52:55.000Z | 2021-04-19T22:20:07.000Z | compute_samples/core/ocl_utils/test/ocl_utils_integration_tests.cpp | maximd33/compute-samples | b16a666b76b43c2a7bd1671edc563b45e978f1a7 | [
"MIT"
] | 17 | 2018-03-15T01:48:55.000Z | 2022-02-10T11:10:17.000Z | /*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "ocl_utils/ocl_utils.hpp"
#include "gtest/gtest.h"
#include "utils/utils.hpp"
#include <fstream>
#include <boost/compute/utility/source.hpp>
#include "test_harness/test_harness.hpp"
namespace cs = compute_samples;
namespace compute = boost::compute;
class BuildProgram : public testing::Test {
protected:
void SetUp() override {
device = compute::system::default_device();
context = compute::context(device);
}
void TearDown() override { std::remove(cl_file.c_str()); }
const std::string cl_file = "kernel.cl";
const std::string spv_file = "kernel.spv";
compute::device device;
compute::context context;
};
HWTEST_F(BuildProgram, ValidProgram) {
const char source[] =
BOOST_COMPUTE_STRINGIZE_SOURCE(kernel void my_kernel(){});
cs::save_text_file(source, cl_file);
EXPECT_NE(compute::program(), cs::build_program(context, cl_file));
}
HWTEST_F(BuildProgram, InvalidProgram) {
const char source[] =
BOOST_COMPUTE_STRINGIZE_SOURCE(kernel invalid_type my_kernel(){});
cs::save_text_file(source, cl_file);
EXPECT_THROW(cs::build_program(context, cl_file), compute::opencl_error);
}
HWTEST_F(BuildProgram, BuildOptions) {
const char source[] =
BOOST_COMPUTE_STRINGIZE_SOURCE(kernel MY_TYPE my_kernel(){});
cs::save_text_file(source, cl_file);
EXPECT_NE(compute::program(),
cs::build_program(context, cl_file, "-DMY_TYPE=void"));
}
HWTEST_F(BuildProgram, ValidProgramSpirV) {
std::vector<uint8_t> spriv_file_source = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0b, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x4f, 0x70, 0x65, 0x6e,
0x43, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00,
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00,
0x03, 0x00, 0x00, 0x00, 0x70, 0x8e, 0x01, 0x00};
compute_samples::save_binary_file(spriv_file_source, spv_file);
EXPECT_NE(compute::program(),
cs::build_program_il(context, spv_file, "-cl-std=CL2.0"));
}
HWTEST_F(BuildProgram, InvalidProgramSpirV) {
std::vector<uint8_t> spriv_file_source = {
0x0A, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0b, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x4f, 0x70, 0x65, 0x6e,
0x43, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00,
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00,
0x03, 0x00, 0x00, 0x00, 0x70, 0x8e, 0x01, 0x00};
compute_samples::save_binary_file(spriv_file_source, spv_file);
EXPECT_THROW(cs::build_program_il(context, spv_file, "-cl-std=CL2.0"),
compute::opencl_error);
}
| 36.642857 | 77 | 0.68681 | [
"vector"
] |
356e81f54b2876faeac36f9df5f9c6b950dd658d | 7,998 | cc | C++ | src/AMOS/datatypes_AMOS.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-03-20T18:25:56.000Z | 2020-06-02T22:00:08.000Z | src/AMOS/datatypes_AMOS.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 5 | 2015-05-14T17:51:20.000Z | 2020-07-19T04:17:47.000Z | src/AMOS/datatypes_AMOS.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-05-17T16:01:23.000Z | 2020-05-20T08:13:43.000Z | ////////////////////////////////////////////////////////////////////////////////
//! \file
//! \author Adam M Phillippy
//! \date 10/30/2003
//!
//! \brief Source for datatypes_AMOS.hh
//!
////////////////////////////////////////////////////////////////////////////////
#include "datatypes_AMOS.hh"
#include <sstream>
using namespace AMOS;
using namespace std;
//================================================ Distribution_t ==============
const NCode_t Distribution_t::NCODE = M_DISTRIBUTION;
//----------------------------------------------------- readMessage ------------
void Distribution_t::readMessage (const Message_t & msg)
{
clear( );
try {
istringstream ss;
ss . str (msg . getField (F_MEAN));
ss >> mean;
if ( !ss )
AMOS_THROW_ARGUMENT ("Invalid mean format");
ss . clear( );
ss . str (msg . getField (F_SD));
ss >> sd;
if ( !ss )
AMOS_THROW_ARGUMENT ("Invalid standard deviation format");
ss . clear( );
}
catch (ArgumentException_t) {
clear( );
throw;
}
}
//--------------------------------------------------- readRecord -------------
void Distribution_t::readRecord (std::istream & in)
{
readLE (in, &mean);
readLE (in, &sd);
}
//----------------------------------------------------- writeMessage -----------
void Distribution_t::writeMessage (Message_t & msg) const
{
msg . clear( );
try {
ostringstream ss;
msg . setMessageCode (Distribution_t::getNCode( ));
ss << mean;
msg . setField (F_MEAN, ss . str( ));
ss . str (NULL_STRING);
ss << sd;
msg . setField (F_SD, ss . str( ));
ss . str (NULL_STRING);
}
catch (ArgumentException_t) {
msg . clear( );
throw;
}
}
//--------------------------------------------------- writeRecord ------------
void Distribution_t::writeRecord (std::ostream & out) const
{
writeLE (out, &mean);
writeLE (out, &sd);
}
//================================================ Tile_t ======================
const NCode_t Tile_t::NCODE = M_TILE;
//----------------------------------------------------- clear ------------------
void Tile_t::clear ( )
{
source = NULL_ID;
source_type = NULL_NCODE;
gaps . clear( );
offset = 0;
range . clear( );
}
//----------------------------------------------------- readMessage ------------
void Tile_t::readMessage (const Message_t & msg)
{
clear( );
try {
Pos_t gap;
istringstream ss;
if ( msg . exists (F_SOURCE) )
{
string str;
ss . str (msg . getField (F_SOURCE));
ss >> source;
ss . ignore( );
ss >> str;
if ( !ss || str . length( ) != NCODE_SIZE )
source_type = NULL_NCODE;
else
source_type = Encode(str);
ss . clear( );
}
if ( msg . exists (F_OFFSET) )
{
ss . str (msg . getField (F_OFFSET));
ss >> offset;
if ( !ss )
AMOS_THROW_ARGUMENT ("Invalid offset format");
ss . clear( );
}
if ( msg . exists (F_CLEAR) )
{
ss . str (msg . getField (F_CLEAR));
ss >> range . begin;
ss . ignore( );
ss >> range . end;
if ( !ss )
AMOS_THROW_ARGUMENT ("Invalid clear range format");
ss . clear( );
}
if ( msg . exists (F_GAPS) )
{
ss . str (msg . getField (F_GAPS));
while ( ss )
{
ss >> gap;
if ( ! ss . fail( ) )
gaps . push_back (gap);
}
if ( !ss . eof( ) )
AMOS_THROW_ARGUMENT ("Invalid gaps format");
ss . clear( );
}
}
catch (ArgumentException_t) {
clear( );
throw;
}
}
//----------------------------------------------------- readRecord -------------
void Tile_t::readRecord (istream & in)
{
Size_t size;
readLE (in, &size);
gaps . resize (size);
for ( Pos_t i = 0; i < size; i ++ )
readLE (in, &(gaps [i]));
readLE (in, &source);
readLE (in, &source_type);
readLE (in, &offset);
readLE (in, &(range . begin));
readLE (in, &(range . end));
}
//----------------------------------------------------- writeMessage -----------
void Tile_t::writeMessage (Message_t & msg) const
{
msg . clear( );
try {
vector<Pos_t>::const_iterator vi;
ostringstream ss;
msg . setMessageCode (Tile_t::getNCode( ));
if ( source != NULL_ID)
{
ss << source;
if (source_type != NULL_NCODE)
ss << ',' << Decode (source_type);
msg . setField (F_SOURCE, ss . str( ));
ss . str (NULL_STRING);
}
ss << offset;
msg . setField (F_OFFSET, ss . str( ));
ss . str (NULL_STRING);
ss << range . begin << ',' << range . end;
msg . setField (F_CLEAR, ss . str( ));
ss . str (NULL_STRING);
if ( !gaps . empty( ) )
{
for ( vi = gaps . begin( ); vi != gaps . end( ); vi ++ )
ss << *vi << '\n';
msg . setField (F_GAPS, ss . str( ));
ss . str (NULL_STRING);
}
}
catch (ArgumentException_t) {
msg . clear( );
throw;
}
}
//----------------------------------------------------- writeRecord ------------
void Tile_t::writeRecord (ostream & out) const
{
Size_t size = gaps . size( );
writeLE (out, &size);
for ( Pos_t i = 0; i < size; i ++ )
writeLE (out, &(gaps [i]));
writeLE (out, &source);
writeLE (out, &source_type);
writeLE (out, &offset);
writeLE (out, &(range . begin));
writeLE (out, &(range . end));
}
//================================================ Helper Functions ============
//----------------------------------------------------- operator& --------------
Range_t AMOS::operator& (Range_t a, Range_t b)
{
if ( a . begin > a . end )
{
Pos_t tmp = a . begin;
a . begin = a . end;
a . end = tmp;
}
if ( b . begin > b . end )
{
Pos_t tmp = b . begin;
b . begin = b . end;
b . end = tmp;
}
if ( a . begin >= b . end || a . end <= b . begin )
return Range_t (0,0);
else if ( a . begin < b . begin )
return Range_t (b . begin, a . end < b . end ? a . end : b . end);
else
return Range_t (a . begin, a . end < b . end ? a . end : b . end);
}
//----------------------------------------------------- operator| --------------
Range_t AMOS::operator| (Range_t a, Range_t b)
{
if ( a . begin > a . end )
{
Pos_t tmp = a . begin;
a . begin = a . end;
a . end = tmp;
}
if ( b . begin > b . end )
{
Pos_t tmp = b . begin;
b . begin = b . end;
b . end = tmp;
}
if ( a . begin >= b . end || a . end <= b . begin )
return Range_t (0,0);
else
return Range_t (a . begin < b . begin ? a . begin : b . begin,
a . end > b . end ? a . end : b . end);
}
//----------------------------------------------------- operator== -------------
bool AMOS::operator== (const Range_t & a, const Range_t & b)
{
return ( a . begin == b . begin && a . end == b . end );
}
bool AMOS::operator!= (const Range_t & a, const Range_t & b)
{
return !(a == b);
}
//----------------------------------------------------- operator== -------------
bool AMOS::operator== (const Distribution_t & a, const Distribution_t & b)
{
return ( a . mean == b . mean &&
a . sd == b . sd );
}
bool AMOS::operator!= (const Distribution_t & a, const Distribution_t & b)
{
return !(a == b);
}
//----------------------------------------------------- operator== -------------
bool AMOS::operator== (const Tile_t & a, const Tile_t & b)
{
return ( a . source == b . source &&
a . gaps == b . gaps &&
a . offset == b . offset &&
a . range == b . range );
}
bool AMOS::operator!= (const Tile_t & a, const Tile_t & b)
{
return !(a == b);
}
//----------------------------------------------------- WrapStirng -------------
void AMOS::WrapString (ostream & out, const string & s, int per)
{
int i, n;
n = s . size ( );
for (i = 0; i < n; i += per)
{
int j, last;
last = i + per;
if (n < last)
last = n;
for (j = i; j < last; j ++)
out << s [j];
out << endl;
}
}
| 22.155125 | 80 | 0.437484 | [
"vector"
] |
357323f2f80093d011069313f34c675e265ac8b3 | 1,762 | cpp | C++ | test/reporter/templateprocessor_test.cpp | pefoo/MoSer2 | f593126112637c9fa3a7e6a66e34e80f515b796b | [
"MIT"
] | 1 | 2019-06-01T11:39:53.000Z | 2019-06-01T11:39:53.000Z | test/reporter/templateprocessor_test.cpp | pefoo/MoSer2 | f593126112637c9fa3a7e6a66e34e80f515b796b | [
"MIT"
] | null | null | null | test/reporter/templateprocessor_test.cpp | pefoo/MoSer2 | f593126112637c9fa3a7e6a66e34e80f515b796b | [
"MIT"
] | null | null | null | #include "reporter/templateprocessor/templateprocessor.hpp"
#include <filesystem>
#include <fstream>
#include <sstream>
#include "catch2/catch.hpp"
#include "reporter/templateprocessor/templatetoken.hpp"
std::string GetTestFile(const std::string file_name) {
std::stringstream ss{};
ss << TESTDATA_DIR;
ss << file_name;
return ss.str();
}
std::vector<reporter::templateprocessor::TemplateToken> Tokens() {
return {reporter::templateprocessor::TemplateToken{
"key1", []() { return "unit test _1"; }},
reporter::templateprocessor::TemplateToken{
"%%foobar%%", []() { return "foobar"; }}};
}
std::string ExpectedContent() {
return "this\nis some\nrandom\ntext\nhere is the first key: unit test "
"_1\n\nnext "
"line contains the second key\nfoobar\nanother random line\n";
}
TEST_CASE("Tokenprocessor normal run", "[Reporter]") {
reporter::templateprocessor::TemplateProcessor processor{Tokens(), nullptr};
auto result = processor.ProcessTemplate(GetTestFile("reporter_template"));
std::ifstream content{result};
std::stringstream buffer;
buffer << content.rdbuf();
REQUIRE(buffer.str() == ExpectedContent());
std::remove(result.c_str());
}
TEST_CASE("Tokenprocessor in place", "[Reporter]") {
reporter::templateprocessor::TemplateProcessor processor{Tokens(), nullptr};
std::filesystem::copy(GetTestFile("reporter_template"), ".tmp",
std::filesystem::copy_options::overwrite_existing);
auto result = processor.ProcessTemplate(".tmp", true);
REQUIRE(result == ".tmp");
std::ifstream content{result};
std::stringstream buffer;
buffer << content.rdbuf();
REQUIRE(buffer.str() == ExpectedContent());
std::remove(result.c_str());
}
| 30.37931 | 78 | 0.690125 | [
"vector"
] |
357bd68dc1682b7f66a0fe7c01329bf2706da9e6 | 11,845 | cpp | C++ | src/tools/Segmentation.cpp | tomasiser/pepr3d | 5eaacd573c553e0e8eb79212842894bf32b5c666 | [
"BSD-2-Clause"
] | 128 | 2019-11-18T16:09:58.000Z | 2022-01-15T03:59:51.000Z | src/tools/Segmentation.cpp | tomasiser/pepr3d | 5eaacd573c553e0e8eb79212842894bf32b5c666 | [
"BSD-2-Clause"
] | 3 | 2019-04-01T17:41:19.000Z | 2020-07-23T08:55:08.000Z | src/tools/Segmentation.cpp | tomasiser/pepr3d | 5eaacd573c553e0e8eb79212842894bf32b5c666 | [
"BSD-2-Clause"
] | 31 | 2019-04-04T11:28:11.000Z | 2022-03-14T08:52:38.000Z | #include "tools/Segmentation.h"
#include <random>
#include <vector>
#include "commands/CmdPaintSingleColor.h"
#include "geometry/SdfValuesException.h"
#include "ui/MainApplication.h"
namespace pepr3d {
void Segmentation::drawToSidePane(SidePane& sidePane) {
if(!mGeometryCorrect) {
sidePane.drawText("Polyhedron not built, since the geometry was damaged. Tool disabled.");
return;
}
const bool isSdfComputed = mApplication.getCurrentGeometry()->isSdfComputed();
if(!isSdfComputed) {
sidePane.drawText("Warning: This computation may take a long time to perform.");
if(sidePane.drawButton("Compute SDF")) {
mApplication.enqueueSlowOperation([this]() { safeComputeSdf(mApplication); }, []() {}, true);
}
sidePane.drawTooltipOnHover("Compute the shape diameter function of the model to enable the segmentation.");
} else {
if(sidePane.drawButton("Segment!")) {
computeSegmentation();
}
sidePane.drawTooltipOnHover("Start segmentation on the model.");
sidePane.drawFloatDragger("Robustness", mNumberOfClusters, 0.25f, 0.0f, 100.0f, "%.0f %%", 70.0f);
sidePane.drawTooltipOnHover(
"Higher values increase the computation time and might result in better region grouping. The default value "
"should be good for most use cases.");
sidePane.drawFloatDragger("Edge tolerance", mSmoothingLambda, 0.25f, 0.0f, 100.0f, "%.0f %%", 70.0f);
sidePane.drawTooltipOnHover(
"The higher the number, the more the segmentation will tolerate sharp edges and thus make less segments. "
"If you have more segments than you wanted, increase this value. If you have less, decrease.");
}
sidePane.drawSeparator();
ColorManager& colorManager = mApplication.getCurrentGeometry()->getColorManager();
if(mPickState) {
sidePane.drawText("Segmented into " + std::to_string(mNumberOfSegments) +
" segments. Assign a color from the palette to each segment.");
sidePane.drawColorPalette();
for(const auto& toPaint : mSegmentToTriangleIds) {
std::string displayText = "Segment " + std::to_string(toPaint.first);
glm::vec4 colorOfSegment(0, 0, 0, 1);
if(mNewColors[toPaint.first] != std::numeric_limits<size_t>::max()) {
colorOfSegment = colorManager.getColor(mNewColors[toPaint.first]);
} else {
colorOfSegment = mSegmentationColors[toPaint.first];
}
glm::vec3 hsvButtonColor = ci::rgbToHsv(static_cast<ci::ColorA>(colorOfSegment));
hsvButtonColor.y = 0.75; // reduce the saturation
ci::ColorA borderColor = ci::hsvToRgb(hsvButtonColor);
float thickness = 3.0f;
if(mHoveredTriangleId) {
auto find = mTriangleToSegmentMap.find(*mHoveredTriangleId);
assert(find != mTriangleToSegmentMap.end());
assert(find->first == *mHoveredTriangleId);
if(find->second == toPaint.first) {
borderColor = ci::ColorA(1, 0, 0, 1);
displayText = "Currently hovered";
thickness = 5.0f;
}
}
if(sidePane.drawColoredButton(displayText.c_str(), borderColor, thickness)) {
mNewColors[toPaint.first] = colorManager.getActiveColorIndex();
const glm::vec4 newColor = colorManager.getColor(colorManager.getActiveColorIndex());
setSegmentColor(toPaint.first, newColor);
}
sidePane.drawTooltipOnHover(
"Click to color this segment with the currently active color from the palette.");
}
if(sidePane.drawButton("Accept")) {
// Find the maximum index of the color assignment
size_t maxColorIndex = std::numeric_limits<size_t>::min();
for(const auto& segment : mSegmentToTriangleIds) {
const size_t activeColorAssigned = mNewColors[segment.first];
if(activeColorAssigned > maxColorIndex) {
maxColorIndex = activeColorAssigned;
}
}
// If the user assigned colors are valid (i.e. there aren't colors out of the palette size), apply.
if(maxColorIndex < colorManager.size()) {
for(const auto& segment : mSegmentToTriangleIds) {
const size_t activeColorAssigned = mNewColors[segment.first];
auto proxy = segment.second;
CommandManager<Geometry>* const commandManager = mApplication.getCommandManager();
commandManager->execute(
std::make_unique<CmdPaintSingleColor>(std::move(proxy), activeColorAssigned), false);
}
reset();
CI_LOG_I("Segmentation applied.");
} else { // Else report the error to the user and continue.
mApplication.pushDialog(Dialog(
DialogType::Error, "Please assign a color to all segments",
"The segmentation was not accepted. Please assign all segments a color from the palette first!"));
CI_LOG_W("Please assign all segments a color from the palette first.");
}
}
sidePane.drawTooltipOnHover("Apply the results to the model.");
if(sidePane.drawButton("Cancel")) {
cancel();
}
sidePane.drawTooltipOnHover("Revert the model back to the previous coloring.");
sidePane.drawSeparator();
}
}
void Segmentation::cancel() {
if(mPickState) {
reset();
CI_LOG_I("Segmentation canceled.");
}
}
void Segmentation::onToolDeselect(ModelView& modelView) {
if(!mGeometryCorrect) {
return;
}
cancel();
}
void Segmentation::onModelViewMouseMove(ModelView& modelView, ci::app::MouseEvent event) {
ci::Ray mLastRay = modelView.getRayFromWindowCoordinates(event.getPos());
const auto geometry = mApplication.getCurrentGeometry();
if(geometry == nullptr) {
mHoveredTriangleId = {};
return;
}
mHoveredTriangleId = safeIntersectMesh(mApplication, mLastRay);
}
void Segmentation::drawToModelView(ModelView& modelView) {
if(mHoveredTriangleId && mPickState && mGeometryCorrect) {
modelView.drawTriangleHighlight(*mHoveredTriangleId);
}
}
void Segmentation::onModelViewMouseDown(ModelView& modelView, ci::app::MouseEvent event) {
if(!event.isLeftDown()) {
return;
}
if(!mHoveredTriangleId) {
return;
}
if(!mPickState) {
return;
}
if(!mGeometryCorrect) {
return;
}
auto find = mTriangleToSegmentMap.find(*mHoveredTriangleId);
assert(find != mTriangleToSegmentMap.end());
assert(find->first == *mHoveredTriangleId);
const size_t segId = find->second;
assert(segId < mNumberOfSegments);
assert(segId < mNewColors.size());
ColorManager& colorManager = mApplication.getCurrentGeometry()->getColorManager();
mNewColors[segId] = colorManager.getActiveColorIndex();
const glm::vec4 newColor = colorManager.getColor(colorManager.getActiveColorIndex());
setSegmentColor(segId, newColor);
}
void Segmentation::reset() {
mApplication.getModelView().toggleMeshOverride(false);
mNumberOfSegments = 0;
mPickState = false;
mSdfEnabled = nullptr;
mNewColors.clear();
mSegmentationColors.clear();
mHoveredTriangleId = {};
mSegmentToTriangleIds.clear();
mTriangleToSegmentMap.clear();
}
void Segmentation::computeSegmentation() {
cancel();
Geometry* geometry = mApplication.getCurrentGeometry();
assert(geometry);
float smoothingLambda = mSmoothingLambda / 100.0f;
smoothingLambda = std::min<float>(smoothingLambda, 1.0f);
smoothingLambda = std::max<float>(smoothingLambda, 0.01f);
int numberOfClusters = static_cast<int>(std::floor(mNumberOfClusters / 100.0f / (1.0f / 14.0f)) + 2.0f);
numberOfClusters = std::min<int>(numberOfClusters, 15);
numberOfClusters = std::min<int>(numberOfClusters, static_cast<int>(geometry->getTriangleCount()) - 2);
numberOfClusters = std::max<int>(2, numberOfClusters);
assert(0.0f < smoothingLambda && smoothingLambda <= 1.0f);
assert(2 <= numberOfClusters && numberOfClusters <= geometry->getTriangleCount() && numberOfClusters <= 15);
try {
mNumberOfSegments =
geometry->segmentation(numberOfClusters, smoothingLambda, mSegmentToTriangleIds, mTriangleToSegmentMap);
} catch(std::exception& e) {
const std::string errorCaption = "Error: Failed to compute the segmentation";
const std::string errorDescription =
"An internal error occured while computing the the segmentation. If the problem persists, try re-loading "
"the mesh.\n\n"
"Please report this bug to the developers. The full description of the problem is:\n";
mApplication.pushDialog(Dialog(DialogType::Error, errorCaption, errorDescription + e.what(), "OK"));
return;
}
if(mNumberOfSegments > 0) {
mPickState = true;
// If we this time segment into more segments than previously
if(mNewColors.size() < mNumberOfSegments) {
mNewColors.resize(mNumberOfSegments);
for(size_t i = 0; i < mNumberOfSegments; ++i) {
mNewColors[i] = std::numeric_limits<size_t>::max();
}
}
assert(mNumberOfSegments != std::numeric_limits<size_t>::max());
assert(mNumberOfSegments <= PEPR3D_MAX_PALETTE_COLORS);
// Generate new colors
pepr3d::ColorManager::generateColors(mNumberOfSegments, mSegmentationColors);
assert(mSegmentationColors.size() == mNumberOfSegments);
// Create an override color buffer based on the segmentation
std::vector<glm::vec4> newOverrideBuffer;
newOverrideBuffer.resize(geometry->getTriangleCount() * 3);
for(const auto& toPaint : mSegmentToTriangleIds) {
for(const auto& tri : toPaint.second) {
newOverrideBuffer[3 * tri] = mSegmentationColors[toPaint.first];
newOverrideBuffer[3 * tri + 1] = mSegmentationColors[toPaint.first];
newOverrideBuffer[3 * tri + 2] = mSegmentationColors[toPaint.first];
}
}
mApplication.getModelView().toggleMeshOverride(true);
mApplication.getModelView().initOverrideFromBasicGeoemtry();
mApplication.getModelView().getOverrideColorBuffer() = newOverrideBuffer;
}
}
void Segmentation::setSegmentColor(const size_t segmentId, const glm::vec4 newColor) {
std::vector<glm::vec4>& overrideBuffer = mApplication.getModelView().getOverrideColorBuffer();
auto segmentTris = mSegmentToTriangleIds.find(segmentId);
if(segmentTris == mSegmentToTriangleIds.end()) {
assert(false);
return;
}
assert((*segmentTris).first == segmentId);
assert(!overrideBuffer.empty());
for(const auto& tri : (*segmentTris).second) {
overrideBuffer[3 * tri] = newColor;
overrideBuffer[3 * tri + 1] = newColor;
overrideBuffer[3 * tri + 2] = newColor;
}
}
void Segmentation::onNewGeometryLoaded(ModelView& modelView) {
Geometry* const currentGeometry = mApplication.getCurrentGeometry();
assert(currentGeometry != nullptr);
if(currentGeometry == nullptr) {
return;
}
mGeometryCorrect = currentGeometry->polyhedronValid();
if(!mGeometryCorrect) {
return;
}
CI_LOG_I("Model changed, segmentation reset");
reset();
mSdfEnabled = currentGeometry->sdfValuesValid();
}
} // namespace pepr3d | 41.271777 | 120 | 0.644913 | [
"mesh",
"geometry",
"shape",
"vector",
"model"
] |
3583ef09f6e87cfb0d070fca5091859d8ff1ceb6 | 1,814 | cpp | C++ | ocl_c_test/logging.cpp | cpieloth/GPGPU-on-Hadoop | 533d27d1ee4440de35d71906f42af9eaa1471108 | [
"Apache-2.0"
] | 4 | 2016-01-08T15:23:45.000Z | 2016-08-26T15:03:00.000Z | ocl_c_test/logging.cpp | cpieloth/GPGPU-on-Hadoop | 533d27d1ee4440de35d71906f42af9eaa1471108 | [
"Apache-2.0"
] | null | null | null | ocl_c_test/logging.cpp | cpieloth/GPGPU-on-Hadoop | 533d27d1ee4440de35d71906f42af9eaa1471108 | [
"Apache-2.0"
] | 1 | 2022-01-05T07:45:40.000Z | 2022-01-05T07:45:40.000Z | /**
* @file
*/
#include "logging.hpp"
#include <limits>
#include <iostream>
using namespace logging;
using namespace std;
// Default level
const Level Level::ERR("ERROR", 1);
const Level Level::WARN("WARN", 2);
const Level Level::INFO("INFO", 4);
const Level Level::TRACE("TRACE", 8);
const Level Level::DEBUG("DEBUG", 16);
const Level Level::ALL("ALL", numeric_limits<unsigned short>::max());
const Level Level::NORMAL("NORMAL", 7);
unsigned short Logger::logMask = Level::ALL.VALUE;
std::stringstream Logger::sStream;
unsigned short
Logger::getLogMask()
{
return Logger::logMask;
}
void
Logger::setLogMask(Level level)
{
Logger::logMask = level.VALUE;
}
void
Logger::setLogMask(vector<Level> levels)
{
Logger::clearLogMask();
vector<Level>::iterator it = levels.begin();
for (; it != levels.end(); it++)
Logger::logMask += it.base()->VALUE;
}
void
Logger::clearLogMask()
{
Logger::logMask = 0;
}
void
Logger::log(string clazz, Level level, std::basic_ostream<char>& msg)
{
if ((Logger::logMask & level.VALUE) == level.VALUE)
cout << "[" << level.NAME << "] " << clazz << ": " << msg.rdbuf() << endl;
Logger::sStream.str("");
}
void
Logger::logDebug(string clazz, std::basic_ostream<char>& msg)
{
Logger::log(clazz, Level::DEBUG, msg);
}
void
Logger::logTrace(string clazz, std::basic_ostream<char>& msg)
{
Logger::log(clazz, Level::TRACE, msg);
}
void
Logger::logInfo(string clazz, std::basic_ostream<char>& msg)
{
Logger::log(clazz, Level::INFO, msg);
}
void
Logger::logWarn(string clazz, std::basic_ostream<char>& msg)
{
Logger::log(clazz, Level::WARN, msg);
}
void
Logger::logError(string clazz, std::basic_ostream<char>& msg)
{
Logger::log(clazz, Level::ERR, msg);
}
| 20.155556 | 79 | 0.640022 | [
"vector"
] |
35882414c4114657ac97cf4d2cd5977a08004631 | 970 | cpp | C++ | src/textureLoader.cpp | JM-Ski/CarGame | af7329780e55e550dd787f6dd233bb7a079a7d84 | [
"MIT"
] | null | null | null | src/textureLoader.cpp | JM-Ski/CarGame | af7329780e55e550dd787f6dd233bb7a079a7d84 | [
"MIT"
] | null | null | null | src/textureLoader.cpp | JM-Ski/CarGame | af7329780e55e550dd787f6dd233bb7a079a7d84 | [
"MIT"
] | null | null | null | #include "textureLoader.h"
#include <iostream>
//<! Initializer
TextureLoader::TextureLoader()
{
setBaseDirectory(".\\assets\\textures\\");
}
//<! Sets our base directory
void TextureLoader::setBaseDirectory(std::string dir)
{
baseDirectory = dir;
}
//<! Loads textures based on the string input
void TextureLoader::load(std::vector<std::string> fileNames)
{
//Loop throug hthe input
for (auto it = fileNames.begin(); it != fileNames.end(); ++it)
{
sf::Texture text; // Create an empty texture
text.loadFromFile(baseDirectory + *it); //Apply the textture so it's no longer empty
textures.push_back(text); // Add it to our vector of textures
}
}
//<! Returns texture with said index
sf::Texture& TextureLoader::getTexture(int fIndex)
{
int num = 0; //Our index number
for (auto it = textures.begin(); it != textures.end(); ++it)
{
if (num == fIndex) return *it; //Return the said texture if it matches our index
num++; //Increment the number
}
} | 26.216216 | 86 | 0.694845 | [
"vector"
] |
358e273e8e35752d25079c1f2dbe2511e932a45d | 6,001 | hpp | C++ | src-unused/dispersion_threshold_bak.hpp | lucas137/eyelib | e88eaea6dd2c2e4b365d178f67869a3cd47751a5 | [
"MIT"
] | null | null | null | src-unused/dispersion_threshold_bak.hpp | lucas137/eyelib | e88eaea6dd2c2e4b365d178f67869a3cd47751a5 | [
"MIT"
] | null | null | null | src-unused/dispersion_threshold_bak.hpp | lucas137/eyelib | e88eaea6dd2c2e4b365d178f67869a3cd47751a5 | [
"MIT"
] | null | null | null | //===========================================================================//
/// @file
/// @brief @ref eye::DispersionThreshold algorithm.
/// @author Nathan Lucas
/// @date 2016
//===========================================================================//
#ifndef EYE_DISPERSION_THRESHOLD_HPP
#define EYE_DISPERSION_THRESHOLD_HPP
#include <deque> // std::deque
#include <algorithm> // std::minmax_element
namespace eye {
/// @addtogroup module_fixation
/// @{
/** @brief Dispersion threshold (DT) fixation detection algorithm.
@headerfile eye/dispersion_threshold.hpp
@par Header
@header{eye/dispersion_threshold.hpp}
Identifies a fixation as a group of consecutive points within a dispersion,
or maximum separation, that spans a minimum duration.
@sa [eyelib-analysis Manual](@ref fixation_dt)
*/
class DispersionThreshold
{
public:
/**
@brief Constructs a gaze data processing object.
@param [in] min_pt Minimum number of points in the moving window.
@param [in] max_px Maximum dispersion in pixels of fixation points.
*/
/*inline*/
DispersionThreshold(unsigned min_pt, double max_px);
/**
@brief Add a gaze point.
@param [in] x Horizontal coordinate.
@param [in] y Vertical coordinate.
*/
/*inline*/ void
push_back(double x, double y);
/**
@brief Checks if the last point added is part of a fixation cluster.
@return `true` if the last point belongs to a fixation, `false` otherwise.
The minimum window condition must be met before a point can be identified
with a fixation cluster. See the constructor parameter <em>min_pt</em>.
That means this method will only return `true` if at least
<em>min_pt</em> points have been collected since object instantiation
or the last fixation terminated.
@note Consecutive points within the dispersion
threshold represent the same fixation.
*/
/*inline*/ bool
is_fixation() const;
/**
@brief Returns the current fixation point, and the
number of gaze points within the fixation cluster.
@param [out] x Horizontal coordinate.
@param [out] y Vertical coordinate.
@param [out] n Number of points in the fixation cluster, or `0` if
the last point has not been identified with a fixation.
The fixation point is computed as the centroid
of the gaze points within the fixation cluster.
@note See the minimum window condition described at `fixation()`.
*/
/*inline*/ Fixation
fixation() const;
private: //-----------------------------------------------------------
unsigned min_pt_;
double max_px_;
bool fixation_;
std::deque<double> x_, y_;
double max_x_, min_x_, max_y_, min_y_;
eye::PointGroup points_;
};
/// @}
//---------------------------------------------------------------------------//
inline
DispersionThreshold::DispersionThreshold(unsigned min_pt, double max_px)
: min_pt_(min_pt)
, max_px_(max_px)
, fixation_(false)
, x_()
, y_()
, max_x_(0.0)
, min_x_(0.0)
, max_y_(0.0)
, min_y_(0.0)
{}
inline void
DispersionThreshold::push_back(double x, double y)
{
// The following statements avoid an assignment operation if the min or
// max value does not change. Alternatively, each call to std::max and
// std::min may perform an assignment, even if there is no change to the
// min and max value respectively.
if (x > max_x_) { max_x_ = x }
if (x < min_x_) { min_x_ = x }
if (y > max_y_) { max_y_ = y }
if (y < min_y_) { min_y_ = y }
x_.push_back(x);
y_.push_back(y);
points_.push_back(p);
// Duration threshold is implemented as a minimum
// number of points within a fixation cluster.
if (x_.size() < min_pt_)
{
// Continue accumulating points until duration threshold is met
return;
}
// Dispersion threshold is implemented as a maximum dispersion in pixels.
double d = ((max_x_ - min_x)_ + (max_y_ - min_y_));
// If `d` is within dispersion threshold `max_px`, the cluster of
// points in the window are considered to represent a fixation.
if (d <= max_px_)
{
// Keep adding points until dispersion threshold is exceeded.
fixation_ = true;
return;
}
// Exceeded threshold.
if (fixation_)
{
// If a fixation occurred, reset all variables, but keep
// the current point as the first point in a new window.
x_.clear(); // Remove all points.
y_.clear();
x_.push_back(x); // Re-add non-fixation point.
y_.push_back(y);
max_x_ = x;
min_x_ = x;
max_y_ = y;
min_y_ = y;
fixation_ = false;
return;
}
x_.pop_front(); // Remove first point in window.
y_.pop_front();
// Re-compute min and max values.
auto minmax_x = std::minmax_element(x_.begin(), x_.end());
min_x_ = *minmax_x.first;
max_x_ = *minmax_x.second;
auto minmax_y = std::minmax_element(y_.begin(), y_.end());
min_y_ = *minmax_y.first;
max_y_ = *minmax_y.second;
}
inline bool
DispersionThreshold::is_fixation() const
{
return fixation_;
}
inline Fixation
DispersionThreshold::fixation() const
{
Fixation f;
if (fixation_)
{
// Verify coordinate vectors are not empty.
if (x_.empty() || y_.empty())
{
return; // empty vector
}
// Verify equal vector sizes.
if (x_.size() != y_.size())
{
return; // unequal vector sizes
}
// Number of points in fixation cluster.
f.n = x_.size();
// Compute centroid of cluster points.
double sum_x = std::accumulate(x_.begin(), x_.end(), 0.0);
f.x = sum_x / f.n;
double sum_y = std::accumulate(y_.begin(), y_.end(), 0.0);
f.y = sum_y / f.n;
}
return f;
}
} // eye
#endif // EYE_DISPERSION_THRESHOLD_HPP
//===========================================================================//
| 28.042056 | 80 | 0.604066 | [
"object",
"vector"
] |
3595c351c12f3304dd6213310e4e1b0ab8c7783d | 2,819 | hpp | C++ | Pods/Realm/include/core/realm/chunked_binary.hpp | EetuHernesniemi/iOS-Todoye | 353e503dd897571e7c1fc7e5658f1d03f7f31ec7 | [
"MIT"
] | null | null | null | Pods/Realm/include/core/realm/chunked_binary.hpp | EetuHernesniemi/iOS-Todoye | 353e503dd897571e7c1fc7e5658f1d03f7f31ec7 | [
"MIT"
] | null | null | null | Pods/Realm/include/core/realm/chunked_binary.hpp | EetuHernesniemi/iOS-Todoye | 353e503dd897571e7c1fc7e5658f1d03f7f31ec7 | [
"MIT"
] | null | null | null | /*************************************************************************
*
* Copyright 2019 Realm 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.
*
**************************************************************************/
#ifndef REALM_NOINST_CHUNKED_BINARY_HPP
#define REALM_NOINST_CHUNKED_BINARY_HPP
#include <realm/binary_data.hpp>
#include <realm/column_binary.hpp>
#include <realm/table.hpp>
#include <realm/util/buffer.hpp>
#include <realm/util/buffer_stream.hpp>
#include <realm/util/input_stream.hpp>
namespace realm {
/// ChunkedBinaryData manages a vector of BinaryData. It is used to facilitate
/// extracting large binaries from binary columns and tables.
class ChunkedBinaryData {
public:
ChunkedBinaryData() {}
ChunkedBinaryData(const BinaryData& bd)
: m_begin{bd}
{
}
ChunkedBinaryData(const BinaryColumn& col, size_t index)
: m_begin{&col, index}
{
}
/// size() returns the number of bytes in the chunked binary.
/// FIXME: This operation is O(n).
size_t size() const noexcept;
/// is_null returns true if the chunked binary has zero chunks or if
/// the first chunk points to the nullptr.
bool is_null() const;
/// FIXME: O(n)
char operator[](size_t index) const;
std::string hex_dump(const char* separator = " ", int min_digits = -1) const;
void write_to(util::ResettableExpandableBufferOutputStream& out) const;
/// copy_to() clears the target buffer and then copies the chunked binary
/// data to it.
void copy_to(util::AppendBuffer<char>& dest) const;
/// get_first_chunk() is used in situations
/// where it is known that there is exactly one
/// chunk. This is the case if the ChunkedBinary
/// has been constructed from BinaryData.
BinaryData get_first_chunk() const;
BinaryIterator iterator() const noexcept;
private:
BinaryIterator m_begin;
};
class ChunkedBinaryInputStream : public util::NoCopyInputStream {
public:
explicit ChunkedBinaryInputStream(const ChunkedBinaryData& chunks)
: m_it(chunks.iterator())
{
}
util::Span<const char> next_block() override
{
return m_it.get_next();
}
private:
BinaryIterator m_it;
};
} // namespace realm
#endif // REALM_NOINST_CHUNKED_BINARY_HPP
| 28.474747 | 81 | 0.671515 | [
"vector"
] |
35a182445770fb0bdc2a25d1fc202f37ada295b9 | 7,001 | cc | C++ | chrome/browser/sync/test/integration/two_client_web_apps_integration_sync_test.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/test/integration/two_client_web_apps_integration_sync_test.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/test/integration/two_client_web_apps_integration_sync_test.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/barrier_closure.h"
#include "base/path_service.h"
#include "base/test/bind.h"
#include "chrome/browser/sync/test/integration/apps_helper.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/ui/views/web_apps/web_app_integration_browsertest_base.h"
#include "chrome/browser/web_applications/test/web_app_install_observer.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_sync_bridge.h"
#include "content/public/test/browser_test.h"
#include "services/network/public/cpp/network_switches.h"
namespace web_app {
namespace {
const std::string kTestCaseFileName =
"web_app_integration_browsertest_sync_cases.csv";
// Returns the path of the requested file in the test data directory.
base::FilePath GetTestFileDir() {
base::FilePath file_path;
base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
file_path = file_path.Append(FILE_PATH_LITERAL("chrome"));
file_path = file_path.Append(FILE_PATH_LITERAL("test"));
file_path = file_path.Append(FILE_PATH_LITERAL("data"));
return file_path.Append(FILE_PATH_LITERAL("web_apps"));
}
std::vector<std::string> BuildAllPlatformTestCaseSet() {
return WebAppIntegrationBrowserTestBase::BuildAllPlatformTestCaseSet(
GetTestFileDir(), kTestCaseFileName);
}
} // anonymous namespace
class TwoClientWebAppsIntegrationSyncTest
: public SyncTest,
public WebAppIntegrationBrowserTestBase::TestDelegate,
public testing::WithParamInterface<std::string> {
public:
TwoClientWebAppsIntegrationSyncTest() : SyncTest(TWO_CLIENT), helper_(this) {}
// WebAppIntegrationBrowserTestBase::TestDelegate
Browser* CreateBrowser(Profile* profile) override {
return InProcessBrowserTest::CreateBrowser(profile);
}
void AddBlankTabAndShow(Browser* browser) override {
InProcessBrowserTest::AddBlankTabAndShow(browser);
}
net::EmbeddedTestServer* EmbeddedTestServer() override {
return embedded_test_server();
}
std::vector<Profile*> GetAllProfiles() override {
return SyncTest::GetAllProfiles();
}
bool UserSigninInternal() override { return SyncTest::SetupSync(); }
void TurnSyncOff() override {
for (auto* client : GetSyncClients()) {
client->StopSyncServiceAndClearData();
}
}
void TurnSyncOn() override {
for (auto* client : GetSyncClients()) {
ASSERT_TRUE(client->StartSyncService());
}
ASSERT_TRUE(AwaitQuiescence());
AwaitWebAppQuiescence();
}
WebAppIntegrationBrowserTestBase helper_;
private:
// InProcessBrowserTest
void SetUp() override {
helper_.SetUp(GetChromeTestDataDir());
SyncTest::SetUp();
}
// BrowserTestBase
void SetUpOnMainThread() override {
SyncTest::SetUpOnMainThread();
ASSERT_TRUE(SetupClients());
helper_.SetUpOnMainThread();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
SyncTest::SetUpCommandLine(command_line);
ASSERT_TRUE(embedded_test_server()->Start());
command_line->AppendSwitchASCII(
network::switches::kUnsafelyTreatInsecureOriginAsSecure,
helper_.GetInstallableAppURL().GetOrigin().spec());
command_line->AppendSwitch("disable-fake-server-failure-output");
}
// Helpers
void AwaitWebAppQuiescence() {
// Wait until all pending app installs and uninstalls have finished.
std::vector<std::unique_ptr<WebAppInstallObserver>> install_observers;
std::vector<std::unique_ptr<WebAppInstallObserver>> uninstall_observers;
for (auto* profile : GetAllProfiles()) {
install_observers.push_back(SetupSyncInstallObserverForProfile(profile));
uninstall_observers.push_back(
SetupSyncUninstallObserverForProfile(profile));
}
for (const auto& observer : install_observers) {
if (!observer) {
continue;
}
// This actually waits for all observed apps to be installed.
observer->AwaitNextInstall();
}
for (const auto& observer : uninstall_observers) {
if (!observer) {
continue;
}
// This actually waits for all observed apps to be uninstalled.
WebAppInstallObserver::AwaitNextUninstall(observer.get());
}
for (auto* profile : GetAllProfiles()) {
DCHECK(GetAppIdsToBeSyncInstalledForProfile(profile).empty());
std::set<AppId> apps_in_sync_uninstall =
helper_.GetProviderForProfile(profile)
->registry_controller()
.AsWebAppSyncBridge()
->GetAppsInSyncUninstallForTest();
DCHECK(apps_in_sync_uninstall.empty());
}
}
std::set<AppId> GetAppIdsToBeSyncInstalledForProfile(Profile* profile) {
WebAppRegistrar* registrar =
helper_.GetProviderForProfile(profile)->registrar().AsWebAppRegistrar();
// Make sure that |registrar| is a WebAppRegistrar instance.
DCHECK(registrar);
std::vector<AppId> profile_apps = registrar->GetAppsInSyncInstall();
return std::set<AppId>(profile_apps.begin(), profile_apps.end());
}
bool SetupClients() override {
if (!SyncTest::SetupClients()) {
return false;
}
for (Profile* profile : GetAllProfiles()) {
auto* web_app_provider = WebAppProvider::Get(profile);
base::RunLoop loop;
web_app_provider->on_registry_ready().Post(FROM_HERE, loop.QuitClosure());
loop.Run();
}
return true;
}
std::unique_ptr<WebAppInstallObserver> SetupSyncInstallObserverForProfile(
Profile* profile) {
std::set<AppId> apps_to_be_sync_installed =
GetAppIdsToBeSyncInstalledForProfile(profile);
if (apps_to_be_sync_installed.empty()) {
return nullptr;
}
return WebAppInstallObserver::CreateInstallListener(
profile, apps_to_be_sync_installed);
}
std::unique_ptr<WebAppInstallObserver> SetupSyncUninstallObserverForProfile(
Profile* profile) {
base::flat_map<Profile*, std::unique_ptr<WebAppInstallObserver>> output;
std::set<AppId> apps_in_sync_uninstall =
helper_.GetProviderForProfile(profile)
->registry_controller()
.AsWebAppSyncBridge()
->GetAppsInSyncUninstallForTest();
if (apps_in_sync_uninstall.empty()) {
return nullptr;
}
return WebAppInstallObserver::CreateUninstallListener(
profile, apps_in_sync_uninstall);
}
};
IN_PROC_BROWSER_TEST_P(TwoClientWebAppsIntegrationSyncTest, Default) {
helper_.ParseParams(GetParam());
for (const auto& action : helper_.testing_actions()) {
helper_.ExecuteAction(action);
}
}
INSTANTIATE_TEST_SUITE_P(All,
TwoClientWebAppsIntegrationSyncTest,
testing::ValuesIn(BuildAllPlatformTestCaseSet()));
} // namespace web_app
| 33.023585 | 82 | 0.724896 | [
"vector"
] |
35b7278e06fd966b199c3fa33a3ef9b0a300f75d | 2,740 | cxx | C++ | odb-tests-2.4.0/pgsql/types/driver.cxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/pgsql/types/driver.cxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/pgsql/types/driver.cxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | // file : pgsql/types/driver.cxx
// copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC
// license : GNU GPL v2; see accompanying LICENSE file
// Test PostgreSQL type conversion.
//
#include <memory> // std::auto_ptr
#include <cassert>
#include <iostream>
#include <odb/pgsql/database.hxx>
#include <odb/pgsql/transaction.hxx>
#include <common/common.hxx>
#include "test.hxx"
#include "test-odb.hxx"
using namespace std;
namespace pgsql = odb::pgsql;
using namespace pgsql;
int
main (int argc, char* argv[])
{
try
{
auto_ptr<database> db (create_specific_database<database> (argc, argv));
object o (1);
o.bool_ = true;
o.short_ = 12345;
o.int_ = -123456;
o.long_long_ = 123456;
o.float_ = 1.123F;
o.float8_ = 1.123;
o.double_ = 1.123;
o.date_ = 4015;
o.time_ = 48180000000LL;
o.timestamp_ = 346896000LL;
string short_str (128, 's');
string medium_str (250, 'm');
string long_str (2040, 'l');
o.char_ = short_str;
o.varchar_ = medium_str;
o.text_ = long_str;
o.bytea_.assign (long_str.c_str (), long_str.c_str () + long_str.size ());
unsigned char varbit_buf[8] = {1, 3, 1, 3, 1, 3, 1, 3};
o.varbit_.size = 52;
o.varbit_.ubuffer_ = ubuffer (varbit_buf, 8);
o.bit_.a = 0;
o.bit_.b = 1;
o.bit_.c = 0;
o.bit_.d = 1;
// 6F846D41-C89A-4E4D-B22F-56443CFA543F
memcpy (o.uuid_, "\x6F\x84\x6D\x41\xC8\x9A\x4E\x4D\xB2\x2F"
"\x56\x44\x3C\xFA\x54\x3F", 16);
o.enum_ = green;
// Persist.
//
{
transaction t (db->begin ());
db->persist (o);
t.commit ();
}
// Load.
//
{
transaction t (db->begin ());
auto_ptr<object> o1 (db->load<object> (1));
t.commit ();
assert (o == *o1);
}
// Test char array.
//
{
char_array o1 (1, "");
char_array o2 (2, "1234567890");
char_array o3 (3, "1234567890123456");
{
transaction t (db->begin ());
db->persist (o1);
db->persist (o2);
db->persist (o3);
t.commit ();
}
// PostgreSQL returns padded values for CHAR(N).
//
memcpy (o1.s2, " ", 16);
o1.s3[0] = o1.c1 = ' ';
memcpy (o2.s2, "1234567890 ", 16);
{
transaction t (db->begin ());
auto_ptr<char_array> p1 (db->load<char_array> (1));
auto_ptr<char_array> p2 (db->load<char_array> (2));
auto_ptr<char_array> p3 (db->load<char_array> (3));
t.commit ();
assert (o1 == *p1);
assert (o2 == *p2);
assert (o3 == *p3);
}
}
}
catch (const odb::exception& e)
{
cerr << e.what () << endl;
return 1;
}
}
| 21.076923 | 78 | 0.544891 | [
"object"
] |
35bef3ba851b9281359c5cf48a2da8f8ae1abea6 | 34,040 | cpp | C++ | src/kernels/cpu/math_cpu.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/kernels/cpu/math_cpu.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/kernels/cpu/math_cpu.cpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by kier on 2018/7/19.
//
#include "kernels/cpu/math_cpu.h"
#include "kernels/common/math.h"
#include "utils/assert.h"
#include "runtime/inside/thread_pool.h"
#include "utils/ctxmgr.h"
#include "utils/box.h"
#include <iostream>
#include <cmath>
#include <runtime/inside/parallel.h>
#include "kernels/common/openmp.h"
#include "kernels/common/simd.h"
#include <core/dtype.h>
#include <core/tensor.h>
namespace ts {
namespace cpu {
template<typename T_IN,typename T_OUT>
inline T_OUT inline_dot(int N, const T_IN *x, int incx, const T_IN *y, int incy) {
T_OUT sum = 0;
const int BLOCK = 4;
int BODY = N / BLOCK, TAIL = N % BLOCK;
for (; BODY; --BODY) {
sum += *x * *y; x += incx; y += incy;
sum += *x * *y; x += incx; y += incy;
sum += *x * *y; x += incx; y += incy;
sum += *x * *y; x += incx; y += incy;
}
for (; TAIL; --TAIL) {
sum += *x * *y; x += incx; y += incy;
}
return sum;
}
#ifdef TS_USE_SIMD
template <>
inline float inline_dot<float,float>(int N, const float *x, int incx, const float *y, int incy) {
const auto incx1 = incx;
const auto incx2 = incx1 + incx;
const auto incx3 = incx2 + incx;
const auto incx4 = incx3 + incx;
const auto incy1 = incy;
const auto incy2 = incy1 + incy;
const auto incy3 = incy2 + incy;
const auto incy4 = incy3 + incy;
float sum = 0;
int i = 0;
float32x4 sumx4 = 0;
for (; i < N - 3; i += 4) {
sumx4 += float32x4(x[0], x[incx1], x[incx2], x[incx3]) * float32x4(y[0], y[incy1], y[incy2], y[incy3]);
x += incx4;
y += incy4;
}
sum = ts::sum(sumx4);
for (; i < N; ++i) {
sum += *x * *y;
x += incx;
y += incy;
}
return sum;
}
#endif
template<typename T_IN>
inline void inline_zero(int N, T_IN *x, int incx) {
if (incx == 1) {
std::memset(x, 0, N * sizeof(T_IN));
return;
}
TS_PARALLEL_RANGE_BEGIN(range, 0, N)
auto xx = x + range.first * incx;
const auto count = range.second - range.first;
int i = 0;
for (; i < count - 3; i += 4) {
*xx = 0; xx += incx;
*xx = 0; xx += incx;
*xx = 0; xx += incx;
*xx = 0; xx += incx;
}
for (; i < count; ++i) {
*xx = 0; xx += incx;
}
TS_PARALLEL_RANGE_END()
}
template<typename T_IN>
inline void inline_scal(int N, T_IN alpha, T_IN *x, int incx) {
if (ts::near(alpha, T_IN(1))) return; // TODO: update float number equal check method
if (ts::near(alpha, T_IN(0))) {
inline_zero<T_IN>(N, x, incx);
return;
}
// use thread
TS_PARALLEL_RANGE_BEGIN(range, 0, N)
auto xx = x + range.first * incx;
const auto count = range.second - range.first;
int i = 0;
for (; i < count - 3; i += 4) {
*xx *= alpha; xx += incx;
*xx *= alpha; xx += incx;
*xx *= alpha; xx += incx;
*xx *= alpha; xx += incx;
}
for (; i < count; ++i) {
*xx *= alpha; xx += incx;
}
TS_PARALLEL_RANGE_END()
}
template<typename T_IN,typename T_OUT>
T_OUT math<T_IN,T_OUT>::dot(int N, const T_IN *x, int incx, const T_IN *y, int incy) {
std::vector<T_OUT> parallel_sum(TS_PARALLEL_SIZE, T_OUT(0));
TS_PARALLEL_RANGE_BEGIN(range, 0, N)
auto xx = x + range.first * incx;
auto yy = y + range.first * incy;
const auto count = range.second - range.first;
parallel_sum[__parallel_id] += inline_dot<T_IN,T_OUT>(count, xx, incx, yy, incy);
TS_PARALLEL_RANGE_END()
T_OUT sum = 0;
for (auto value : parallel_sum) sum += value;
return sum;
}
template<typename T_IN,typename T_OUT>
inline void inline_gemm_row_major(
blas::Transpose TransA,
blas::Transpose TransB,
int M, int N, int K,
T_IN alpha,
const T_IN *A, int lda,
const T_IN *B, int ldb,
T_IN beta,
T_OUT *C, int ldc) {
// TODO: check if lda, ldb, ldc use correct
TS_AUTO_CHECK(lda >= (TransA == blas::NoTrans ? K : M));
TS_AUTO_CHECK(ldb >= (TransB == blas::NoTrans ? N : K));
TS_AUTO_CHECK(ldc >= N);
//auto gun = try_threads_on(size_t(M), 4);
// calculate beta * C
// C is RowMajor
if (ldc == N) inline_scal<T_OUT>(M * N, beta, C, 1);
else {
TS_PARALLEL_FOR_BEGIN(m, 0, M)
auto CC = &C[m * ldc];
inline_scal<T_OUT>(N, beta, CC, 1);
TS_PARALLEL_FOR_END()
}
if (ts::near(alpha, T_IN(0))) return;
unsigned int condition = (TransA == blas::NoTrans ? 0U : 1U) | ((TransB == blas::NoTrans ? 0U : 2U));
switch (condition) {
case 0: // A: NoTrans, B: NoTrans
TS_PARALLEL_FOR_BEGIN(i, 0, M)
T_OUT *C_anchor = &C[i * ldc];
for (int j = 0; j < N; ++j) {
*C_anchor += alpha * inline_dot<T_IN, T_OUT>(K, &A[i * lda], 1, &B[j], ldb);
C_anchor++;
}
TS_PARALLEL_FOR_END()
break;
case 1: // A: Trans, B: NoTrans
TS_PARALLEL_FOR_BEGIN(i, 0, M)
T_OUT *C_anchor = &C[i * ldc];
for (int j = 0; j < N; ++j) {
*C_anchor += alpha * inline_dot<T_IN, T_OUT>(K, &A[i], lda, &B[j], ldb);
C_anchor++;
}
TS_PARALLEL_FOR_END()
break;
case 2: // A: NoTrans, B: Trans
TS_PARALLEL_FOR_BEGIN(i, 0, M)
T_OUT *C_anchor = &C[i * ldc];
for (int j = 0; j < N; ++j) {
*C_anchor += alpha * inline_dot<T_IN, T_OUT>(K, &A[i * lda], 1, &B[j * ldb], 1);
C_anchor++;
}
TS_PARALLEL_FOR_END()
break;
default: // A: Trans, B: Trans
TS_PARALLEL_FOR_BEGIN(i, 0, M)
T_OUT *C_anchor = &C[i * ldc];
for (int j = 0; j < N; ++j) {
*C_anchor += alpha * inline_dot<T_IN, T_OUT>(K, &A[i], lda, &B[j * ldb], 1);
C_anchor++;
}
TS_PARALLEL_FOR_END()
break;
}
}
// TODO: it has deviation in some case, when N, M, K is large
template<typename T_IN,typename T_OUT>
void
math<T_IN,T_OUT>::gemm(
blas::Order Order,
blas::Transpose TransA,
blas::Transpose TransB,
int M, int N, int K,
T_IN alpha,
const T_IN *A, int lda,
const T_IN *B, int ldb,
T_IN beta,
T_OUT *C, int ldc) {
if (Order == blas::ColMajor) {
inline_gemm_row_major<T_IN, T_OUT>(TransB, TransA, N, M, K, alpha, B, ldb, A, lda, beta, C, ldc);
} else {
inline_gemm_row_major<T_IN, T_OUT>(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
}
template<typename T_IN,typename T_OUT>
T_OUT math<T_IN,T_OUT>::dot(int N, const T_IN *x, const T_IN *y) {
return dot(N, x, 1, y, 1);
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::gemm(blas::Transpose TransA, blas::Transpose TransB, int M, int N, int K, T_IN alpha, const T_IN *A,
const T_IN *B, T_IN beta, T_OUT *C) {
int lda = (TransA == blas::NoTrans ? K : M);
int ldb = (TransB == blas::NoTrans ? N : K);
int ldc = N;
inline_gemm_row_major<T_IN, T_OUT>(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::pack8_A(int row, int col, const T_IN *from, int lda, T_IN *to) {
int out_loop = row >> 3;
int remain = out_loop << 3;
//T_OUT* to_at = to;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int nn = 0; nn < out_loop; nn++) {
int n = nn * 8;
const T_IN* k0 = from + n * lda;
const T_IN* k1 = k0 + lda;
const T_IN* k2 = k1 + lda;
const T_IN* k3 = k2 + lda;
const T_IN* k4 = k3 + lda;
const T_IN* k5 = k4 + lda;
const T_IN* k6 = k5 + lda;
const T_IN* k7 = k6 + lda;
T_IN* to_at = to + n * col;
for (int i = 0; i < col; i++) {
*to_at++ = *k0++;
*to_at++ = *k1++;
*to_at++ = *k2++;
*to_at++ = *k3++;
*to_at++ = *k4++;
*to_at++ = *k5++;
*to_at++ = *k6++;
*to_at++ = *k7++;
}
}
//NOTE:Maybe i should pack 4x4 on remain size
//to_at = to + remain * col;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int n = remain; n < row; n++) {
const T_IN* k0 = from + n * lda;
T_IN* to_at = to + n * col;
for (int i = 0; i < col; i++) {
*to_at++ = *k0++;
}
}
}
template<typename T_IN, typename T_OUT>
inline void inline_pack8_B(int row, int col, const T_IN *from, int ldb, T_IN *to) {
int out_loop = col >> 3;
int remain = out_loop << 3;
//T_OUT* to_at = to;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int nn = 0; nn < out_loop; nn++) {
int n = nn * 8;
const T_IN* from_at = from + n;
T_IN* to_at = to + n * row;
for (int i = 0; i < row; i++) {
*to_at++ = from_at[0];
*to_at++ = from_at[1];
*to_at++ = from_at[2];
*to_at++ = from_at[3];
*to_at++ = from_at[4];
*to_at++ = from_at[5];
*to_at++ = from_at[6];
*to_at++ = from_at[7];
from_at += ldb;
}
}
//to_at = to + remain * row;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int n = remain; n < col; n++) {
const T_IN* from_at = from + n;
T_IN* to_at = to + n * row;
for (int i = 0; i < row; i++) {
*to_at++ = from_at[0];
from_at += ldb;
}
}
}
template<>
inline void inline_pack8_B<float, float>(int row, int col, const float *from, int ldb, float *to) {
int out_loop = col >> 3;
int remain = out_loop << 3;
//float* to_at = to;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int nn = 0; nn < out_loop; nn++) {
int n = nn * 8;
const float* from_at = from + n;
float* to_at = to + n * row;
for (int i = 0; i < row; i++) {
float32x4x2 from_at_x4x2(from_at);
from_at_x4x2.store(to_at);
from_at += ldb;
to_at += 8;
}
}
//to_at = to + remain * row;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int n = remain; n < col; n++) {
const float* from_at = from + n;
float* to_at = to + n * row;
for (int i = 0; i < row; i++) {
*to_at++ = from_at[0];
from_at += ldb;
}
}
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::pack8_B(int row, int col, const T_IN *from, int ldb, T_IN *to) {
inline_pack8_B<T_IN, T_OUT>(row, col, from, ldb, to);
}
template<typename T_IN, typename T_OUT>
inline void kernel_8x8(int M, int K, int N, T_IN alpha, const T_IN *A, const T_IN *B, T_IN beta, T_OUT *C, int ldc) {
}
template<>
inline void kernel_8x8<float, float>(int M, int K, int N, float alpha, const float *A, const float *B, float beta, float *C, int ldc) {
const float* p_A = A;
const float* p_B = B;
float* p_C = C;
int out_loop = M >> 3;
int remain = out_loop << 3;
float* output_at = p_C;
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int mm = 0; mm < out_loop; mm++) {
int m = mm * 8;
float* output_row0 = output_at + m * ldc;
float* output_row1 = output_row0 + ldc;
float* output_row2 = output_row1 + ldc;
float* output_row3 = output_row2 + ldc;
float* output_row4 = output_row3 + ldc;
float* output_row5 = output_row4 + ldc;
float* output_row6 = output_row5 + ldc;
float* output_row7 = output_row6 + ldc;
const float* A_store = p_A + m * K;
int n_loop = N >> 3;
int n_remain = n_loop << 3;
for (int nn = 0; nn < n_loop; nn++)
{
int n = nn * 8;
const float* A_at = A_store;
const float* B_at = p_B + n * K;
float32x4x2 c0(0.f), c1(0.f), c2(0.f), c3(0.f);
float32x4x2 c4(0.f), c5(0.f), c6(0.f), c7(0.f);
int k_loop = K >> 2;
int k_remain = k_loop << 2;
for (int kk = 0; kk < k_loop; kk++) {
//=====================pack_gemm k==0=====================
float32x4x2 k0 = broadcast2float32x4x2(A_at); //[k00,k00,k00,k00,k00,k00,k00,k00]
float32x4x2 k1 = broadcast2float32x4x2(A_at + 1); //[k10,k10,k10,k10,k10,k10,k10,k10]
float32x4x2 k2 = broadcast2float32x4x2(A_at + 2); //[k20,k20,k20,k20,k20,k20,k20,k20]
float32x4x2 k3 = broadcast2float32x4x2(A_at + 3); //[k30,k30,k30,k30,k30,k30,k30,k30]
float32x4x2 a0(B_at); //[a00,a01,a02,a03,a04,a05,a06,a07]
c0 = fmadd(a0, k0, c0);
c1 = fmadd(a0, k1, c1);
c2 = fmadd(a0, k2, c2);
c3 = fmadd(a0, k3, c3);
//Note:The number of registers is limited
k0 = broadcast2float32x4x2(A_at + 4); //[k40,k40,k40,k40,k40,k40,k40,k40]
k1 = broadcast2float32x4x2(A_at + 5); //[k50,k50,k50,k50,k50,k50,k50,k50]
k2 = broadcast2float32x4x2(A_at + 6); //[k60,k60,k60,k60,k60,k60,k60,k60]
k3 = broadcast2float32x4x2(A_at + 7); //[k70,k70,k70,k70,k70,k70,k70,k70]
c4 = fmadd(a0, k0, c4);
c5 = fmadd(a0, k1, c5);
c6 = fmadd(a0, k2, c6);
c7 = fmadd(a0, k3, c7);
//=====================pack_gemm k==1=====================
k0 = broadcast2float32x4x2(A_at + 8); //[k01,k01,k01,k01,k01,k01,k01,k01]
k1 = broadcast2float32x4x2(A_at + 9); //[k11,k11,k11,k11,k11,k11,k11,k11]
k2 = broadcast2float32x4x2(A_at + 10); //[k21,k21,k21,k21,k21,k21,k21,k21]
k3 = broadcast2float32x4x2(A_at + 11); //[k31,k31,k31,k31,k31,k31,k31,k31]
float32x4x2 a1(B_at + 8); //[a10,a11,a12,a13,a14,a15,a16,a17]
c0 = fmadd(a1, k0, c0);
c1 = fmadd(a1, k1, c1);
c2 = fmadd(a1, k2, c2);
c3 = fmadd(a1, k3, c3);
k0 = broadcast2float32x4x2(A_at + 12); //[k41,k41,k41,k41,k41,k41,k41,k41]
k1 = broadcast2float32x4x2(A_at + 13); //[k51,k51,k51,k51,k51,k51,k51,k51]
k2 = broadcast2float32x4x2(A_at + 14); //[k61,k61,k61,k61,k61,k61,k61,k61]
k3 = broadcast2float32x4x2(A_at + 15); //[k71,k71,k71,k71,k71,k71,k71,k71]
c4 = fmadd(a1, k0, c4);
c5 = fmadd(a1, k1, c5);
c6 = fmadd(a1, k2, c6);
c7 = fmadd(a1, k3, c7);
//=====================pack_gemm k==2=====================
k0 = broadcast2float32x4x2(A_at + 16); //[k02,k02,k02,k02,k02,k02,k02,k02]
k1 = broadcast2float32x4x2(A_at + 17); //[k12,k12,k12,k12,k12,k12,k12,k12]
k2 = broadcast2float32x4x2(A_at + 18); //[k22,k21,k21,k21,k21,k21,k21,k21]
k3 = broadcast2float32x4x2(A_at + 19); //[k32,k32,k32,k32,k32,k32,k32,k32]
float32x4x2 a2(B_at + 16); //[a20,a21,a22,a23,a24,a25,a26,a27]
c0 = fmadd(a2, k0, c0);
c1 = fmadd(a2, k1, c1);
c2 = fmadd(a2, k2, c2);
c3 = fmadd(a2, k3, c3);
k0 = broadcast2float32x4x2(A_at + 20); //[k42,k42,k42,k42,k42,k42,k42,k42]
k1 = broadcast2float32x4x2(A_at + 21); //[k52,k52,k52,k52,k52,k52,k52,k52]
k2 = broadcast2float32x4x2(A_at + 22); //[k62,k62,k62,k62,k62,k62,k62,k62]
k3 = broadcast2float32x4x2(A_at + 23); //[k72,k72,k72,k72,k72,k72,k72,k72]
c4 = fmadd(a2, k0, c4);
c5 = fmadd(a2, k1, c5);
c6 = fmadd(a2, k2, c6);
c7 = fmadd(a2, k3, c7);
//=====================pack_gemm k==3=====================
k0 = broadcast2float32x4x2(A_at + 24); //[k03,k03,k03,k03,k03,k03,k03,k03]
k1 = broadcast2float32x4x2(A_at + 25); //[k13,k13,k13,k13,k13,k13,k13,k13]
k2 = broadcast2float32x4x2(A_at + 26); //[k23,k23,k23,k23,k23,k23,k23,k23]
k3 = broadcast2float32x4x2(A_at + 27); //[k33,k33,k33,k33,k33,k33,k33,k33]
float32x4x2 a3(B_at + 24); //[a30,a31,a32,a33,a34,a35,a36,a37]
c0 = fmadd(a3, k0, c0);
c1 = fmadd(a3, k1, c1);
c2 = fmadd(a3, k2, c2);
c3 = fmadd(a3, k3, c3);
k0 = broadcast2float32x4x2(A_at + 28); //[k43,k43,k43,k43,k43,k43,k43,k43]
k1 = broadcast2float32x4x2(A_at + 29); //[k53,k53,k53,k53,k53,k53,k53,k53]
k2 = broadcast2float32x4x2(A_at + 30); //[k63,k63,k63,k63,k63,k63,k63,k63]
k3 = broadcast2float32x4x2(A_at + 31); //[k73,k73,k73,k73,k73,k73,k73,k73]
c4 = fmadd(a3, k0, c4);
c5 = fmadd(a3, k1, c5);
c6 = fmadd(a3, k2, c6);
c7 = fmadd(a3, k3, c7);
A_at += 32;
B_at += 32;
}
for (int k = k_remain; k < K; k++) {
float32x4x2 k0 = broadcast2float32x4x2(A_at); //[k00,k00,k00,k00,k00,k00,k00,k00]
float32x4x2 k1 = broadcast2float32x4x2(A_at + 1); //[k10,k10,k10,k10,k10,k10,k10,k10]
float32x4x2 k2 = broadcast2float32x4x2(A_at + 2); //[k20,k20,k20,k20,k20,k20,k20,k20]
float32x4x2 k3 = broadcast2float32x4x2(A_at + 3); //[k30,k30,k30,k30,k30,k30,k30,k30]
float32x4x2 a0(B_at); //[a00,a01,a02,a03,a04,a05,a06,a07]
c0 = fmadd(a0, k0, c0);
c1 = fmadd(a0, k1, c1);
c2 = fmadd(a0, k2, c2);
c3 = fmadd(a0, k3, c3);
k0 = broadcast2float32x4x2(A_at + 4); //[k40,k40,k40,k40,k40,k40,k40,k40]
k1 = broadcast2float32x4x2(A_at + 5); //[k50,k50,k50,k50,k50,k50,k50,k50]
k2 = broadcast2float32x4x2(A_at + 6); //[k60,k60,k60,k60,k60,k60,k60,k60]
k3 = broadcast2float32x4x2(A_at + 7); //[k70,k70,k70,k70,k70,k70,k70,k70]
c4 = fmadd(a0, k0, c4);
c5 = fmadd(a0, k1, c5);
c6 = fmadd(a0, k2, c6);
c7 = fmadd(a0, k3, c7);
A_at += 8;
B_at += 8;
}
c0.store(output_row0); c1.store(output_row1);
c2.store(output_row2); c3.store(output_row3);
c4.store(output_row4); c5.store(output_row5);
c6.store(output_row6); c7.store(output_row7);
output_row0 += 8; output_row1 += 8;
output_row2 += 8; output_row3 += 8;
output_row4 += 8; output_row5 += 8;
output_row6 += 8; output_row7 += 8;
}
for (int n = n_remain; n < N; n++)
{
const float* A_at = A_store;
const float* B_at = p_B + n * K;
float32x4x2 sum_col0(0.f), sum_col1(0.f), sum_col2(0.f), sum_col3(0.f);
float32x4x2 sum_col(0.f);
int k_loop = K >> 2;
int k_remain = k_loop << 2;
for (int kk = 0; kk < k_loop; kk++) {
// int k = kk * 4;
float32x4x2 a0 = broadcast2float32x4x2(B_at); //[a00,a00,a00,a00,a00,a00,a00,a00]
float32x4x2 a1 = broadcast2float32x4x2(B_at + 1); //[a10,a10,a10,a10,a10,a10,a10,a10]
float32x4x2 a2 = broadcast2float32x4x2(B_at + 2); //[a20,a20,a20,a20,a20,a20,a20,a20]
float32x4x2 a3 = broadcast2float32x4x2(B_at + 3); //[a30,a30,a30,a30,a30,a30,a30,a30]
float32x4x2 k0(A_at); //[k00,k10,k20,k30,k40,k50,k60,k70]
float32x4x2 k1(A_at + 8); //[k01,k11,k21,k31,k41,k51,k61,k71]
float32x4x2 k2(A_at + 16); //[k02,k12,k22,k32,k42,k52,k62,k72]
float32x4x2 k3(A_at + 24); //[k03,k13,k23,k33,k43,k53,k63,k73]
sum_col0 = fmadd(k0, a0, sum_col0);
sum_col1 = fmadd(k1, a1, sum_col1);
sum_col2 = fmadd(k2, a2, sum_col2);
sum_col3 = fmadd(k3, a3, sum_col3);
A_at += 32;
B_at += 4;
}
sum_col0 += sum_col1;
sum_col2 += sum_col3;
sum_col += sum_col0;
sum_col += sum_col2;
for (int k = k_remain; k < K; k++) {
float32x4x2 a0 = broadcast2float32x4x2(B_at); //[a00,a00,a00,a00,a00,a00,a00,a00]
float32x4x2 k0(A_at); //[k00,k10,k20,k30,k40,k50,k60,k70]
sum_col = fmadd(k0, a0, sum_col);
A_at += 8;
B_at += 1;
}
*output_row0++ = *((float*)&sum_col.value);
*output_row1++ = *(((float*)&sum_col.value) + 1);
*output_row2++ = *(((float*)&sum_col.value) + 2);
*output_row3++ = *(((float*)&sum_col.value) + 3);
*output_row4++ = *(((float*)&sum_col.value) + 4);
*output_row5++ = *(((float*)&sum_col.value) + 5);
*output_row6++ = *(((float*)&sum_col.value) + 6);
*output_row7++ = *(((float*)&sum_col.value) + 7);
}
}
#ifdef TS_USE_OPENMP
#pragma omp parallel for num_threads(openmp_threads())
#endif
for (int m = remain; m < M; m++) {
float* output_row0 = output_at + m * ldc;
const float* A_store = p_A + m * K;
int n_loop = N >> 3;
int n_remain = n_loop << 3;
for (int nn = 0; nn < n_loop; nn++) {
int n = nn * 8;
const float* A_at = A_store;
const float* B_at = p_B + n * K;
float32x4x2 c0(0.f);
int k_loop = K >> 2;
int k_remain = k_loop << 2;
for (int kk = 0; kk < k_loop; kk++) {
float32x4x2 k0 = broadcast2float32x4x2(A_at); //[k00,k00,k00,k00,k00,k00,k00,k00]
float32x4x2 k1 = broadcast2float32x4x2(A_at + 1); //[k01,k01,k01,k01,k01,k01,k01,k01]
float32x4x2 k2 = broadcast2float32x4x2(A_at + 2); //[k02,k02,k02,k02,k02,k02,k02,k02]
float32x4x2 k3 = broadcast2float32x4x2(A_at + 3); //[k03,k03,k03,k03,k03,k03,k03,k03]
float32x4x2 a0(B_at); //[a00,a01,a02,a03,a04,a05,a06,a07]
float32x4x2 a1(B_at + 8); //[a10,a11,a12,a13,a14,a15,a16,a17]
float32x4x2 a2(B_at + 16); //[a20,a21,a22,a23,a24,a25,a26,a27]
float32x4x2 a3(B_at + 24); //[a30,a31,a32,a33,a34,a35,a36,a37]
c0 = fmadd(k0, a0, c0);
c0 = fmadd(k1, a1, c0);
c0 = fmadd(k2, a2, c0);
c0 = fmadd(k3, a3, c0);
A_at += 4;
B_at += 32;
}
for (int k = k_remain; k < K; k++) {
float32x4x2 k0 = broadcast2float32x4x2(A_at); //[k00,k00,k00,k00,k00,k00,k00,k00]
float32x4x2 a0(B_at); //[a00,a01,a02,a03,a04,a05,a06,a07]
c0 = fmadd(k0, a0, c0);
A_at += 1;
B_at += 8;
}
c0.store(output_row0);
output_row0 += 8;
}
for (int n = n_remain; n < N; n++) {
float32x4 c0(0.f);
float sum0 = 0;
const float* A_at = A_store;
const float* B_at = p_B + n * K;
int k_loop = K >> 2;
int k_remain = k_loop << 2;
for (int kk = 0; kk < k_loop; kk++) {
// int k = kk * 4;
float32x4 k0(A_at);
float32x4 a0(B_at);
c0 = fmadd(k0, a0, c0);
A_at += 4;
B_at += 4;
}
sum0 = ts::sum(c0);
for (int k = k_remain; k < K; k++) {
sum0 += (*A_at) * (*B_at);
A_at++;
B_at++;
}
*output_row0 = sum0;
output_row0++;
}
}
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::gemm(int M, int N, int K, T_IN alpha, const T_IN *A, const T_IN *B,
T_IN beta, T_OUT *C, bool A_need_pack, bool B_need_pack) {
Tensor A_packed;
Tensor B_packed;
if (A_need_pack) {
A_packed = Tensor(Tensor::InFlow::HOST, dtypeid<T_IN>::id, {int32_t(M * K),});
}
if (B_need_pack) {
B_packed = Tensor(Tensor::InFlow::HOST, dtypeid<T_IN>::id, {int32_t(N * K),});
}
self::gemm(M, N, K, alpha, A, A_packed.data<T_IN>(), B, B_packed.data<T_IN>(), beta, C, A_need_pack, B_need_pack);
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::gemm(int M, int N, int K, T_IN alpha, const T_IN *A, T_IN *A_packed, const T_IN *B, T_IN *B_packed,
T_IN beta, T_OUT *C, bool A_need_pack, bool B_need_pack) {
if (!ts::near(alpha, T_IN(1)) || !ts::near(beta, T_IN(0))) {
TS_LOG_ERROR << "alpha should be one and beta should be zero now!"<< eject;
}
if (A_need_pack) {
math<T_IN, T_OUT>::pack8_A(M, K, A, K, A_packed);
}
if (B_need_pack) {
math<T_IN, T_OUT>::pack8_B(K, N, B, N, B_packed);
}
if (A_need_pack && B_need_pack) {
kernel_8x8<T_IN, T_OUT>(M, K, N, alpha, A_packed, B_packed, beta, C, N);
}
else if (A_need_pack && !B_need_pack) {
kernel_8x8<T_IN, T_OUT>(M, K, N, alpha, A_packed, B, beta, C, N);
}
else if (!A_need_pack && B_need_pack) {
kernel_8x8<T_IN, T_OUT>(M, K, N, alpha, A, B_packed, beta, C, N);
}
else {
kernel_8x8<T_IN, T_OUT>(M, K, N, alpha, A, B, beta, C, N);
}
}
template<typename T_IN, typename T_OUT>
inline T_OUT inline_asum(int N, const T_IN *x, int incx) {
T_OUT sum = 0;
// block: 4
int i = 0;
static const int block_size = 4;
int blocked_N = N % block_size ? N - block_size : N;
for (; i < blocked_N; i += block_size) {
sum += abs(*x); x += incx;
sum += abs(*x); x += incx;
sum += abs(*x); x += incx;
sum += abs(*x); x += incx;
}
for (; i < N; ++i) {
sum += abs(*x); x += incx;
}
return sum;
}
template<typename T_IN, typename T_OUT>
T_OUT math<T_IN, T_OUT>::asum(int N, const T_IN *x, int incx) {
std::vector<T_OUT> parallel_sum(TS_PARALLEL_SIZE, T_OUT(0));
TS_PARALLEL_RANGE_BEGIN(range, 0, N)
const T_IN *xx = x + range.first * incx;
const auto count = range.second - range.first;
parallel_sum[__parallel_id] += inline_asum<T_IN, T_OUT>(count, xx, incx);
TS_PARALLEL_RANGE_END()
T_OUT sum = 0;
for (auto value : parallel_sum) sum += value;
return sum;
}
template<typename T_IN, typename T_OUT>
T_OUT math<T_IN, T_OUT>::abs(T_IN val) {
return T_OUT(std::fabs(val));
}
template<typename T_IN, typename T_OUT>
void math<T_IN, T_OUT>::matrix_transpose(const T_IN* A, T_OUT* B, int m, int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
B[i*m + j] = A[j*n + i];
}
}
}
}
}
template class ts::cpu::math<ts::dtype<ts::FLOAT32>::declare, ts::dtype<ts::FLOAT32>::declare>;
template class ts::cpu::math<ts::dtype<ts::FLOAT64>::declare, ts::dtype<ts::FLOAT64>::declare>;
template class ts::cpu::math<ts::dtype<ts::INT8>::declare, ts::dtype<ts::INT32>::declare>; | 42.710163 | 143 | 0.418684 | [
"vector"
] |
35c08bd63600871700b5505ce8f31f7283f2a838 | 2,901 | cpp | C++ | api-cpp-validator/src/OrganizationValidator.cpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp-validator/src/OrganizationValidator.cpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | api-cpp-validator/src/OrganizationValidator.cpp | nuralogix/dfx-api-client-cpp | 6b45307ddf4b0036c107eebd7e8915f6c501c3b0 | [
"MIT"
] | null | null | null | // Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
#include "dfx/api/validator/OrganizationValidator.hpp"
#include "CloudValidatorMacros.hpp"
using namespace dfx::api;
using namespace dfx::api::validator;
const OrganizationValidator& OrganizationValidator::instance()
{
static const OrganizationValidator instance;
return instance;
}
CloudStatus OrganizationValidator::create(const CloudConfig& config,
const std::string& name,
const std::string& identifier,
const std::string& public_key,
const dfx::api::OrganizationStatus& status,
const std::string& logo,
std::string& organizationID)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
MACRO_RETURN_ERROR_IF_EMPTY(name);
MACRO_RETURN_ERROR_IF_EMPTY(identifier);
MACRO_RETURN_ERROR_IF_EMPTY(public_key);
MACRO_RETURN_ERROR_IF_EMPTY(logo);
return CloudStatus(CLOUD_OK);
}
CloudStatus OrganizationValidator::list(const CloudConfig& config,
const std::unordered_map<OrganizationFilter, std::string>& filters,
uint16_t offset,
std::vector<dfx::api::Organization>& organizations,
int16_t& totalCount)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
return CloudStatus(CLOUD_OK);
}
CloudStatus OrganizationValidator::retrieve(const CloudConfig& config,
const std::string& organizationID,
dfx::api::Organization& organization)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
MACRO_RETURN_ERROR_IF_EMPTY(organizationID);
return CloudStatus(CLOUD_OK);
}
CloudStatus OrganizationValidator::retrieveMultiple(const CloudConfig& config,
const std::vector<std::string>& organizationIDs,
std::vector<dfx::api::Organization>& organizations)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
MACRO_RETURN_ERROR_IF_EMPTY(organizationIDs);
return CloudStatus(CLOUD_OK);
}
CloudStatus OrganizationValidator::update(const CloudConfig& config, dfx::api::Organization& organization)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
return CloudStatus(CLOUD_OK);
}
CloudStatus OrganizationValidator::remove(const CloudConfig& config, const std::string& organizationID)
{
MACRO_RETURN_ERROR_IF_NO_USER_TOKEN(config);
MACRO_RETURN_ERROR_IF_EMPTY(organizationID);
return CloudStatus(CLOUD_OK);
}
| 40.291667 | 107 | 0.632196 | [
"vector"
] |
35cdf17de53ae14ba991d659552c775df29b3a02 | 299 | cpp | C++ | Arrays/Maximum_Subarray_Leetcode.cpp | AK-aShH/DSA-Practice | 625215232669260cf333eac46baa1cb0287aac03 | [
"MIT"
] | null | null | null | Arrays/Maximum_Subarray_Leetcode.cpp | AK-aShH/DSA-Practice | 625215232669260cf333eac46baa1cb0287aac03 | [
"MIT"
] | null | null | null | Arrays/Maximum_Subarray_Leetcode.cpp | AK-aShH/DSA-Practice | 625215232669260cf333eac46baa1cb0287aac03 | [
"MIT"
] | null | null | null |
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int l=nums.size();
int s=-10001, ts=0;
for(int i=0;i<l;i++){
ts+=nums[i];
if(ts>s)
s=ts;
if(ts<0)
ts=0;
}return s;
}
};
| 18.6875 | 40 | 0.371237 | [
"vector"
] |
35cfab76b697d5bceef462254b4c2f9b5f5b34de | 19,290 | tpp | C++ | projects/Viz/include/Viz/Traversals/programmable.tpp | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | projects/Viz/include/Viz/Traversals/programmable.tpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | projects/Viz/include/Viz/Traversals/programmable.tpp | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z |
#include "jsonxx.h"
extern void build_sage_name_variant_map(std::map<std::string, VariantT> & name_variant_map);
extern void build_sage_variant_name_map(std::map<VariantT, std::string> & variant_name_map);
extern void build_sage_parent_variant_map(std::map<VariantT, VariantT> & parent_variant_map);
namespace Rose {
namespace Viz {
namespace Traversals {
template <class InheritedAttr, class SynthesizedAttr>
Programmable<InheritedAttr, SynthesizedAttr>::Program::Program() :
name_variant_map(), variant_name_map(), parent_variant_map(),
graph_title(""), graph_color("black"), graph_style(e_none), graph_rankdir(e_top_bottom), graph_ranksep(1),
cluster_label_map(), cluster_color_map(), cluster_style_map(), cluster_pen_width_map(),
cluster_default_label(""), cluster_default_color("black"), cluster_default_style(e_none), cluster_default_pen_width(1),
edge_default_label(""), edge_default_color("black"), edge_default_style(e_none), edge_default_min_len(1), edge_default_pen_width(1), edge_default_constraint(true),
node_label_map(), node_color_map(), node_style_map(), node_shape_map(), node_fill_color_map(), node_pen_width_map()
{
node_label_map.insert(std::pair<VariantT, std::string>((VariantT)SgNode::static_variant, ""));
node_color_map.insert(std::pair<VariantT, std::string>((VariantT)SgNode::static_variant, "black"));
node_style_map.insert(std::pair<VariantT, style_e>((VariantT)SgNode::static_variant, e_filled));
node_shape_map.insert(std::pair<VariantT, std::string>((VariantT)SgNode::static_variant, "box"));
node_fill_color_map.insert(std::pair<VariantT, std::string>((VariantT)SgNode::static_variant, "white"));
node_pen_width_map.insert(std::pair<VariantT, float>((VariantT)SgNode::static_variant, 1));
build_sage_name_variant_map(name_variant_map);
build_sage_variant_name_map(variant_name_map);
build_sage_parent_variant_map(parent_variant_map);
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::Program::open(const std::string & file) {
std::ifstream viz_file;
viz_file.open(file.c_str());
assert(viz_file.is_open());
jsonxx::Object viz;
viz.parse(viz_file);
jsonxx::Object & graph = viz.get<jsonxx::Object>("graph");
graph_color = graph.get<jsonxx::String>("color");
graph_style = styleFromString(graph.get<jsonxx::String>("style"));
graph_rankdir = rankDirFromString(graph.get<jsonxx::String>("rankdir"));
graph_ranksep = graph.get<jsonxx::Number>("ranksep");
jsonxx::Object & edge = viz.get<jsonxx::Object>("edge");
jsonxx::Object & edge_default = edge.get<jsonxx::Object>("default");
edge_default_label = edge_default.get<jsonxx::String >("label");
edge_default_color = edge_default.get<jsonxx::String >("color");
edge_default_style = styleFromString(edge_default.get<jsonxx::String >("style"));
edge_default_min_len = edge_default.get<jsonxx::Number >("min_len");
edge_default_pen_width = edge_default.get<jsonxx::Number >("pen_width");
edge_default_constraint = edge_default.get<jsonxx::Boolean>("constraint");
jsonxx::Object & cluster = viz.get<jsonxx::Object>("cluster");
jsonxx::Object & cluster_default = edge.get<jsonxx::Object>("default");
cluster_default_label = cluster_default.get<jsonxx::String >("label");
cluster_default_color = cluster_default.get<jsonxx::String >("color");
cluster_default_style = styleFromString(cluster_default.get<jsonxx::String >("style"));
cluster_default_pen_width = cluster_default.get<jsonxx::Number >("pen_width");
const std::map<std::string, jsonxx::Value *> & cluster_map = cluster.get<jsonxx::Object>("map").kv_map();
std::map<std::string, jsonxx::Value *>::const_iterator it_cluster;
for (it_cluster = cluster_map.begin(); it_cluster != cluster_map.end(); it_cluster++) {
jsonxx::Object & cluster_map_element = it_cluster->second->get<jsonxx::Object>();
cluster_label_map[it_cluster->first] = cluster_map_element.get<jsonxx::String >("label");
cluster_color_map[it_cluster->first] = cluster_map_element.get<jsonxx::String >("color");
cluster_style_map[it_cluster->first] = styleFromString(cluster_map_element.get<jsonxx::String >("style"));
cluster_pen_width_map[it_cluster->first] = cluster_map_element.get<jsonxx::Number >("pen_width");
}
jsonxx::Object & node = viz.get<jsonxx::Object>("node");
const std::map<std::string, jsonxx::Value *> & node_map = node.get<jsonxx::Object>("map").kv_map();
std::map<std::string, jsonxx::Value *>::const_iterator it_node;
for (it_node = node_map.begin(); it_node != node_map.end(); it_node++) {
VariantT variant = name_variant_map[it_node->first];
jsonxx::Object & node_map_element = it_node->second->get<jsonxx::Object>();
node_label_map[variant] = node_map_element.get<jsonxx::String >("label");
node_color_map[variant] = node_map_element.get<jsonxx::String >("color");
node_style_map[variant] = styleFromString(node_map_element.get<jsonxx::String >("style"));
node_shape_map[variant] = node_map_element.get<jsonxx::String >("shape");
node_fill_color_map[variant] = node_map_element.get<jsonxx::String >("fill_color");
node_pen_width_map[variant] = node_map_element.get<jsonxx::Number >("pen_width");
}
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::Program::setTitle(const std::string & title) {
graph_title = title;
}
template <class InheritedAttr, class SynthesizedAttr>
std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::toString(style_e style) {
switch (style) {
case e_none: return "";
case e_filled: return "filled";
case e_invisible: return "invis";
default: assert(false);
}
}
template <class InheritedAttr, class SynthesizedAttr>
std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::toString(rankdir_e rankdir) {
switch (rankdir) {
case e_top_bottom: return "TB";
case e_bottom_top: return "BT";
case e_left_right: return "LR";
case e_right_left: return "RL";
default: assert(false);
}
}
template <class InheritedAttr, class SynthesizedAttr>
typename Programmable<InheritedAttr, SynthesizedAttr>::Program::style_e Programmable<InheritedAttr, SynthesizedAttr>::Program::styleFromString(const std::string & str) {
if (str == "") return e_none;
else if (str == "filled") return e_filled;
else if (str == "invis" || str == "invisible") return e_invisible;
else assert(false);
}
template <class InheritedAttr, class SynthesizedAttr>
typename Programmable<InheritedAttr, SynthesizedAttr>::Program::rankdir_e Programmable<InheritedAttr, SynthesizedAttr>::Program::rankDirFromString(const std::string & str) {
if (str == "TB") return e_top_bottom;
else if (str == "BT") return e_bottom_top;
else if (str == "LR") return e_left_right;
else if (str == "RL") return e_right_left;
else assert(false);
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getGraphLabel() const {
return graph_title;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getGraphColor() const {
return graph_color;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getGraphStyle() const {
return toString(graph_style);
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getGraphRankDir() const {
return toString(graph_rankdir);
}
template <class InheritedAttr, class SynthesizedAttr>
const float Programmable<InheritedAttr, SynthesizedAttr>::Program::getGraphRankSep() const {
return graph_ranksep;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getClusterLabel(Objects::graph_t * graph) const {
int pos = graph->tag.find_first_of('_');
std::string prefix = graph->tag.substr(0, pos);
std::map<std::string, std::string>::const_iterator it = cluster_label_map.find(prefix);
if (it == cluster_label_map.end())
return cluster_default_label;
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getClusterColor(Objects::graph_t * graph) const {
int pos = graph->tag.find_first_of('_');
std::string prefix = graph->tag.substr(0, pos);
std::map<std::string, std::string>::const_iterator it = cluster_color_map.find(prefix);
if (it == cluster_color_map.end())
return cluster_default_color;
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getClusterStyle(Objects::graph_t * graph) const {
style_e style = cluster_default_style;
int pos = graph->tag.find_first_of('_');
std::string prefix = graph->tag.substr(0, pos);
typename std::map<std::string, style_e>::const_iterator it = cluster_style_map.find(prefix);
if (it != cluster_style_map.end())
style = it->second;
return toString(style);
}
template <class InheritedAttr, class SynthesizedAttr>
const float Programmable<InheritedAttr, SynthesizedAttr>::Program::getClusterPenWidth(Objects::graph_t * graph) const {
int pos = graph->tag.find_first_of('_');
std::string prefix = graph->tag.substr(0, pos);
std::map<std::string, float>::const_iterator it = cluster_pen_width_map.find(prefix);
if (it == cluster_pen_width_map.end())
return cluster_default_pen_width;
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgeLabel(SgNode * node, SgNode * parent) const {
return edge_default_label;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgeColor(SgNode * node, SgNode * parent) const {
return edge_default_color;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgeStyle(SgNode * node, SgNode * parent) const {
return toString(edge_default_style);
}
template <class InheritedAttr, class SynthesizedAttr>
const int Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgeMinLen(SgNode * node, SgNode * parent) const {
return edge_default_min_len;
}
template <class InheritedAttr, class SynthesizedAttr>
const float Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgePenWidth(SgNode * node, SgNode * parent) const {
return edge_default_pen_width;
}
template <class InheritedAttr, class SynthesizedAttr>
const bool Programmable<InheritedAttr, SynthesizedAttr>::Program::getEdgeConstraint(SgNode * node, SgNode * parent) const {
return edge_default_constraint;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodeLabel(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
std::map<VariantT, std::string>::const_iterator it = node_label_map.find(variant);
while (it == node_label_map.end() && variant != (VariantT)SgNode::static_variant) {
variant = parent_variant_map.at(variant);
it = node_label_map.find(variant);
}
assert(it != node_label_map.end());
std::string label = it->second;
if (!label.empty() && label[0] == '@') {
// TODO programmatic display
}
return label;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodeColor(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
//std::cerr << "[getNodeColor] node->class_name() = " << node->class_name() << std::endl;
std::map<VariantT, std::string>::const_iterator it = node_color_map.find(variant);
while (it == node_color_map.end() && variant != (VariantT)SgNode::static_variant) {
//std::cerr << "[getNodeColor] variant = " << variant << std::endl;
//std::cerr << "[getNodeColor] node = " << variant_name_map.at(variant) << std::endl;
variant = parent_variant_map.at(variant);
it = node_color_map.find(variant);
}
assert(it != node_color_map.end());
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodeStyle(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
//std::cerr << "[getNodeStyle] node->class_name() = " << node->class_name() << std::endl;
typename std::map<VariantT, style_e>::const_iterator it = node_style_map.find(variant);
while (it == node_style_map.end() && variant != (VariantT)SgNode::static_variant) {
//std::cerr << "[getNodeStyle] variant = " << variant << std::endl;
//std::cerr << "[getNodeStyle] node = " << variant_name_map.at(variant) << std::endl;
variant = parent_variant_map.at(variant);
it = node_style_map.find(variant);
}
assert(it != node_style_map.end());
return toString(it->second);
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodeShape(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
//std::cerr << "[getNodeShape] node->class_name() = " << node->class_name() << std::endl;
std::map<VariantT, std::string>::const_iterator it = node_shape_map.find(variant);
while (it == node_shape_map.end() && variant != (VariantT)SgNode::static_variant) {
//std::cerr << "[getNodeShape] variant = " << variant << std::endl;
//std::cerr << "[getNodeShape] node = " << variant_name_map.at(variant) << std::endl;
variant = parent_variant_map.at(variant);
it = node_shape_map.find(variant);
}
assert(it != node_shape_map.end());
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const std::string Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodeFillColor(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
//std::cerr << "[getNodeFillColor] node->class_name() = " << node->class_name() << std::endl;
std::map<VariantT, std::string>::const_iterator it = node_fill_color_map.find(variant);
while (it == node_fill_color_map.end() && variant != (VariantT)SgNode::static_variant) {
//std::cerr << "[getNodeFillColor] variant = " << variant << std::endl;
//std::cerr << "[getNodeFillColor] node = " << variant_name_map.at(variant) << std::endl;
variant = parent_variant_map.at(variant);
it = node_fill_color_map.find(variant);
}
assert(it != node_fill_color_map.end());
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
const float Programmable<InheritedAttr, SynthesizedAttr>::Program::getNodePenWidth(SgNode * node, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
VariantT variant = node->variantT();
//std::cerr << "[getNodePenWidth] node->class_name() = " << node->class_name() << std::endl;
std::map<VariantT, float>::const_iterator it = node_pen_width_map.find(variant);
while (it == node_pen_width_map.end() && variant != (VariantT)SgNode::static_variant) {
//std::cerr << "[getNodePenWidth] variant = " << variant << std::endl;
//std::cerr << "[getNodePenWidth] node = " << variant_name_map.at(variant) << std::endl;
variant = parent_variant_map.at(variant);
it = node_pen_width_map.find(variant);
}
assert(it != node_pen_width_map.end());
return it->second;
}
template <class InheritedAttr, class SynthesizedAttr>
Programmable<InheritedAttr, SynthesizedAttr>::Programmable(const Program & program_) :
Traversal<InheritedAttr, SynthesizedAttr>(),
program(program_)
{}
// Implements virtuals
template <class InheritedAttr, class SynthesizedAttr>
InheritedAttr Programmable<InheritedAttr, SynthesizedAttr>::evaluateInheritedAttribute(SgNode * node, InheritedAttr attr) {
InheritedAttr res;
return res;
}
template <class InheritedAttr, class SynthesizedAttr>
SynthesizedAttr Programmable<InheritedAttr, SynthesizedAttr>::evaluateSynthesizedAttribute(SgNode * node, InheritedAttr attr, StackFrameVector<SynthesizedAttr> attrs) {
SynthesizedAttr res;
return res;
}
template <class InheritedAttr, class SynthesizedAttr>
bool Programmable<InheritedAttr, SynthesizedAttr>::stopAfter(SgNode *) {
return false;
}
template <class InheritedAttr, class SynthesizedAttr>
bool Programmable<InheritedAttr, SynthesizedAttr>::skip(SgNode *) {
return false;
}
template <class InheritedAttr, class SynthesizedAttr>
Objects::graph_t * Programmable<InheritedAttr, SynthesizedAttr>::startOn(SgNode *) {
return NULL;
}
template <class InheritedAttr, class SynthesizedAttr>
Objects::graph_t * Programmable<InheritedAttr, SynthesizedAttr>::getSubgraph(SgNode * node, Objects::graph_t * graph) {
return graph;
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::edit(SgNode * node, Objects::node_desc_t & desc, const InheritedAttr & inhr_attr, const SynthesizedAttr & synth_attr) const {
desc.label = program.getNodeLabel(node, inhr_attr, synth_attr);
desc.color = program.getNodeColor(node, inhr_attr, synth_attr);
desc.style = program.getNodeStyle(node, inhr_attr, synth_attr);
desc.shape = program.getNodeShape(node, inhr_attr, synth_attr);
desc.fillcolor = program.getNodeFillColor(node, inhr_attr, synth_attr);
desc.penwidth = program.getNodePenWidth(node, inhr_attr, synth_attr);
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::edit(SgNode * node, SgNode * parent, Objects::edge_desc_t & desc) const {
desc.label = program.getEdgeLabel(node, parent);
desc.color = program.getEdgeColor(node, parent);
desc.style = program.getEdgeStyle(node, parent);
desc.minlen = program.getEdgeMinLen(node, parent);
desc.penwidth = program.getEdgePenWidth(node, parent);
desc.constraint = program.getEdgeConstraint(node, parent);
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::edit(Objects::graph_t * graph, Objects::cluster_desc_t & desc) const {
desc.label = program.getClusterLabel(graph);
desc.color = program.getClusterColor(graph);
desc.style = program.getClusterStyle(graph);
desc.penwidth = program.getClusterPenWidth(graph);
}
template <class InheritedAttr, class SynthesizedAttr>
void Programmable<InheritedAttr, SynthesizedAttr>::edit(Objects::graph_desc_t & desc) const {
desc.label = program.getGraphLabel();
desc.color = program.getGraphColor();
desc.style = program.getGraphStyle();
desc.rankdir = program.getGraphRankDir();
desc.ranksep = program.getGraphRankSep();
}
}
}
}
| 47.747525 | 181 | 0.746138 | [
"object",
"shape"
] |
35e6b6f0ce7585248a1c1f6eaade88f7ff03aafa | 2,303 | cpp | C++ | src/shaders/lightingshaderdemo.cpp | Alec-Sobeck/FPS-Game | 3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35 | [
"MIT"
] | null | null | null | src/shaders/lightingshaderdemo.cpp | Alec-Sobeck/FPS-Game | 3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35 | [
"MIT"
] | null | null | null | src/shaders/lightingshaderdemo.cpp | Alec-Sobeck/FPS-Game | 3a0f3e82bdbc651ee99e7b10d71d55ba43bb6d35 | [
"MIT"
] | 1 | 2015-02-04T23:29:59.000Z | 2015-02-04T23:29:59.000Z |
#include <sstream>
#include "shaders/lightingshaderdemo.h"
#include "graphics/gluhelper.h"
#include "graphics/windowhelper.h"
void LightingShaderDemo::render()
{
using namespace gl;
startRenderCycle();
glLoadIdentity();
//Draw
shader1->bindShader();
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -1.0f);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glEnd();
shader1->releaseShader();
swapBuffers();
endRenderCycle();
}
void LightingShaderDemo::init(int argc, char **argv)
{
using namespace gl;
int w = 1024;
int h = 768;
initFreeglut(argc, argv);
createWindow(100, 100, w, h, "Shader Demo");
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
setPerspective(45.0f, (static_cast<float>(w)/static_cast<float>(h)),0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
initLights();
std::string vertFilepath = "shaders/debug_vert_shader.vert";
std::string fragFilepath = "shaders/debug_frag_shader.frag";
shader1 = createShader(&vertFilepath, &fragFilepath);
shader1->glUniform1("numPointLights", numPointLights);
shader1->glUniform1("numDirectionLights", numDirectionLights);
for(int i = 0; i < numPointLights; i++)
{
std::stringstream ss;
ss << "pointLights[" << i << "]";
shader1->glUniform3(ss.str(), pointLights[i]);
}
for(int i = 0; i < numDirectionLights; i++)
{
std::stringstream ss;
ss << "directionLights[" << i << "]";
shader1->glUniform3(ss.str(), directionLights[i]);
}
}
void LightingShaderDemo::initLights()
{
numPointLights = 0;
numDirectionLights = 0;
pointLights = std::vector<glm::vec3>();
//Fill stuff in
directionLights = std::vector<glm::vec3>();
//Fill stuff in
}
void LightingShaderDemo::run(int argc, char **argv)
{
init(argc, argv);
while(!done)
{
render();
}
}
| 25.876404 | 85 | 0.633956 | [
"render",
"vector"
] |
e305f96c68ca6b3cebff5d93dc91805a494f9d8c | 742 | cpp | C++ | JContainers/src/basic_part.cpp | Verteiron/JContainers | a5c83198c782458a7c2ae683319558cc88959d25 | [
"MIT"
] | 1 | 2018-07-30T21:36:28.000Z | 2018-07-30T21:36:28.000Z | JContainers/src/basic_part.cpp | Verteiron/JContainers | a5c83198c782458a7c2ae683319558cc88959d25 | [
"MIT"
] | null | null | null | JContainers/src/basic_part.cpp | Verteiron/JContainers | a5c83198c782458a7c2ae683319558cc88959d25 | [
"MIT"
] | 1 | 2021-03-03T06:28:53.000Z | 2021-03-03T06:28:53.000Z |
#include <thread>
#include <mutex>
#include <chrono>
#include <algorithm>
#include <vector>
#include <atomic>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/version.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "rw_mutex.h"
#include "plugin_info.h"
#include "object_base.h"
#include "shared_state.h"
#include "id_generator.h"
#include "object_registry.h"
#include "autorelease_queue.h"
#include "object_base.hpp"
#include "shared_state.hpp"
namespace collections
{
} | 18.097561 | 48 | 0.773585 | [
"vector"
] |
e313c444da66bbe05bc10bda297fdf7a8a70e3fa | 7,155 | cpp | C++ | CPlusPlus/Random Program/Main.cpp | BillyFrcs/CPPPrograming | 3904d30413aaea6c9109b8c5250c44c67aa0fc20 | [
"MIT"
] | 3 | 2021-12-17T02:45:51.000Z | 2022-03-31T23:55:38.000Z | CPlusPlus/Random Program/Main.cpp | BillyFrcs/Programming | 32dc67ce4c12189b56921de63446d79c25799457 | [
"MIT"
] | 1 | 2021-06-12T08:28:38.000Z | 2021-06-12T08:28:38.000Z | CPlusPlus/Random Program/Main.cpp | BillyFrcs/Programming | 32dc67ce4c12189b56921de63446d79c25799457 | [
"MIT"
] | 2 | 2021-04-28T20:08:55.000Z | 2021-05-25T08:45:54.000Z | #include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>
constexpr bool EXT = true;
using namespace std;
class Crud
{
private:
//Max limits data
const int maxRow = 20;
std::string namaMahasiswa[20], npmMahasiswa[20];
public:
// tambahkan data
virtual void addData()
{
char nama[50];
char NPM[13];
std::cin.ignore();
std::cout << "Nama Mahasiswa: ";
std::cin.getline(nama, 50);
std::cout << "NPM Mahasiswa (Max 12 Digits): ";
std::cin.getline(NPM, 13);
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] == "\0") && (namaMahasiswa[x] == "\0"))
{
namaMahasiswa[x] = nama;
npmMahasiswa[x] = NPM;
break;
}
}
}
//Update or change Data
void updateData(std::string search)
{
char nama[50];
char npm[13];
int counter = 0;
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] == search) || (npmMahasiswa[x] == search))
{
counter++;
std::cout << "Nama baru mahasiswa: ";
std::cin.getline(nama, 50);
std::cout << "NPM baru mahasiswa: ";
std::cin.getline(npm, 13);
namaMahasiswa[x] = nama;
npmMahasiswa[x] = npm;
std::cout << "Update berhasil!" << std::endl;
break;
}
}
if (counter == 0)
{
std::cout << "Tidak valid!" << std::endl;
}
}
//Delete or remove data
void deleteData(std::string search)
{
int counter = 0;
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] == search) || (namaMahasiswa[x] == search))
{
counter++;
namaMahasiswa[x] = "";
npmMahasiswa[x] = "";
std::cout << "Penghapusan sukses" << std::endl;
}
}
if (counter == 0)
{
std::cout << "Invalid!" << std::endl;
}
}
//Display list data
virtual void displayListData()
{
system("cls");
std::cout << "Lists Data Mahasiswa \n";
std::cout << "========================================\n";
std::cout << "No\t\t|Nama\t\t|NPM\t\t" << std::endl;
std::cout << "----------------------------------------\n";
int counter = 0;
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] != "\0") && (npmMahasiswa[x] != "\0"))
{
counter++;
std::cout << counter << ""
<< "\t\t" << namaMahasiswa[x] << "\t\t" << npmMahasiswa[x] << std::endl;
}
}
if (counter == 0)
{
std::cout << "Data tidak ada \n";
}
std::cout << "========================================\n\n";
}
//Searching data
void searchingData(std::string search);
//Open file CRUD
void openFileCrud();
//Save file CRUD
void saveFileCrud();
};
void Crud::searchingData(string search)
{
system("cls");
cout << "Hasil Pencarian Data Mahasiswa \n";
cout << "========================================\n";
cout << "No\t\t|Nama\t\t|NPM\t\t" << endl;
cout << "---------------------------------------\n";
int counter = 0;
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] == search) || (npmMahasiswa[x] == search))
{
counter++;
cout << counter << ""
<< "\t\t" << namaMahasiswa[x] << "\t\t" << npmMahasiswa[x] << endl;
break;
}
}
if (counter == 0)
{
cout << "Pencarian tidak ditemukan! \n";
}
cout << "========================================\n\n";
}
void Crud::openFileCrud()
{
string line;
ifstream crudFile("DataMahasiswa.txt");
if (crudFile.is_open())
{
int x = 0;
while (getline(crudFile, line))
{
int l = line.length();
namaMahasiswa[x] = line.substr(0, 12); //0, 3
npmMahasiswa[x] = line.substr(0, l - 12); //4, l - 4
x++;
}
}
}
void Crud::saveFileCrud()
{
//Saving file .txt
ofstream crudFile;
crudFile.open("DataMahasiswa.txt"); //This can change with another file location
for (int x = 0; x < maxRow; x++)
{
if ((namaMahasiswa[x] == "\0") && (npmMahasiswa[x] == "\0"))
{
break;
}
else
{
crudFile << namaMahasiswa[x] + "," + npmMahasiswa[x] << endl;
}
}
if (EXT == true)
{
//Save data
cout << "Exit and saving file...\n";
exit(EXT); //Function from stdlib.h header
}
}
int main(void)
{
//Object heap memory
Crud *crud = new Crud;
system("cls");
//User select menu
int options;
string cariData;
do
{
cout << "====Program CRUD Data Mahasiswa====" << endl;
cout << "1. Tambahkan Data" << endl;
cout << "2. Perbarui Data" << endl;
cout << "3. Hapus Data" << endl;
cout << "4. Cari Data" << endl;
cout << "5. Perlihatkan Data" << endl;
cout << "6. Keluar & Simpan" << endl;
cout << "=========================" << endl
<< endl;
cout << "Pilih Menu: ";
cin >> options;
//All crud data conditions
switch (options)
{
// Tambahkan data
case 1:
crud->addData();
system("cls");
break;
// Perbarui data
case 2:
cin.ignore();
cout << "Update nama atau NPM: ";
getline(cin, cariData);
crud->updateData(cariData);
system("cls");
break;
// Hapus data
case 3:
cin.ignore();
cout << "Hapus nama atau NPM: ";
getline(cin, cariData);
crud->deleteData(cariData);
system("cls");
break;
// cari data
case 4:
cin.ignore();
cout << "Search by name or ID: ";
getline(cin, cariData);
crud->searchingData(cariData);
break;
// perlihatkan semua data
case 5:
crud->displayListData();
break;
default:
std::cout << "Tidak ditemukan! \n";
break;
}
} while (options != 100);
return EXIT_SUCCESS;
} | 23.613861 | 102 | 0.396087 | [
"object"
] |
e3150f424093132d8e28fe83969b4319e78b4cf4 | 5,094 | cc | C++ | path-tracer/core/node.cc | sdao/path-tracer-nacl | abb3eb0a51059e5109b87bafd7de60a8d4055453 | [
"BSD-2-Clause"
] | null | null | null | path-tracer/core/node.cc | sdao/path-tracer-nacl | abb3eb0a51059e5109b87bafd7de60a8d4055453 | [
"BSD-2-Clause"
] | null | null | null | path-tracer/core/node.cc | sdao/path-tracer-nacl | abb3eb0a51059e5109b87bafd7de60a8d4055453 | [
"BSD-2-Clause"
] | null | null | null | #include "node.h"
#include <exception>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include "scene.h"
using boost::format;
Node::Node(const boost::property_tree::ptree& attr, const Scene& cont)
: attributes(attr), container(cont) {}
std::string Node::getString(std::string key) const {
auto result = attributes.get_optional<std::string>(key);
if (!result) {
throw std::runtime_error(
str(format("Cannot read string property '%1%'") % key)
);
}
return *result;
}
int Node::getInt(std::string key) const {
auto result = attributes.get_optional<int>(key);
if (!result) {
throw std::runtime_error(
str(format("Cannot read integer property '%1%'") % key)
);
}
return *result;
}
bool Node::getBool(std::string key) const {
auto result = attributes.get_optional<bool>(key);
if (!result) {
throw std::runtime_error(
str(format("Cannot read boolean property '%1%'") % key)
);
}
return *result;
}
float Node::getFloat(std::string key) const {
auto result = attributes.get_optional<float>(key);
if (!result) {
throw std::runtime_error(
str(format("Cannot read float property '%1%'") % key)
);
}
return *result;
}
Vec Node::getVec(std::string key) const {
const NodeVecTranslator t;
auto result = attributes.get_optional<Vec, NodeVecTranslator>(key, t);
if (!result) {
throw std::runtime_error(
str(format("Cannot read vector property '%1%'") % key)
);
}
return *result;
}
const AreaLight* Node::getLight(std::string key) const {
using NodeLightTranslator = Node::NodeLookupTranslator<const AreaLight*>;
const NodeLightTranslator t(container.lights);
auto result =
attributes.get_optional<const AreaLight*, NodeLightTranslator>(key, t);
if (!result) {
const std::string itemName = attributes.get<std::string>(key);
const std::string msg =
"Cannot resolve light reference '%1%' in property '%2%'";
throw std::runtime_error(str(format(msg) % itemName % key));
}
return *result;
}
const Material* Node::getMaterial(std::string key) const {
using NodeMaterialTranslator = Node::NodeLookupTranslator<const Material*>;
const NodeMaterialTranslator t(container.materials);
auto result =
attributes.get_optional<const Material*, NodeMaterialTranslator>(key, t);
if (!result) {
const std::string itemName = attributes.get<std::string>(key);
const std::string msg =
"Cannot resolve material reference '%1%' in property '%2%'";
throw std::runtime_error(str(format(msg) % itemName % key));
}
return *result;
}
const Geom* Node::getGeometry(std::string key) const {
using NodeGeometryTranslator = Node::NodeLookupTranslator<const Geom*>;
const NodeGeometryTranslator t(container.geometry);
auto result =
attributes.get_optional<const Geom*, NodeGeometryTranslator>(key, t);
if (!result) {
const std::string itemName = attributes.get<std::string>(key);
const std::string msg =
"Cannot resolve geometry reference '%1%' in property '%2%'";
throw std::runtime_error(str(format(msg) % itemName % key));
}
return *result;
}
std::vector<const Geom*> Node::getGeometryList(std::string key) const {
using NodeGeometryTranslator = Node::NodeLookupTranslator<const Geom*, false>;
const NodeGeometryTranslator t(container.geometry);
const auto& listRoot = attributes.get_child_optional(key);
if (!listRoot) {
throw std::runtime_error(str(format("Cannot read list '%1%'") % key));
}
std::vector<const Geom*> result;
for (const auto& listItem : *listRoot) {
const auto item = listItem.second.get_value_optional<const Geom*>(t);
if (!item) {
const std::string itemName = listItem.second.get_value<std::string>();
const std::string msg =
"Cannot resolve geometry reference '%1%' in list '%2%'";
throw std::runtime_error(str(format(msg) % itemName % key));
}
result.push_back(*item);
}
return result;
}
Node::NodeVecTranslator::NodeVecTranslator() {}
boost::optional<Vec> Node::NodeVecTranslator::get_value(
const std::string& data
) const {;
std::vector<std::string> tokens;
boost::algorithm::split(
tokens,
data,
boost::is_space(),
boost::token_compress_on
);
if (tokens.size() != 3) {
return boost::optional<Vec>();
}
Vec result;
try {
result[0] = std::stof(tokens[0]);
result[1] = std::stof(tokens[1]);
result[2] = std::stof(tokens[2]);
} catch (...) {
return boost::optional<Vec>();
}
return boost::optional<Vec>(result);
}
template <typename T, bool allowNull>
Node::NodeLookupTranslator<T, allowNull>::NodeLookupTranslator(
const std::map<std::string, T>& l
) : lookup(l) {}
template <typename T, bool allowNull>
boost::optional<T> Node::NodeLookupTranslator<T, allowNull>::get_value(
const std::string& data
) const {
if (data.length() == 0 && allowNull) {
return boost::optional<T>(nullptr);
} else if (lookup.count(data) != 0) {
return boost::optional<T>(lookup.at(data));
}
return boost::optional<T>();
}
| 26.393782 | 80 | 0.670985 | [
"geometry",
"vector"
] |
e315ee4aabede16b5a9e54f9418ad1655bcaa2a6 | 546 | hpp | C++ | caffparser/header/parser.hpp | Jezus-es-a-haverok/CaffShop | 222f9945e77228ecc8fa73c9bb4fad8799af0825 | [
"MIT"
] | null | null | null | caffparser/header/parser.hpp | Jezus-es-a-haverok/CaffShop | 222f9945e77228ecc8fa73c9bb4fad8799af0825 | [
"MIT"
] | null | null | null | caffparser/header/parser.hpp | Jezus-es-a-haverok/CaffShop | 222f9945e77228ecc8fa73c9bb4fad8799af0825 | [
"MIT"
] | null | null | null | #ifndef FILE_PARSER_HPP
#define FILE_PARSER_HPP
#include <vector>
#include <string>
/**
* @file
*/
#include <caff.hpp>
/** Parses the given CAFF file.
* Creates a CAFF class in the heap, calls it's parse function and returns it to
* the caller. The CAFF class contains the gathered data, it's getter methods can
* can be used to get them.
* @see CAFF::parse()
* @param caffByte is the whole CAFF file in memory.
* @param length is the length of the file.
*/
CAFF parse(char* caffByte, uint64_t length);
#endif /* FILE_PARSER_HPP */
| 22.75 | 81 | 0.708791 | [
"vector"
] |
e31ca08675474531c6e2653886f5d056edd6b2b2 | 3,075 | cpp | C++ | src/main/algorithms/cpp/array/kth_largest_element_in_a_stream_703/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/cpp/array/kth_largest_element_in_a_stream_703/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | src/main/algorithms/cpp/array/kth_largest_element_in_a_stream_703/solution.cpp | algorithmlover2016/leet_code | 2eecc7971194c8a755e67719d8f66c636694e7e9 | [
"Apache-2.0"
] | null | null | null | #include "../../head.h"
// #define DEBUG
class KthLargest {
public:
KthLargest(int k_, std::vector<int> const & nums_) : k(k_), nums(nums_) {
}
int add(int val) {
nums.emplace_back(val);
// quickSort(nums, 0, nums.size() - 1);
quickSortDD(nums, 0, nums.size() - 1);
#ifdef DEBUG
for (int idx = 0; idx < nums.size(); idx++) {
std::cout << nums[idx] << "\t";
}
std::cout << "\n";
#endif
int targetIdx = nums.size() - k;
return nums[targetIdx];
}
private:
void quickSortDD(std::vector<int> & nums, int left, int right) {
if (left >= right) {
return ;
}
int low = left, high = right;
int mid = nums[left + (right - left) / 2];
while (left < right) {
while (nums[left] < mid) {
left++;
}
while (nums[right] > mid) {
right--;
}
if (left <= right) {
std::swap(nums[left++], nums[right--]);
}
}
quickSortDD(nums, low, right);
quickSortDD(nums, left, high);
}
void quickSort(std::vector<int> & nums, int left, int right) {
if (left >= right) {
return ;
}
int pIdx = partition(nums, left, right);
// int pIdx = partitionDD(nums, left, right);
quickSort(nums, left, pIdx - 1);
quickSort(nums, pIdx + 1, right);
}
int partitionDD(std::vector<int> & nums, int left, int right) {
// can't deal with same elements in nums,
// which means each element only appear once
int num = nums[right];
while (left < right) {
while (left < right && nums[left] < num) {
left++;
}
while (right > left && nums[right] > num) {
right--;
}
std::swap(nums[left], nums[right]);
}
return left;
}
int partition(std::vector<int> & nums, int left, int right) {
int num = nums[right];
for (int idx = left; idx < right; idx++) {
if (nums[idx] <= num) {
std::swap(nums[left++], nums[idx]);
}
}
std::swap(nums[left], nums[right]);
return left;
}
private:
int k = 0;
std::vector<int> nums;
};
#define DEBUG
class KthLargest {
public:
KthLargest(int k_, std::vector<int> const & nums) : k(k_) {
// plagiarizing from https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/149050/Java-Priority-Queue
for (int idx = 0; idx < nums.size(); idx++) {
minHeap.emplace(nums[idx]);
if (minHeap.size() > k) {
minHeap.pop();
}
}
}
int add(int val) {
minHeap.emplace(val);
if (minHeap.size() > k) {
minHeap.pop();
}
return minHeap.top();
}
private:
int k = 0;
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
};
| 26.059322 | 125 | 0.478049 | [
"vector"
] |
e31eae96f932b14be7192bb7b56fe7b5a34238b3 | 2,625 | cpp | C++ | tools/ShaderHeaderProcessor.cpp | Pratool/learning-vulkan | 616a0c331f0af62b4ff974f643fc033742f1f7d9 | [
"MIT"
] | null | null | null | tools/ShaderHeaderProcessor.cpp | Pratool/learning-vulkan | 616a0c331f0af62b4ff974f643fc033742f1f7d9 | [
"MIT"
] | null | null | null | tools/ShaderHeaderProcessor.cpp | Pratool/learning-vulkan | 616a0c331f0af62b4ff974f643fc033742f1f7d9 | [
"MIT"
] | null | null | null | #include <cmath>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <netinet/in.h>
/// This should process the binary SPIR-V file and put it into a std::array in a .cpp or .hpp file that can be
/// included in the main program.
void processFile(const std::string& inputFilename, const std::string& sourceFilename, const std::string& headerFilename,
const std::string& variableName)
{
std::ifstream input(inputFilename, std::ios::ate | std::ios::binary);
if (!input.is_open())
{
throw std::runtime_error("Failed to open file");
}
const auto fileSize = input.tellg();
std::vector<uint32_t> buffer(static_cast<uint32_t>(std::ceil(static_cast<float>(fileSize)/4.0f)));
input.seekg(0);
input.read(reinterpret_cast<char*>(buffer.data()), fileSize);
input.close();
std::ofstream output(sourceFilename);
std::ofstream header(headerFilename);
if (!output.is_open() || !header.is_open())
{
throw std::runtime_error("Failed to open file");
}
const std::string arrayType = [&buffer]() {
std::stringstream ss;
ss << "std::array<uint32_t, " << buffer.size() << "> ";
return ss.str();
}();
header << "#include <array>" << std::endl
<< arrayType << variableName << "();" << std::endl;
header.close();
output << "#include <array>" << std::endl
<< arrayType << variableName << "() { " << std::endl
<< arrayType << "shader = {" << std::endl;
int n = 0;
for (const auto& value : buffer)
{
output << "0x" << std::hex << std::setfill('0') << std::setw(8) << static_cast<uint32_t>(value) << ',';
if ((++n % 8) == 0)
{
output << std::endl;
}
else
{
output << ' ';
}
}
output << "};" << std::endl
<< "return shader;" << std::endl << "}";
output.close();
}
int main(int argc, char** argv)
{
if (argc != 9)
{
return 1;
}
std::string inputFilename;
std::string sourceFilename;
std::string variableName;
std::string headerFilename;
for (int idx = 1; idx < argc -1; idx += 2)
{
const auto arg = std::string{argv[idx]};
if (arg == "-i")
{
inputFilename = argv[idx+1];
}
else if (arg == "-o")
{
sourceFilename = argv[idx+1];
}
else if (arg == "-n")
{
variableName = argv[idx+1];
}
else if (arg == "-h")
{
headerFilename = argv[idx+1];
}
else
{
throw std::runtime_error("Invalid argument found");
}
}
processFile(inputFilename, sourceFilename, headerFilename, variableName);
return 0;
}
| 24.082569 | 120 | 0.583238 | [
"vector"
] |
e3252d27f96f8be0ad32f5feba9bb4c01b9ae93f | 38,425 | cc | C++ | chrome/browser/android/vr_shell/vr_shell_gl.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/android/vr_shell/vr_shell_gl.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/android/vr_shell/vr_shell_gl.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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/android/vr_shell/vr_shell_gl.h"
#include "base/android/jni_android.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/android/vr_shell/ui_elements.h"
#include "chrome/browser/android/vr_shell/ui_scene.h"
#include "chrome/browser/android/vr_shell/vr_controller.h"
#include "chrome/browser/android/vr_shell/vr_gl_util.h"
#include "chrome/browser/android/vr_shell/vr_input_manager.h"
#include "chrome/browser/android/vr_shell/vr_math.h"
#include "chrome/browser/android/vr_shell/vr_shell.h"
#include "chrome/browser/android/vr_shell/vr_shell_renderer.h"
#include "third_party/WebKit/public/platform/WebInputEvent.h"
#include "ui/gfx/vsync_provider.h"
#include "ui/gl/android/scoped_java_surface.h"
#include "ui/gl/android/surface_texture.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_surface.h"
#include "ui/gl/init/gl_factory.h"
namespace vr_shell {
namespace {
// Constant taken from treasure_hunt demo.
static constexpr long kPredictionTimeWithoutVsyncNanos = 50000000;
static constexpr float kZNear = 0.1f;
static constexpr float kZFar = 1000.0f;
// Screen angle in degrees. 0 = vertical, positive = top closer.
static constexpr float kDesktopScreenTiltDefault = 0;
static constexpr float kReticleWidth = 0.025f;
static constexpr float kReticleHeight = 0.025f;
static constexpr float kLaserWidth = 0.01f;
// Angle (radians) the beam down from the controller axis, for wrist comfort.
static constexpr float kErgoAngleOffset = 0.26f;
static constexpr gvr::Vec3f kOrigin = {0.0f, 0.0f, 0.0f};
// In lieu of an elbow model, we assume a position for the user's hand.
// TODO(mthiesse): Handedness options.
static constexpr gvr::Vec3f kHandPosition = {0.2f, -0.5f, -0.2f};
// If there is no content quad, and the reticle isn't hitting another element,
// draw the reticle at this distance.
static constexpr float kDefaultReticleDistance = 2.0f;
// Fraction of the distance to the object the cursor is drawn at to avoid
// rounding errors drawing the cursor behind the object.
static constexpr float kReticleOffset = 0.99f;
// Limit the rendering distance of the reticle to the distance to a corner of
// the content quad, times this value. This lets the rendering distance
// adjust according to content quad placement.
static constexpr float kReticleDistanceMultiplier = 1.5f;
// GVR buffer indices for use with viewport->SetSourceBufferIndex
// or frame.BindBuffer. We use one for world content (with reprojection)
// including main VrShell and WebVR content plus world-space UI.
// The headlocked buffer is for UI that should not use reprojection.
static constexpr int kFramePrimaryBuffer = 0;
static constexpr int kFrameHeadlockedBuffer = 1;
// Pixel dimensions and field of view for the head-locked content. This
// is currently sized to fit the WebVR "insecure transport" warnings,
// adjust it as needed if there is additional content.
static constexpr gvr::Sizei kHeadlockedBufferDimensions = {1024, 1024};
static constexpr gvr::Rectf kHeadlockedBufferFov = {20.f, 20.f, 20.f, 20.f};
// The GVR viewport list has two entries (left eye and right eye) for each
// GVR buffer.
static constexpr int kViewportListPrimaryOffset = 0;
static constexpr int kViewportListHeadlockedOffset = 2;
// Magic numbers used to mark valid pose index values encoded in frame
// data. Must match the magic numbers used in blink's VRDisplay.cpp.
static constexpr std::array<uint8_t, 2> kWebVrPosePixelMagicNumbers{{42, 142}};
float Distance(const gvr::Vec3f& vec1, const gvr::Vec3f& vec2) {
float xdiff = (vec1.x - vec2.x);
float ydiff = (vec1.y - vec2.y);
float zdiff = (vec1.z - vec2.z);
float scale = xdiff * xdiff + ydiff * ydiff + zdiff * zdiff;
return std::sqrt(scale);
}
// Generate a quaternion representing the rotation from the negative Z axis
// (0, 0, -1) to a specified vector. This is an optimized version of a more
// general vector-to-vector calculation.
gvr::Quatf GetRotationFromZAxis(gvr::Vec3f vec) {
vr_shell::NormalizeVector(vec);
gvr::Quatf quat;
quat.qw = 1.0f - vec.z;
if (quat.qw < 1e-6f) {
// Degenerate case: vectors are exactly opposite. Replace by an
// arbitrary 180 degree rotation to avoid invalid normalization.
quat.qx = 1.0f;
quat.qy = 0.0f;
quat.qz = 0.0f;
quat.qw = 0.0f;
} else {
quat.qx = vec.y;
quat.qy = -vec.x;
quat.qz = 0.0f;
vr_shell::NormalizeQuat(quat);
}
return quat;
}
std::unique_ptr<blink::WebMouseEvent> MakeMouseEvent(WebInputEvent::Type type,
double timestamp,
float x,
float y) {
std::unique_ptr<blink::WebMouseEvent> mouse_event(new blink::WebMouseEvent(
type, blink::WebInputEvent::NoModifiers, timestamp));
mouse_event->pointerType = blink::WebPointerProperties::PointerType::Mouse;
mouse_event->x = x;
mouse_event->y = y;
mouse_event->windowX = x;
mouse_event->windowY = y;
mouse_event->clickCount = 1;
return mouse_event;
}
enum class ViewerType {
UNKNOWN_TYPE = 0,
CARDBOARD = 1,
DAYDREAM = 2,
VIEWER_TYPE_MAX,
};
int GetPixelEncodedPoseIndexByte() {
TRACE_EVENT0("gpu", "VrShellGl::GetPixelEncodedPoseIndex");
// Read the pose index encoded in a bottom left pixel as color values.
// See also third_party/WebKit/Source/modules/vr/VRDisplay.cpp which
// encodes the pose index, and device/vr/android/gvr/gvr_device.cc
// which tracks poses. Returns the low byte (0..255) if valid, or -1
// if not valid due to bad magic number.
uint8_t pixels[4];
// Assume we're reading from the framebuffer we just wrote to.
// That's true currently, we may need to use glReadBuffer(GL_BACK)
// or equivalent if the rendering setup changes in the future.
glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Check for the magic number written by VRDevice.cpp on submit.
// This helps avoid glitches from garbage data in the render
// buffer that can appear during initialization or resizing. These
// often appear as flashes of all-black or all-white pixels.
if (pixels[1] == kWebVrPosePixelMagicNumbers[0] &&
pixels[2] == kWebVrPosePixelMagicNumbers[1]) {
// Pose is good.
return pixels[0];
}
VLOG(1) << "WebVR: reject decoded pose index " << (int)pixels[0] <<
", bad magic number " << (int)pixels[1] << ", " << (int)pixels[2];
return -1;
}
int64_t TimeInMicroseconds() {
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
void WaitForSwapAck(const base::Closure& callback, gfx::SwapResult result) {
callback.Run();
}
} // namespace
VrShellGl::VrShellGl(
const base::WeakPtr<VrShell>& weak_vr_shell,
const base::WeakPtr<VrInputManager>& content_input_manager,
const base::WeakPtr<VrInputManager>& ui_input_manager,
scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner,
gvr_context* gvr_api,
bool initially_web_vr,
bool reprojected_rendering)
: web_vr_mode_(initially_web_vr),
surfaceless_rendering_(reprojected_rendering),
task_runner_(base::ThreadTaskRunnerHandle::Get()),
weak_vr_shell_(weak_vr_shell),
content_input_manager_(content_input_manager),
ui_input_manager_(ui_input_manager),
main_thread_task_runner_(std::move(main_thread_task_runner)),
weak_ptr_factory_(this) {
GvrInit(gvr_api);
}
VrShellGl::~VrShellGl() {
draw_task_.Cancel();
}
void VrShellGl::Initialize() {
gvr::Mat4f identity;
SetIdentityM(identity);
webvr_head_pose_.resize(kPoseRingBufferSize, identity);
webvr_head_pose_valid_.resize(kPoseRingBufferSize, false);
scene_.reset(new UiScene);
if (surfaceless_rendering_) {
// If we're rendering surfaceless, we'll never get a java surface to render
// into, so we can initialize GL right away.
InitializeGl(nullptr);
}
}
void VrShellGl::InitializeGl(gfx::AcceleratedWidget window) {
CHECK(!ready_to_draw_);
if (gl::GetGLImplementation() == gl::kGLImplementationNone &&
!gl::init::InitializeGLOneOff()) {
LOG(ERROR) << "gl::init::InitializeGLOneOff failed";
ForceExitVr();
return;
}
if (window) {
CHECK(!surfaceless_rendering_);
surface_ = gl::init::CreateViewGLSurface(window);
} else {
CHECK(surfaceless_rendering_);
surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size());
}
if (!surface_.get()) {
LOG(ERROR) << "gl::init::CreateOffscreenGLSurface failed";
ForceExitVr();
return;
}
context_ = gl::init::CreateGLContext(nullptr, surface_.get(),
gl::GLContextAttribs());
if (!context_.get()) {
LOG(ERROR) << "gl::init::CreateGLContext failed";
ForceExitVr();
return;
}
if (!context_->MakeCurrent(surface_.get())) {
LOG(ERROR) << "gl::GLContext::MakeCurrent() failed";
ForceExitVr();
return;
}
// TODO(mthiesse): We don't appear to have a VSync provider ever here. This is
// sort of okay, because the GVR swap chain will block if we render too fast,
// but we should address this properly.
if (surface_->GetVSyncProvider()) {
surface_->GetVSyncProvider()->GetVSyncParameters(base::Bind(
&VrShellGl::UpdateVSyncParameters, weak_ptr_factory_.GetWeakPtr()));
} else {
LOG(ERROR) << "No VSync Provider";
}
unsigned int textures[2];
glGenTextures(2, textures);
ui_texture_id_ = textures[0];
content_texture_id_ = textures[1];
ui_surface_texture_ = gl::SurfaceTexture::Create(ui_texture_id_);
content_surface_texture_ = gl::SurfaceTexture::Create(content_texture_id_);
ui_surface_.reset(new gl::ScopedJavaSurface(ui_surface_texture_.get()));
content_surface_.reset(new gl::ScopedJavaSurface(
content_surface_texture_.get()));
ui_surface_texture_->SetFrameAvailableCallback(base::Bind(
&VrShellGl::OnUIFrameAvailable, weak_ptr_factory_.GetWeakPtr()));
content_surface_texture_->SetFrameAvailableCallback(base::Bind(
&VrShellGl::OnContentFrameAvailable, weak_ptr_factory_.GetWeakPtr()));
content_surface_texture_->SetDefaultBufferSize(
content_tex_physical_size_.width, content_tex_physical_size_.height);
ui_surface_texture_->SetDefaultBufferSize(ui_tex_physical_size_.width,
ui_tex_physical_size_.height);
main_thread_task_runner_->PostTask(FROM_HERE, base::Bind(
&VrShell::SurfacesChanged, weak_vr_shell_,
content_surface_->j_surface().obj(),
ui_surface_->j_surface().obj()));
InitializeRenderer();
draw_task_.Reset(base::Bind(&VrShellGl::DrawFrame, base::Unretained(this)));
ScheduleNextDrawFrame();
ready_to_draw_ = true;
}
void VrShellGl::OnUIFrameAvailable() {
ui_surface_texture_->UpdateTexImage();
}
void VrShellGl::OnContentFrameAvailable() {
content_surface_texture_->UpdateTexImage();
}
void VrShellGl::GvrInit(gvr_context* gvr_api) {
gvr_api_ = gvr::GvrApi::WrapNonOwned(gvr_api);
controller_.reset(new VrController(gvr_api));
ViewerType viewerType;
switch (gvr_api_->GetViewerType()) {
case gvr::ViewerType::GVR_VIEWER_TYPE_DAYDREAM:
viewerType = ViewerType::DAYDREAM;
break;
case gvr::ViewerType::GVR_VIEWER_TYPE_CARDBOARD:
viewerType = ViewerType::CARDBOARD;
break;
default:
NOTREACHED();
viewerType = ViewerType::UNKNOWN_TYPE;
break;
}
UMA_HISTOGRAM_ENUMERATION("VRViewerType", static_cast<int>(viewerType),
static_cast<int>(ViewerType::VIEWER_TYPE_MAX));
}
void VrShellGl::InitializeRenderer() {
// While WebVR is going through the compositor path, it shares
// the same texture ID. This will change once it gets its own
// surface, but store it separately to avoid future confusion.
// TODO(klausw,crbug.com/655722): remove this.
webvr_texture_id_ = content_texture_id_;
// Out of paranoia, explicitly reset the "pose valid" flags to false
// from the GL thread. The constructor ran in the UI thread.
// TODO(klausw,crbug.com/655722): remove this.
webvr_head_pose_valid_.assign(kPoseRingBufferSize, false);
gvr_api_->InitializeGl();
std::vector<gvr::BufferSpec> specs;
// For kFramePrimaryBuffer (primary VrShell and WebVR content)
specs.push_back(gvr_api_->CreateBufferSpec());
render_size_primary_ = specs[kFramePrimaryBuffer].GetSize();
// For kFrameHeadlockedBuffer (for WebVR insecure content warning).
// Set this up at fixed resolution, the (smaller) FOV gets set below.
specs.push_back(gvr_api_->CreateBufferSpec());
specs.back().SetSize(kHeadlockedBufferDimensions);
render_size_headlocked_ = specs[kFrameHeadlockedBuffer].GetSize();
swap_chain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs)));
vr_shell_renderer_.reset(new VrShellRenderer());
// Allocate a buffer viewport for use in UI drawing. This isn't
// initialized at this point, it'll be set from other viewport list
// entries as needed.
buffer_viewport_.reset(
new gvr::BufferViewport(gvr_api_->CreateBufferViewport()));
// Set up main content viewports. The list has two elements, 0=left
// eye and 1=right eye.
buffer_viewport_list_.reset(
new gvr::BufferViewportList(gvr_api_->CreateEmptyBufferViewportList()));
buffer_viewport_list_->SetToRecommendedBufferViewports();
// Set up head-locked UI viewports, these will be elements 2=left eye
// and 3=right eye. For now, use a hardcoded 20-degree-from-center FOV
// frustum to reduce rendering cost for this overlay. This fits the
// current content, but will need to be adjusted once there's more dynamic
// head-locked content that could be larger.
headlocked_left_viewport_.reset(
new gvr::BufferViewport(gvr_api_->CreateBufferViewport()));
buffer_viewport_list_->GetBufferViewport(GVR_LEFT_EYE,
headlocked_left_viewport_.get());
headlocked_left_viewport_->SetSourceBufferIndex(kFrameHeadlockedBuffer);
headlocked_left_viewport_->SetReprojection(GVR_REPROJECTION_NONE);
headlocked_left_viewport_->SetSourceFov(kHeadlockedBufferFov);
headlocked_right_viewport_.reset(
new gvr::BufferViewport(gvr_api_->CreateBufferViewport()));
buffer_viewport_list_->GetBufferViewport(GVR_RIGHT_EYE,
headlocked_right_viewport_.get());
headlocked_right_viewport_->SetSourceBufferIndex(kFrameHeadlockedBuffer);
headlocked_right_viewport_->SetReprojection(GVR_REPROJECTION_NONE);
headlocked_right_viewport_->SetSourceFov(kHeadlockedBufferFov);
// Save copies of the first two viewport items for use by WebVR, it
// sets its own UV bounds.
webvr_left_viewport_.reset(
new gvr::BufferViewport(gvr_api_->CreateBufferViewport()));
buffer_viewport_list_->GetBufferViewport(GVR_LEFT_EYE,
webvr_left_viewport_.get());
webvr_left_viewport_->SetSourceBufferIndex(kFramePrimaryBuffer);
webvr_right_viewport_.reset(
new gvr::BufferViewport(gvr_api_->CreateBufferViewport()));
buffer_viewport_list_->GetBufferViewport(GVR_RIGHT_EYE,
webvr_right_viewport_.get());
webvr_right_viewport_->SetSourceBufferIndex(kFramePrimaryBuffer);
main_thread_task_runner_->PostTask(FROM_HERE, base::Bind(
&VrShell::GvrDelegateReady, weak_vr_shell_));
}
void VrShellGl::UpdateController(const gvr::Vec3f& forward_vector) {
controller_->UpdateState();
// Note that button up/down state is transient, so ButtonUpHappened only
// returns true for a single frame (and we're guaranteed not to miss it).
if (controller_->ButtonUpHappened(
gvr::ControllerButton::GVR_CONTROLLER_BUTTON_APP)) {
main_thread_task_runner_->PostTask(
FROM_HERE, base::Bind(&VrShell::AppButtonPressed, weak_vr_shell_));
}
if (web_vr_mode_) {
// Process screen touch events for Cardboard button compatibility.
// Also send tap events for controller "touchpad click" events.
if (touch_pending_ || controller_->ButtonUpHappened(
gvr::ControllerButton::GVR_CONTROLLER_BUTTON_CLICK)) {
touch_pending_ = false;
std::unique_ptr<WebGestureEvent> gesture(new WebGestureEvent(
WebInputEvent::GestureTapDown, WebInputEvent::NoModifiers,
(base::TimeTicks::Now() - base::TimeTicks()).InSecondsF()));
gesture->sourceDevice = blink::WebGestureDeviceTouchpad;
gesture->x = 0;
gesture->y = 0;
SendGesture(InputTarget::CONTENT, std::move(gesture));
}
return;
}
gvr::Vec3f ergo_neutral_pose;
if (!controller_->IsConnected()) {
// No controller detected, set up a gaze cursor that tracks the
// forward direction.
ergo_neutral_pose = {0.0f, 0.0f, -1.0f};
controller_quat_ = GetRotationFromZAxis(forward_vector);
} else {
ergo_neutral_pose = {0.0f, -sin(kErgoAngleOffset), -cos(kErgoAngleOffset)};
controller_quat_ = controller_->Orientation();
}
gvr::Mat4f mat = QuatToMatrix(controller_quat_);
gvr::Vec3f forward = MatrixVectorMul(mat, ergo_neutral_pose);
gvr::Vec3f origin = kHandPosition;
// If we place the reticle based on elements intersecting the controller beam,
// we can end up with the reticle hiding behind elements, or jumping laterally
// in the field of view. This is physically correct, but hard to use. For
// usability, do the following instead:
//
// - Project the controller laser onto an outer surface, which is the
// closer of the desktop plane, or a distance-limiting sphere.
// - Create a vector between the eyes and the outer surface point.
// - If any UI elements intersect this vector, choose the closest to the eyes,
// and place the reticle at the intersection point.
// Find distance to a corner of the content quad, and limit the cursor
// distance to a multiple of that distance. This lets us keep the reticle on
// the content plane near the content window, and on the surface of a sphere
// in other directions. Note that this approach uses distance from controller,
// rather than eye, for simplicity. This will make the sphere slightly
// off-center.
float distance = kDefaultReticleDistance;
ContentRectangle* content_plane = scene_->GetContentQuad();
if (content_plane) {
distance = content_plane->GetRayDistance(origin, forward);
gvr::Vec3f corner = {0.5f, 0.5f, 0.0f};
corner = MatrixVectorMul(content_plane->transform.to_world, corner);
float max_distance = Distance(origin, corner) * kReticleDistanceMultiplier;
if (distance > max_distance || distance <= 0.0f) {
distance = max_distance;
}
}
target_point_ = GetRayPoint(origin, forward, distance);
gvr::Vec3f eye_to_target = target_point_;
NormalizeVector(eye_to_target);
// Determine which UI element (if any) intersects the line between the eyes
// and the controller target position.
float closest_element_distance = std::numeric_limits<float>::infinity();
int pixel_x = 0;
int pixel_y = 0;
target_element_ = nullptr;
InputTarget input_target = InputTarget::NONE;
for (const auto& plane : scene_->GetUiElements()) {
if (!plane->IsHitTestable())
continue;
float distance_to_plane = plane->GetRayDistance(kOrigin, eye_to_target);
gvr::Vec3f plane_intersection_point =
GetRayPoint(kOrigin, eye_to_target, distance_to_plane);
gvr::Vec3f rect_2d_point =
MatrixVectorMul(plane->transform.from_world, plane_intersection_point);
if (distance_to_plane > 0 && distance_to_plane < closest_element_distance) {
float x = rect_2d_point.x + 0.5f;
float y = 0.5f - rect_2d_point.y;
bool is_inside = x >= 0.0f && x < 1.0f && y >= 0.0f && y < 1.0f;
if (!is_inside)
continue;
closest_element_distance = distance_to_plane;
Rectf pixel_rect;
if (plane->content_quad) {
pixel_rect = {0, 0, content_tex_css_width_, content_tex_css_height_};
} else {
pixel_rect = {plane->copy_rect.x, plane->copy_rect.y,
plane->copy_rect.width, plane->copy_rect.height};
}
pixel_x = pixel_rect.width * x + pixel_rect.x;
pixel_y = pixel_rect.height * y + pixel_rect.y;
target_point_ = plane_intersection_point;
target_element_ = plane.get();
input_target = plane->content_quad ? InputTarget::CONTENT
: InputTarget::UI;
}
}
SendEventsToTarget(input_target, pixel_x, pixel_y);
}
void VrShellGl::SendEventsToTarget(InputTarget input_target,
int pixel_x,
int pixel_y) {
std::vector<std::unique_ptr<WebGestureEvent>> gesture_list =
controller_->DetectGestures();
double timestamp = gesture_list.front()->timeStampSeconds();
if (touch_pending_) {
touch_pending_ = false;
std::unique_ptr<WebGestureEvent> event(new WebGestureEvent(
WebInputEvent::GestureTapDown, WebInputEvent::NoModifiers, timestamp));
event->sourceDevice = blink::WebGestureDeviceTouchpad;
event->x = pixel_x;
event->y = pixel_y;
gesture_list.push_back(std::move(event));
}
for (const auto& gesture : gesture_list) {
switch (gesture->type()) {
case WebInputEvent::GestureScrollBegin:
case WebInputEvent::GestureScrollUpdate:
case WebInputEvent::GestureScrollEnd:
case WebInputEvent::GestureFlingCancel:
case WebInputEvent::GestureFlingStart:
SendGesture(InputTarget::CONTENT,
base::WrapUnique(new WebGestureEvent(*gesture)));
break;
case WebInputEvent::GestureTapDown:
gesture->x = pixel_x;
gesture->y = pixel_y;
if (input_target != InputTarget::NONE)
SendGesture(input_target,
base::WrapUnique(new WebGestureEvent(*gesture)));
break;
case WebInputEvent::Undefined:
break;
default:
NOTREACHED();
}
}
// Hover support
bool new_target = input_target != current_input_target_;
if (new_target && current_input_target_ != InputTarget::NONE) {
// Send a move event indicating that the pointer moved off of an element.
SendGesture(current_input_target_,
MakeMouseEvent(WebInputEvent::MouseLeave, timestamp, 0, 0));
}
current_input_target_ = input_target;
if (current_input_target_ != InputTarget::NONE) {
WebInputEvent::Type type =
new_target ? WebInputEvent::MouseEnter : WebInputEvent::MouseMove;
SendGesture(input_target,
MakeMouseEvent(type, timestamp, pixel_x, pixel_y));
}
}
void VrShellGl::SendGesture(InputTarget input_target,
std::unique_ptr<blink::WebInputEvent> event) {
DCHECK(input_target != InputTarget::NONE);
const base::WeakPtr<VrInputManager>& weak_ptr =
input_target == InputTarget::CONTENT ? content_input_manager_
: ui_input_manager_;
main_thread_task_runner_->PostTask(
FROM_HERE,
base::Bind(&VrInputManager::ProcessUpdatedGesture, weak_ptr,
base::Passed(std::move(event))));
}
void VrShellGl::SetGvrPoseForWebVr(const gvr::Mat4f& pose, uint32_t pose_num) {
webvr_head_pose_[pose_num % kPoseRingBufferSize] = pose;
webvr_head_pose_valid_[pose_num % kPoseRingBufferSize] = true;
}
bool VrShellGl::WebVrPoseByteIsValid(int pose_index_byte) {
if (pose_index_byte < 0) {
return false;
}
if (!webvr_head_pose_valid_[pose_index_byte % kPoseRingBufferSize]) {
VLOG(1) << "WebVR: reject decoded pose index " << pose_index_byte <<
", not a valid pose";
return false;
}
return true;
}
void VrShellGl::DrawFrame() {
TRACE_EVENT0("gpu", "VrShellGl::DrawFrame");
// Reset the viewport list to just the pair of viewports for the
// primary buffer each frame. Head-locked viewports get added by
// DrawVrShell if needed.
buffer_viewport_list_->SetToRecommendedBufferViewports();
gvr::Frame frame = swap_chain_->AcquireFrame();
gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow();
target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos;
gvr::Mat4f head_pose =
gvr_api_->GetHeadSpaceFromStartSpaceRotation(target_time);
gvr::Vec3f position = GetTranslation(head_pose);
if (position.x == 0.0f && position.y == 0.0f && position.z == 0.0f) {
// This appears to be a 3DOF pose without a neck model. Add one.
// The head pose has redundant data. Assume we're only using the
// object_from_reference_matrix, we're not updating position_external.
// TODO: Not sure what object_from_reference_matrix is. The new api removed
// it. For now, removing it seems working fine.
gvr_api_->ApplyNeckModel(head_pose, 1.0f);
}
frame.BindBuffer(kFramePrimaryBuffer);
// Update the render position of all UI elements (including desktop).
const float screen_tilt = kDesktopScreenTiltDefault * M_PI / 180.0f;
scene_->UpdateTransforms(screen_tilt, TimeInMicroseconds());
UpdateController(GetForwardVector(head_pose));
if (web_vr_mode_) {
DrawWebVr();
// When using async reprojection, we need to know which pose was used in
// the WebVR app for drawing this frame. Due to unknown amounts of
// buffering in the compositor and SurfaceTexture, we read the pose number
// from a corner pixel. There's no point in doing this for legacy
// distortion rendering since that doesn't need a pose, and reading back
// pixels is an expensive operation. TODO(klausw,crbug.com/655722): stop
// doing this once we have working no-compositor rendering for WebVR.
if (gvr_api_->GetAsyncReprojectionEnabled()) {
int pose_index_byte = GetPixelEncodedPoseIndexByte();
if (WebVrPoseByteIsValid(pose_index_byte)) {
// We have a valid pose, use it for reprojection.
webvr_left_viewport_->SetReprojection(GVR_REPROJECTION_FULL);
webvr_right_viewport_->SetReprojection(GVR_REPROJECTION_FULL);
head_pose = webvr_head_pose_[pose_index_byte % kPoseRingBufferSize];
// We can't mark the used pose as invalid since unfortunately
// we have to reuse them. The compositor will re-submit stale
// frames on vsync, and we can't tell that this has happened
// until we've read the pose index from it, and at that point
// it's too late to skip rendering.
} else {
// If we don't get a valid frame ID back we shouldn't attempt
// to reproject by an invalid matrix, so turn off reprojection
// instead. Invalid poses can permanently break reprojection
// for this GVR instance: http://crbug.com/667327
webvr_left_viewport_->SetReprojection(GVR_REPROJECTION_NONE);
webvr_right_viewport_->SetReprojection(GVR_REPROJECTION_NONE);
}
}
}
DrawVrShell(head_pose, frame);
frame.Unbind();
frame.Submit(*buffer_viewport_list_, head_pose);
// No need to swap buffers for surfaceless rendering.
if (surfaceless_rendering_) {
ScheduleNextDrawFrame();
return;
}
if (surface_->SupportsAsyncSwap()) {
surface_->SwapBuffersAsync(base::Bind(&WaitForSwapAck, base::Bind(
&VrShellGl::ScheduleNextDrawFrame, weak_ptr_factory_.GetWeakPtr())));
} else {
surface_->SwapBuffers();
ScheduleNextDrawFrame();
}
}
void VrShellGl::DrawVrShell(const gvr::Mat4f& head_pose,
gvr::Frame &frame) {
TRACE_EVENT0("gpu", "VrShellGl::DrawVrShell");
std::vector<const ContentRectangle*> head_locked_elements;
std::vector<const ContentRectangle*> world_elements;
for (const auto& rect : scene_->GetUiElements()) {
if (!rect->IsVisible())
continue;
if (rect->lock_to_fov) {
head_locked_elements.push_back(rect.get());
} else {
world_elements.push_back(rect.get());
}
}
if (web_vr_mode_) {
// WebVR is incompatible with 3D world compositing since the
// depth buffer was already populated with unknown scaling - the
// WebVR app has full control over zNear/zFar. Just leave the
// existing content in place in the primary buffer without
// clearing. Currently, there aren't any world elements in WebVR
// mode, this will need further testing if those get added
// later.
} else {
// Non-WebVR mode, enable depth testing and clear the primary buffers.
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
if (!world_elements.empty()) {
DrawUiView(&head_pose, world_elements, render_size_primary_,
kViewportListPrimaryOffset);
}
if (!head_locked_elements.empty()) {
// Add head-locked viewports. The list gets reset to just
// the recommended viewports (for the primary buffer) each frame.
buffer_viewport_list_->SetBufferViewport(
kViewportListHeadlockedOffset + GVR_LEFT_EYE,
*headlocked_left_viewport_);
buffer_viewport_list_->SetBufferViewport(
kViewportListHeadlockedOffset + GVR_RIGHT_EYE,
*headlocked_right_viewport_);
// Bind the headlocked framebuffer.
// TODO(mthiesse): We don't unbind this? Maybe some cleanup is in order
// here.
frame.BindBuffer(kFrameHeadlockedBuffer);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawUiView(nullptr, head_locked_elements, render_size_headlocked_,
kViewportListHeadlockedOffset);
}
}
gvr::Sizei VrShellGl::GetWebVRCompositorSurfaceSize() {
// This is a stopgap while we're using the WebVR compositor rendering path.
// TODO(klausw,crbug.com/655722): Remove this method and member once we're
// using a separate WebVR render surface.
return content_tex_physical_size_;
}
void VrShellGl::DrawUiView(const gvr::Mat4f* head_pose,
const std::vector<const ContentRectangle*>& elements,
const gvr::Sizei& render_size,
int viewport_offset) {
TRACE_EVENT0("gpu", "VrShellGl::DrawUiView");
for (auto eye : {GVR_LEFT_EYE, GVR_RIGHT_EYE}) {
buffer_viewport_list_->GetBufferViewport(
eye + viewport_offset, buffer_viewport_.get());
gvr::Mat4f view_matrix = gvr_api_->GetEyeFromHeadMatrix(eye);
if (head_pose != nullptr) {
view_matrix = MatrixMul(view_matrix, *head_pose);
}
gvr::Recti pixel_rect =
CalculatePixelSpaceRect(render_size, buffer_viewport_->GetSourceUv());
glViewport(pixel_rect.left, pixel_rect.bottom,
pixel_rect.right - pixel_rect.left,
pixel_rect.top - pixel_rect.bottom);
const gvr::Mat4f render_matrix = MatrixMul(
PerspectiveMatrixFromView(
buffer_viewport_->GetSourceFov(), kZNear, kZFar),
view_matrix);
DrawElements(render_matrix, elements);
if (head_pose != nullptr && !web_vr_mode_) {
DrawCursor(render_matrix);
}
}
}
void VrShellGl::DrawElements(
const gvr::Mat4f& render_matrix,
const std::vector<const ContentRectangle*>& elements) {
for (const auto& rect : elements) {
Rectf copy_rect;
jint texture_handle;
if (rect->content_quad) {
copy_rect = {0, 0, 1, 1};
texture_handle = content_texture_id_;
} else {
copy_rect.x = static_cast<float>(rect->copy_rect.x) / ui_tex_css_width_;
copy_rect.y = static_cast<float>(rect->copy_rect.y) / ui_tex_css_height_;
copy_rect.width = static_cast<float>(rect->copy_rect.width) /
ui_tex_css_width_;
copy_rect.height = static_cast<float>(rect->copy_rect.height) /
ui_tex_css_height_;
texture_handle = ui_texture_id_;
}
gvr::Mat4f transform = MatrixMul(render_matrix, rect->transform.to_world);
vr_shell_renderer_->GetTexturedQuadRenderer()->Draw(
texture_handle, transform, copy_rect, rect->computed_opacity);
}
}
void VrShellGl::DrawCursor(const gvr::Mat4f& render_matrix) {
gvr::Mat4f mat;
SetIdentityM(mat);
// Draw the reticle.
// Scale the pointer to have a fixed FOV size at any distance.
const float eye_to_target = Distance(target_point_, kOrigin);
ScaleM(mat, mat, kReticleWidth * eye_to_target,
kReticleHeight * eye_to_target, 1.0f);
gvr::Quatf rotation;
if (target_element_ != nullptr) {
// Make the reticle planar to the element it's hitting.
rotation = GetRotationFromZAxis(target_element_->GetNormal());
} else {
// Rotate the cursor to directly face the eyes.
rotation = GetRotationFromZAxis(target_point_);
}
mat = MatrixMul(QuatToMatrix(rotation), mat);
// Place the pointer slightly in front of the plane intersection point.
TranslateM(mat, mat, target_point_.x * kReticleOffset,
target_point_.y * kReticleOffset,
target_point_.z * kReticleOffset);
gvr::Mat4f transform = MatrixMul(render_matrix, mat);
vr_shell_renderer_->GetReticleRenderer()->Draw(transform);
// Draw the laser.
// Find the length of the beam (from hand to target).
const float laser_length = Distance(kHandPosition, target_point_);
// Build a beam, originating from the origin.
SetIdentityM(mat);
// Move the beam half its height so that its end sits on the origin.
TranslateM(mat, mat, 0.0f, 0.5f, 0.0f);
ScaleM(mat, mat, kLaserWidth, laser_length, 1);
// Tip back 90 degrees to flat, pointing at the scene.
const gvr::Quatf q = QuatFromAxisAngle({1.0f, 0.0f, 0.0f}, -M_PI / 2);
mat = MatrixMul(QuatToMatrix(q), mat);
const gvr::Vec3f beam_direction = {
target_point_.x - kHandPosition.x,
target_point_.y - kHandPosition.y,
target_point_.z - kHandPosition.z
};
const gvr::Mat4f beam_direction_mat =
QuatToMatrix(GetRotationFromZAxis(beam_direction));
// Render multiple faces to make the laser appear cylindrical.
const int faces = 4;
for (int i = 0; i < faces; i++) {
// Rotate around Z.
const float angle = M_PI * 2 * i / faces;
const gvr::Quatf rot = QuatFromAxisAngle({0.0f, 0.0f, 1.0f}, angle);
gvr::Mat4f face_transform = MatrixMul(QuatToMatrix(rot), mat);
// Orient according to target direction.
face_transform = MatrixMul(beam_direction_mat, face_transform);
// Move the beam origin to the hand.
TranslateM(face_transform, face_transform, kHandPosition.x, kHandPosition.y,
kHandPosition.z);
transform = MatrixMul(render_matrix, face_transform);
vr_shell_renderer_->GetLaserRenderer()->Draw(transform);
}
}
void VrShellGl::DrawWebVr() {
TRACE_EVENT0("gpu", "VrShellGl::DrawWebVr");
// Don't need face culling, depth testing, blending, etc. Turn it all off.
glDisable(GL_CULL_FACE);
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_BLEND);
glDisable(GL_POLYGON_OFFSET_FILL);
glViewport(0, 0, render_size_primary_.width, render_size_primary_.height);
vr_shell_renderer_->GetWebVrRenderer()->Draw(webvr_texture_id_);
buffer_viewport_list_->SetBufferViewport(GVR_LEFT_EYE,
*webvr_left_viewport_);
buffer_viewport_list_->SetBufferViewport(GVR_RIGHT_EYE,
*webvr_right_viewport_);
}
void VrShellGl::OnTriggerEvent() {
// Set a flag to handle this on the render thread at the next frame.
touch_pending_ = true;
}
void VrShellGl::OnPause() {
draw_task_.Cancel();
controller_->OnPause();
gvr_api_->PauseTracking();
}
void VrShellGl::OnResume() {
gvr_api_->RefreshViewerProfile();
gvr_api_->ResumeTracking();
controller_->OnResume();
if (ready_to_draw_) {
draw_task_.Reset(base::Bind(&VrShellGl::DrawFrame, base::Unretained(this)));
ScheduleNextDrawFrame();
}
}
void VrShellGl::SetWebVrMode(bool enabled) {
web_vr_mode_ = enabled;
}
void VrShellGl::UpdateWebVRTextureBounds(const gvr::Rectf& left_bounds,
const gvr::Rectf& right_bounds) {
webvr_left_viewport_->SetSourceUv(left_bounds);
webvr_right_viewport_->SetSourceUv(right_bounds);
}
gvr::GvrApi* VrShellGl::gvr_api() {
return gvr_api_.get();
}
void VrShellGl::ContentBoundsChanged(int width, int height) {
TRACE_EVENT0("gpu", "VrShellGl::ContentBoundsChanged");
content_tex_css_width_ = width;
content_tex_css_height_ = height;
}
void VrShellGl::ContentPhysicalBoundsChanged(int width, int height) {
if (content_surface_texture_.get())
content_surface_texture_->SetDefaultBufferSize(width, height);
content_tex_physical_size_.width = width;
content_tex_physical_size_.height = height;
}
void VrShellGl::UIBoundsChanged(int width, int height) {
ui_tex_css_width_ = width;
ui_tex_css_height_ = height;
}
void VrShellGl::UIPhysicalBoundsChanged(int width, int height) {
if (ui_surface_texture_.get())
ui_surface_texture_->SetDefaultBufferSize(width, height);
ui_tex_physical_size_.width = width;
ui_tex_physical_size_.height = height;
}
base::WeakPtr<VrShellGl> VrShellGl::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void VrShellGl::UpdateVSyncParameters(const base::TimeTicks timebase,
const base::TimeDelta interval) {
vsync_timebase_ = timebase;
vsync_interval_ = interval;
}
void VrShellGl::ScheduleNextDrawFrame() {
base::TimeTicks now = base::TimeTicks::Now();
base::TimeTicks target;
if (vsync_interval_.is_zero()) {
target = now;
} else {
target = now + vsync_interval_;
int64_t intervals = (target - vsync_timebase_) / vsync_interval_;
target = vsync_timebase_ + intervals * vsync_interval_;
}
task_runner_->PostDelayedTask(FROM_HERE, draw_task_.callback(), target - now);
}
void VrShellGl::ForceExitVr() {
main_thread_task_runner_->PostTask(
FROM_HERE, base::Bind(&VrShell::ForceExitVr, weak_vr_shell_));
}
void VrShellGl::UpdateScene(std::unique_ptr<base::ListValue> commands) {
scene_->HandleCommands(std::move(commands), TimeInMicroseconds());
}
} // namespace vr_shell
| 38.348303 | 80 | 0.710007 | [
"render",
"object",
"vector",
"model",
"transform",
"3d"
] |
e3304c4002a13dce21b71ef11b1ae57ab3a49664 | 446 | cpp | C++ | c++/leetCode/august/12.pascals-triangle-II.cpp | 08pixels/juizes-online | 7202eeaed6886e8ff33fc2031c213348043d5909 | [
"Apache-2.0"
] | 1 | 2020-06-23T06:23:03.000Z | 2020-06-23T06:23:03.000Z | c++/leetCode/august/12.pascals-triangle-II.cpp | 08pixels/juizes-online | 7202eeaed6886e8ff33fc2031c213348043d5909 | [
"Apache-2.0"
] | null | null | null | c++/leetCode/august/12.pascals-triangle-II.cpp | 08pixels/juizes-online | 7202eeaed6886e8ff33fc2031c213348043d5909 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> memo[2];
memo[0].resize(rowIndex + 1);
memo[1].resize(rowIndex + 1);
memo[0][0] = memo[1][0] = 1;
for(int i = 1; i <= rowIndex; ++i) {
for(int j = 1; j <= i; ++j)
memo[i&1][j] = memo[~i&1][j] + memo[~i&1][j - 1];
}
return memo[rowIndex&1];
}
};
| 22.3 | 65 | 0.408072 | [
"vector"
] |
e330ae75bc43a606842c615590ab4c8aa151fd80 | 4,111 | cc | C++ | tests/testfoundation/float4test.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 377 | 2018-10-24T08:34:21.000Z | 2022-03-31T23:37:49.000Z | tests/testfoundation/float4test.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 11 | 2020-01-22T13:34:46.000Z | 2022-03-07T10:07:34.000Z | tests/testfoundation/float4test.cc | sirAgg/nebula | 3fbccc73779944aa3e56b9e8acdd6fedd1d38006 | [
"BSD-2-Clause"
] | 23 | 2019-07-13T16:28:32.000Z | 2022-03-20T09:00:59.000Z | //------------------------------------------------------------------------------
// float4test.cc
// (C) 2007 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "float4test.h"
namespace Test
{
__ImplementClass(Test::Float4Test, 'F4TS', Test::TestCase);
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
void
Float4Test::Run()
{
// construction
vec4 v0(1.0f, 2.0f, 3.0f, 4.0f);
vec4 v1(4.0f, 3.0f, 2.0f, 1.0f);
vec4 v2(v0);
vec4 v3(v1);
VERIFY(v0 == v2);
VERIFY(v1 == v3);
VERIFY(v0 != v1);
VERIFY(v2 != v3);
VERIFY(v0 == vec4(1.0f, 2.0f, 3.0f, 4.0));
// assignemt
v2 = v1;
VERIFY(v2 == v1);
v2 = v0;
VERIFY(v2 == v0);
// operators
v0 = -v0;
VERIFY(v0 == vec4(-1.0f, -2.0f, -3.0f, -4.0f));
v0 = -v0;
VERIFY(v0 == v2);
v2 += v3;
VERIFY(v2 == vec4(5.0f, 5.0f, 5.0f, 5.0f));
v2 -= v3;
VERIFY(v2 == v0);
v2 *= 2.0f;
VERIFY(v2 == vec4(2.0f, 4.0f, 6.0f, 8.0f));
v2 = v0 + v1;
VERIFY(v2 == vec4(5.0f, 5.0f, 5.0f, 5.0f));
v2 = v0 - v1;
VERIFY(v2 == vec4(-3.0f, -1.0f, 1.0f, 3.0f));
v2 = v0 * 2.0f;
VERIFY(v2 == vec4(2.0f, 4.0f, 6.0f, 8.0f));
// load and store
NEBULA_ALIGN16 scalar f[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
NEBULA_ALIGN16 scalar f0[4];
v2.load(f);
VERIFY(v2 == vec4(1.0f, 2.0f, 3.0f, 4.0f));
v2.loadu(f);
VERIFY(v2 == vec4(1.0f, 2.0f, 3.0f, 4.0f));
v2.store(f0);
VERIFY((f0[0] == 1.0f) && (f0[1] == 2.0f) && (f0[2] == 3.0f) && (f0[3] == 4.0f));
v2.storeu(f0);
VERIFY((f0[0] == 1.0f) && (f0[1] == 2.0f) && (f0[2] == 3.0f) && (f0[3] == 4.0f));
v2.stream(f0);
VERIFY((f0[0] == 1.0f) && (f0[1] == 2.0f) && (f0[2] == 3.0f) && (f0[3] == 4.0f));
// setting and getting content
v2.set(2.0f, 3.0f, 4.0f, 5.0f);
VERIFY(v2 == vec4(2.0f, 3.0f, 4.0f, 5.0f));
VERIFY(v2.x == 2.0f);
VERIFY(v2.y == 3.0f);
VERIFY(v2.z == 4.0f);
VERIFY(v2.w == 5.0f);
v2.x = 1.0f;
v2.y = 2.0f;
v2.z = 3.0f;
v2.w = 4.0f;
VERIFY(v2 == vec4(1.0f, 2.0f, 3.0f, 4.0f));
// length and abs
v2.set(0.0f, 2.0f, 0.0f, 0.0f);
VERIFY(fequal(length(v2), 2.0f, 0.0001f));
VERIFY(fequal(lengthsq(v2), 4.0f, 0.0001f));
v2.set(-1.0f, 2.0f, -3.0f, 4.0f);
VERIFY(abs(v2) == vec4(1.0f, 2.0f, 3.0f, 4.0f));
// cross3
v0.set(1.0f, 0.0f, 0.0f, 0.0f);
v1.set(0.0f, 0.0f, 1.0f, 0.0f);
v2 = cross3(v0, v1);
VERIFY(v2 == vec4(0.0f, -1.0f, 0.0f, 0.0f));
// dot3
v0.set(1.0f, 0.0f, 0.0f, 0.0f);
v1.set(1.0f, 0.0f, 0.0f, 0.0f);
VERIFY(dot3(v0, v1) == 1.0f);
v1.set(-1.0f, 0.0f, 0.0f, 0.0f);
VERIFY(dot3(v0, v1) == -1.0f);
v1.set(0.0f, 1.0f, 0.0f, 0.0f);
VERIFY(dot3(v0, v1) == 0.0f);
// @todo: test barycentric(), catmullrom(), hermite()
// lerp
v0.set(1.0f, 2.0f, 3.0f, 4.0f);
v1.set(2.0f, 3.0f, 4.0f, 5.0f);
v2 = vecLerp(v0, v1, 0.5f);
VERIFY(v2 == vec4(1.5f, 2.5f, 3.5f, 4.5f));
// maximize/minimize
v0.set(1.0f, 2.0f, 3.0f, 4.0f);
v1.set(4.0f, 3.0f, 2.0f, 1.0f);
v2 = maximize(v0, v1);
VERIFY(v2 == vec4(4.0f, 3.0f, 3.0f, 4.0f));
v2 = minimize(v0, v1);
VERIFY(v2 == vec4(1.0f, 2.0f, 2.0f, 1.0f));
// normalize
v0.set(2.5f, 0.0f, 0.0f, 0.0f);
v1 = normalize(v0);
VERIFY(v1 == vec4(1.0f, 0.0f, 0.0f, 0.0f));
// transform (point and vector)
mat4 m = translation(1.0f, 2.0f, 3.0f);
v0.set(1.0f, 0.0f, 0.0f, 1.0f);
v1 = m * v0;
VERIFY(v1 == vec4(2.0f, 2.0f, 3.0f, 1.0f));
v0.set(1.0f, 0.0f, 0.0f, 0.0f);
v1 = m * v0;
VERIFY(v0 == vec4(1.0f, 0.0f, 0.0f, 0.0f));
// component-wise comparison
v0.set(1.0f, 1.0f, 1.0f, 1.0f);
v1.set(0.5f, 1.5f, 0.5f, 1.5f);
v2.set(2.0f, 2.0f, 2.0f, 2.0f);
VERIFY(less_any(v0, v1));
VERIFY(greater_any(v0, v1));
VERIFY(!less_all(v0, v1));
VERIFY(!greater_all(v0, v1));
VERIFY(lessequal_all(v0, v2));
VERIFY(greaterequal_all(v2, v0));
}
} | 28.157534 | 85 | 0.467283 | [
"vector",
"transform"
] |
e33b1858ae4c55fb43f5f20bed9bb57b29c7afd7 | 1,994 | hpp | C++ | stack.hpp | dkarthus/containers_ft | 9877bfc5143742bbc57a27b16eadbbdbf5aa9af8 | [
"MIT"
] | null | null | null | stack.hpp | dkarthus/containers_ft | 9877bfc5143742bbc57a27b16eadbbdbf5aa9af8 | [
"MIT"
] | null | null | null | stack.hpp | dkarthus/containers_ft | 9877bfc5143742bbc57a27b16eadbbdbf5aa9af8 | [
"MIT"
] | null | null | null | #pragma once
namespace ft
{
template <class T, class Container = ft::vector<T> >
class stack
{
public:
typedef T value_type;
typedef Container container_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename Container::size_type size_type;
protected:
container_type _cnt;
public:
explicit stack(const container_type& cont = container_type()) : _cnt(cont){};
stack(const stack& other) : _cnt(other._cnt) {}
stack& operator=(const stack& other)
{
if (*this != other)
_cnt = other._cnt;
return (*this);
}
reference top()
{
return (_cnt.back());
}
const_reference top() const
{
return (_cnt.back());
}
bool empty() const
{
return (_cnt.empty());
}
size_type size() const
{
return (_cnt.size());
}
void push(const value_type& value)
{
_cnt.push_back(value);
}
void pop()
{
_cnt.pop_back();
}
template <class AnyType, class Cont>
friend bool operator==(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt == rhs._cnt);
}
template <class AnyType, class Cont>
friend bool operator!=(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt != rhs._cnt);
}
template <class AnyType, class Cont>
friend bool operator<(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt < rhs._cnt);
}
template <class AnyType, class Cont>
friend bool operator<=(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt <= rhs._cnt);
}
template <class AnyType, class Cont>
friend bool operator>(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt > rhs._cnt);
}
template <class AnyType, class Cont>
friend bool operator>=(const stack<AnyType,Cont>& lhs, const stack<AnyType,Cont>& rhs)
{
return (lhs._cnt >= rhs._cnt);
}
};
}
#endif
| 20.141414 | 88 | 0.650451 | [
"vector"
] |
e33b21a1ec8497540880a33d0adfa0ae2577c46a | 6,242 | cpp | C++ | sources/common/src/platform/baseplatform.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 3 | 2020-07-30T19:41:00.000Z | 2020-10-28T12:52:37.000Z | sources/common/src/platform/baseplatform.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | null | null | null | sources/common/src/platform/baseplatform.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 2 | 2020-05-11T03:19:00.000Z | 2021-07-07T17:40:47.000Z | /**
##########################################################################
# If not stated otherwise in this file or this component's LICENSE
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# 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 "common.h"
BasePlatform::BasePlatform() {
}
BasePlatform::~BasePlatform() {
}
#if defined FREEBSD || defined LINUX || defined OSX || defined SOLARIS
void GetFinishedProcesses(vector<pid_t> &pids, bool &noMorePids) {
pids.clear();
noMorePids = false;
int statLoc = 0;
while (true) {
pid_t pid = waitpid(-1, &statLoc, WNOHANG);
if (pid < 0) {
int err = errno;
if (err != ECHILD)
WARN("waitpid failed %d %s", err, strerror(err));
noMorePids = true;
break;
}
if (pid == 0)
break;
ADD_VECTOR_END(pids, pid);
}
}
bool LaunchProcess(string fullBinaryPath, vector<string> &arguments, vector<string> &envVars, pid_t &pid) {
#ifndef NO_SPAWN
char **_ppArgs = NULL;
char **_ppEnv = NULL;
ADD_VECTOR_BEGIN(arguments, fullBinaryPath);
_ppArgs = new char*[arguments.size() + 1];
for (uint32_t i = 0; i < arguments.size(); i++) {
_ppArgs[i] = new char[arguments[i].size() + 1];
strcpy(_ppArgs[i], arguments[i].c_str());
}
_ppArgs[arguments.size()] = NULL;
if (envVars.size() > 0) {
_ppEnv = new char*[envVars.size() + 1];
for (uint32_t i = 0; i < envVars.size(); i++) {
_ppEnv[i] = new char[envVars[i].size() + 1];
strcpy(_ppEnv[i], envVars[i].c_str());
}
_ppEnv[envVars.size()] = NULL;
}
if (posix_spawn(&pid, STR(fullBinaryPath), NULL, NULL, _ppArgs, _ppEnv) != 0) {
int err = errno;
FATAL("posix_spawn failed %d %s", err, strerror(err));
IOBuffer::ReleaseDoublePointer(&_ppArgs);
IOBuffer::ReleaseDoublePointer(&_ppEnv);
return false;
}
IOBuffer::ReleaseDoublePointer(&_ppArgs);
IOBuffer::ReleaseDoublePointer(&_ppEnv);
#endif /* NO_SPAWN */
return true;
}
bool setFdCloseOnExec(int fd) {
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
int err = errno;
FATAL("fcntl failed %d %s", err, strerror(err));
return false;
}
return true;
}
void killProcess(pid_t pid) {
kill(pid, SIGKILL);
}
#ifdef HAS_STACK_DUMP
#include <execinfo.h>
/*
* what signals are we going to intercept
*/
const int gInterceptedSignals[] = {
SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS
};
/*
* How many signals are we going to intercept?
*/
const size_t gInterceptedSignalsCount = sizeof (gInterceptedSignals) / sizeof (gInterceptedSignals[0]);
/*
* the handler to be called on all signals
*/
void DumpStackWrapper(int signal, siginfo_t *pInfo, void *pIgnored);
/*
* this class implements all the stack trace dumper functionality.
* It is globally initialized and there will only be one instance at
* any given time.
*/
class CrashDumpHandler {
private:
//where to deposit the output
int _outputFd;
//Where to store the old/default signal handlers. Will need them to call
//the default handler after we do our magic
struct sigaction _oldSignals[gInterceptedSignalsCount];
//the path to the output fd
string _stackFilePath;
//this flasg is set inside the signal handler. When true, don't delete
//the stack file. That means we caught an actual signal, so that file
//contains valuable data
bool _deleteFile;
//how many frames do we prepare for (last BACKTRACE_SIZE)
#define BACKTRACE_SIZE 1024
void *_pBacktraceBuffer[BACKTRACE_SIZE];
//stack variables used inside the signal handler. Remember, we are not allowed
//to declare any new ones
int _i;
public:
CrashDumpHandler() {
memset(&_oldSignals, 0, sizeof (_oldSignals));
memset(_pBacktraceBuffer, 0, sizeof (_pBacktraceBuffer));
_deleteFile = true;
}
virtual ~CrashDumpHandler() {
if (_deleteFile)
deleteFile(_stackFilePath);
}
bool Init(const char *pPrefix) {
_stackFilePath = format("%s%"PRIu32"_%"PRIu64".txt",
pPrefix != NULL ? pPrefix : "/tmp/rmscore_",
(uint32_t) getpid(), (uint64_t) time(NULL));
_outputFd = creat(_stackFilePath.c_str(),
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (_outputFd < 0) {
FATAL("Unable to create stack file to `%s`", _stackFilePath.c_str());
return false;
}
for (size_t i = 0; i < gInterceptedSignalsCount; i++) {
//prepare a new signal handler
struct sigaction newSignal;
memset(&newSignal, 0, sizeof (newSignal));
sigemptyset(&newSignal.sa_mask);
newSignal.sa_sigaction = DumpStackWrapper;
newSignal.sa_flags = SA_ONSTACK | SA_SIGINFO;
//install the new signal handler and save the old one
if (sigaction(gInterceptedSignals[i], &newSignal, &_oldSignals[i]) != 0) {
FATAL("sigaction failed");
return false;
}
//store the signal type on one of the members. Used later to search for
//the default action
_oldSignals[i].sa_flags = gInterceptedSignals[i];
}
return true;
}
void DumpStack(int signal, siginfo_t *pInfo, void *pCastedContext) {
//no matter what, we don't delete the stack file anymore! the signal
//was executed....
_deleteFile = false;
//get the stack
_i = backtrace(_pBacktraceBuffer, BACKTRACE_SIZE);
//dump it into the file
backtrace_symbols_fd(_pBacktraceBuffer, _i, _outputFd);
//done
exit(signal);
}
};
CrashDumpHandler gCrashDumper;
void InstallCrashDumpHandler(const char *pPrefix) {
gCrashDumper.Init(pPrefix);
}
void DumpStackWrapper(int signal, siginfo_t *pInfo, void *pCastedContext) {
gCrashDumper.DumpStack(signal, pInfo, pCastedContext);
}
#else /* HAS_STACK_DUMP */
void InstallCrashDumpHandler(const char *pPrefix) {
}
#endif /* HAS_STACK_DUMP */
#endif /* defined FREEBSD || defined LINUX || defined OSX || defined SOLARIS */
| 27.619469 | 107 | 0.689843 | [
"vector"
] |
e33f346071fd0c147d0e3eb26f1d5fc2bb2275cc | 10,492 | cpp | C++ | src/plugins/matrixops/vstack_operation.cpp | diehlpk/phylanx | 7eba54f0f22dc66d18addac0b24f006380d0f798 | [
"BSL-1.0"
] | null | null | null | src/plugins/matrixops/vstack_operation.cpp | diehlpk/phylanx | 7eba54f0f22dc66d18addac0b24f006380d0f798 | [
"BSL-1.0"
] | null | null | null | src/plugins/matrixops/vstack_operation.cpp | diehlpk/phylanx | 7eba54f0f22dc66d18addac0b24f006380d0f798 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2018 Bibek Wagle
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/node_data_helpers.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/plugins/matrixops/vstack_operation.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/naming.hpp>
#include <hpx/include/util.hpp>
#include <hpx/throw_exception.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include <blaze/Math.h>
///////////////////////////////////////////////////////////////////////////////
namespace phylanx { namespace execution_tree { namespace primitives
{
///////////////////////////////////////////////////////////////////////////
match_pattern_type const vstack_operation::match_data =
{
hpx::util::make_tuple("vstack",
std::vector<std::string>{"vstack(__1)"},
&create_vstack_operation, &create_primitive<vstack_operation>,
"args\n"
"Args:\n"
"\n"
" *args (list of number) : a list of numbers\n"
"\n"
"Returns:\n"
"\n"
"An N by 1 matrix of numbeers, where N is the quantity "
"of numbers in `args`.")
};
///////////////////////////////////////////////////////////////////////////
vstack_operation::vstack_operation(
primitive_arguments_type&& operands,
std::string const& name, std::string const& codename)
: primitive_component_base(std::move(operands), name, codename)
{}
///////////////////////////////////////////////////////////////////////////
template <typename T>
primitive_argument_type vstack_operation::vstack0d_helper(
primitive_arguments_type&& args) const
{
std::size_t vec_size = args.size();
blaze::DynamicMatrix<T> result(vec_size, 1);
auto col = blaze::column(result, 0);
std::size_t i = 0;
for (auto && arg : args)
{
auto && val = extract_node_data<T>(std::move(arg));
if (val.num_dimensions() != 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"vstack_operation::vstack0d",
generate_error_message(
"the vstack_operation primitive requires all the "
"inputs be a scalar for 0d stacking"));
}
col[i++] = val.scalar();
}
return primitive_argument_type{ir::node_data<T>{std::move(result)}};
}
primitive_argument_type vstack_operation::vstack0d(
primitive_arguments_type&& args) const
{
switch (extract_common_type(args))
{
case node_data_type_bool:
return vstack0d_helper<std::uint8_t>(std::move(args));
case node_data_type_int64:
return vstack0d_helper<std::int64_t>(std::move(args));
case node_data_type_double:
return vstack0d_helper<double>(std::move(args));
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"hstack_operation::vstack0d",
util::generate_error_message(
"the vstack_operation primitive requires for all arguments to "
"be numeric data types",
name_, codename_));
}
///////////////////////////////////////////////////////////////////////////
template <typename T>
primitive_argument_type vstack_operation::vstack1d2d_helper(
primitive_arguments_type&& args) const
{
std::size_t args_size = args.size();
std::size_t num_dims_first =
extract_numeric_value_dimension(args[0], name_, codename_);
std::array<std::size_t, 2> prevdim =
extract_numeric_value_dimensions(args[0], name_, codename_);
std::size_t total_rows = 1;
std::size_t num_cols = prevdim[1];
if (num_dims_first == 2)
{
total_rows = prevdim[0];
}
std::size_t first_size = num_cols;
for (std::size_t i = 1; i != args_size; ++i)
{
std::size_t num_dims_second =
extract_numeric_value_dimension(args[i], name_, codename_);
if (num_dims_first == 0 || num_dims_second == 0)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"vstack_operation::vstack2d",
util::generate_error_message(
"the vstack_operation primitive can not stack "
"matrices/vectors with a scalar",
name_, codename_));
}
std::array<std::size_t, 2> dim =
extract_numeric_value_dimensions(args[i], name_, codename_);
std::size_t second_size = dim[1];
if (num_dims_second == 2)
{
total_rows += dim[0];
}
else
{
++total_rows;
}
if (first_size != second_size)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"vstack_operation::vstack2d",
util::generate_error_message(
"the vstack_operation primitive requires for the "
"number of columns/size to be equal for all "
"matrices/vectors being stacked",
name_, codename_));
}
num_dims_first = num_dims_second;
first_size = second_size;
}
blaze::DynamicMatrix<double> result(total_rows, num_cols);
std::size_t step = 0;
for (auto && arg : args)
{
auto && val = extract_node_data<T>(std::move(arg));
if (val.num_dimensions() == 2)
{
std::size_t num_rows = val.dimension(0);
for (std::size_t j = 0; j != num_rows; ++j)
{
blaze::row(result, j + step) =
blaze::row(val.matrix(), j);
}
step += num_rows;
}
else
{
blaze::row(result, step) = blaze::trans(val.vector());
++step;
}
}
return primitive_argument_type{ir::node_data<T>{std::move(result)}};
}
primitive_argument_type vstack_operation::vstack1d2d(
primitive_arguments_type&& args) const
{
switch (extract_common_type(args))
{
case node_data_type_bool:
return vstack1d2d_helper<std::uint8_t>(std::move(args));
case node_data_type_int64:
return vstack1d2d_helper<std::int64_t>(std::move(args));
case node_data_type_double:
return vstack1d2d_helper<double>(std::move(args));
default:
break;
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::primitives::"
"vstack_operation::vstack1d2d",
util::generate_error_message(
"the vstack_operation primitive requires for all arguments to "
"be numeric data types",
name_, codename_));
}
///////////////////////////////////////////////////////////////////////////
hpx::future<primitive_argument_type> vstack_operation::eval(
primitive_arguments_type const& operands,
primitive_arguments_type const& args) const
{
if (operands.empty())
{
// hstack() without arguments returns an empty column
using storage2d_type = ir::node_data<std::int64_t>::storage2d_type;
return hpx::make_ready_future(primitive_argument_type{
ir::node_data<std::int64_t>{storage2d_type(0, 1)}});
}
bool arguments_valid = true;
for (std::size_t i = 0; i != operands.size(); ++i)
{
if (!valid(operands[i]))
{
arguments_valid = false;
}
}
if (!arguments_valid)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"vstack_operation::eval",
util::generate_error_message(
"the vstack_operation primitive requires "
"that the arguments given by the operands "
"array are valid",
name_, codename_));
}
auto this_ = this->shared_from_this();
return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping(
[this_ = std::move(this_)](primitive_arguments_type&& args)
-> primitive_argument_type
{
std::size_t matrix_dims = extract_numeric_value_dimension(
args[0], this_->name_, this_->codename_);
switch (matrix_dims)
{
case 0:
return this_->vstack0d(std::move(args));
case 1: HPX_FALLTHROUGH;
case 2:
return this_->vstack1d2d(std::move(args));
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"vstack_operation::eval",
util::generate_error_message(
"left hand side operand has unsupported "
"number of dimensions",
this_->name_, this_->codename_));
}
}),
detail::map_operands(
operands, functional::value_operand{}, args,
name_, codename_));
}
//////////////////////////////////////////////////////////////////////////
hpx::future<primitive_argument_type> vstack_operation::eval(
primitive_arguments_type const& args, eval_mode) const
{
if (this->no_operands())
{
return eval(args, noargs);
}
return eval(this->operands(), args);
}
}}}
| 34.175896 | 80 | 0.513439 | [
"vector"
] |
e33fdd55ac68fb7d1db3237fbb26259902829a75 | 46,462 | cc | C++ | cow/src/components/audio_src_pulse.cc | halleyzhao/alios-mm | bef2a6de0c207a5ae9bf4f63de2e562df864aa3e | [
"Apache-2.0"
] | null | null | null | cow/src/components/audio_src_pulse.cc | halleyzhao/alios-mm | bef2a6de0c207a5ae9bf4f63de2e562df864aa3e | [
"Apache-2.0"
] | null | null | null | cow/src/components/audio_src_pulse.cc | halleyzhao/alios-mm | bef2a6de0c207a5ae9bf4f63de2e562df864aa3e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2017 Alibaba Group Holding Limited. 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 "audio_src_pulse.h"
#include "multimedia/mm_types.h"
#include "multimedia/mm_errors.h"
#include "multimedia/mmlistener.h"
#include "multimedia/mm_cpp_utils.h"
#include "multimedia/media_buffer.h"
#include "multimedia/media_meta.h"
#include "multimedia/media_attr_str.h"
#include "multimedia/mm_audio.h"
#include <pulse/sample.h>
#include <pulse/pulseaudio.h>
#include <pulse/thread-mainloop.h>
#include <pthread.h>
#include <stdio.h>
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
#include <multimedia/mm_amhelper.h>
#endif
#ifndef MM_LOG_OUTPUT_V
//#define MM_LOG_OUTPUT_V
#endif
#include <multimedia/mm_debug.h>
namespace YUNOS_MM {
MM_LOG_DEFINE_MODULE_NAME("MSRCP")
static const char * COMPONENT_NAME = "AudioSrcPulse";
static const char * MMTHREAD_NAME = "AudioSinkPulse::Private::InputThread";
#define DEFAULT_VOLUME 1.0
#define DEFAULT_MUTE false
#define MAX_VOLUME 10.0
#define DEFAULT_SAMPLE_RATE 48000
#define DEFAULT_CHANNEL 2
#define DEFAULT_FORMAT SND_FORMAT_PCM_16_BIT
#define CLOCK_TIME_NONE -1
#define PA_ERROR(_retcode, _info, _pa_err_no) do {\
ERROR("%s, retcode: %d, pa: %s\n", _info, _retcode, pa_strerror(_pa_err_no));\
return _retcode;\
}while(0)
static const struct format_entry {
snd_format_t spformat;
pa_sample_format_t pa;
} format_map[] = {
{SND_FORMAT_PCM_16_BIT, PA_SAMPLE_S16LE},
{SND_FORMAT_PCM_32_BIT, PA_SAMPLE_S32LE},
{SND_FORMAT_PCM_8_BIT, PA_SAMPLE_U8},
{SND_FORMAT_INVALID, PA_SAMPLE_INVALID}
};
#define ENTER() VERBOSE(">>>\n")
#define EXIT() do {VERBOSE(" <<<\n"); return;}while(0)
#define EXIT_AND_RETURN(_code) do {VERBOSE("<<<(status: %d)\n", (_code)); return (_code);}while(0)
#define ENTER1() DEBUG(">>>\n")
#define EXIT1() do {DEBUG(" <<<\n"); return;}while(0)
#define EXIT_AND_RETURN1(_code) do {DEBUG("<<<(status: %d)\n", (_code)); return (_code);}while(0)
#define setState(_param, _deststate) do {\
INFO("change state from %d to %s\n", _param, #_deststate);\
(_param) = (_deststate);\
}while(0)
class PAMMAutoLock
{
public:
explicit PAMMAutoLock(pa_threaded_mainloop* loop) : mPALoop(loop)
{
pa_threaded_mainloop_lock (mPALoop);
}
~PAMMAutoLock()
{
pa_threaded_mainloop_unlock (mPALoop);
}
pa_threaded_mainloop* mPALoop;
private:
MM_DISALLOW_COPY(PAMMAutoLock);
};
class AudioSrcPulse::Private
{
public:
enum state_t {
STATE_IDLE,
STATE_PREPARED,
STATE_STARTED,
STATE_PAUSED,
STATE_STOPED,
};
struct QueueEntry {
MediaBufferSP mBuffer;
mm_status_t mFinalResult;
};
class AudioSrcReader : public Reader {
public:
AudioSrcReader(AudioSrcPulse * src){
mSrc = src;
mContinue = true;
}
~AudioSrcReader(){
MMAutoLock locker(mSrc->mPriv->mLock);
mContinue = false;
mSrc->mPriv->mCondition.signal();
}
public:
virtual mm_status_t read(MediaBufferSP & buffer);
virtual MediaMetaSP getMetaData();
private:
AudioSrcPulse *mSrc;
bool mContinue;
};
/* start of inputthread*/
class InputThread;
typedef MMSharedPtr <InputThread> InputThreadSP;
class InputThread : public MMThread {
public:
InputThread(Private* render)
: MMThread(MMTHREAD_NAME)
, mPriv(render)
, mContinue(true)
{
ENTER();
EXIT();
}
~InputThread()
{
ENTER();
EXIT();
}
void signalExit()
{
ENTER();
MMAutoLock locker(mPriv->mLock);
mContinue = false;
mPriv->mCondition.signal();
EXIT();
}
void signalContinue()
{
ENTER();
mPriv->mCondition.signal();
EXIT();
}
static bool releaseInputBuffer(MediaBuffer* mediaBuffer)
{
uint8_t *buffer = NULL;
if (!(mediaBuffer->getBufferInfo((uintptr_t *)&buffer, NULL, NULL, 1))) {
WARNING("error in release mediabuffer");
return false;
}
MM_RELEASE_ARRAY(buffer);
return true;
}
protected:
// Read PCM data from pulseaudio
void main()
{
ENTER();
int toRead = 0;
size_t readSize = 0;
while(1) {
{
MMAutoLock locker(mPriv->mLock);
if (!mContinue) {
MediaBufferSP mediaBuf = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawAudio);
mediaBuf->setSize((int64_t)0);
mediaBuf->setPts(mPriv->mPTS);
mediaBuf->setFlag(MediaBuffer::MBFT_EOS);
mPriv->mAvailableSourceBuffers.push(mediaBuf);
mPriv->mCondition.signal();
break;
}
if (mPriv->mIsPaused || mPriv->mPAReadSize == 0) {
VERBOSE("waitting condition\n");
mPriv->mCondition.wait();
VERBOSE("wakeup condition\n");
continue;
}
toRead = mPriv->mPAReadSize;
mPriv->mPAReadSize = 0;
readSize = 0;
}
mPriv->mPAReadData = NULL;
while(toRead > 0) {
MediaBufferSP mediaBuf = MediaBuffer::createMediaBuffer(MediaBuffer::MBT_RawAudio);
uint8_t *buffer = NULL;
{
PAMMAutoLock paLoop(mPriv->mPALoop);
int ret = pa_stream_peek(mPriv->mPAStream, (const void**)&mPriv->mPAReadData, &readSize);
if (ret != 0) {
ERROR("read error: %s\n", pa_strerror(ret));
continue;
}
if (readSize <= 0) {
ERROR("no data\n");
break;
}
if (!mPriv->mPAReadData) {
pa_stream_drop(mPriv->mPAStream);
toRead -= readSize;
mPriv->mPAReadData = NULL;
readSize = 0;
ERROR("there is a hole.\n");
continue;
}
VERBOSE("read size: %u", readSize);
buffer = new uint8_t[readSize];
memcpy(buffer, mPriv->mPAReadData, readSize);
#ifdef DUMP_SRC_PULSE_DATA
fwrite(buffer, 1, readSize, mPriv->mDumpFile);
#endif
ret = pa_stream_drop(mPriv->mPAStream);
if (ret != 0) {
MMLOGE("drop error: %d\n", ret);
}
mediaBuf->setPts(mPriv->mPTS);
pa_sample_spec sample_spec = {
.format = mPriv->convertFormatToPulse((snd_format_t)mPriv->mFormat),
.rate = (uint32_t)mPriv->mSampleRate,
.channels = (uint8_t)mPriv->mChannelCount
};
mPriv->mPTS += pa_bytes_to_usec((uint64_t)readSize, &sample_spec);
mediaBuf->setBufferInfo((uintptr_t *)&buffer, NULL, (int32_t *)&readSize, 1);
mediaBuf->setSize((int64_t)readSize);
mediaBuf->addReleaseBufferFunc(releaseInputBuffer);
toRead -= readSize;
mPriv->mPAReadData = NULL;
readSize = 0;
}
{
MMAutoLock locker(mPriv->mLock);
mPriv->mAvailableSourceBuffers.push(mediaBuf);
mPriv->mCondition.signal();
}
}
}
INFO("Input thread exited\n");
EXIT();
}
private:
AudioSrcPulse::Private *mPriv;
bool mContinue;
};
/* end of InputThread*/
static PrivateSP create()
{
ENTER();
PrivateSP priv(new Private());
if (priv) {
INFO("private create success");
}
return priv;
}
mm_status_t init(AudioSrcPulse *audioSource) {
ENTER();
mAudioSource = audioSource;
#ifdef DUMP_SRC_PULSE_DATA
mDumpFile = fopen("/data/audio_src_pulse.pcm","wb");
#endif
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t uninit() {
#ifdef DUMP_SRC_PULSE_DATA
fclose(mDumpFile);
#endif
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
~Private() {
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
ENSURE_AUDIO_DEF_CONNECTION_CLEAN();
#endif
}
snd_format_t convertFormatFromPulse(pa_sample_format paFormat);
pa_sample_format convertFormatToPulse(snd_format_t format);
static void contextStateCallback(pa_context *c, void *userdata);
static void contextSourceOutputInfoCallback(pa_context *c, const pa_source_output_info *i, int eol, void *userdata);
static void contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata);
static void contextSourceInfoCallback(pa_context *c, const pa_source_output_info *i, int is_last, void *userdata);
static void streamStateCallback(pa_stream *s, void *userdata);
static void streamLatencyUpdateCallback(pa_stream *s, void *userdata);
static void streamUnderflowCallback(pa_stream *s, void *userdata);
static void streamOverflowCallback(pa_stream *s, void *userdata);
static void streamReadCallback(pa_stream *s, size_t length, void *userdata);
static void streamSuccessCallback(pa_stream*s, int success, void *userdata);
static void streamSuspendedCallback (pa_stream * s, void *userdata);
static void streamStartedCallback (pa_stream * s, void *userdata);
static void streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata);
mm_status_t creatPAContext();
mm_status_t creatPAStream();
mm_status_t release();
mm_status_t freePAContext();
mm_status_t freePASteam();
mm_status_t freePALoop();
mm_status_t streamFlush();
static void streamFlushCallback(pa_stream*s, int success, void *userdata);
mm_status_t cork(int b);
static void streamCorkCallback(pa_stream*s, int success, void *userdata);
void clearPACallback();
void clearSourceBuffers();
mm_status_t setVolume(double volume);
double getVolume();
mm_status_t setMute(bool mute);
bool getMute();
bool waitPAOperation(pa_operation *op);
mm_status_t resumeInternal();
pa_threaded_mainloop *mPALoop;
pa_context *mPAContext;
pa_stream *mPAStream;
size_t mPAReadSize;
double mVolume;
bool mMute;
int32_t mFormat;
int32_t mSampleRate;
int32_t mChannelCount;
int mCorkResult;
int mFlushResult;
std::queue<MediaBufferSP> mAvailableSourceBuffers;
bool mIsPaused;
Condition mCondition;
Lock mLock;
state_t mState;
int32_t mTotalBuffersQueued;
InputThreadSP mInputThread;
AudioSrcPulse *mAudioSource;
MediaMetaSP mMetaData;
const uint8_t * mPAReadData;
uint64_t mDoubleDuration;
uint64_t mPTS;
#ifdef DUMP_SRC_PULSE_DATA
FILE* mDumpFile;
#endif
std::string mAudioConnectionId;
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
ENSURE_AUDIO_DEF_CONNECTION_DECLARE()
#endif
Private()
:mPALoop(NULL),
mPAContext(NULL),
mPAStream(NULL),
mPAReadSize(0),
mVolume(DEFAULT_VOLUME),
mMute(DEFAULT_MUTE),
mFormat(DEFAULT_FORMAT),
mSampleRate(DEFAULT_SAMPLE_RATE),
mChannelCount(DEFAULT_CHANNEL),
mCorkResult(0),
mFlushResult(0),
mIsPaused(true),
mCondition(mLock),
mState(STATE_IDLE),
mTotalBuffersQueued(0),
mPAReadData(NULL),
mDoubleDuration(0),
mPTS(0)
{
ENTER();
mMetaData = MediaMeta::create();
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
ENSURE_AUDIO_DEF_CONNECTION_INIT();
#endif
EXIT();
}
MM_DISALLOW_COPY(Private);
};
#define ASP_MSG_prepare (msg_type)1
#define ASP_MSG_start (msg_type)2
#define ASP_MSG_resume (msg_type)3
#define ASP_MSG_pause (msg_type)4
#define ASP_MSG_stop (msg_type)5
#define ASP_MSG_flush (msg_type)6
#define ASP_MSG_seek (msg_type)7
#define ASP_MSG_reset (msg_type)8
#define ASP_MSG_setParameters (msg_type)9
#define ASP_MSG_getParameters (msg_type)10
BEGIN_MSG_LOOP(AudioSrcPulse)
MSG_ITEM(ASP_MSG_prepare, onPrepare)
MSG_ITEM(ASP_MSG_start, onStart)
MSG_ITEM(ASP_MSG_resume, onResume)
MSG_ITEM(ASP_MSG_pause, onPause)
MSG_ITEM(ASP_MSG_stop, onStop)
MSG_ITEM(ASP_MSG_flush, onFlush)
MSG_ITEM(ASP_MSG_seek, onSeek)
MSG_ITEM(ASP_MSG_reset, onReset)
MSG_ITEM(ASP_MSG_setParameters, onSetParameters)
MSG_ITEM(ASP_MSG_getParameters, onGetParameters)
END_MSG_LOOP()
AudioSrcPulse::AudioSrcPulse(const char *mimeType, bool isEncoder) :MMMsgThread(COMPONENT_NAME)
,mComponentName(COMPONENT_NAME)
{
mPriv = Private::create();
if (!mPriv)
ERROR("no render");
}
AudioSrcPulse::~AudioSrcPulse()
{
//release();
}
Component::ReaderSP AudioSrcPulse::getReader(MediaType mediaType)
{
ENTER();
if ( (int)mediaType != Component::kMediaTypeAudio ) {
ERROR("not supported mediatype: %d\n", mediaType);
return Component::ReaderSP((Component::Reader*)NULL);
}
Component::ReaderSP rsp(new AudioSrcPulse::Private::AudioSrcReader(this));
return rsp;
}
mm_status_t AudioSrcPulse::init()
{
if (!mPriv)
return MM_ERROR_NO_COMPONENT;
int ret = mPriv->init(this); // MMMsgThread->run();
if (ret)
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
ret = MMMsgThread::run();
if (ret != 0) {
ERROR("init failed, ret %d", ret);
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
}
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
void AudioSrcPulse::uninit()
{
ENTER();
mPriv->uninit();
MMMsgThread::exit();
EXIT();
}
const char * AudioSrcPulse::name() const
{
return mComponentName.c_str();
}
mm_status_t AudioSrcPulse::signalEOS() {
mPriv->mIsPaused = true;
if (mPriv->mInputThread) {
mPriv->mInputThread->signalExit();
mPriv->mInputThread.reset();
}
return MM_ERROR_SUCCESS;
}
mm_status_t AudioSrcPulse::setAudioConnectionId(const char * connectionId)
{
mPriv->mAudioConnectionId = connectionId;
}
const char * AudioSrcPulse::getAudioConnectionId() const
{
return mPriv->mAudioConnectionId.c_str();
}
mm_status_t AudioSrcPulse::prepare()
{
postMsg(ASP_MSG_prepare, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::start()
{
postMsg(ASP_MSG_start, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::resume()
{
postMsg(ASP_MSG_resume, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::stop()
{
postMsg(ASP_MSG_stop, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::pause()
{
postMsg(ASP_MSG_pause, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::seek(int msec, int seekSequence)
{
postMsg(ASP_MSG_seek, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::reset()
{
postMsg(ASP_MSG_reset, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::flush()
{
postMsg(ASP_MSG_flush, 0, NULL);
return MM_ERROR_ASYNC;
}
mm_status_t AudioSrcPulse::Private::AudioSrcReader::read(MediaBufferSP & buffer)
{
ENTER();
MMAutoLock locker(mSrc->mPriv->mLock);
if (mSrc->mPriv->mAvailableSourceBuffers.empty()) {
mSrc->mPriv->mCondition.timedWait(mSrc->mPriv->mDoubleDuration);
EXIT_AND_RETURN(MM_ERROR_AGAIN);
} else {
buffer = mSrc->mPriv->mAvailableSourceBuffers.front();
mSrc->mPriv->mAvailableSourceBuffers.pop();
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
}
MediaMetaSP AudioSrcPulse::Private::AudioSrcReader::getMetaData()
{
mSrc->mPriv->mMetaData->setInt32(MEDIA_ATTR_SAMPLE_FORMAT, mSrc->mPriv->mFormat);
mSrc->mPriv->mMetaData->setInt32(MEDIA_ATTR_SAMPLE_RATE, mSrc->mPriv->mSampleRate);
mSrc->mPriv->mMetaData->setInt32(MEDIA_ATTR_CHANNEL_COUNT, mSrc->mPriv->mChannelCount);
mSrc->mPriv->mMetaData->setFraction(MEDIA_ATTR_TIMEBASE, 1, 1000000);
return mSrc->mPriv->mMetaData;
}
mm_status_t AudioSrcPulse::setParameter(const MediaMetaSP & meta)
{
ENTER();
if (!mPriv)
return MM_ERROR_NO_COMPONENT;
if (mPriv->mPALoop)
PAMMAutoLock paLoop(mPriv->mPALoop);
for ( MediaMeta::iterator i = meta->begin(); i != meta->end(); ++i ) {
const MediaMeta::MetaItem & item = *i;
if ( !strcmp(item.mName, MEDIA_ATTR_MUTE) ) {
if ( item.mType != MediaMeta::MT_Int32 ) {
MMLOGW("invalid type for %s\n", item.mName);
continue;
}
mPriv->mMute = item.mValue.ii;
mPriv->setMute(mPriv->mMute);
MMLOGI("key: %s, value: %d\n", item.mName, mPriv->mMute);
continue;
}
if ( !strcmp(item.mName, MEDIA_ATTR_VOLUME) ) {
if ( item.mType != MediaMeta::MT_Int64 ) {
MMLOGW("invalid type for %s\n", item.mName);
continue;
}
mPriv->mVolume = item.mValue.ld;
mPriv->setVolume(mPriv->mVolume);
MMLOGI("key: %s, value: %" PRId64 "\n", item.mName, mPriv->mVolume);
continue;
}
if ( !strcmp(item.mName, MEDIA_ATTR_SAMPLE_FORMAT) ) {
if ( item.mType != MediaMeta::MT_Int32 ) {
MMLOGW("invalid type for %s\n", item.mName);
continue;
}
mPriv->mFormat = item.mValue.ii;
MMLOGI("key: %s, value: %d\n", item.mName, mPriv->mFormat);
continue;
}
if ( !strcmp(item.mName, MEDIA_ATTR_SAMPLE_RATE) ) {
if ( item.mType != MediaMeta::MT_Int32 ) {
MMLOGW("invalid type for %s\n", item.mName);
continue;
}
mPriv->mSampleRate = item.mValue.ii;
MMLOGI("key: %s, value: %d\n", item.mName, mPriv->mSampleRate);
continue;
}
if ( !strcmp(item.mName, MEDIA_ATTR_CHANNEL_COUNT) ) {
if ( item.mType != MediaMeta::MT_Int32 ) {
MMLOGW("invalid type for %s\n", item.mName);
continue;
}
mPriv->mChannelCount = item.mValue.ii;
MMLOGI("key: %s, value: %d\n", item.mName, mPriv->mChannelCount);
continue;
}
}
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t AudioSrcPulse::getParameter(MediaMetaSP & meta) const
{
ENTER();
if (!mPriv)
return MM_ERROR_NO_COMPONENT;
if (!mPriv->mPALoop)
EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM);
PAMMAutoLock paLoop(mPriv->mPALoop);
meta->setInt64(MEDIA_ATTR_VOLUME, mPriv->getVolume());
meta->setInt32(MEDIA_ATTR_MUTE, mPriv->getMute());
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
void AudioSrcPulse::onPrepare(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
mPriv->mPAReadSize = 0;
mm_status_t ret = mPriv->creatPAContext();
if ( ret != MM_ERROR_SUCCESS ) {
ERROR("failed to create context\n");
notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam);
EXIT1();
}
ret = mPriv->creatPAStream();
if ( ret != MM_ERROR_SUCCESS ) {
ERROR("failed to create stream\n");
notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam);
EXIT1();
}
pa_sample_spec sample_spec = {
.format = mPriv->convertFormatToPulse((snd_format_t)mPriv->mFormat),
.rate = (uint32_t)mPriv->mSampleRate,
.channels = (uint8_t)mPriv->mChannelCount
};
size_t frameSize = pa_frame_size(&sample_spec);
mPriv->mDoubleDuration = pa_bytes_to_usec((uint64_t)frameSize, &sample_spec) * 1000ll;
setState(mPriv->mState, mPriv->STATE_PREPARED);
notify(kEventPrepareResult, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
mm_status_t AudioSrcPulse::Private::resumeInternal()
{
if (!mIsPaused) {
ERROR("Aready started\n");
mAudioSource->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam);
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t ret = cork(0);
if ( ret != MM_ERROR_SUCCESS ) {
ERROR("failed to create stream\n");
mAudioSource->notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM);
}
mIsPaused = false;
setState(mState, STATE_STARTED);
mAudioSource->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam);
mInputThread->signalContinue();
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
void AudioSrcPulse::onStart(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
PAMMAutoLock paLoop(mPriv->mPALoop);
// create thread to handle output buffer
if (!mPriv->mInputThread) {
mPriv->mInputThread.reset (new AudioSrcPulse::Private::InputThread(mPriv.get()),MMThread::releaseHelper);
mPriv->mInputThread->create();
}
mPriv->resumeInternal();
EXIT1();
}
void AudioSrcPulse::onResume(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
PAMMAutoLock paLoop(mPriv->mPALoop);
mPriv->resumeInternal();
EXIT1();
}
void AudioSrcPulse::onStop(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
{
mPriv->mIsPaused = true;
if (mPriv->mInputThread) {
mPriv->mInputThread->signalExit();
mPriv->mInputThread.reset();
}
}
PAMMAutoLock paLoop(mPriv->mPALoop);
if (mPriv->mState == mPriv->STATE_IDLE || mPriv->mState == mPriv->STATE_STOPED) {
notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
if (mPriv->mState == mPriv->STATE_STARTED) {
mm_status_t ret = mPriv->streamFlush();
if (MM_ERROR_SUCCESS != ret) {
ERROR("flush fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
ret = mPriv->cork(1);
if (MM_ERROR_SUCCESS != ret) {
ERROR("cork fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
}
mPriv->clearPACallback();
setState(mPriv->mState, mPriv->STATE_STOPED);
notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
void AudioSrcPulse::onPause(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
PAMMAutoLock paLoop(mPriv->mPALoop);
mPriv->mIsPaused = true;
if (mPriv->mState == mPriv->STATE_PAUSED) {
notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
mm_status_t ret = mPriv->cork(1);
if ( ret != MM_ERROR_SUCCESS ) {
ERROR("failed to create stream\n");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT();
}
setState(mPriv->mState, mPriv->STATE_PAUSED);
notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
void AudioSrcPulse::onFlush(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
{
PAMMAutoLock paLoop(mPriv->mPALoop);
mm_status_t ret = mPriv->streamFlush();
if (MM_ERROR_SUCCESS != ret) {
ERROR("flush fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
}
MMAutoLock locker(mPriv->mLock);
mPriv->clearSourceBuffers();
notify(kEventFlushComplete, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
void AudioSrcPulse::onSeek(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
{
PAMMAutoLock paLoop(mPriv->mPALoop);
mm_status_t ret = mPriv->streamFlush();
if (MM_ERROR_SUCCESS != ret) {
ERROR("flush fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
}
MMAutoLock locker(mPriv->mLock);
mPriv->clearSourceBuffers();
notify(kEventSeekComplete, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
void AudioSrcPulse::onReset(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER1();
{
mPriv->mIsPaused = true;
if (mPriv->mInputThread) {
mPriv->mInputThread->signalExit();
mPriv->mInputThread.reset();
}
}
{
PAMMAutoLock paLoop(mPriv->mPALoop);
if (mPriv->mState == mPriv->STATE_STARTED) {
mm_status_t ret = mPriv->streamFlush();
if (MM_ERROR_SUCCESS != ret) {
ERROR("flush fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
ret = mPriv->cork(1);
if (MM_ERROR_SUCCESS != ret) {
ERROR("cork fail");
notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam);
EXIT1();
}
}
mPriv->clearPACallback();
}
{
MMAutoLock locker(mPriv->mLock);
mPriv->clearSourceBuffers();
}
mPriv->release();
setState(mPriv->mState, mPriv->STATE_IDLE);
notify(kEventResetComplete, MM_ERROR_SUCCESS, 0, nilParam);
EXIT1();
}
void AudioSrcPulse::onSetParameters(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER();
/*
if (!strcmp((char *)param1, "setVolume")) {
setVolume((double)param2);
} else if (!strcmp((char *)param1, "setMute")) {
setMute((bool)param2);
} else if (!strcmp((char *)param1, "sampleRate")) {
mSampleRate = (uint32_t)param2;
} else if (!strcmp((char *)param1, "format")) {
mFormat = (snd_format_t)param2;
} else if (!strcmp((char *)param1, "channel")) {
mChannelCount = (uint8_t)param2;
}
*/
//notify(EVENT_SETPARAMETERSCOMPLETE, MM_ERROR_SUCCESS, 0, NULL);
EXIT();
}
void AudioSrcPulse::onGetParameters(param1_type param1, param2_type param2, uint32_t rspId)
{
ENTER();
//if (!strcmp((char *)param1, "getVolume")) {
// notify(EVENT_GETPARAMETERSCOMPLETE, getVolume(), 0, NULL);
//} else if (!strcmp((char *)param1, "getMute")) {
// notify(EVENT_GETPARAMETERSCOMPLETE, getMute(), 0, NULL);
//}
EXIT();
}
bool AudioSrcPulse::Private::waitPAOperation(pa_operation *op) {
if (!op) {
return false;
}
pa_operation_state_t state = pa_operation_get_state(op);
while (state == PA_OPERATION_RUNNING) {
pa_threaded_mainloop_wait(mPALoop);
state = pa_operation_get_state(op);
}
pa_operation_unref(op);
return state == PA_OPERATION_DONE;
}
snd_format_t AudioSrcPulse::Private::convertFormatFromPulse(pa_sample_format paFormat)
{
ENTER();
for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) {
if (format_map[i].pa == paFormat)
EXIT_AND_RETURN(format_map[i].spformat);
}
EXIT_AND_RETURN(SND_FORMAT_INVALID);
}
pa_sample_format AudioSrcPulse::Private::convertFormatToPulse(snd_format_t format)
{
ENTER();
for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) {
if (format_map[i].spformat == format)
EXIT_AND_RETURN(format_map[i].pa);
}
EXIT_AND_RETURN(PA_SAMPLE_INVALID);
}
void AudioSrcPulse::Private::contextStateCallback(pa_context *c, void *userdata)
{
ENTER();
if (c == NULL) {
ERROR("invalid param\n");
return;
}
AudioSrcPulse::Private * me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
switch (pa_context_get_state(c)) {
case PA_CONTEXT_CONNECTING:
case PA_CONTEXT_AUTHORIZING:
case PA_CONTEXT_SETTING_NAME:
break;
case PA_CONTEXT_READY:
case PA_CONTEXT_TERMINATED:
case PA_CONTEXT_FAILED:
pa_threaded_mainloop_signal (me->mPALoop, 0);
break;
default:
break;
}
EXIT();
}
void AudioSrcPulse::Private::contextSourceOutputInfoCallback(pa_context *c, const pa_source_output_info *i, int eol, void *userdata)
{
ENTER();
AudioSrcPulse::Private *me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
if (!i)
goto done;
if (!me->mPAStream)
goto done;
if (i->index == pa_stream_get_index (me->mPAStream)) {
me->mVolume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume));
me->mMute = i->mute;
}
done:
pa_threaded_mainloop_signal (me->mPALoop, 0);
EXIT();
}
void AudioSrcPulse::Private::contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata)
{
ENTER();
AudioSrcPulse::Private *me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
pa_subscription_event_type_t t = pa_subscription_event_type_t(type & PA_SUBSCRIPTION_EVENT_TYPE_MASK);
switch (facility) {
case PA_SUBSCRIPTION_EVENT_SOURCE:
break;
case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT:
if (me->mPAStream && idx == pa_stream_get_index(me->mPAStream )) {
switch (t) {
case PA_SUBSCRIPTION_EVENT_REMOVE:
INFO("PulseAudio source killed");
break;
default:
pa_operation *op = pa_context_get_source_output_info(c, idx, contextSourceOutputInfoCallback, me);
if (!op) {
ERROR("failed to get pa source output info");
}
break;
}
}
break;
case PA_SUBSCRIPTION_EVENT_CARD:
INFO("PA_SUBSCRIPTION_EVENT_CARD");
break;
default:
break;
}
EXIT();
}
void AudioSrcPulse::Private::contextSourceInfoCallback(pa_context *c, const pa_source_output_info *i, int is_last, void *userdata)
{
ENTER();
INFO("context source info");
EXIT();
}
void AudioSrcPulse::Private::streamStateCallback(pa_stream *s, void *userdata)
{
ENTER();
AudioSrcPulse::Private *me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
switch (pa_stream_get_state(s)) {
case PA_STREAM_FAILED:
INFO("pa stream failed");
pa_threaded_mainloop_signal(me->mPALoop, 0);
break;
case PA_STREAM_READY:
INFO("pa stream ready");
pa_threaded_mainloop_signal(me->mPALoop, 0);
break;
case PA_STREAM_TERMINATED:
INFO("pa stream terminated");
pa_threaded_mainloop_signal(me->mPALoop, 0);
break;
default:
break;
}
EXIT();
}
void AudioSrcPulse::Private::streamLatencyUpdateCallback(pa_stream *s, void *userdata)
{
ENTER();
#if 0
AudioSrcPulse *me = static_cast<AudioSrcPulse*>(userdata);
MMASSERT(me);
const pa_timing_info *info;
pa_usec_t sink_usec;
info = pa_stream_get_timing_info (s);
if (!info) {
return;
}
sink_usec = info->configured_sink_usec;
VERBOSE("write_index_corrupt = %d write_index = %llu read_index_corrupt = %d read_index = %d info->sink_usec = %llu configured_sink_usec = %llu \n",
info->write_index_corrupt,
info->write_index,
info->read_index_corrupt,
info->read_index,
info->sink_usec,
sink_usec);
#endif
EXIT();
}
void AudioSrcPulse::Private::streamUnderflowCallback(pa_stream *s, void *userdata)
{
ENTER();
INFO("under flow");
EXIT();
}
void AudioSrcPulse::Private::streamOverflowCallback(pa_stream *s, void *userdata)
{
ENTER();
INFO("over flow");
EXIT();
}
void AudioSrcPulse::Private::streamReadCallback(pa_stream *s, size_t length, void *userdata)
{
ENTER();
AudioSrcPulse::Private *me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
MMAutoLock locker(me->mLock);
if (!me->mIsPaused) {
me->mPAReadSize = length;
me->mCondition.signal();
VERBOSE("stream readable length = %d", length);
}
EXIT();
}
void AudioSrcPulse::Private::streamSuspendedCallback (pa_stream * s, void *userdata)
{
ENTER();
AudioSrcPulse::Private *me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
if (pa_stream_is_suspended (s))
INFO ("stream suspended");
else
INFO ("stream resumed");
EXIT();
}
void AudioSrcPulse::Private::streamStartedCallback (pa_stream * s, void *userdata)
{
ENTER();
INFO ("stream started");
EXIT();
}
void AudioSrcPulse::Private::streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata)
{
ENTER();
INFO ("stream event name = %s",name);
EXIT();
}
mm_status_t AudioSrcPulse::Private::creatPAContext()
{
ENTER();
int ret;
pa_mainloop_api *api;
/* Set up a new main loop */
MMLOGV("newing pa thread main loop\n");
mPALoop = pa_threaded_mainloop_new();
if (mPALoop == NULL){
PA_ERROR(MM_ERROR_NO_MEM, "failed to get pa api", pa_context_errno(mPAContext));
}
api = pa_threaded_mainloop_get_api(mPALoop);
pa_proplist *proplist = pa_proplist_new();
if ( !proplist ) {
PA_ERROR(MM_ERROR_NO_MEM, "failed to new proplist", pa_context_errno(mPAContext));
}
ret = pa_proplist_sets(proplist, "log-backtrace", "10");
if ( ret < 0 ) {
pa_proplist_free(proplist);
PA_ERROR(MM_ERROR_NO_MEM, "failed to set proplist", ret);
}
mPAContext = pa_context_new_with_proplist(api, COMPONENT_NAME, proplist);
pa_proplist_free(proplist);
if (mPAContext == NULL) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa api", pa_context_errno(mPAContext));
}
pa_context_set_state_callback(mPAContext, contextStateCallback, this);
/* Connect the context */
INFO("connecting pa context\n");
ret = pa_context_connect(mPAContext, "127.0.0.1", PA_CONTEXT_NOFLAGS, NULL);
if ( ret < 0) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to connect to context", ret);
}
INFO("starting pa mainloop\n");
ret = pa_threaded_mainloop_start(mPALoop);
if(ret != 0){
PA_ERROR(MM_ERROR_OP_FAILED, "failed to start mainloop", ret);
}
mm_status_t result;
INFO("waitting context ready\n");
PAMMAutoLock paLoop(mPALoop);
while ( 1 ) {
pa_context_state_t state = pa_context_get_state (mPAContext);
INFO("now state: %d\n", state);
if ( state == PA_CONTEXT_READY ) {
INFO("ready\n");
result = MM_ERROR_SUCCESS;
break;
} else if ( state == PA_CONTEXT_TERMINATED || state == PA_CONTEXT_FAILED ) {
INFO("terminated or failed\n");
result = MM_ERROR_OP_FAILED;
break;
}
INFO("not expected state, wait\n");
pa_threaded_mainloop_wait (mPALoop);
}
EXIT_AND_RETURN(result);
}
mm_status_t AudioSrcPulse::Private::creatPAStream()
{
ENTER();
uint32_t flags = PA_STREAM_AUTO_TIMING_UPDATE |
PA_STREAM_START_CORKED;
#ifdef USE_PA_STREAM_INTERPOLATE_TIMING
flags |= PA_STREAM_INTERPOLATE_TIMING;
#endif
#ifdef USE_PA_STREAM_ADJUST_LATENCY
flags |= PA_STREAM_ADJUST_LATENCY;
#endif
pa_sample_spec ss = {
.format = convertFormatToPulse((snd_format_t)mFormat),
.rate = (uint32_t)mSampleRate,
.channels = (uint8_t)mChannelCount
};
MMLOGI("format: format: %d, rate: %d, channels: %d\n", ss.format, ss.rate, ss.channels);
pa_proplist *pl = pa_proplist_new();
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
ENSURE_AUDIO_DEF_CONNECTION_ENSURE(mAudioConnectionId, MMAMHelper::recordChnnelMic());
#endif
MMLOGI("connection_id: %s\n", mAudioConnectionId.c_str());
pa_proplist_sets(pl, "connection_id", mAudioConnectionId.c_str());
mPAStream = pa_stream_new_with_proplist(mPAContext, COMPONENT_NAME, &ss, NULL, pl);
//mPAStream = pa_stream_new(mPAContext, COMPONENT_NAME, &ss, NULL);
if (!mPAStream) {
ERROR("PulseAudio: failed to create a stream");
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
}
pa_buffer_attr attr;
memset(&attr, 0, sizeof(attr));
attr.maxlength = (uint32_t) -1;;
attr.tlength = (uint32_t) -1;
attr.prebuf = (uint32_t)-1;
attr.minreq = (uint32_t) -1;
attr.fragsize = (uint32_t) -1;
int ret = pa_stream_connect_record(mPAStream, NULL, &attr, (pa_stream_flags_t)flags);
if( ret != 0 ){
ERROR("PulseAudio: failed to connect record stream");
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
}
/* install essential callbacks */
pa_stream_set_read_callback(mPAStream, streamReadCallback, this);
pa_stream_set_state_callback(mPAStream, streamStateCallback, this);
pa_stream_set_underflow_callback (mPAStream, streamUnderflowCallback, this);
pa_stream_set_overflow_callback (mPAStream, streamOverflowCallback, this);
//pa_stream_set_latency_update_callback (mPAStream, streamLatencyUpdateCallback, this);
pa_stream_set_suspended_callback (mPAStream, streamSuspendedCallback, this);
pa_stream_set_started_callback (mPAStream, streamStartedCallback, this);
pa_stream_set_event_callback (mPAStream, streamEventCallback, this);
PAMMAutoLock paLoop(mPALoop);
while (true) {
const pa_stream_state_t st = pa_stream_get_state(mPAStream);
if (st == PA_STREAM_READY)
break;
if (!PA_STREAM_IS_GOOD(st)) {
ERROR("PulseAudio stream init failed");
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
}
pa_threaded_mainloop_wait(mPALoop);
}
if (pa_stream_is_suspended(mPAStream)) {
ERROR("PulseAudio stream is suspende");
EXIT_AND_RETURN(MM_ERROR_OP_FAILED);
}
INFO("over\n");
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t AudioSrcPulse::Private::freePAContext()
{
PAMMAutoLock paLoop(mPALoop);
if (mPAContext) {
pa_context_disconnect (mPAContext);
pa_context_unref (mPAContext);
mPAContext = NULL;
}
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t AudioSrcPulse::Private::freePASteam()
{
ENTER();
PAMMAutoLock paLoop(mPALoop);
if (mPAStream) {
pa_stream_disconnect (mPAStream);
pa_stream_unref(mPAStream);
mPAStream = NULL;
}
#ifdef ENABLE_DEFAULT_AUDIO_CONNECTION
ENSURE_AUDIO_DEF_CONNECTION_CLEAN();
#endif
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t AudioSrcPulse::Private::freePALoop()
{
ENTER();
if (mPALoop) {
pa_threaded_mainloop_stop(mPALoop);
pa_threaded_mainloop_free(mPALoop);
mPALoop = NULL;
}
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
}
mm_status_t AudioSrcPulse::Private::streamFlush()
{
ENTER();
mFlushResult = 0;
if (!waitPAOperation(pa_stream_flush(mPAStream, streamFlushCallback, this))) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
}
INFO("result: %d\n", mFlushResult);
EXIT_AND_RETURN(mFlushResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED);
}
void AudioSrcPulse::Private::streamFlushCallback(pa_stream*s, int success, void *userdata)
{
ENTER();
AudioSrcPulse::Private * me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
me->mFlushResult = success ? 1 : -1;
pa_threaded_mainloop_signal (me->mPALoop, 0);
EXIT();
}
mm_status_t AudioSrcPulse::Private::cork(int b)
{
ENTER();
mCorkResult = 0;
if (!waitPAOperation(pa_stream_cork(mPAStream, b, streamCorkCallback, this))) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
}
INFO("result: %d\n", mCorkResult);
EXIT_AND_RETURN(mCorkResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED);
}
void AudioSrcPulse::Private::streamCorkCallback(pa_stream*s, int success, void *userdata)
{
ENTER();
AudioSrcPulse::Private * me = static_cast<AudioSrcPulse::Private*>(userdata);
MMASSERT(me);
me->mCorkResult = success ? 1 : -1;
pa_threaded_mainloop_signal (me->mPALoop, 0);
EXIT();
}
mm_status_t AudioSrcPulse::Private::release()
{
ENTER();
mm_status_t ret;
ret = freePASteam();
ret = freePAContext();
ret = freePALoop();
EXIT_AND_RETURN(ret);
}
void AudioSrcPulse::Private::clearPACallback()
{
if (mPAContext) {
/* Make sure we don't get any further callbacks */
pa_context_set_state_callback (mPAContext, NULL, NULL);
pa_context_set_subscribe_callback (mPAContext, NULL, NULL);
}
if (mPAStream) {
/* Make sure we don't get any further callbacks */
pa_stream_set_state_callback(mPAStream, NULL, NULL);
pa_stream_set_write_callback(mPAStream, NULL, NULL);
pa_stream_set_underflow_callback(mPAStream, NULL, NULL);
pa_stream_set_overflow_callback(mPAStream, NULL, NULL);
pa_stream_set_latency_update_callback (mPAStream, NULL, NULL);
pa_stream_set_suspended_callback (mPAStream, NULL, NULL);
pa_stream_set_started_callback (mPAStream, NULL, NULL);
pa_stream_set_event_callback (mPAStream, NULL, NULL);
}
}
void AudioSrcPulse::Private::clearSourceBuffers()
{
while(!mAvailableSourceBuffers.empty()) {
mAvailableSourceBuffers.pop();
}
}
mm_status_t AudioSrcPulse::Private::setVolume(double volume)
{
ENTER();
pa_cvolume vol;
pa_operation *o = NULL;
uint32_t idx;
mVolume = volume;
if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX)
goto no_index;
pa_cvolume_reset(&vol, mChannelCount);
pa_cvolume_set(&vol, mChannelCount, pa_volume_t(volume*double(PA_VOLUME_NORM)));
if (!(o = pa_context_set_source_output_volume (mPAContext, idx, &vol, NULL, NULL)))
goto volume_failed;
unlock:
if (o)
pa_operation_unref (o);
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
/* ERRORS */
no_index:
{
INFO ("we don't have a stream index");
goto unlock;
}
volume_failed:
{
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto unlock;
}
}
double AudioSrcPulse::Private::getVolume()
{
ENTER();
double v = DEFAULT_VOLUME;
pa_operation *o = NULL;
uint32_t idx;
if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX)
goto no_index;
if (!waitPAOperation(pa_context_get_source_output_info(mPAContext, idx, contextSourceOutputInfoCallback, this))) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto volume_failed;
}
unlock:
v = mVolume;
if (o)
pa_operation_unref (o);
EXIT_AND_RETURN(v);
/* ERRORS */
no_index:
{
INFO ("we don't have a stream index");
goto unlock;
}
volume_failed:
{
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto unlock;
}
}
mm_status_t AudioSrcPulse::Private::setMute(bool mute)
{
ENTER();
pa_operation *o = NULL;
uint32_t idx;
mMute = mute;
if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX)
goto no_index;
if (!(o = pa_context_set_source_output_mute (mPAContext, idx, mute, NULL, NULL)))
goto mute_failed;
unlock:
if (o)
pa_operation_unref (o);
EXIT_AND_RETURN(MM_ERROR_SUCCESS);
/* ERRORS */
no_index:
{
INFO ("we don't have a stream index");
goto unlock;
}
mute_failed:
{
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto unlock;
}
}
bool AudioSrcPulse::Private::getMute()
{
ENTER();
pa_operation *o = NULL;
uint32_t idx;
bool mute = mMute;
if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX)
goto no_index;
if (!waitPAOperation(pa_context_get_source_output_info(mPAContext, idx, contextSourceOutputInfoCallback, this))) {
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto mute_failed;
}
unlock:
mute = mMute;
if (o)
pa_operation_unref (o);
EXIT_AND_RETURN(mute);
/* ERRORS */
no_index:
{
INFO ("we don't have a stream index");
goto unlock;
}
mute_failed:
{
PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa source output info", pa_context_errno(mPAContext));
goto unlock;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////
extern "C" {
YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder)
{
//INFO("createComponent");
YUNOS_MM::AudioSrcPulse *sourceComponent = new YUNOS_MM::AudioSrcPulse(mimeType, isEncoder);
if (sourceComponent == NULL) {
return NULL;
}
return static_cast<YUNOS_MM::Component*>(sourceComponent);
}
void releaseComponent(YUNOS_MM::Component *component)
{
//INFO("createComponent");
delete component;
}
}
| 29.994835 | 153 | 0.62832 | [
"render"
] |
e344014eb6ebcb2ec7d9915730215170d8277092 | 6,147 | cpp | C++ | src/dbobjects/common/DbTrigger.cpp | Ascent-Group/visual-db | 4cd074fb64fac2def74bb5005fc0d46caa0e96f7 | [
"BSD-3-Clause"
] | 1 | 2015-06-25T18:12:50.000Z | 2015-06-25T18:12:50.000Z | src/dbobjects/common/DbTrigger.cpp | Ascent-Group/visual-db | 4cd074fb64fac2def74bb5005fc0d46caa0e96f7 | [
"BSD-3-Clause"
] | null | null | null | src/dbobjects/common/DbTrigger.cpp | Ascent-Group/visual-db | 4cd074fb64fac2def74bb5005fc0d46caa0e96f7 | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 2009, Ascent Group.
* 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 Ascent Group nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <common/DbSchema.h>
#include <common/DbTrigger.h>
#include <QtDebug>
namespace DbObjects
{
namespace Common
{
/*!
* Constructor
*
* \param[in] ipName - Name of a trigger
* \param[in] ipSchema - Handle to schema that contains the given trigger
*/
DbTrigger::DbTrigger(QString ipName, const DbSchemaPtr &ipSchema)
: DbObject(ipName),
mTable(),
mSchema(ipSchema),
mProcedure(),
mEnabled(),
mIsConstraint(false),
mConstraintName(""),
mReferencedTable(),
mIsDeferrable(false),
mIsInitiallyDeferred(false),
mNumArgs(0)
{
if (!mSchema.get()) qDebug() << "DbTrigger::DbTrigger> mSchema is NULL!";
}
/*!
* Destructor
*/
DbTrigger::~DbTrigger()
{
}
/*!
* \return Handle to parent schema
*/
DbSchemaPtr
DbTrigger::schema() const
{
return mSchema;
}
/*!
* \param[in] ipSchema - Parent schema handle
*/
void
DbTrigger::setSchema(const DbSchemaPtr &ipSchema)
{
mSchema = ipSchema;
}
/*!
* \return Handle for the table this trigger is on
*/
DbTablePtr
DbTrigger::table() const
{
return mTable;
}
/*!
* Sets the table
* \param[in] ipTable - Table handle
*/
void
DbTrigger::setTable(const DbTablePtr &ipTable)
{
mTable = ipTable;
}
/*!
* \return The procedure that runs when trigger fires
*/
DbProcedurePtr
DbTrigger::procedure() const
{
return mProcedure;
}
/*!
* Sets the procedure
*
* \param[in] ipProcedure - Procedure handle
*/
void
DbTrigger::setProcedure(const DbProcedurePtr &ipProcedure)
{
mProcedure = ipProcedure;
}
/*!
* \return 'Enabled' flag
*/
QChar
DbTrigger::enabled() const
{
return mEnabled;
}
/*!
* \return Trigger's fullname in "Schema.Trigger" format
*/
QString
DbTrigger::fullName() const
{
return QString("%1.%2").arg(mSchema->name()).arg(mName);
}
/*!
* Sets the enabled flag
* \param[in] ipFlag - Indicates whether the trigger is enabled
*/
void
DbTrigger::setEnabled(const QChar &ipFlag)
{
mEnabled = ipFlag;
}
/*!
* \return true - If trigger is a constraint
* \return false - Otherwise
*/
bool
DbTrigger::isConstraint() const
{
return mIsConstraint;
}
/*!
* Sets the constraint flag
*
*/
void
DbTrigger::setConstraint(bool ipFlag)
{
mIsConstraint = ipFlag;
}
/*!
* \return The constraint name if the trigger is a constraint
*/
QString
DbTrigger::constraintName() const
{
if (!mIsConstraint) {
return QString("");
}
return mConstraintName;
}
/*!
* Sets the constraint name for a constraint trigger
*
* \param[in] ipName - Constraint name
*/
void
DbTrigger::setConstraintName(const QString &ipName)
{
mConstraintName = ipName;
}
/*!
* \return The referenced table handle
*/
DbTablePtr
DbTrigger::referencedTable() const
{
return mReferencedTable;
}
/*!
* Sets the table referenced by this trigger
*
* \param[in] ipTable
*/
void
DbTrigger::setReferencedTable(const DbTablePtr &ipTable)
{
mReferencedTable = ipTable;
}
/*!
* \return true - If the trigger if deferrable
* \return false - Otherwise
*/
bool
DbTrigger::isDeferrable() const
{
return mIsDeferrable;
}
/*!
* Sets the deferrrable flag
*
* \param[in] ipFlag - Inidicates whether the trigger is deferrable
*/
void
DbTrigger::setDeferrable(bool ipFlag)
{
mIsDeferrable = ipFlag;
}
/*!
* \return true - If the trigger is initially deferred
* \return false - Otherwise
*/
bool
DbTrigger::isInitiallyDeferred() const
{
return mIsInitiallyDeferred;
}
/*!
* Sets the initially deferred flag
*
* \param[in] ipFlag - Indicates, whether the trigger is initially deferred
*/
void
DbTrigger::setInitiallyDeferred(bool ipFlag)
{
mIsInitiallyDeferred = ipFlag;
}
/*!
* \return The number of args passed to the trigger
*/
quint16
DbTrigger::numArgs() const
{
return mNumArgs;
}
/*!
* Sets the number of arguments passed to the trigger
*
* \param[in] ipNum - Number of args
*/
void
DbTrigger::setNumArgs(const quint16 &ipNum)
{
mNumArgs = ipNum;
}
/*!
* \return The database object type identifier
*/
DbObject::Type
DbTrigger::type() const
{
return DbObject::TriggerObject;
}
/*!
* \brief Resets data read from database
*/
void
DbTrigger::resetData()
{
mTable = DbTablePtr();
mSchema = DbSchemaPtr();
mProcedure = DbProcedurePtr();
mEnabled = 0;
mIsConstraint = false;
mConstraintName = "";
mReferencedTable = DbTablePtr();
mIsDeferrable = false;
mIsInitiallyDeferred = false;
mNumArgs = 0;
DbObject::resetData();
}
} // namespace Common
} // namespace DbObjects
| 19.514286 | 85 | 0.693997 | [
"object"
] |
e34c1aa84c645658cbff52e46228e6fb3685c08e | 1,162 | hpp | C++ | src/gizmo/TranslateGizmo.hpp | buresu/OgreMockup | 7084ea520900b41a6a56ac4b261d52823eba00bc | [
"MIT"
] | null | null | null | src/gizmo/TranslateGizmo.hpp | buresu/OgreMockup | 7084ea520900b41a6a56ac4b261d52823eba00bc | [
"MIT"
] | null | null | null | src/gizmo/TranslateGizmo.hpp | buresu/OgreMockup | 7084ea520900b41a6a56ac4b261d52823eba00bc | [
"MIT"
] | null | null | null | #pragma once
#include "AbstractGizmo.hpp"
class TranslateGizmo : public AbstractGizmo {
public:
enum TranslateType {
TranslateType_None,
TranslateType_X,
TranslateType_Y,
TranslateType_Z,
TranslateType_Camera
};
explicit TranslateGizmo(const Ogre::String &name);
virtual ~TranslateGizmo();
virtual bool mousePressed(const Ogre::Ray &ray) override;
virtual bool mouseMoved(const Ogre::Ray &ray) override;
virtual bool mouseReleased(const Ogre::Ray &ray) override;
protected:
virtual void render() override;
TranslateType mCurrentTranslateType = TranslateType_None;
Ogre::Vector3 mStartPosition = Ogre::Vector3::ZERO;
Ogre::Vector3 mTargetStart = Ogre::Vector3::ZERO;
};
class TranslateGizmoFactory : public Ogre::MovableObjectFactory {
public:
static Ogre::String FACTORY_TYPE_NAME;
TranslateGizmoFactory() {}
~TranslateGizmoFactory() {}
const Ogre::String &getType(void) const override;
void destroyInstance(Ogre::MovableObject *obj) override;
protected:
Ogre::MovableObject *
createInstanceImpl(const Ogre::String &name,
const Ogre::NameValuePairList *params) override;
};
| 25.26087 | 69 | 0.745267 | [
"render"
] |
e355a6000b52f91d768fa4a029d3872e45b167e8 | 5,369 | cpp | C++ | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Collisions/RIGID_BODY_IMPULSE_ACCUMULATOR.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Collisions/RIGID_BODY_IMPULSE_ACCUMULATOR.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Solids/PhysBAM_Rigids/Collisions/RIGID_BODY_IMPULSE_ACCUMULATOR.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | //#####################################################################
// Copyright 2004-2005, Zhaosheng Bao, Eran Guendelman, Sergey Koltakov.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Arrays/INDIRECT_ARRAY.h>
#include <PhysBAM_Tools/Log/LOG.h>
#include <PhysBAM_Geometry/Basic_Geometry/BASIC_SIMPLEX_POLICY.h>
#include <PhysBAM_Geometry/Basic_Geometry/TETRAHEDRON.h>
#include <PhysBAM_Geometry/Basic_Geometry/TRIANGLE_2D.h>
#include <PhysBAM_Geometry/Basic_Geometry/TRIANGLE_3D.h>
#include <PhysBAM_Geometry/Topology_Based_Geometry/TETRAHEDRALIZED_VOLUME.h>
#include <PhysBAM_Geometry/Topology_Based_Geometry/TRIANGULATED_AREA.h>
#include <PhysBAM_Geometry/Topology_Based_Geometry/TRIANGULATED_SURFACE.h>
#include <PhysBAM_Solids/PhysBAM_Rigids/Collisions/RIGID_BODY_IMPULSE_ACCUMULATOR.h>
#include <PhysBAM_Solids/PhysBAM_Rigids/Rigid_Bodies/RIGID_BODY.h>
using namespace PhysBAM;
//#####################################################################
// Function Reset
//#####################################################################
template<class TV,int d> void RIGID_BODY_IMPULSE_ACCUMULATOR<TV,d>::
Reset()
{
accumulated_impulse=TWIST<TV>();
if(accumulated_node_impulses){
accumulated_node_impulses->Resize(simplicial_object->particles.array_collection->Size(),false,false);
ARRAYS_COMPUTATIONS::Fill(*accumulated_node_impulses,TV());}
}
//#####################################################################
// Function Initialize_Simplicial_Object
//#####################################################################
template<class TV,int d> void RIGID_BODY_IMPULSE_ACCUMULATOR<TV,d>::
Initialize_Simplicial_Object(T_SIMPLICIAL_OBJECT* simplicial_object_input,ARRAY<TV>* accumulated_node_impulses_input)
{
simplicial_object=simplicial_object_input;
accumulated_node_impulses=accumulated_node_impulses_input;
{std::stringstream ss;ss<<" "<<simplicial_object->particles.array_collection->Size();LOG::filecout(ss.str());}
}
//#####################################################################
// Function Add_Impulse
//#####################################################################
template<class T_OBJECT,class T,class TV> static int
Inside_Helper(T_OBJECT& object,const TV& object_space_location,const T surface_roughness)
{
//return object.Inside(object_space_location,surface_roughness);
return 0;
}
template<class T,class TV> static int
Inside_Helper(TRIANGULATED_SURFACE<T>& triangulated_surface,const TV& object_space_location,const T surface_roughness)
{
if(!triangulated_surface.triangle_list) triangulated_surface.Update_Triangle_List();
if(!triangulated_surface.hierarchy) triangulated_surface.Initialize_Hierarchy();
int simplex=0;triangulated_surface.Inside_Any_Triangle(object_space_location,simplex,surface_roughness);
assert(simplex);return simplex;
}
template<class T,class TV> static int
Inside_Helper(TETRAHEDRALIZED_VOLUME<T>& tetrahedralized_volume,const TV& object_space_location,const T surface_roughness)
{
if(!tetrahedralized_volume.tetrahedron_list) tetrahedralized_volume.Update_Tetrahedron_List();
if(!tetrahedralized_volume.hierarchy) tetrahedralized_volume.Initialize_Hierarchy(true);
return tetrahedralized_volume.Inside(object_space_location,surface_roughness);
}
template<class TV,int d> void RIGID_BODY_IMPULSE_ACCUMULATOR<TV,d>::
Add_Impulse(const TV& location,const TWIST<TV>& impulse)
{
accumulated_impulse+=impulse;
if(simplicial_object && accumulated_node_impulses){
typedef typename BASIC_SIMPLEX_POLICY<TV,d>::SIMPLEX T_SIMPLEX;
TV object_space_location=rigid_body.Object_Space_Point(location);
TV object_space_impulse=rigid_body.Object_Space_Vector(impulse.linear);
ARRAY_VIEW<TV> X(simplicial_object->particles.X);
int simplex=Inside_Helper(*simplicial_object,object_space_location,surface_roughness);
if(simplex){
VECTOR<int,d+1>& nodes=simplicial_object->mesh.elements(simplex);
//VECTOR<T,d+1> weights=T_SIMPLEX::Barycentric_Coordinates(object_space_location,X.Subset(nodes));
VECTOR<T,d+1> weights;
for(int i=1;i<=weights.m;i++) (*accumulated_node_impulses)(nodes[i])+=weights[i]*object_space_impulse;}}
}
//#####################################################################
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,1>,0>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,1>,1>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,2>,1>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,2>,2>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,3>,2>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<float,3>,3>;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,1>,0>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,1>,1>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,2>,1>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,2>,2>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,3>,2>;
template class RIGID_BODY_IMPULSE_ACCUMULATOR<VECTOR<double,3>,3>;
#endif
| 57.117021 | 135 | 0.714844 | [
"mesh",
"object",
"vector"
] |
e35d50404842586766bf77764a01ea80bd714d95 | 1,053 | cpp | C++ | GFG/Backtracking/tugofwar.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | GFG/Backtracking/tugofwar.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | GFG/Backtracking/tugofwar.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int dp[100][100] = {-1};
int subSetSum(vector<int> &nums, int target)
{
for (int i = 0; i <= nums.size(); i++)
{
dp[i][0] = 1;
}
for (int i = 1; i <= target; i++)
{
dp[0][i] = 0;
}
for (int i = 1; i <= nums.size(); i++)
{
for (int j = 1; j <= target; j++)
{
if (j == 0)
return 1;
if (j >= nums[i])
{
dp[i][j] = dp[i - 1][j - nums[i - 1]] || dp[i - 1][j];
}
else if (j < nums[i])
dp[i][j] = dp[i - 1][j];
}
}
return dp[nums.size()][target];
}
int tugofwarMinDiff(vector<int> &nums)
{
int target = 0;
for (int &j : nums)
{
target += j;
}
int x = subSetSum(nums, target);
int min = INT_MAX;
for (int i = 0; i <= target / 2; i++)
{
if (dp[nums.size()][i])
if (target - 2 * i < min)
min = target - 2 * i;
}
return min;
} | 22.404255 | 70 | 0.391263 | [
"vector"
] |
e3611914d1a05734af3eb54a881794d56f62dbfe | 417 | hpp | C++ | backend/Simulator/processor.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | null | null | null | backend/Simulator/processor.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | null | null | null | backend/Simulator/processor.hpp | Ridhii/SyncdSim | 4cd120e9f7d4db348d405db4608ef9c6f9499d01 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PROCESSOR_HPP
#define PROCESSOR_HPP
#include "common.hpp"
#include "context.hpp"
class Context;
class Processor{
private:
contech::Task* currTask;
std::vector<contech::MemoryAction> memActionQueue;
Context* myContext;
int tempTotalTask;
public:
Processor(Context* context);
void run();
void populateMemActionQueue();
void reAddCurrMemOp(uint64_t addr, contech::action_type type);
};
#endif
| 13.9 | 63 | 0.757794 | [
"vector"
] |
e3650f075d2f715223b3206606152042fc293819 | 12,886 | cpp | C++ | ELM_GUI_lib/ELM_GUI_lib/ELM.cpp | therealddx/EagleLibraryManager | bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8 | [
"MIT"
] | null | null | null | ELM_GUI_lib/ELM_GUI_lib/ELM.cpp | therealddx/EagleLibraryManager | bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8 | [
"MIT"
] | null | null | null | ELM_GUI_lib/ELM_GUI_lib/ELM.cpp | therealddx/EagleLibraryManager | bc6dfb2f9dbbc6cf8d3145befdeb71e5c9c8e0e8 | [
"MIT"
] | null | null | null | #include "Stdafx.h"
#include "ELM.h"
#include "ctype.h"
namespace ELM_GUI_lib {
//Declare constructors.
ELM::ELM() {
}
ELM::ELM(const ELM& orig) {
}
ELM::~ELM() {
}
//Declare variables.
int ELM::numDevices;
Device * ELM::deviceList;
std::string ELM::preMaterial;
std::string ELM::postMaterial;
//Level IV
void ELM::getPreMaterial(std::string filename) {
std::ifstream readIn(filename.c_str());
std::string buf_string;
preMaterial = "";
while (std::getline(readIn, buf_string, '\n')) {
preMaterial.append(buf_string.append("\n"));
if (matchHeaderXML(buf_string, XMLParse::LAYERS_END))
break;
}
readIn.close();
}
void ELM::getPostMaterial(std::string filename) {
std::ifstream readIn(filename.c_str());
std::string buf_string;
bool postMaterial_FLAG = false;
postMaterial = "";
while (std::getline(readIn,buf_string,'\n')) {
if (matchHeaderXML(buf_string, XMLParse::DRAWING_END))
postMaterial_FLAG = true;
if (postMaterial_FLAG == true) {
postMaterial.append(buf_string.append("\n"));
}
}
postMaterial = postMaterial.substr(0, postMaterial.length() - 1);
readIn.close();
}
bool ELM::isValidName(std::string name) {
//to be valid:
//name cannot have spaces.
//name cannot have lowercase letters.
if (name.find(" ") != std::string::npos)
return false;
for (char c : name) {
if (islower(c))
return false;
}
return true;
}
//Level III
void ELM::countDevices(std::string filename) {
std::ifstream readIn(filename.c_str());
numDevices = 0;
std::string buf_string;
while (std::getline(readIn, buf_string, '\n')) {
if (matchHeaderXML(buf_string, XMLParse::DEVICESET_START)) {
//std::cout<<buf_string<<'\n';
numDevices++;
}
}
readIn.close();
}
bool ELM::matchHeaderXML(std::string buf_string, XMLParse::XML_TAGS match_header_xml) {
switch (match_header_xml)
{
case XMLParse::DEVICESET_START:
return (buf_string.find("<deviceset name=") != std::string::npos);
case XMLParse::DEVICESET_END:
return (buf_string.find("</deviceset>") != std::string::npos);
case XMLParse::SYMBOL_START:
return (buf_string.find("<symbol name=") != std::string::npos);
case XMLParse::SYMBOL_END:
return (buf_string.find("</symbol>") != std::string::npos);
case XMLParse::PACKAGE_START:
return (buf_string.find("<package name=") != std::string::npos);
case XMLParse::PACKAGE_END:
return (buf_string.find("</package>") != std::string::npos);
case XMLParse::LAYERS_END:
return (buf_string.find("</layers>") != std::string::npos);
case XMLParse::DEVICESETS_END:
return (buf_string.find("</devicesets>") != std::string::npos);
case XMLParse::DRAWING_END:
return (buf_string.find("</drawing>") != std::string::npos);
default:
return false;
}
}
int ELM::findDeviceName(std::string nameToFind) {
//returns an integer corresponding to the index n s/t dlist[n].name == name.
//if not found, returns -1.
for (int n = 0; n < numDevices; n++) {
if (deviceList[n].name.compare(nameToFind) == 0)
return n;
}
return -1;
}
//Level II
std::string ELM::getXML_givenName(std::string filename, std::string name, XMLParse::XML_TAGS START_ENUM, XMLParse::XML_TAGS END_ENUM) {
//Gets XML for any name, for any Class. (Device, package, or symbol).
std::ifstream readIn(filename.c_str());
readIn.clear();
readIn.seekg(0, readIn.beg);
std::string XML_out = "";
std::string buf_string;
bool nameFound_FLAG = false;
while (std::getline(readIn,buf_string, '\n')) {
if ((matchHeaderXML(buf_string, START_ENUM)) && (name.compare(XMLParse::nameFromXML(buf_string)) == 0)) {
//Once you find this start tag, and it's the name you want.
nameFound_FLAG = true;
//Tack on the XML.
buf_string.append("\n");
XML_out.append(buf_string);
//Get the rest of the XML code.
while (!matchHeaderXML(buf_string, END_ENUM)) { //While you don't see end-tag
std::getline(readIn, buf_string, '\n');
buf_string.append("\n");
XML_out.append(buf_string); //Tack it on
}
break;
}
}
readIn.close();
return XML_out;
}
void ELM::getXML_AllDevices(std::string filename) {
//Returns a Device * with all your devices, and their XML / name filled out.
deviceList = new Device[numDevices];
int device_ind = 0;
std::ifstream readIn(filename.c_str());
std::string buf_string;
std::string XML_out;
while (std::getline(readIn, buf_string, '\n')) {
if (matchHeaderXML(buf_string, XMLParse::DEVICESET_START)) {
//You find a start tag.
//Tack on the XML.
buf_string.append("\n");
XML_out.append(buf_string);
//Get the rest of the XML code.
while (!matchHeaderXML(buf_string, XMLParse::DEVICESET_END)) { //While you don't see end-tag
std::getline(readIn, buf_string, '\n'); //Read in new line
buf_string.append("\n");
XML_out.append(buf_string); //Tack it on
}
deviceList[device_ind].XMLtext = XML_out;
deviceList[device_ind].name = XMLParse::nameFromXML(XML_out);
device_ind++;
XML_out = "";
if (device_ind == numDevices)
break;
}
}
readIn.close();
}
void ELM::makeDeviceList(std::string filename) {
deviceList = new Device[numDevices];
ELM::getXML_AllDevices(filename);
for (int device_ind = 0; device_ind < numDevices; device_ind++) {
deviceList[device_ind].s.name = deviceList[device_ind].name;
deviceList[device_ind].s.XMLtext =
ELM::getXML_givenName(filename, deviceList[device_ind].s.name, XMLParse::SYMBOL_START, XMLParse::SYMBOL_END);
deviceList[device_ind].p.name = deviceList[device_ind].name;
deviceList[device_ind].p.XMLtext =
ELM::getXML_givenName(filename, deviceList[device_ind].p.name, XMLParse::PACKAGE_START, XMLParse::PACKAGE_END);
}
}
void ELM::addToDeviceList(Device d) {
//Make room
Device * deviceList_OLD = ELM::deviceList;
ELM::deviceList = new Device[ELM::numDevices + 1];
//Copy
for (int n = 0; n < ELM::numDevices; n++)
ELM::deviceList[n] = deviceList_OLD[n];
//Add new
ELM::deviceList[ELM::numDevices] = d;
ELM::numDevices++;
}
//Level I
void ELM::ReadFileIn(std::string filename) {
ELM::countDevices(filename); //count the number of devices
ELM::makeDeviceList(filename); //make the device list
ELM::getPreMaterial(filename); //everything before devices, packages, symbols we care about
ELM::getPostMaterial(filename); //everything after devices, packages, symbols we care about
}
void ELM::WriteFileOut(std::string filename) {
remove(filename.c_str());
std::ofstream writeOut(filename.c_str());
writeOut.flush();
//If filename exists: Delete it.
//This gets it out of our way when we're about to write.
//std::remove(filename.c_str());
//Concatenate XMLs of each Package.
//Wrap this concatenated XML in tag <packages></packages>.
std::string packageXML;
for (int n = 0; n < numDevices; n++)
packageXML.append(deviceList[n].p.XMLtext);
packageXML = XMLParse::tagWrapXML(packageXML, "<packages>", "</packages>");
//Concatenate XMLs of each Symbol.
//Wrap this concatenated XML in tag <symbols></symbols>.
std::string symbolXML;
for (int n = 0; n < numDevices; n++)
symbolXML.append(deviceList[n].s.XMLtext);
symbolXML = XMLParse::tagWrapXML(symbolXML, "<symbols>", "</symbols>");
//Concatenate XMLs of each Device.
//Wrap this concatenated XML in tag <devicesets></devicesets>.
std::string deviceXML;
for (int n = 0; n < numDevices; n++)
deviceXML.append(deviceList[n].XMLtext);
deviceXML = XMLParse::tagWrapXML(deviceXML, "<devicesets>", "</devicesets>");
//Concatenate the three aforementioned XMLs.
//Wrap this concatenated XML in tag <library></library>.
std::string libraryXML;
libraryXML = packageXML.append(symbolXML.append(deviceXML));
libraryXML = XMLParse::tagWrapXML(libraryXML, "<library>", "</library>");
//Concatenate pre-material(settings, layers..) and post-material(tags..).
std::string XML_out = preMaterial.append(libraryXML.append(postMaterial));
writeOut << XML_out;
writeOut.close();
}
int ELM::RemoveDevices(std::vector<std::string> namesToRemove) {
int nameInd;
int numRemoved = 0;
for (std::string name_remove : namesToRemove) {
//For each name you want to remove.
//Try to find that name in deviceList.
nameInd = ELM::findDeviceName(name_remove);
if (nameInd == -1) //If not found:
continue; //continue
//If found:
//Declare a new deviceList pointer with one less size than before
Device * temp = deviceList;
deviceList = new Device[numDevices - 1];
//I iterate through temp.
//I shuffle everything on top of the term at nameInd.
for (int n = nameInd; n + 1 < numDevices; n++)
temp[n] = temp[n + 1];
//Now it's organized for me to do a term-by-term into deviceList.
for (int n = 0; n < numDevices - 1; n++)
deviceList[n] = temp[n];
numDevices--;
numRemoved++;
}
return numRemoved;
}
int ELM::AddNewDevices(std::vector<std::string> namesToAdd) {
//Adding devices...
//Ensure you don't have duplicate names in namesToAdd vs. deviceList:
int numToAdd = 0;
std::vector<std::string> namesToAdd_TRUE;
for (std::string name : namesToAdd) {
//For each item in namesToAdd
if ((ELM::findDeviceName(name) == -1) && ELM::isValidName(name)) { //Only if we don't have this name AND it is valid.
namesToAdd_TRUE.push_back(name); //Mark to add.
numToAdd++; //Increment numToAdd
}
}
//Generate new deviceList.
//Load current deviceList into deviceList_OLD.
Device * deviceList_OLD = deviceList;
//Make a new pointer to store new deviceList.
deviceList = new Device[numDevices + numToAdd];
//Put deviceList_OLD at the beginning of newDeviceList.
for (int n = 0; n < numDevices; n++)
deviceList[n] = deviceList_OLD[n];
//Initialize each new device with dummy XML text and given names.
Device * deviceList_ADD = Device::makeDummyDevices(namesToAdd_TRUE);
for (int n = numDevices; n < numDevices + numToAdd; n++)
deviceList[n] = deviceList_ADD[n - numDevices];
numDevices += numToAdd; //Increase numDevices
return numToAdd;
}
void ELM::AddDevice_2xN(
std::string d_name,
std::vector<std::string> padNames,
double d_space_x, double d_space_y, double d_dim_x, double d_dim_y, int N
) {
if (ELM::findDeviceName(d_name) == -1) {
Device d(d_name, padNames, d_space_x, d_space_y, d_dim_x, d_dim_y, N);
//Device d(d_name);
//Make room
Device * deviceList_OLD = ELM::deviceList;
ELM::deviceList = new Device[ELM::numDevices + 1];
//Copy
for (int n = 0; n < ELM::numDevices; n++)
ELM::deviceList[n] = deviceList_OLD[n];
//Add new
ELM::deviceList[ELM::numDevices] = d;
ELM::numDevices++;
}
}
void ELM::AddDevice_RA(
std::string d_name,
std::vector<std::string> d_padNames,
double d_REF, int d_N, double d_padW, double d_padL, double d_padSpace,
double d_centeredSquarePad_DIM,
double d_cornerSquarePads_REF, double d_cornerSquarePads_DIM
) {
if (ELM::findDeviceName(d_name) == -1) {
Device d(
d_name,
d_padNames,
d_REF, d_N, d_padW, d_padL, d_padSpace,
d_centeredSquarePad_DIM,
d_cornerSquarePads_REF, d_cornerSquarePads_DIM
);
//Device d(d_name);
//Make room
Device * deviceList_OLD = ELM::deviceList;
ELM::deviceList = new Device[ELM::numDevices + 1];
//Copy
for (int n = 0; n < ELM::numDevices; n++)
ELM::deviceList[n] = deviceList_OLD[n];
//Add new
ELM::deviceList[ELM::numDevices] = d;
ELM::numDevices++;
}
}
void ELM::AddDevice_RxR(
std::string d_name,
std::vector<std::string> d_padNames,
int d_N_rows,
int* d_N_pads, double* d_padX, double* d_padY, double* d_padSpace, //length N_rows
double* d_horizontalOffset, double* d_verticalOffset //length N_rows - 1
) {
if (findDeviceName(d_name) == -1) {
Device d(
d_name,
d_padNames,
d_N_rows,
d_N_pads, d_padX, d_padY, d_padSpace, //length N_rows
d_horizontalOffset, d_verticalOffset //length N_rows - 1
);
//Device d(d_name);
//Make room
Device * deviceList_OLD = ELM::deviceList;
ELM::deviceList = new Device[ELM::numDevices + 1];
//Copy
for (int n = 0; n < ELM::numDevices; n++)
ELM::deviceList[n] = deviceList_OLD[n];
//Add new
ELM::deviceList[ELM::numDevices] = d;
ELM::numDevices++;
}
}
} | 28.635556 | 137 | 0.649853 | [
"vector"
] |
e368244f29316838a0d990b112f8193167405eb4 | 3,037 | cpp | C++ | src/components/renderer.cpp | Socapex/opengl_water | b9935285e8f8cda77d86b44d743e9a79c2523200 | [
"BSD-3-Clause"
] | 1 | 2018-04-19T17:29:41.000Z | 2018-04-19T17:29:41.000Z | src/components/renderer.cpp | p-groarke/opengl_water | b9935285e8f8cda77d86b44d743e9a79c2523200 | [
"BSD-3-Clause"
] | null | null | null | src/components/renderer.cpp | p-groarke/opengl_water | b9935285e8f8cda77d86b44d743e9a79c2523200 | [
"BSD-3-Clause"
] | null | null | null | #include "components/renderer.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace {
static inline bool gl_program_was_linked(int id) {
int result;
char info[1024];
glGetProgramiv(id, GL_LINK_STATUS, &result);
if (!result) {
glGetProgramInfoLog(id, 1024, nullptr, (char *)info);
OUTPUT_ERROR("OpenGL initialization error : %s\n", info);
}
return result != 0;
}
static inline bool gl_shader_was_compiled(int id) {
int result;
char info[1024];
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (!result) {
glGetShaderInfoLog(id, 1024, nullptr, (char *)info);
OUTPUT_ERROR("OpenGL initialization error : %s\n", info);
}
return result != 0;
}
std::string _relative_path = "shaders/";
} // namespace anonymous
void Renderer::load_shader(GLenum shader_type, const std::string& filename) {
std::string path = Engine::folder_path + _relative_path + filename;
std::ifstream f(path, std::ios::binary | std::ios::ate);
if (!f.is_open()) {
OUTPUT_ERROR("Couldn't read shader file : %s", path.c_str());
std::exit(-1);
}
auto size = f.tellg();
f.seekg(std::ios::beg);
std::string buffer;
buffer.resize(size);
f.read(&buffer[0], size);
Shader& ret = get_shader(shader_type);
ret.handle = glCreateShader(shader_type);
const char* src = buffer.c_str();
glShaderSource(ret.handle, 1, &src, NULL);
glCompileShader(ret.handle);
if (!gl_shader_was_compiled(ret.handle)) {
OUTPUT_MSG("In shader file : %s", path.c_str());
std::exit(-1);
}
}
void Renderer::create() {
program = glCreateProgram();
for (size_t i = 0; i < _shader_count; ++i) {
if (_shaders[i].invalid())
continue;
glAttachShader(program, _shaders[i].handle);
}
glLinkProgram(program);
GL_CHECK_ERROR();
bool was_init = true;
for (size_t i = 0; i < _shader_count; ++i) {
if (_shaders[i].invalid())
continue;
was_init &= gl_shader_was_compiled(_shaders[i].handle);
}
was_init &= gl_program_was_linked(program);
if (!was_init)
std::exit(-1);
}
void Renderer::init() {
}
void Renderer::update(float) {
if (glfwGetKey(Window::main->window, GLFW_KEY_1) == GLFW_PRESS) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (glfwGetKey(Window::main->window, GLFW_KEY_2) == GLFW_PRESS) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
}
void Renderer::render(float) {
GL_CHECK_ERROR();
}
void Renderer::destroy() {
glDeleteProgram(program);
}
Renderer::Shader& Renderer::get_shader(GLenum shader_type) {
switch (shader_type) {
// OpenGL 4.3 fuck Apple
// case GL_COMPUTE_SHADER: {
// return compute_shader;
// } break;
case GL_VERTEX_SHADER: {
return vertex_shader;
} break;
case GL_TESS_CONTROL_SHADER: {
return tess_control_shader;
} break;
case GL_TESS_EVALUATION_SHADER: {
return tess_eval_shader;
} break;
case GL_GEOMETRY_SHADER: {
return geometry_shader;
} break;
case GL_FRAGMENT_SHADER: {
return fragment_shader;
} break;
}
OUTPUT_ERROR("Invalid shader type %u", shader_type);
std::exit(-1);
return vertex_shader;
}
| 22.664179 | 77 | 0.69674 | [
"render",
"vector"
] |
e3694a5d85893ada309121c00d7b9befb57759f2 | 806 | hpp | C++ | GameContext.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | 1 | 2018-10-26T08:48:07.000Z | 2018-10-26T08:48:07.000Z | GameContext.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | null | null | null | GameContext.hpp | Derjik/Outpost | 93a419df75c1a17c1ffa30b0b9061bb3dfd7ce57 | [
"0BSD"
] | null | null | null | #ifndef GAME_CONTEXT_HPP_INCLUDED
#define GAME_CONTEXT_HPP_INCLUDED
#include <VBN/IGameContext.hpp>
class Platform;
class IEventHandler;
class IView;
class IModel;
class GameContext : public IGameContext
{
private:
std::shared_ptr<Platform> _platform;
std::shared_ptr<IModel> _model;
std::shared_ptr<IView> _view;
std::shared_ptr<IEventHandler> _eventHandler;
public:
GameContext(
std::shared_ptr<IModel> model,
std::shared_ptr<IView> view,
std::shared_ptr<IEventHandler> eventHandler);
/* View */
void display(void);
/* Model */
void elapse(Uint32 const gameTicks,
std::shared_ptr<EngineUpdate> engineUpdate);
/* Controller */
void handleEvent(
SDL_Event const & event,
std::shared_ptr<EngineUpdate> engineUpdate);
};
#endif // GAME_CONTEXT_HPP_INCLUDED
| 20.15 | 48 | 0.744417 | [
"model"
] |
e36a64f2b2e431a47506a86409ec16f4ecaa24e3 | 900 | cpp | C++ | Layer.cpp | unigoetheradaw/prg2-pr_milestone3-master | 47395c1479838b9e1a45e5d16953d0db5c2b3453 | [
"MIT"
] | null | null | null | Layer.cpp | unigoetheradaw/prg2-pr_milestone3-master | 47395c1479838b9e1a45e5d16953d0db5c2b3453 | [
"MIT"
] | null | null | null | Layer.cpp | unigoetheradaw/prg2-pr_milestone3-master | 47395c1479838b9e1a45e5d16953d0db5c2b3453 | [
"MIT"
] | null | null | null | /**
* Project NeuralNet
*/
#include "Layer.h"
#include <vector>
#include "Node.h"
Layer::Layer(std::size_t num, std::function<double(double)> activation_function, std::function<double(double)> activation_function_diff)
: nodes_(std::vector<Node>(num, Node(activation_function, activation_function_diff)))
{
nodes_.push_back(Node([](double value) { return 1; }, [](double value) { return 0; }));
}
std::ostream& operator<<(std::ostream& stream, const Layer& elem)
{
for(Node node : elem.nodes_)
{
for(auto weight : node.out_weights())
{
stream << weight;
}
stream << std::endl;
}
return stream;
}
void Layer::set_out_weights(std::vector< std::vector <double> > weights)
{
for(std::size_t i = 0; i < weights.size(); ++i)
{
for(std::size_t j = 0; j < weights.size(); ++j)
{
nodes_[i].out_edges()[j].set_weight(weights[i][j]);
}
}
} | 23.076923 | 136 | 0.631111 | [
"vector"
] |
e36a97ef5f5787cd7e200f7eacbf8f8856806971 | 15,037 | cc | C++ | webkit/fileapi/file_system_path_manager_unittest.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2015-10-12T09:14:22.000Z | 2015-10-12T09:14:22.000Z | webkit/fileapi/file_system_path_manager_unittest.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | null | null | null | webkit/fileapi/file_system_path_manager_unittest.cc | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T07:22:28.000Z | 2020-11-04T07:22:28.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 "webkit/fileapi/file_system_path_manager.h"
#include <set>
#include <string>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_callback_factory.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/fileapi/sandbox_mount_point_provider.h"
#include "webkit/quota/special_storage_policy.h"
using namespace fileapi;
namespace {
// PS stands for path separator.
#if defined(FILE_PATH_USES_WIN_SEPARATORS)
#define PS "\\"
#else
#define PS "/"
#endif
struct RootPathTestCase {
fileapi::FileSystemType type;
const char* origin_url;
const char* expected_path;
};
const struct RootPathTest {
fileapi::FileSystemType type;
const char* origin_url;
const char* expected_path;
} kRootPathTestCases[] = {
{ fileapi::kFileSystemTypeTemporary, "http://foo:1/",
"http_foo_1" PS "Temporary" },
{ fileapi::kFileSystemTypePersistent, "http://foo:1/",
"http_foo_1" PS "Persistent" },
{ fileapi::kFileSystemTypeTemporary, "http://bar.com/",
"http_bar.com_0" PS "Temporary" },
{ fileapi::kFileSystemTypePersistent, "http://bar.com/",
"http_bar.com_0" PS "Persistent" },
{ fileapi::kFileSystemTypeTemporary, "https://foo:2/",
"https_foo_2" PS "Temporary" },
{ fileapi::kFileSystemTypePersistent, "https://foo:2/",
"https_foo_2" PS "Persistent" },
{ fileapi::kFileSystemTypeTemporary, "https://bar.com/",
"https_bar.com_0" PS "Temporary" },
{ fileapi::kFileSystemTypePersistent, "https://bar.com/",
"https_bar.com_0" PS "Persistent" },
#if defined(OS_CHROMEOS)
{ fileapi::kFileSystemTypeExternal, "chrome-extension://foo/",
"chrome-extension__0" PS "External" },
#endif
};
const struct RootPathFileURITest {
fileapi::FileSystemType type;
const char* origin_url;
const char* expected_path;
const char* virtual_path;
} kRootPathFileURITestCases[] = {
{ fileapi::kFileSystemTypeTemporary, "file:///",
"file__0" PS "Temporary", NULL },
{ fileapi::kFileSystemTypePersistent, "file:///",
"file__0" PS "Persistent", NULL },
#if defined(OS_CHROMEOS)
{ fileapi::kFileSystemTypeExternal, "chrome-extension://foo/",
"chrome-extension__0" PS "External", "testing" },
#endif
};
const struct CheckValidPathTest {
FilePath::StringType path;
bool expected_valid;
} kCheckValidPathTestCases[] = {
{ FILE_PATH_LITERAL("//tmp/foo.txt"), false, },
{ FILE_PATH_LITERAL("//etc/hosts"), false, },
{ FILE_PATH_LITERAL("foo.txt"), true, },
{ FILE_PATH_LITERAL("a/b/c"), true, },
// Any paths that includes parent references are considered invalid.
{ FILE_PATH_LITERAL(".."), false, },
{ FILE_PATH_LITERAL("tmp/.."), false, },
{ FILE_PATH_LITERAL("a/b/../c/.."), false, },
};
const char* const kPathToVirtualPathTestCases[] = {
"",
"a",
"a" PS "b",
"a" PS "b" PS "c",
};
const struct IsRestrictedNameTest {
FilePath::StringType name;
bool expected_dangerous;
} kIsRestrictedNameTestCases[] = {
// Name that has restricted names in it.
{ FILE_PATH_LITERAL("con"), true, },
{ FILE_PATH_LITERAL("Con.txt"), true, },
{ FILE_PATH_LITERAL("Prn.png"), true, },
{ FILE_PATH_LITERAL("AUX"), true, },
{ FILE_PATH_LITERAL("nUl."), true, },
{ FILE_PATH_LITERAL("coM1"), true, },
{ FILE_PATH_LITERAL("COM3.com"), true, },
{ FILE_PATH_LITERAL("cOM7"), true, },
{ FILE_PATH_LITERAL("com9"), true, },
{ FILE_PATH_LITERAL("lpT1"), true, },
{ FILE_PATH_LITERAL("LPT4.com"), true, },
{ FILE_PATH_LITERAL("lPT8"), true, },
{ FILE_PATH_LITERAL("lPT9"), true, },
// Similar but safe cases.
{ FILE_PATH_LITERAL("con3"), false, },
{ FILE_PATH_LITERAL("PrnImage.png"), false, },
{ FILE_PATH_LITERAL("AUXX"), false, },
{ FILE_PATH_LITERAL("NULL"), false, },
{ FILE_PATH_LITERAL("coM0"), false, },
{ FILE_PATH_LITERAL("COM.com"), false, },
{ FILE_PATH_LITERAL("lpT0"), false, },
{ FILE_PATH_LITERAL("LPT.com"), false, },
// Ends with period or whitespace.
{ FILE_PATH_LITERAL("b "), true, },
{ FILE_PATH_LITERAL("b\t"), true, },
{ FILE_PATH_LITERAL("b\n"), true, },
{ FILE_PATH_LITERAL("b\r\n"), true, },
{ FILE_PATH_LITERAL("b."), true, },
{ FILE_PATH_LITERAL("b.."), true, },
// Similar but safe cases.
{ FILE_PATH_LITERAL("b c"), false, },
{ FILE_PATH_LITERAL("b\tc"), false, },
{ FILE_PATH_LITERAL("b\nc"), false, },
{ FILE_PATH_LITERAL("b\r\nc"), false, },
{ FILE_PATH_LITERAL("b c d e f"), false, },
{ FILE_PATH_LITERAL("b.c"), false, },
{ FILE_PATH_LITERAL("b..c"), false, },
// Name that has restricted chars in it.
{ FILE_PATH_LITERAL("a\\b"), true, },
{ FILE_PATH_LITERAL("a/b"), true, },
{ FILE_PATH_LITERAL("a<b"), true, },
{ FILE_PATH_LITERAL("a>b"), true, },
{ FILE_PATH_LITERAL("a:b"), true, },
{ FILE_PATH_LITERAL("a?b"), true, },
{ FILE_PATH_LITERAL("a|b"), true, },
{ FILE_PATH_LITERAL("ab\\"), true, },
{ FILE_PATH_LITERAL("ab/.txt"), true, },
{ FILE_PATH_LITERAL("ab<.txt"), true, },
{ FILE_PATH_LITERAL("ab>.txt"), true, },
{ FILE_PATH_LITERAL("ab:.txt"), true, },
{ FILE_PATH_LITERAL("ab?.txt"), true, },
{ FILE_PATH_LITERAL("ab|.txt"), true, },
{ FILE_PATH_LITERAL("\\ab"), true, },
{ FILE_PATH_LITERAL("/ab"), true, },
{ FILE_PATH_LITERAL("<ab"), true, },
{ FILE_PATH_LITERAL(">ab"), true, },
{ FILE_PATH_LITERAL(":ab"), true, },
{ FILE_PATH_LITERAL("?ab"), true, },
{ FILE_PATH_LITERAL("|ab"), true, },
};
FilePath UTF8ToFilePath(const std::string& str) {
FilePath::StringType result;
#if defined(OS_POSIX)
result = base::SysWideToNativeMB(UTF8ToWide(str));
#elif defined(OS_WIN)
result = UTF8ToUTF16(str);
#endif
return FilePath(result);
}
class TestSpecialStoragePolicy : public quota::SpecialStoragePolicy {
public:
virtual bool IsStorageProtected(const GURL& origin) {
return false;
}
virtual bool IsStorageUnlimited(const GURL& origin) {
return true;
}
virtual bool IsFileHandler(const std::string& extension_id) {
return true;
}
};
} // namespace
class FileSystemPathManagerTest : public testing::Test {
public:
FileSystemPathManagerTest()
: callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
void SetUp() {
ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
root_path_callback_status_ = false;
root_path_.clear();
file_system_name_.clear();
}
protected:
FileSystemPathManager* NewPathManager(
bool incognito,
bool allow_file_access) {
FileSystemPathManager* manager = new FileSystemPathManager(
base::MessageLoopProxy::CreateForCurrentThread(),
data_dir_.path(),
scoped_refptr<quota::SpecialStoragePolicy>(
new TestSpecialStoragePolicy()),
incognito,
allow_file_access);
#if defined(OS_CHROMEOS)
fileapi::ExternalFileSystemMountPointProvider* ext_provider =
manager->external_provider();
ext_provider->AddMountPoint(FilePath("/tmp/testing"));
#endif
return manager;
}
void OnGetRootPath(bool success,
const FilePath& root_path,
const std::string& name) {
root_path_callback_status_ = success;
root_path_ = root_path;
file_system_name_ = name;
}
bool GetRootPath(FileSystemPathManager* manager,
const GURL& origin_url,
fileapi::FileSystemType type,
bool create,
FilePath* root_path) {
manager->ValidateFileSystemRootAndGetURL(origin_url, type, create,
callback_factory_.NewCallback(
&FileSystemPathManagerTest::OnGetRootPath));
MessageLoop::current()->RunAllPending();
if (root_path)
*root_path = root_path_;
return root_path_callback_status_;
}
FilePath data_path() { return data_dir_.path(); }
FilePath file_system_path() {
return data_dir_.path().Append(
SandboxMountPointProvider::kFileSystemDirectory);
}
FilePath external_file_system_path() {
return UTF8ToFilePath(std::string(fileapi::kExternalDir));
}
FilePath external_file_path_root() {
return UTF8ToFilePath(std::string("/tmp"));
}
private:
ScopedTempDir data_dir_;
base::ScopedCallbackFactory<FileSystemPathManagerTest> callback_factory_;
bool root_path_callback_status_;
FilePath root_path_;
std::string file_system_name_;
DISALLOW_COPY_AND_ASSIGN(FileSystemPathManagerTest);
};
TEST_F(FileSystemPathManagerTest, GetRootPathCreateAndExamine) {
std::vector<FilePath> returned_root_path(
ARRAYSIZE_UNSAFE(kRootPathTestCases));
scoped_ptr<FileSystemPathManager> manager(NewPathManager(false, false));
// Create a new root directory.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathTestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPath (create) #" << i << " "
<< kRootPathTestCases[i].expected_path);
FilePath root_path;
EXPECT_TRUE(GetRootPath(manager.get(),
GURL(kRootPathTestCases[i].origin_url),
kRootPathTestCases[i].type,
true /* create */, &root_path));
if (kRootPathTestCases[i].type != fileapi::kFileSystemTypeExternal) {
FilePath expected = file_system_path().AppendASCII(
kRootPathTestCases[i].expected_path);
EXPECT_EQ(expected.value(), root_path.DirName().value());
EXPECT_TRUE(file_util::DirectoryExists(root_path));
} else {
// External file system root path is virtual one and does not match
// anything from the actual file system.
EXPECT_EQ(external_file_system_path().value(),
root_path.value());
}
ASSERT_TRUE(returned_root_path.size() > i);
returned_root_path[i] = root_path;
}
// Get the root directory with create=false and see if we get the
// same directory.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathTestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPath (get) #" << i << " "
<< kRootPathTestCases[i].expected_path);
FilePath root_path;
EXPECT_TRUE(GetRootPath(manager.get(),
GURL(kRootPathTestCases[i].origin_url),
kRootPathTestCases[i].type,
false /* create */, &root_path));
ASSERT_TRUE(returned_root_path.size() > i);
EXPECT_EQ(returned_root_path[i].value(), root_path.value());
}
}
TEST_F(FileSystemPathManagerTest, GetRootPathCreateAndExamineWithNewManager) {
std::vector<FilePath> returned_root_path(
ARRAYSIZE_UNSAFE(kRootPathTestCases));
scoped_ptr<FileSystemPathManager> manager1(NewPathManager(false, false));
scoped_ptr<FileSystemPathManager> manager2(NewPathManager(false, false));
GURL origin_url("http://foo.com:1/");
FilePath root_path1;
EXPECT_TRUE(GetRootPath(manager1.get(), origin_url,
kFileSystemTypeTemporary, true, &root_path1));
FilePath root_path2;
EXPECT_TRUE(GetRootPath(manager2.get(), origin_url,
kFileSystemTypeTemporary, false, &root_path2));
EXPECT_EQ(root_path1.value(), root_path2.value());
}
TEST_F(FileSystemPathManagerTest, GetRootPathGetWithoutCreate) {
scoped_ptr<FileSystemPathManager> manager(NewPathManager(false, false));
// Try to get a root directory without creating.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathTestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPath (create=false) #" << i << " "
<< kRootPathTestCases[i].expected_path);
EXPECT_FALSE(GetRootPath(manager.get(),
GURL(kRootPathTestCases[i].origin_url),
kRootPathTestCases[i].type,
false /* create */, NULL));
}
}
TEST_F(FileSystemPathManagerTest, GetRootPathInIncognito) {
scoped_ptr<FileSystemPathManager> manager(NewPathManager(
true /* incognito */, false));
// Try to get a root directory.
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathTestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPath (incognito) #" << i << " "
<< kRootPathTestCases[i].expected_path);
EXPECT_FALSE(GetRootPath(manager.get(),
GURL(kRootPathTestCases[i].origin_url),
kRootPathTestCases[i].type,
true /* create */, NULL));
}
}
TEST_F(FileSystemPathManagerTest, GetRootPathFileURI) {
scoped_ptr<FileSystemPathManager> manager(NewPathManager(false, false));
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathFileURITestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPathFileURI (disallow) #"
<< i << " " << kRootPathFileURITestCases[i].expected_path);
EXPECT_FALSE(GetRootPath(manager.get(),
GURL(kRootPathFileURITestCases[i].origin_url),
kRootPathFileURITestCases[i].type,
true /* create */, NULL));
}
}
TEST_F(FileSystemPathManagerTest, GetRootPathFileURIWithAllowFlag) {
scoped_ptr<FileSystemPathManager> manager(NewPathManager(
false, true /* allow_file_access_from_files */));
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kRootPathFileURITestCases); ++i) {
SCOPED_TRACE(testing::Message() << "RootPathFileURI (allow) #"
<< i << " " << kRootPathFileURITestCases[i].expected_path);
FilePath root_path;
EXPECT_TRUE(GetRootPath(manager.get(),
GURL(kRootPathFileURITestCases[i].origin_url),
kRootPathFileURITestCases[i].type,
true /* create */, &root_path));
if (kRootPathFileURITestCases[i].type != fileapi::kFileSystemTypeExternal) {
FilePath expected = file_system_path().AppendASCII(
kRootPathFileURITestCases[i].expected_path);
EXPECT_EQ(expected.value(), root_path.DirName().value());
EXPECT_TRUE(file_util::DirectoryExists(root_path));
} else {
EXPECT_EQ(external_file_path_root().value(), root_path.value());
}
}
}
TEST_F(FileSystemPathManagerTest, IsRestrictedName) {
scoped_ptr<FileSystemPathManager> manager(NewPathManager(false, false));
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kIsRestrictedNameTestCases); ++i) {
SCOPED_TRACE(testing::Message() << "IsRestrictedName #" << i << " "
<< kIsRestrictedNameTestCases[i].name);
FilePath name(kIsRestrictedNameTestCases[i].name);
EXPECT_EQ(kIsRestrictedNameTestCases[i].expected_dangerous,
manager->IsRestrictedFileName(kFileSystemTypeTemporary, name));
}
}
| 36.059952 | 80 | 0.667952 | [
"vector"
] |
e381c00d192c2e8558cd67ab0b8369b555a765fc | 2,062 | cpp | C++ | engine/src/wolf.render/directX/w_graphics/w_direct2D/w_line.cpp | SiminBadri/Wolf.Engine | 3da04471ec26e162e1cbb7cc88c7ce37ee32c954 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | 1 | 2020-07-15T13:14:26.000Z | 2020-07-15T13:14:26.000Z | engine/src/wolf.render/directX/w_graphics/w_direct2D/w_line.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | engine/src/wolf.render/directX/w_graphics/w_direct2D/w_line.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | #include "w_directX_pch.h"
#include "w_line.h"
using namespace D2D1;
using namespace wolf::graphics;
using namespace wolf::graphics::direct2D::shapes;
w_line::w_line(const std::shared_ptr<w_graphics_device>& pGDevice, D2D1_POINT_2F pStartPoint, D2D1_POINT_2F pStopPoint) : _gDevice(pGDevice), _start_point(pStartPoint), _stop_point(pStopPoint),
_stroke_width(1.0f), _update_color(false), _update_border_color(false)
{
_super::set_class_name(typeid(this).name());
this->_color.r = 1.0f; this->_color.g = 1.0f; this->_color.b = 1.0f; this->_color.a = 1.0f;
}
w_line::~w_line()
{
release();
}
HRESULT w_line::draw()
{
if (this->_brush == nullptr || this->_update_color)
{
auto _hr = this->_gDevice->context_2D->CreateSolidColorBrush(this->_color, &this->_brush);
if (FAILED(_hr))
{
V(_hr, L"Create solid color brush for background", this->name, false, true);
return _hr;
}
this->_update_color = false;
}
this->_gDevice->context_2D->DrawLine(this->_start_point, this->_stop_point, this->_brush.Get(), this->_stroke_width, 0);
return S_OK;
}
ULONG w_line::release()
{
if (_super::get_is_released()) return 0;
COMPTR_RELEASE(this->_brush);
this->_gDevice = nullptr;
return _super::release();
}
#pragma region Getters
w_color w_line::get_color() const
{
return w_color(
this->_color.r * 255.000f,
this->_color.g * 255.000f,
this->_color.b * 255.000f,
this->_color.a * 255.000f);
}
D2D1_POINT_2F w_line::get_start_point() const
{
return this->_start_point;
}
D2D1_POINT_2F w_line::get_stop_point() const
{
return this->_stop_point;
}
#pragma endregion
#pragma region Setters
void w_line::set_color(_In_ const w_color pColor)
{
this->_color.r = pColor.r / 255.000f;
this->_color.g = pColor.g / 255.000f;
this->_color.b = pColor.b / 255.000f;
this->_color.a = pColor.a / 255.000f;
this->_update_color = true;
}
void w_line::set_geormetry(_In_ const D2D1_POINT_2F pStartPoint, _In_ const D2D1_POINT_2F pStopPoint)
{
this->_start_point = pStartPoint;
this->_stop_point = pStopPoint;
}
#pragma endregion | 22.659341 | 193 | 0.71969 | [
"solid"
] |
be630118bbce4dbcd3f3a8e2e86d8b8a97055615 | 1,109 | hpp | C++ | third_party/boost/simd/function/maxnummag.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | 5 | 2018-02-20T11:21:12.000Z | 2019-11-12T13:45:09.000Z | third_party/boost/simd/function/maxnummag.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/maxnummag.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | 2 | 2017-12-12T12:29:52.000Z | 2019-04-08T15:55:25.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_MAXNUMMAG_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_MAXNUMMAG_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-ieee
Function object implementing maxnummag capabilities
Returns the input value which have the greatest absolute value, ignoring nan.
@par Semantic:
@code
auto r = maxnummag(x,y);
@endcode
is similar to:
@code
auto r = is_nan(x) ? y : (is_nan(y) ? x : maxmag(x, y));
@endcode
@see maxmag, is_nan
**/
Value maxnummag(Value const & x, Value const& y);
} }
#endif
#include <boost/simd/function/scalar/maxnummag.hpp>
#include <boost/simd/function/simd/maxnummag.hpp>
#endif
| 23.595745 | 100 | 0.577998 | [
"object"
] |
be645aa2882b8d0de2f76ff66149ebc1afdcc067 | 2,985 | cpp | C++ | src/main.cpp | abainbridge/chart-chisel | 5b6a02a77faaf1a76fc40594581873ba820899a0 | [
"MIT"
] | 1 | 2019-02-25T11:13:00.000Z | 2019-02-25T11:13:00.000Z | src/main.cpp | abainbridge/chart-chisel | 5b6a02a77faaf1a76fc40594581873ba820899a0 | [
"MIT"
] | null | null | null | src/main.cpp | abainbridge/chart-chisel | 5b6a02a77faaf1a76fc40594581873ba820899a0 | [
"MIT"
] | null | null | null | // Own header
#include "main.h"
// Standard headers
#include <stdarg.h>
#include <stdio.h>
// Deadfrog headers
#include "fonts/df_mono.h"
#include "df_bmp.h"
#include "df_font.h"
#include "df_message_dialog.h"
#include "df_time.h"
#include "df_window.h"
// Project headers
#include "antialiased_draw.h"
#include "message_sequence_chart.h"
#include "tokenizer.h"
#include "vector2.h"
#define APP_NAME "Chart Chisel"
bool g_interactiveMode = true;
void FatalError(char const *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (g_interactiveMode) {
char buf[2048] = "ERROR:\n\n";
vsnprintf(buf + 8, sizeof(buf)-9, fmt, ap);
buf[sizeof(buf) - 1] = '\0';
MessageDialog(APP_NAME " Error", buf, MsgDlgTypeOk);
}
else {
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
}
exit(-1);
}
void PrintUsageAndExit()
{
puts("Usage: " APP_NAME " <mode> <input filename>");
puts("");
puts("Creates a message sequence chart as a PNG file.");
puts("");
puts("Where mode is either:");
puts(" batch - Generates the output PNG and immediately exits.");
puts(" interactive - Generates the output PNG and displays it.");
exit(0);
}
int main(int argc, char *argv[])
{
// char *filename = "../../message_sequence_charts/hello.msc";
// g_interactiveMode = false;
char *filename = "../../message_sequence_charts/add_with_data.msc";
if (argc != 3) {
PrintUsageAndExit();
}
if (stricmp(argv[1], "batch") == 0) {
g_interactiveMode = false;
}
else if (stricmp(argv[1], "interactive") != 0) {
printf("Unrecognized mode '%s'\n", argv[1]);
return -1;
}
filename = argv[2];
g_defaultFont = LoadFontFromMemory(deadfrog_mono_7x13, sizeof(deadfrog_mono_7x13));
g_antialiasedDraw = new AntialiasedDraw;
MessageSequenceChart msc;
msc.Load(filename);
DfBitmap *bmp = NULL;
if (g_interactiveMode) {
// Setup the window
int width, height;
GetDesktopRes(&width, &height);
CreateWin(1200, height - 100, WT_WINDOWED, APP_NAME);
bmp = g_window->bmp;
BitmapClear(bmp, g_colourWhite);
// Continue to display the window until the user presses escape or clicks the close icon
double lastTime = GetRealTime();
while (!g_window->windowClosed && !g_input.keys[KEY_ESC])
{
InputPoll();
BitmapClear(bmp, g_colourWhite);
msc.Render(bmp);
UpdateWin();
WaitVsync();
}
}
else {
bmp = BitmapCreate(1300, 1600);
BitmapClear(bmp, g_colourWhite);
msc.Render(bmp);
}
char *outputFilename = strdup(filename);
int len = strlen(outputFilename);
memcpy(outputFilename + len - 4, ".bmp", 4);
if (!SaveBmp(bmp, outputFilename)) {
FatalError("Couldn't write output to '%s'", outputFilename);
}
return 0;
}
| 24.467213 | 96 | 0.605025 | [
"render"
] |
be70eea0f50157b59fa1f26a70292fcf4fc973dd | 173,836 | cpp | C++ | ds/security/services/scerpc/client/setupcln.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/services/scerpc/client/setupcln.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/services/scerpc/client/setupcln.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
setupcln.cpp
Abstract:
SCE setup Client APIs
Author:
Jin Huang (jinhuang) 23-Jun-1997 created
Revision History:
jinhuang 23-Jan-1998 split to client-server model
--*/
#include "headers.h"
#include "scerpc.h"
#include "scesetup.h"
#include "sceutil.h"
#include "clntutil.h"
#include "scedllrc.h"
#include "infp.h"
#include <ntrpcp.h>
#include <io.h>
//#include "gpedit.h"
//#include <initguid.h>
#include <lmaccess.h>
#include "commonrc.h"
#include <aclapi.h>
#include <rpcasync.h>
#include <sddl.h>
typedef HRESULT (*PFREGISTERSERVER)(void);
extern BOOL gbClientInDcPromo;
static SCEPR_CONTEXT hSceSetupHandle=NULL;
extern PVOID theCallBack;
extern HANDLE hCallbackWnd;
extern DWORD CallbackType;
extern HINSTANCE MyModuleHandle;
TCHAR szCallbackPrefix[MAX_PATH];
#define STR_GUID_LEN 36
#define SCESETUP_BACKUP_SECURITY 0x40
#define PRODUCT_UNKNOWN 0
#define EFS_NOTIFY_PATH TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\Notify\\EFS")
DWORD dwThisMachine = PRODUCT_UNKNOWN;
WCHAR szUpInfFile[MAX_PATH*2+1] = {'\0'};
BOOL bIsNT5 = TRUE;
DWORD
WhichNTProduct();
BOOL
ScepAddAuthUserToLocalGroup();
DWORD dwCallbackTotal=0;
DWORD
ScepSetupOpenSecurityDatabase(
IN BOOL bSystemOrAdmin
);
DWORD
ScepSetupCloseSecurityDatabase();
typedef enum _SCESETUP_OPERATION_TYPE {
SCESETUP_UPDATE=1,
SCESETUP_MOVE
} SCESETUP_OPERATION_TYPE;
typedef enum _SCESETUP_OBJECT_TYPE {
SCESETUP_FILE=1,
SCESETUP_KEY,
SCESETUP_SERVICE
} SCESETUP_OBJECT_TYPE;
DWORD
SceSetuppLogComponent(
IN DWORD ErrCode,
IN SCESETUP_OBJECT_TYPE ObjType,
IN SCESETUP_OPERATION_TYPE OptType,
IN PWSTR Name,
IN PWSTR SDText OPTIONAL,
IN PWSTR SecondName OPTIONAL
);
SCESTATUS
ScepSetupWriteOneError(
IN HANDLE hFile,
IN DWORD rc,
IN LPTSTR buf
);
SCESTATUS
ScepSetupWriteError(
IN LPTSTR LogFileName,
IN PSCE_ERROR_LOG_INFO pErrlog
);
SCESTATUS
ScepUpdateBackupSecurity(
IN PCTSTR pszSetupInf,
IN PCTSTR pszWindowsFolder,
IN BOOL bIsDC
);
BOOL
pCreateDefaultGPOsInSysvol(
IN LPTSTR DomainDnsName,
IN LPTSTR szSysvolPath,
IN DWORD Options,
IN LPTSTR LogFileName
);
BOOL
pCreateSysvolContainerForGPO(
IN LPCTSTR strGuid,
IN LPTSTR szPath,
IN DWORD dwStart
);
BOOL
pCreateOneGroupPolicyObject(
IN PWSTR pszGPOSysPath,
IN BOOL bDomainLevel,
IN PWSTR LogFileName
);
DWORD
ScepDcPromoSharedInfo(
IN HANDLE ClientToken,
IN BOOL bDeleteLog,
IN BOOL bSetSecurity,
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
);
NTSTATUS
ScepDcPromoRemoveUserRights();
NTSTATUS
ScepDcPromoRemoveTwoRights(
IN LSA_HANDLE PolicyHandle,
IN SID_IDENTIFIER_AUTHORITY *pIA,
IN UCHAR SubAuthCount,
IN DWORD Rid1,
IN DWORD Rid2
);
DWORD
ScepSystemSecurityInSetup(
IN PWSTR InfName,
IN PCWSTR LogFileName OPTIONAL,
IN AREA_INFORMATION Area,
IN UINT nFlag,
IN PSCE_NOTIFICATION_CALLBACK_ROUTINE pSceNotificationCallBack OPTIONAL,
IN OUT PVOID pValue OPTIONAL
);
DWORD
ScepMoveRegistryValue(
IN HKEY hKey,
IN PWSTR KeyFrom,
IN PWSTR ValueFrom,
IN PWSTR KeyTo OPTIONAL,
IN PWSTR ValueTo OPTIONAL
);
DWORD
ScepBreakSDDLToMultiFields(
IN PWSTR pszObjName,
IN PWSTR pszSDDL,
IN DWORD dwSDDLsize,
IN BYTE ObjStatus,
OUT PWSTR *ppszAdjustedInfLine
);
SCESTATUS
SceInfpBreakTextIntoMultiFields(
IN PWSTR szText,
IN DWORD dLen,
OUT LPDWORD pnFields,
OUT LPDWORD *arrOffset
);
#ifndef _WIN64
BOOL
GetIsWow64 (
VOID
);
#endif // _WIN64
//
// Client APIs in scesetup.h (for setup integration)
//
DWORD
WINAPI
SceSetupUpdateSecurityFile(
IN PWSTR FileFullName,
IN UINT nFlag,
IN PWSTR SDText
)
/*
Routine Description:
This routine applies the security specified in SDText to the file on
local system and update the SDDL security information to the SCE
database.
Arguments:
FileFullName - the full path name of the file to update
nFlag - reserved flag for file option
SDText - the SDDL format security descriptor
Return Value:
WIN32 error code for the status of this operation
*/
{
if ( FileFullName == NULL || SDText == NULL ) {
return(ERROR_INVALID_PARAMETER);
}
//
// global database handle
//
SCESTATUS rc = ScepSetupOpenSecurityDatabase(FALSE);
if ( rc == NO_ERROR ) {
RpcTryExcept {
//
// update the file
//
rc = SceRpcSetupUpdateObject(
hSceSetupHandle,
(wchar_t *)FileFullName,
(DWORD)SE_FILE_OBJECT,
nFlag,
(wchar_t *)SDText
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
}
SceSetuppLogComponent(rc,
SCESETUP_FILE,
SCESETUP_UPDATE,
FileFullName,
SDText,
NULL);
return rc;
}
DWORD
WINAPI
SceSetupUpdateSecurityService(
IN PWSTR ServiceName,
IN DWORD StartType,
IN PWSTR SDText
)
/*
Routine Description:
This routine applies the security specified in SDText to the service on
local system and update the SDDL security information to the SCE
database.
Arguments:
ServiceName - the name of the service to update
StartType - startup type of the service
SDText - the SDDL format security descriptor
Return Value:
WIN32 error code for the status of this operation
*/
{
if ( ServiceName == NULL || SDText == NULL )
return(ERROR_INVALID_PARAMETER);
//
// global database handle
//
SCESTATUS rc = ScepSetupOpenSecurityDatabase(FALSE);
if ( rc == NO_ERROR ) {
RpcTryExcept {
//
// Update the object information
//
rc = SceRpcSetupUpdateObject(
hSceSetupHandle,
(wchar_t *)ServiceName,
(DWORD)SE_SERVICE,
(UINT)StartType,
(wchar_t *)SDText
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
}
SceSetuppLogComponent(rc,
SCESETUP_SERVICE,
SCESETUP_UPDATE,
ServiceName,
SDText,
NULL);
return rc;
}
// Registry object names returned by NtQueryObject are prefixed by
// the following
#define REG_OBJ_TAG L"\\REGISTRY\\"
#define REG_OBJ_TAG_LEN (sizeof(REG_OBJ_TAG) / sizeof(WCHAR) - 1)
DWORD
WINAPI
SceSetupUpdateSecurityKey(
IN HKEY hKeyRoot,
IN PWSTR KeyPath,
IN UINT nFlag,
IN PWSTR SDText
)
/*
Routine Description:
This routine applies the security specified in SDText to the registry key
on local system and update the SDDL security information to the SCE
database.
on a 64 bit platform; if the client is 64 bit, then we secure the 64 bit
registry. if the client is 32 bit, then we secure the 32 bit registry. Unless,
SCE_SETUP_32KEY is set in the flags, in which case will secure always the 32 bit
registry; or if the SCE_SETUP_64KEY is set in the flags, in which case will secure the
64 bit registry always. if both are defined the SCE_SETUP_32KEY takes precedence.
Arguments:
hKeyRoot - root handle of the key
KeyPath - the subdir key path relative to the root
nFlag - reserved flag for key option
SDText - the SDDL format security descriptor
Return Value:
WIN32 error code for the status of this operation
*/
{
if ( hKeyRoot == NULL || SDText == NULL )
return(ERROR_INVALID_PARAMETER);
DWORD rc = ERROR_SUCCESS;
PWSTR KeyFullName=NULL;
DWORD Len= 16;
DWORD cLen=0;
POBJECT_NAME_INFORMATION pNI=NULL;
NTSTATUS Status;
LPWSTR pwszPath=NULL;
DWORD cchPath=0;
#ifndef _WIN64
static BOOL bGetWow64 = TRUE;
static BOOL bIsWow64 = FALSE;
#endif //_WIN64
//
// translate the root key first
// to determine the length required for the full name
//
if ( hKeyRoot != HKEY_LOCAL_MACHINE &&
hKeyRoot != HKEY_USERS &&
hKeyRoot != HKEY_CLASSES_ROOT ) {
//
// First, determine the size of the buffer we need...
//
Status = NtQueryObject(hKeyRoot,
ObjectNameInformation,
pNI,
0,
&cLen);
if ( NT_SUCCESS(Status) ||
Status == STATUS_BUFFER_TOO_SMALL ||
Status == STATUS_INFO_LENGTH_MISMATCH ||
Status == STATUS_BUFFER_OVERFLOW ) {
//
// allocate a buffer to get name information
//
pNI = (POBJECT_NAME_INFORMATION)LocalAlloc(LPTR, cLen);
if ( pNI == NULL ) {
rc = ERROR_NOT_ENOUGH_MEMORY;
} else {
Status = NtQueryObject(hKeyRoot,
ObjectNameInformation,
pNI,
cLen,
NULL);
if (!NT_SUCCESS(Status))
{
rc = RtlNtStatusToDosError(Status);
}
else if ( pNI && pNI->Name.Buffer && pNI->Name.Length > 0 )
{
//
// Server doesn't like \REGISTRY as a prefix -- get
// rid of it and the backslash that follows it.
//
DWORD dwSize = sizeof(L"\\REGISTRY\\") - sizeof(WCHAR);
DWORD dwLen = dwSize / sizeof(WCHAR);
if (_wcsnicmp(pNI->Name.Buffer,
L"\\REGISTRY\\",
min(dwLen,
pNI->Name.Length / sizeof(WCHAR))) == 0)
{
RtlMoveMemory(pNI->Name.Buffer,
pNI->Name.Buffer + dwLen,
pNI->Name.Length - dwSize);
pNI->Name.Length -= (USHORT) dwSize;
}
//
// get the required length, plus one space for the backslash,
// and one for null
//
Len = pNI->Name.Length/sizeof(WCHAR) + 2;
}
else
{
rc = ERROR_INVALID_PARAMETER;
}
}
} else {
rc = RtlNtStatusToDosError(Status);
}
}
if ( rc == ERROR_SUCCESS ) {
//
// make a full path name for the key
//
if ( KeyPath != NULL ) {
Len += wcslen(KeyPath);
}
KeyFullName = (PWSTR)LocalAlloc(LMEM_ZEROINIT, Len*sizeof(WCHAR));
if ( KeyFullName == NULL ) {
rc = ERROR_NOT_ENOUGH_MEMORY;
}
}
if ( rc == ERROR_SUCCESS ) {
//
// translate the root key
//
if ( hKeyRoot == HKEY_LOCAL_MACHINE ) {
wcscpy(KeyFullName, L"MACHINE");
} else if ( hKeyRoot == HKEY_USERS ) {
wcscpy(KeyFullName, L"USERS");
} else if ( hKeyRoot == HKEY_CLASSES_ROOT ) {
wcscpy(KeyFullName, L"CLASSES_ROOT");
} else if ( pNI && pNI->Name.Buffer && pNI->Name.Length > 0 ) {
//
// copy the name of the key
//
memcpy(KeyFullName, pNI->Name.Buffer, pNI->Name.Length);
KeyFullName[pNI->Name.Length/sizeof(WCHAR)] = L'\0';
} else {
rc = ERROR_INVALID_PARAMETER;
}
if ( rc == ERROR_SUCCESS && KeyPath != NULL ) {
wcscat(KeyFullName, L"\\");
wcscat(KeyFullName, KeyPath);
}
}
if ( rc == ERROR_SUCCESS ) {
//
// global database handle
//
rc = ScepSetupOpenSecurityDatabase(FALSE);
if ( NO_ERROR == rc ) {
//
// since the server side only understands SCE_SETUP_32KEY,
// and otherwise will set the 64 bit registry then:
//
// we have three possible running enviroments:
// 1. 64 bit scecli -> do nothing
// 2. 32 bit scecli running on 32 bit OS -> do nothing
// 3. 32 bit scecli running on wow64 ->
// a. if SCE_SETUP_64KEY is set -> do nothing
// b. if SCE_SETUP_64KEY is not set -> set SCE_SETUP_32KEY
//
#ifndef _WIN64
if( bGetWow64 ){
bIsWow64 = GetIsWow64();
bGetWow64 = FALSE;
}
if( bIsWow64 ){
if( (nFlag & SCE_SETUP_64KEY) == 0){
nFlag |= SCE_SETUP_32KEY;
}
}
//
// clear out noise going to the server side
//
nFlag &= ~(SCE_SETUP_64KEY);
#endif
RpcTryExcept {
//
// update the object
//
rc = SceRpcSetupUpdateObject(
hSceSetupHandle,
(wchar_t *)KeyFullName,
(DWORD)SE_REGISTRY_KEY,
nFlag,
(wchar_t *)SDText
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
}
}
SceSetuppLogComponent(rc,
SCESETUP_KEY,
SCESETUP_UPDATE,
KeyFullName ? KeyFullName : KeyPath,
SDText,
NULL);
if ( KeyFullName )
LocalFree(KeyFullName);
if ( pNI )
LocalFree(pNI);
return(rc);
}
DWORD
WINAPI
SceSetupMoveSecurityFile(
IN PWSTR FileToSetSecurity,
IN PWSTR FileToSaveInDB OPTIONAL,
IN PWSTR SDText OPTIONAL
)
{
if ( !FileToSetSecurity ) {
return(ERROR_INVALID_PARAMETER);
}
//
// if I am in setup, query the security policy/user rights for any
// policy changes within setup (such as NT4 PDC upgrade where the policy
// filter will fail to save the change)
//
DWORD dwInSetup=0;
DWORD rc = ERROR_SUCCESS;
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("System\\Setup"),
TEXT("SystemSetupInProgress"),
&dwInSetup
);
if ( dwInSetup ) {
rc = ScepSetupOpenSecurityDatabase(FALSE);
if ( NO_ERROR == rc ) {
RpcTryExcept {
//
// move the object
//
rc = SceRpcSetupMoveFile(
hSceSetupHandle,
(wchar_t *)FileToSetSecurity,
(wchar_t *)FileToSaveInDB,
(wchar_t *)SDText
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
}
if ( FileToSaveInDB == NULL &&
rc != NO_ERROR ) {
//
// error occured to delete this file,
// do not report error
//
rc = NO_ERROR;
}
SceSetuppLogComponent(rc,
SCESETUP_FILE,
SCESETUP_MOVE,
FileToSetSecurity,
SDText,
FileToSaveInDB
);
} else {
SceSetuppLogComponent(rc,
SCESETUP_FILE,
SCESETUP_MOVE,
FileToSetSecurity,
NULL,
L"Operation aborted - not in setup"
);
}
return(rc);
}
DWORD
WINAPI
SceSetupUnwindSecurityFile(
IN PWSTR FileFullName,
IN PSECURITY_DESCRIPTOR pSDBackup
)
/*
Routine Description:
This routine reset security settings for the file in SCE database (unwind)
used by two-phase copy file process in setupapi.
Arguments:
FileFullName - The full path name for the file to undo.
pSDBackup - The backup security descriptor
Return Value:
WIN32 error code for the status of this operation
*/
{
if ( !FileFullName || !pSDBackup ) {
return(ERROR_INVALID_PARAMETER);
}
DWORD dwInSetup=0;
DWORD rc = ERROR_SUCCESS;
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("System\\Setup"),
TEXT("SystemSetupInProgress"),
&dwInSetup
);
if ( dwInSetup ) {
rc = ScepSetupOpenSecurityDatabase(FALSE);
PWSTR TextSD=NULL;
DWORD TextSize;
if ( NO_ERROR == rc ) {
rc = ConvertSecurityDescriptorToText(
pSDBackup,
0xF, // all security component
&TextSD,
&TextSize
);
}
if ( NO_ERROR == rc && TextSD ) {
RpcTryExcept {
//
// update security in the database only
//
rc = SceRpcSetupUpdateObject(
hSceSetupHandle,
(wchar_t *)FileFullName,
(DWORD)SE_FILE_OBJECT,
SCESETUP_UPDATE_DB_ONLY,
(wchar_t *)TextSD
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
}
if ( TextSD ) {
LocalFree(TextSD);
}
}
return(rc);
}
DWORD
WINAPI
SceSetupGenerateTemplate(
IN LPTSTR SystemName OPTIONAL,
IN LPTSTR JetDbName OPTIONAL,
IN BOOL bFromMergedTable,
IN LPTSTR InfTemplateName,
IN LPTSTR LogFileName OPTIONAL,
IN AREA_INFORMATION Area
)
/*
Routine Description:
This routine generate a INF format template from the SCE database specified
by JetDbName, or the default SCE database if JetDbName is NULL.
Arguments:
JetDbName - the SCE database name (optional) to get information from.
If NULL, the default security database is used.
InfTemplateName - the inf template name to generate
LogFileName - the log file name (optional)
Area - the security area to generate
Return Value:
WIN32 error code for the status of this operation
*/
{
DWORD rc;
handle_t binding_h;
NTSTATUS NtStatus;
PSCE_ERROR_LOG_INFO pErrlog=NULL;
//
// verify the InfTemplateName for invalid path error
// or access denied error
//
rc = ScepVerifyTemplateName(InfTemplateName, &pErrlog);
if ( NO_ERROR == rc ) {
//
// RPC bind to the server
//
NtStatus = ScepBindSecureRpc(
SystemName,
L"scerpc",
0,
&binding_h
);
if ( NT_SUCCESS(NtStatus) ) {
SCEPR_CONTEXT Context;
RpcTryExcept {
//
// pass to the server site to generate template
//
rc = SceRpcGenerateTemplate(
binding_h,
(wchar_t *)JetDbName,
(wchar_t *)LogFileName,
(PSCEPR_CONTEXT)&Context
);
if ( SCESTATUS_SUCCESS == rc) {
//
// a context handle is opened to generate this template
//
rc = SceCopyBaseProfile(
(PVOID)Context,
bFromMergedTable ? SCE_ENGINE_SCP : SCE_ENGINE_SMP,
(wchar_t *)InfTemplateName,
Area,
&pErrlog
);
ScepSetupWriteError(LogFileName, pErrlog);
ScepFreeErrorLog(pErrlog);
//
// close the context
//
SceRpcCloseDatabase(&Context);
}
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
} else {
rc = RtlNtStatusToDosError( NtStatus );
}
if ( binding_h ) {
//
// Free the binding handle
//
RpcpUnbindRpc( binding_h );
}
} else {
ScepSetupWriteError(LogFileName, pErrlog);
ScepFreeErrorLog(pErrlog);
}
return(rc);
}
DWORD
ScepMoveRegistryValue(
IN HKEY hKey,
IN PWSTR KeyFrom,
IN PWSTR ValueFrom,
IN PWSTR KeyTo OPTIONAL,
IN PWSTR ValueTo OPTIONAL
)
/*
Some registry values are moved to new locations on NT5. This routine is to migrate
the registry values from their old location on NT4 (KeyFrom, ValueFrom) to their
new location on NT5 (KeyTo, ValueTo).
If destination key or value is not specified, the registry value is moved in the same
key or with different value name. Both KeyTo and ValueTo can't be NULL at the same
time.
*/
{
if ( hKey == NULL || KeyFrom == NULL || ValueFrom == NULL ||
(KeyTo == NULL && ValueTo == NULL) ) {
return(ERROR_INVALID_PARAMETER);
}
DWORD rc=ERROR_SUCCESS;
HKEY hKey1=NULL;
HKEY hKey2=NULL;
DWORD RegType=0;
DWORD dSize=0;
//
// open the destination to see if the value already exist
//
if ( KeyTo ) {
rc = RegOpenKeyEx(hKey,
KeyTo,
0,
KEY_READ | KEY_WRITE,
&hKey2);
if ( ERROR_SUCCESS == rc ) {
//
// open the origin
//
rc = RegOpenKeyEx(hKey,
KeyFrom,
0,
KEY_READ,
&hKey1);
}
} else {
//
// if a reg value is moved to the same key as origin,
// open the key with appropriate access
//
rc = RegOpenKeyEx(hKey,
KeyFrom,
0,
KEY_READ | KEY_WRITE,
&hKey2);
hKey1 = hKey2;
}
if ( ERROR_SUCCESS == rc ) {
// query destination
rc = RegQueryValueEx(hKey2,
ValueTo ? ValueTo : ValueFrom,
0,
&RegType,
NULL,
&dSize
);
if ( ERROR_FILE_NOT_FOUND == rc ) {
//
// only move value if the destination doesn't have the value
//
rc = RegQueryValueEx(hKey1,
ValueFrom,
0,
&RegType,
NULL,
&dSize
);
if ( ERROR_SUCCESS == rc ) {
PWSTR pValue = (PWSTR)ScepAlloc( LMEM_ZEROINIT, (dSize+1)*sizeof(TCHAR));
if ( pValue != NULL ) {
rc = RegQueryValueEx(hKey1,
ValueFrom,
0,
&RegType,
(BYTE *)pValue,
&dSize
);
if ( ERROR_SUCCESS == rc ) {
//
// set the value to its new location
//
rc = RegSetValueEx( hKey2,
ValueTo ? ValueTo : ValueFrom,
0,
RegType,
(BYTE *)pValue,
dSize
);
}
ScepFree(pValue);
}
}
}
}
if ( hKey1 && hKey1 != hKey2 ) {
RegCloseKey(hKey1);
}
if ( hKey2 ) {
RegCloseKey(hKey2);
}
return(rc);
}
DWORD
WINAPI
SceSetupSystemByInfName(
IN PWSTR InfName,
IN PCWSTR LogFileName OPTIONAL,
IN AREA_INFORMATION Area,
IN UINT nFlag,
IN PSCE_NOTIFICATION_CALLBACK_ROUTINE pSceNotificationCallBack OPTIONAL,
IN OUT PVOID pValue OPTIONAL
)
/*
Routine Description:
nFlag Operation
SCESETUP_CONFIGURE_SECURITY overwrite security with the template info
SCESETUP_UPDATE_SECURITY apply template on top of existing security
(do not overwrite the security database)
SCESETUP_QUERY_TICKS query total number of ticks for the operation
Note: when nFlag is SCESETUP_QUERY_TICKS, pValue is PDWORD to output total number of ticks
but when nFlag is the other two values, pValue is a input window handle used
for setup's gauge window (required by the call back routine)
*/
{
DWORD rc;
LONG Count=0;
//
// Initialize the SCP engine
//
if ( InfName == NULL ) {
return(ERROR_INVALID_PARAMETER);
}
//
// always configure security policy, user rights, but NO ds objects
// (because this is in setup clean install, no DC available)
//
AREA_INFORMATION Area2;
if ( (nFlag & SCESETUP_UPGRADE_SYSTEM) ||
(nFlag & SCESETUP_UPDATE_FILE_KEY) ) {
Area2 = 0;
if ( nFlag & SCESETUP_UPGRADE_SYSTEM ) {
Area2 = AREA_SECURITY_POLICY |
AREA_PRIVILEGES;
}
if ( nFlag & SCESETUP_UPDATE_FILE_KEY ) {
Area2 |= (Area & ~AREA_DS_OBJECTS);
}
} else {
//
// LSA/SAM are initialized by now (starting 1823)
// configure security policies
//
Area2 = AREA_SECURITY_POLICY |
AREA_PRIVILEGES |
AREA_GROUP_MEMBERSHIP |
(Area & ~AREA_DS_OBJECTS);
// Area2 = (Area & ~AREA_DS_OBJECTS);
}
if ( nFlag & SCESETUP_QUERY_TICKS ) {
//
// only queries ticks from the inf file.
// for the case of updating security, there might be existing objects in
// the SCE database.
//
if ( pValue == NULL ) {
return(ERROR_INVALID_PARAMETER);
}
Count = 0;
HINF InfHandle;
if ( !(nFlag & SCESETUP_UPGRADE_SYSTEM) ||
(nFlag & SCESETUP_UPDATE_FILE_KEY) ) {
InfHandle = SetupOpenInfFile(
InfName,
NULL,
INF_STYLE_WIN4,
NULL
);
if ( InfHandle != INVALID_HANDLE_VALUE ) {
if ( Area2 & AREA_REGISTRY_SECURITY ) {
Count += SetupGetLineCount(InfHandle, szRegistryKeys);
}
if ( Area2 & AREA_FILE_SECURITY ) {
Count += SetupGetLineCount(InfHandle, szFileSecurity);
}
SetupCloseInfFile(InfHandle);
} else {
dwCallbackTotal = 0;
return(GetLastError() );
}
}
else {
//Upgrade
memset(szUpInfFile, 0, sizeof(WCHAR) * (MAX_PATH + 1));
GetSystemWindowsDirectory(szUpInfFile, MAX_PATH);
DWORD TsInstalled = 0;
bIsNT5 = IsNT5();
dwThisMachine = WhichNTProduct();
switch (dwThisMachine) {
case NtProductWinNt:
wcscat(szUpInfFile, L"\\inf\\dwup.inf\0");
break;
case NtProductServer:
//
// determine if this is a terminal server in app mode
//
if ( bIsNT5 ) {
//
// on NT5, check the TSAppCompat value // TSEnabled value
//
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("System\\CurrentControlSet\\Control\\Terminal Server"),
TEXT("TSAppCompat"),
&TsInstalled
);
if ( TsInstalled != 1 ) {
//
// Terminal server is enabled when the value is set to 0x1
//
TsInstalled = 0;
}
} else {
//
// on NT4, base on the ProductSuite value
//
PWSTR pSuite=NULL;
DWORD RegType=0;
DWORD Rcode;
HKEY hKey=NULL;
DWORD dSize=0;
if(( Rcode = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
0,
KEY_READ,
&hKey
)) == ERROR_SUCCESS ) {
if(( Rcode = RegQueryValueEx(hKey,
TEXT("ProductSuite"),
0,
&RegType,
NULL,
&dSize
)) == ERROR_SUCCESS ) {
pSuite = (PWSTR)ScepAlloc( LMEM_ZEROINIT, (dSize+1)*sizeof(TCHAR));
if ( pSuite != NULL ) {
Rcode = RegQueryValueEx(hKey,
TEXT("ProductSuite"),
0,
&RegType,
(BYTE *)pSuite,
&dSize
);
if ( Rcode == ERROR_SUCCESS ) {
if ( RegType == REG_MULTI_SZ ) {
//
// check if the value contains "Terminal Server"
//
PWSTR pTemp=pSuite;
while ( pTemp[0] != L'\0' ) {
if ( lstrcmpi(TEXT("Terminal Server"),pTemp) == 0 ) {
TsInstalled = 1;
break;
} else {
pTemp += wcslen(pTemp)+1;
}
}
} else if ( RegType == REG_SZ ) {
if (lstrcmpi(TEXT("Terminal Server"), pSuite) == 0) {
TsInstalled = 1;
}
}
}
ScepFree(pSuite);
}
}
RegCloseKey( hKey );
}
}
if ( TsInstalled ) {
//
// if terminal server is installed, use the
// special terminal server template
//
wcscat(szUpInfFile, L"\\inf\\dsupt.inf\0");
} else {
wcscat(szUpInfFile, L"\\inf\\dsup.inf\0");
}
break;
case NtProductLanManNt:
if ( bIsNT5 ) {
wcscat(szUpInfFile, L"\\inf\\dcup5.inf\0");
}
else {
szUpInfFile[0] = L'\0';
}
break;
default:
szUpInfFile[0] = L'\0';
}
if (szUpInfFile[0] != L'\0') {
InfHandle = SetupOpenInfFile(
szUpInfFile,
NULL,
INF_STYLE_WIN4,
NULL
);
if ( InfHandle != INVALID_HANDLE_VALUE ) {
if ( Area2 & AREA_REGISTRY_SECURITY ) {
Count += SetupGetLineCount(InfHandle, szRegistryKeys);
}
if ( Area2 & AREA_FILE_SECURITY ) {
Count += SetupGetLineCount(InfHandle, szFileSecurity);
}
SetupCloseInfFile(InfHandle);
} else {
dwCallbackTotal = 0;
return(GetLastError() );
}
}
//
// migrate registry values
// should do this for both NT4 and NT5 upgrades since previous NT5
// may be upgraded from NT4
//
// Having the registry value in the right place will help to fix
// the tattoo problem in the new design
//
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
L"DisableCAD",
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
L"DontDisplayLastUserName",
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
L"LegalNoticeCaption",
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
L"LegalNoticeText",
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
L"ShutdownWithoutLogon",
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"System\\CurrentControlSet\\Services\\Rdr\\Parameters",
L"EnableSecuritySignature",
L"System\\CurrentControlSet\\Services\\LanmanWorkstation\\Parameters",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"System\\CurrentControlSet\\Services\\Rdr\\Parameters",
L"RequireSecuritySignature",
L"System\\CurrentControlSet\\Services\\LanmanWorkstation\\Parameters",
NULL
);
ScepMoveRegistryValue(
HKEY_LOCAL_MACHINE,
L"System\\CurrentControlSet\\Services\\Rdr\\Parameters",
L"EnablePlainTextPassword",
L"System\\CurrentControlSet\\Services\\LanmanWorkstation\\Parameters",
NULL
);
}
if ( Area2 & AREA_SECURITY_POLICY )
Count += TICKS_SECURITY_POLICY_DS + TICKS_SPECIFIC_POLICIES;
if ( Area2 & AREA_GROUP_MEMBERSHIP )
Count += TICKS_GROUPS;
if ( Area2 & AREA_PRIVILEGES )
Count += TICKS_PRIVILEGE;
if ( Area2 & AREA_SYSTEM_SERVICE )
Count += TICKS_GENERAL_SERVICES + TICKS_SPECIFIC_SERVICES;
if ( nFlag & SCESETUP_UPGRADE_SYSTEM ) {
Count += (4*TICKS_MIGRATION_SECTION+TICKS_MIGRATION_V11);
}
*(PDWORD)pValue = Count;
dwCallbackTotal = Count;
return(ERROR_SUCCESS);
}
//
// delete the temp policy filter files and registry value
//
ScepClearPolicyFilterTempFiles(TRUE);
//
// make sure the log file is not too big
//
DWORD dwLogSize=0;
HANDLE hFile = CreateFile(LogFileName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS, // OPEN_EXISTING
FILE_ATTRIBUTE_NORMAL,
NULL);
if ( INVALID_HANDLE_VALUE != hFile ) {
dwLogSize = GetFileSize(hFile, NULL);
CloseHandle(hFile);
}
if ( dwLogSize >= (0x1 << 23) ) {
DWORD nRequired = wcslen(LogFileName);
LPTSTR szTempName = (LPTSTR)LocalAlloc(0, (nRequired+1)*sizeof(TCHAR));
if ( szTempName ) {
wcscpy(szTempName, LogFileName);
szTempName[nRequired-3] = L'o';
szTempName[nRequired-2] = L'l';
szTempName[nRequired-1] = L'd';
CopyFile( LogFileName, szTempName, FALSE );
LocalFree(szTempName);
}
DeleteFile(LogFileName);
}
//
// configure the system now
//
rc = ScepSystemSecurityInSetup(
InfName,
LogFileName,
Area,
(nFlag & 0xFL), // block out other flags such as BIND_NO_AUTH
pSceNotificationCallBack,
pValue
);
if ( rc == ERROR_DATABASE_FAILURE ) {
//
// setup category error - log to eventlog
//
(void) InitializeEvents(L"SceCli");
LogEvent(MyModuleHandle,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_JET_DATABASE,
IDS_ERROR_OPEN_JET_DATABASE,
L"%windir%\\security\\database\\secedit.sdb"
);
(void) ShutdownEvents();
}
return rc;
}
DWORD
ScepSystemSecurityInSetup(
IN PWSTR InfName,
IN PCWSTR LogFileName OPTIONAL,
IN AREA_INFORMATION Area,
IN UINT nFlag,
IN PSCE_NOTIFICATION_CALLBACK_ROUTINE pSceNotificationCallBack OPTIONAL,
IN OUT PVOID pValue OPTIONAL
)
{
SCESTATUS rc;
DWORD ConfigOptions;
handle_t binding_h;
NTSTATUS NtStatus;
//
// always configure security policy, user rights, but NO ds objects
// (because this is in setup clean install, no DC available)
//
AREA_INFORMATION Area2;
if ( (nFlag & SCESETUP_UPGRADE_SYSTEM) ||
(nFlag & SCESETUP_UPDATE_FILE_KEY) ) {
/*
//
// should allow policy filter on W2K DC upgrade (dcup5)
// policy filter is ignored for non DCs in the filter code
// so it's not needed to add condition here
//
// turn off policy filter if this is upgrade
// clean install, policy filter has not been registered yet.
//
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff"),
1
);
*/
ConfigOptions = SCE_UPDATE_DB | SCE_SERVICE_NO_REALTIME_ENFORCE;
Area2 = 0;
if ( nFlag & SCESETUP_UPGRADE_SYSTEM ) {
Area2 = AREA_SECURITY_POLICY |
AREA_PRIVILEGES;
}
if ( nFlag & SCESETUP_UPDATE_FILE_KEY ) {
Area2 |= (Area & ~AREA_DS_OBJECTS);
}
} else if ( nFlag & SCESETUP_BACKUP_SECURITY ) {
ConfigOptions = SCE_UPDATE_DB | SCE_SERVICE_NO_REALTIME_ENFORCE;
Area2 = Area;
} else {
ConfigOptions = SCE_OVERWRITE_DB;
//
// LSA/SAM are initialized by now (starting 1823)
// configure security policies
//
Area2 = AREA_SECURITY_POLICY |
AREA_PRIVILEGES |
AREA_GROUP_MEMBERSHIP |
(Area & ~AREA_DS_OBJECTS);
// Area2 = (Area & ~AREA_DS_OBJECTS);
}
//
// a callback routine is passed in
//
ScepSetCallback((PVOID)pSceNotificationCallBack,
(HANDLE)pValue,
SCE_SETUP_CALLBACK
);
//
// should we close the database opened by single
// object update ?
// ScepSetupCloseSecurityDatabase();
//
// RPC bind to the server
//
NtStatus = ScepBindRpc(
NULL,
L"scerpc",
L"security=impersonation dynamic false",
&binding_h
);
/*
if ( nFlag & SCESETUP_BIND_NO_AUTH ) {
NtStatus = ScepBindRpc(
NULL,
L"scerpc",
L"security=impersonation dynamic false",
&binding_h
);
} else {
NtStatus = ScepBindSecureRpc(
NULL,
L"scerpc",
L"security=impersonation dynamic false",
&binding_h
);
}*/
if (NT_SUCCESS(NtStatus)){
//
// if there is notification handle, set the notify bit
//
if ( pSceNotificationCallBack ) {
ConfigOptions |= SCE_CALLBACK_DELTA;
}
LPVOID pebClient = GetEnvironmentStrings();
DWORD ebSize = ScepGetEnvStringSize(pebClient);
RpcTryExcept {
DWORD dWarn=0;
if ( nFlag & SCESETUP_RECONFIG_SECURITY ) {
ConfigOptions = SCE_UPDATE_DB;
Area2 = AREA_FILE_SECURITY;//AREA_ALL;
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)InfName,
NULL,
(wchar_t *)LogFileName,
ConfigOptions | SCE_DEBUG_LOG,
(AREAPR)Area2,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
else if ( (ConfigOptions & SCE_UPDATE_DB) &&
(nFlag & SCESETUP_UPGRADE_SYSTEM) ) {
//
// save a flag to indicate this is an upgrade
//
if ( ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("SetupUpgraded"),
1
) != ERROR_SUCCESS) {
//
// try again to create the key and then set the value
// don't worry about error this time around
//
HKEY hKey = NULL;
DWORD dwValue = 1;
if ( ERROR_SUCCESS == RegCreateKeyEx (HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_WRITE | KEY_SET_VALUE,
NULL,
&hKey,
NULL) ) {
RegSetValueEx( hKey,
TEXT("SetupUpgraded"),
0,
REG_DWORD,
(BYTE *)&dwValue,
4
);
RegCloseKey(hKey);
}
}
//
// Migrate databases if necessary
// if NT4 upgrade, create the database
// this call will also empty the local policy table if necessary
// ignore this error
//
if ( dwThisMachine == NtProductLanManNt &&
!bIsNT5 ) {
//
// NT4 DC upgrade. Should snapshot account policy into the database
// because SAM won't be available in dcpormo (later on)
//
rc = SceRpcAnalyzeSystem(
binding_h,
NULL,
NULL,
(wchar_t *)LogFileName,
AREA_SECURITY_POLICY,
ConfigOptions | SCE_DEBUG_LOG | SCE_NO_ANALYZE | SCE_RE_ANALYZE,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
} else {
//
// everything else, just create/migrate the database
//
rc = SceRpcAnalyzeSystem(
binding_h,
NULL,
NULL,
(wchar_t *)LogFileName,
0,
ConfigOptions | SCE_DEBUG_LOG | SCE_NO_ANALYZE,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
rc = SCESTATUS_SUCCESS;
if ( nFlag & SCESETUP_UPDATE_FILE_KEY ) {
Area2 = (Area & ~(AREA_DS_OBJECTS | AREA_SECURITY_POLICY | AREA_PRIVILEGES) );
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)InfName,
NULL,
(wchar_t *)LogFileName,
ConfigOptions | SCE_DEBUG_LOG,
(AREAPR)Area2,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
if ( !(nFlag & SCESETUP_BIND_NO_AUTH) ) {
if ( szUpInfFile[0] != L'\0' ) {
if (dwThisMachine == NtProductServer || dwThisMachine == NtProductWinNt) {
Area2 = AREA_ALL;
}
else {
Area2 = AREA_FILE_SECURITY | AREA_REGISTRY_SECURITY |
AREA_PRIVILEGES | AREA_SECURITY_POLICY;
// DS is not running, do not configure account policies.
// ConfigOptions |= SCE_NO_DOMAIN_POLICY;
}
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)szUpInfFile,
NULL,
(wchar_t *)LogFileName,
ConfigOptions | SCE_DEBUG_LOG,
(AREAPR)Area2,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
// should add Authenticated Users to Users group on DC too
// if (dwThisMachine == NtProductServer || dwThisMachine == NtProductWinNt) {
if (!ScepAddAuthUserToLocalGroup()) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
STATUS_SEVERITY_WARNING,
SCEEVENT_WARNING_BACKUP_SECURITY,
IDS_ERR_ADD_AUTH_USER );
}
// }
}
} else {
//
// clean install, the upgraded flag should be 0
// no need to set it; clear the log
//
if ( LogFileName ) {
DeleteFile(LogFileName);
}
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)InfName,
NULL,
(wchar_t *)LogFileName,
ConfigOptions | SCE_DEBUG_LOG,
(AREAPR)Area2,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
rc = ScepSceStatusToDosError(rc);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
if(pebClient)
{
FreeEnvironmentStrings((LPTSTR)pebClient);
}
} else {
rc = RtlNtStatusToDosError(NtStatus);
}
if ( binding_h ) {
//
// Free the binding handle
//
RpcpUnbindRpc( binding_h );
}
ScepSetCallback(NULL, NULL, 0);
dwCallbackTotal = 0;
/*
//
// should allow policy filter on W2K DC upgrade (dcup5)
// policy filter is ignored for non DCs in the filter code
// so it's not needed to add condition here
//
if ( (nFlag & SCESETUP_UPGRADE_SYSTEM) ||
(nFlag & SCESETUP_UPDATE_FILE_KEY) ) {
DWORD rCode = ScepRegDeleteValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff")
);
if ( rCode != ERROR_SUCCESS &&
rCode != ERROR_FILE_NOT_FOUND &&
rCode != ERROR_PATH_NOT_FOUND ) {
// if can't delete the value, set the value to 0
ScepRegSetIntValue( HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff"),
0
);
}
}
*/
return(rc);
}
DWORD
WINAPI
SceDcPromoteSecurity(
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
)
{
return SceDcPromoteSecurityEx(NULL, dwPromoteOptions, pScePromoteCallBack);
}
DWORD
WINAPI
SceDcPromoteSecurityEx(
IN HANDLE ClientToken,
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
)
/*
Routine Description:
This routine promote security for a domain controller when a server is
promoted to a DC.
Arguments:
dwPromoteOptions - options for the promotion, for example, create a new domain
or joining an existing domain
pScePromoteCallBack - the call back pointer
Return Value:
WIN32 error code
*/
{
BOOL bDeleteLog;
if ( (dwPromoteOptions & SCE_PROMOTE_FLAG_REPLICA) ||
(dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE) ) {
bDeleteLog = TRUE;
} else {
bDeleteLog = FALSE;
}
//
// delete temporary filter file generated in setup if it hasn't been
// processed by policy prop
// because we are setting up a new product.
// Note, this is a special case for NT4 DC upgrade
//
ScepClearPolicyFilterTempFiles(TRUE);
//
// configure security for both replica and first domain case.
//
DWORD rc32 = ScepDcPromoSharedInfo(ClientToken,
bDeleteLog, // delete log
TRUE, // not set security
dwPromoteOptions,
pScePromoteCallBack
);
TCHAR Buffer[MAX_PATH+1];
TCHAR szNewName[MAX_PATH+51];
Buffer[0] = L'\0';
GetSystemWindowsDirectory(Buffer, MAX_PATH);
Buffer[MAX_PATH] = L'\0';
szNewName[0] = L'\0';
//
// make sure the log file is re-created
//
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\security\\logs\\scedcpro.log\0");
DWORD rcSave = rc32;
//
// generate the updated database (for emergency repair)
// even if there is an error configuring security
//
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE ) {
rc32 = SceSetupBackupSecurity(NULL);
}
else {
rc32 = SceSetupBackupSecurity(szNewName);
}
//
// re-register the notify dll (seclogon.dll) so that
// at next logon after reboot, the group policy object
// can be created.
//
// if it's a replica created, EFS policy should come from
// the domain so no need to create group policy object
//
if ( !(dwPromoteOptions & SCE_PROMOTE_FLAG_REPLICA) &&
!(dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE) ) {
(void) InitializeEvents(L"SceCli");
HINSTANCE hNotifyDll = LoadLibrary(TEXT("sclgntfy.dll"));
if ( hNotifyDll) {
PFREGISTERSERVER pfRegisterServer = (PFREGISTERSERVER)GetProcAddress(
hNotifyDll,
"DllRegisterServer");
if ( pfRegisterServer ) {
//
// do not care errors
//
(void) (*pfRegisterServer)();
LogEvent(MyModuleHandle,
STATUS_SEVERITY_INFORMATIONAL,
SCEEVENT_INFO_REGISTER,
0,
TEXT("sclgntfy.dll")
);
} else {
LogEvent(MyModuleHandle,
STATUS_SEVERITY_WARNING,
SCEEVENT_WARNING_REGISTER,
IDS_ERROR_GET_PROCADDR,
GetLastError(),
TEXT("DllRegisterServer in sclgntfy.dll")
);
}
FreeLibrary(hNotifyDll);
} else {
LogEvent(MyModuleHandle,
STATUS_SEVERITY_WARNING,
SCEEVENT_WARNING_REGISTER,
IDS_ERROR_LOADDLL,
GetLastError(),
TEXT("sclgntfy.dll")
);
}
(void) ShutdownEvents();
}
if ( rcSave )
return(rcSave);
else
return(rc32);
}
DWORD
WINAPI
SceDcPromoCreateGPOsInSysvol(
IN LPTSTR DomainDnsName,
IN LPTSTR SysvolRoot,
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
)
{
return SceDcPromoCreateGPOsInSysvolEx(NULL, DomainDnsName, SysvolRoot,
dwPromoteOptions, pScePromoteCallBack
);
}
DWORD
WINAPI
SceDcPromoCreateGPOsInSysvolEx(
IN HANDLE ClientToken,
IN LPTSTR DomainDnsName,
IN LPTSTR SysvolRoot,
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
)
{
//
// create default policy object for domain and domain controllers ou
// if it's not an replica
//
if ( NULL == DomainDnsName || NULL == SysvolRoot ) {
return ERROR_INVALID_PARAMETER;
}
DWORD rc32=ERROR_SUCCESS;
TCHAR Buffer[MAX_PATH+1];
TCHAR szGenName[MAX_PATH+51];
Buffer[0] = L'\0';
GetSystemWindowsDirectory(Buffer, MAX_PATH);
Buffer[MAX_PATH] = L'\0';
if ( !(dwPromoteOptions & SCE_PROMOTE_FLAG_REPLICA) ) {
rc32 = ScepDcPromoSharedInfo(ClientToken,
TRUE, // delete log
FALSE, // not set security
dwPromoteOptions,
pScePromoteCallBack
);
if ( rc32 == ERROR_SUCCESS ) {
//
// now create the GPOs in sysvol
//
(void) InitializeEvents(L"SceCli");
TCHAR szNewName[MAX_PATH+51];
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\security\\logs\\scedcpro.log\0");
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstDGPO.inf\0");
intptr_t hFile;
struct _wfinddata_t FileInfo;
hFile = _wfindfirst(szGenName, &FileInfo);
if ( hFile == -1 ) {
rc32 = ERROR_OBJECT_NOT_FOUND;
LogEventAndReport(MyModuleHandle,
szNewName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_GETGPO_FILE_PATH,
rc32,
szGenName
);
} else {
_findclose(hFile);
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstOGPO.inf\0");
hFile = _wfindfirst(szGenName, &FileInfo);
if ( hFile == -1 ) {
rc32 = ERROR_OBJECT_NOT_FOUND;
LogEventAndReport(MyModuleHandle,
szNewName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_GETGPO_FILE_PATH,
rc32,
szGenName
);
} else {
_findclose(hFile);
if ( FALSE == pCreateDefaultGPOsInSysvol( DomainDnsName,
SysvolRoot,
dwPromoteOptions,
szNewName ) ) {
rc32 = GetLastError();
}
}
}
(void) ShutdownEvents();
}
}
//
// make sure the temp files are deleted
//
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstDGPO.inf\0");
DeleteFile(szGenName);
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstOGPO.inf\0");
DeleteFile(szGenName);
return rc32;
}
DWORD
ScepDcPromoSharedInfo(
IN HANDLE ClientToken,
IN BOOL bDeleteLog,
IN BOOL bSetSecurity,
IN DWORD dwPromoteOptions,
IN PSCE_PROMOTE_CALLBACK_ROUTINE pScePromoteCallBack OPTIONAL
)
{
SCESTATUS rc;
DWORD rc32=NO_ERROR;
TCHAR Buffer[MAX_PATH+1];
TCHAR szGenName[MAX_PATH+51];
TCHAR szNewName[MAX_PATH+51];
handle_t binding_h;
NTSTATUS NtStatus;
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff"),
1
);
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyPropOff"),
1
);
//
// a callback routine is passed in
//
ScepSetCallback((PVOID)pScePromoteCallBack,
NULL,
SCE_DCPROMO_CALLBACK
);
//
// should we close the database opened by single
// object update ?
// ScepSetupCloseSecurityDatabase();
//
// RPC bind to the server
//
NtStatus = ScepBindRpc(
NULL,
L"scerpc",
L"security=impersonation dynamic false", // 0
&binding_h
);
/*
NtStatus = ScepBindSecureRpc(
NULL,
L"scerpc",
0,
&binding_h
);
*/
if (NT_SUCCESS(NtStatus)){
//
// if there is notification handle, set the notify bit
//
DWORD ConfigOptions = SCE_UPDATE_DB | SCE_DEBUG_LOG;
if ( pScePromoteCallBack ) {
ConfigOptions |= SCE_CALLBACK_DELTA;
}
//
// the following calls shouldn't fail because Buffer is big enough
//
Buffer[0] = L'\0';
GetSystemWindowsDirectory(Buffer, MAX_PATH);
Buffer[MAX_PATH] = L'\0';
//
// if it's not set security (then it's create GPOs)
// make sure FirstOGPO and FirstDGPO are initialized properly
//
if ( bSetSecurity == FALSE ) {
//
// this code should be only called for non replica promotion
//
wcscpy(szNewName, Buffer);
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_UPGRADE ) {
//
// upgrade from NT4 DC to NT5 DC
//
wcscat(szNewName, L"\\inf\\dcup.inf\0");
} else {
wcscat(szNewName, L"\\inf\\defltdc.inf\0");
}
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstOGPO.inf\0");
// DeleteFile(szGenName);
CopyFile(szNewName, szGenName, FALSE);
//
// delete the sections do not belong to local policy object
//
WritePrivateProfileSection(
szSystemAccess,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szGroupMembership,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szAccountProfiles,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szRegistryKeys,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szFileSecurity,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szDSSecurity,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
L"LanManServer",
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szServiceGeneral,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szKerberosPolicy,
NULL,
(LPCTSTR)szGenName);
/*
WritePrivateProfileSection(
szRegistryValues,
NULL,
(LPCTSTR)szGenName);
*/
WritePrivateProfileSection(
szAuditSystemLog,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szAuditSecurityLog,
NULL,
(LPCTSTR)szGenName);
WritePrivateProfileSection(
szAuditApplicationLog,
NULL,
(LPCTSTR)szGenName);
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\FirstDGPO.inf\0");
//
// prepare the temp domain and local policy template
// write default kerberos policy into the temp domain template
//
szNewName[0] = L'\0';
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\inf\\Dcfirst.inf\0");
CopyFile(szNewName, szGenName, FALSE);
}
//
// make sure the log file is re-created
//
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\security\\logs\\scedcpro.log\0");
if ( bDeleteLog ) {
DeleteFile(szNewName);
}
//
// choose the template to use
//
szGenName[0] = L'\0';
wcscpy(szGenName, Buffer);
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_UPGRADE ) {
//
// upgrade from NT4 DC to NT5 DC
//
wcscat(szGenName, L"\\inf\\dcup.inf\0");
} else if ( dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE ) {
//
// demote from DC to server
//
wcscat(szGenName, L"\\inf\\defltsv.inf\0");
} else{
wcscat(szGenName, L"\\inf\\defltdc.inf\0");
}
LPVOID pebClient = GetEnvironmentStrings();
DWORD ebSize = ScepGetEnvStringSize(pebClient);
//
// impersonate
//
BOOL bImpersonated = FALSE;
if ( ClientToken ) {
if ( !ImpersonateLoggedOnUser(ClientToken) ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)szNewName,
0,
0,
IDS_ERROR_PROMOTE_IMPERSONATE,
GetLastError()
);
} else {
bImpersonated = TRUE;
}
}
szCallbackPrefix[0] = L'\0';
LoadString( MyModuleHandle,
bSetSecurity ? SCECLI_CALLBACK_PREFIX : SCECLI_CREATE_GPO_PREFIX,
szCallbackPrefix,
MAX_PATH
);
szCallbackPrefix[MAX_PATH-1] = L'\0';
if ( szCallbackPrefix[0] == L'\0' ) {
//
// in case loadString fails
//
if ( bSetSecurity ) {
wcscpy(szCallbackPrefix, L"Securing ");
} else {
wcscpy(szCallbackPrefix, L"Creating ");
}
}
//
// revert
//
if ( ClientToken && bImpersonated ) {
if ( !RevertToSelf() ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)szNewName,
0,
0,
IDS_ERROR_PROMOTE_REVERT,
GetLastError()
);
}
}
//
// configure security
//
DWORD dWarn;
AREA_INFORMATION Area;
rc = SCESTATUS_SUCCESS;
RpcTryExcept {
//
// also make sure the builtin accounts for NT5 DC are
// created if they are not there (which will be created in reboot after dcpromo)
//
LPTSTR pTemplateFile;
if ( bSetSecurity == FALSE ) {
Area = AREA_PRIVILEGES;
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_UPGRADE ) {
//
// upgrade from NT4 DC to NT5 DC, need copy the current policy setting
//
Area |= AREA_SECURITY_POLICY;
}
ConfigOptions |= (SCE_COPY_LOCAL_POLICY |
SCE_NO_CONFIG |
SCE_DCPROMO_WAIT |
SCE_NO_DOMAIN_POLICY );
pTemplateFile = NULL; // szGenName;
} else {
//
// flag it so that special registry values (such as LmCompatibilityLevel) can be handled
//
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PromoteUpgradeInProgress"),
(dwPromoteOptions & SCE_PROMOTE_FLAG_UPGRADE) ? 1 : 0
);
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE ) {
//
// security policy, privileges, and group membership must be configured
// at reboot (in policy propagation) so these settings must
// be imported to the tattoo table first (when SCE_DC_DEMOTE is set)
// Plus SAM will be recreated at reboot
//
Area = AREA_SECURITY_POLICY | AREA_PRIVILEGES | AREA_GROUP_MEMBERSHIP;
ConfigOptions |= SCE_NO_CONFIG | SCE_DCPROMO_WAIT | SCE_DC_DEMOTE;
}
else {
//
// remove "Power Users" explcitly
// since privileges are not configured anymore
//
ScepDcPromoRemoveUserRights();
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_UPGRADE ) {
// NT4 DC upgrade.
// import AREA_SECURITY_POLICY from dsup.inf
// so that registry values gets secured correctly
// on NT4 DC upgrades.
//
DWORD dwSize = (wcslen(TEXT("\\inf\\dsup.inf")) + wcslen(Buffer) + 1)*sizeof(WCHAR);
PWSTR pszTempName = (PWSTR) ScepAlloc(LMEM_ZEROINIT, dwSize);
if(pszTempName){
Area = AREA_SECURITY_POLICY;
wcscpy(pszTempName, Buffer);
wcscat(pszTempName, TEXT("\\inf\\dsup.inf"));
rc = SceRpcConfigureSystem(binding_h,
(wchar_t *)pszTempName,
NULL,
(wchar_t *)szNewName,
ConfigOptions | SCE_NO_CONFIG | SCE_NO_DOMAIN_POLICY,
(AREAPR)Area,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
ScepFree(pszTempName);
pszTempName = NULL;
}
else{
rc = SCESTATUS_NOT_ENOUGH_RESOURCE;
}
}
Area = AREA_FILE_SECURITY | AREA_REGISTRY_SECURITY |
AREA_SYSTEM_SERVICE | AREA_SECURITY_POLICY;
ConfigOptions |= ( SCE_NO_DOMAIN_POLICY |
SCE_SERVICE_NO_REALTIME_ENFORCE );
//
// user rights need to be configured for first DC as well as replica
// because there are new user rights that are not defined in group policies.
//
Area |= AREA_PRIVILEGES;
ConfigOptions |= (SCE_DCPROMO_WAIT | SCE_CREATE_BUILTIN_ACCOUNTS);
}
pTemplateFile = szGenName;
}
if(SCESTATUS_SUCCESS == rc){
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)pTemplateFile,
NULL,
(wchar_t *)szNewName,
ConfigOptions,
(AREAPR)Area,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
rc32 = ScepSceStatusToDosError(rc);
if ( bSetSecurity == TRUE ) {
//
// reset the flag
//
ScepRegDeleteValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PromoteUpgradeInProgress")
);
}
if ( rc32 == NO_ERROR && (dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE) ) {
//
// Now we need to import the file/registry/services
// permissions from dsup.inf (vs. getting them
// from "defltsv.inf") because we are using "0" mode
// in dsup.inf which allows protected acls for components
// to be preserved, thus not break on demotion.
// Also, on demotion we need to import "syscomp.inf"
// so we can get the Consol apps lock down
//
TCHAR szTempName[MAX_PATH + 51] = {0};
wcscpy(szTempName, Buffer);
wcscat(szTempName, TEXT("\\inf\\dsup.inf"));
//
// remove the SCE_DC_DEMOTE flag so we don't delete the existing
// security in the database.
//
ConfigOptions &= ~(SCE_DC_DEMOTE);
//
// Areas with acls
//
Area = AREA_FILE_SECURITY | AREA_REGISTRY_SECURITY | AREA_SYSTEM_SERVICE;
//
// import "dsup.inf"
//
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)szTempName,
NULL,
(wchar_t *)szNewName,
ConfigOptions,
(AREAPR)Area,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
if(SCESTATUS_SUCCESS == rc){
//
// Now "syscomp.inf"
//
wcscpy(szTempName, Buffer);
wcscat(szTempName, TEXT("\\inf\\syscomp.inf"));
//
// only file security section
//
Area = AREA_FILE_SECURITY;
//
// import "syscomp.inf"
//
rc = SceRpcConfigureSystem(
binding_h,
(wchar_t *)szTempName,
NULL,
(wchar_t *)szNewName,
ConfigOptions,
(AREAPR)Area,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
if(SCESTATUS_SUCCESS == rc){
//
// can't reset account policy since SAM is going away (re-created)
//
Area = AREA_FILE_SECURITY | AREA_REGISTRY_SECURITY | AREA_SYSTEM_SERVICE;
ConfigOptions = SCE_DEBUG_LOG | SCE_DCPROMO_WAIT | SCE_NO_DOMAIN_POLICY | SCE_SERVICE_NO_REALTIME_ENFORCE;
if ( pScePromoteCallBack ) {
ConfigOptions |= SCE_CALLBACK_DELTA;
}
rc = SceRpcConfigureSystem(
binding_h,
NULL,
NULL,
(wchar_t *)szNewName,
ConfigOptions,
(AREAPR)Area,
ebSize,
(UCHAR *)pebClient,
&dWarn
);
}
}
rc32 = ScepSceStatusToDosError(rc);
//
// reset the previousPolicyArea so that at reboot after demotion
// the above policy will get reset
//
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
GPT_SCEDLL_NEW_PATH,
TEXT("PreviousPolicyAreas"),
AREA_SECURITY_POLICY | AREA_PRIVILEGES | AREA_GROUP_MEMBERSHIP
);
}
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc32 = RpcExceptionCode();
LogEventAndReport(MyModuleHandle,
(wchar_t *)szNewName,
STATUS_SEVERITY_WARNING,
SCEEVENT_WARNING_PROMOTE_SECURITY,
IDS_ERROR_PROMOTE_SECURITY,
rc32
);
} RpcEndExcept;
//
// Free the binding handle
//
RpcpUnbindRpc( binding_h );
if(pebClient)
{
FreeEnvironmentStrings((LPTSTR)pebClient);
}
} else {
rc32 = RtlNtStatusToDosError(NtStatus);
}
ScepSetCallback(NULL, NULL, 0);
rc = ScepRegDeleteValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff")
);
if ( rc != ERROR_SUCCESS &&
rc != ERROR_FILE_NOT_FOUND &&
rc != ERROR_PATH_NOT_FOUND ) {
// if can't delete the value, set the value to 0
ScepRegSetIntValue( HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyFilterOff"),
0
);
}
rc = ScepRegDeleteValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyPropOff")
);
if ( rc != ERROR_SUCCESS &&
rc != ERROR_FILE_NOT_FOUND &&
rc != ERROR_PATH_NOT_FOUND ) {
// if can't delete the value, set the value to 0
ScepRegSetIntValue( HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("PolicyPropOff"),
0
);
}
if ( dwPromoteOptions & SCE_PROMOTE_FLAG_DEMOTE ) {
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("DemoteInProgress"),
1
);
}
return(rc32);
}
NTSTATUS
ScepDcPromoRemoveUserRights()
{
NTSTATUS NtStatus;
LSA_HANDLE PolicyHandle=NULL;
SID_IDENTIFIER_AUTHORITY ia=SECURITY_NT_AUTHORITY;
SID_IDENTIFIER_AUTHORITY ia2=SECURITY_WORLD_SID_AUTHORITY;
PSID AccountSid=NULL;
//
// open LSA policy
//
NtStatus = ScepOpenLsaPolicy(
MAXIMUM_ALLOWED, //GENERIC_ALL,
&PolicyHandle,
TRUE
);
if ( NT_SUCCESS(NtStatus) ) {
//
// remove Power Users account totally
//
NtStatus = RtlAllocateAndInitializeSid (&ia,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_POWER_USERS,
0, 0, 0, 0, 0, 0,
&AccountSid);
if ( NT_SUCCESS(NtStatus) ) {
NtStatus = LsaRemoveAccountRights(
PolicyHandle,
AccountSid,
TRUE, // remove all rights
NULL,
0
);
RtlFreeSid(AccountSid);
}
//
// Users
//
ScepDcPromoRemoveTwoRights(PolicyHandle,
&ia,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS
);
//
// Guests
//
ScepDcPromoRemoveTwoRights(PolicyHandle,
&ia,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_GUESTS
);
//
// Authenticated Users
//
ScepDcPromoRemoveTwoRights(PolicyHandle,
&ia,
1,
SECURITY_AUTHENTICATED_USER_RID,
0
);
//
// Everyone
//
ScepDcPromoRemoveTwoRights(PolicyHandle,
&ia2,
1,
SECURITY_WORLD_RID,
0
);
LsaClose(PolicyHandle);
}
return NtStatus;
}
NTSTATUS
ScepDcPromoRemoveTwoRights(
IN LSA_HANDLE PolicyHandle,
IN SID_IDENTIFIER_AUTHORITY *pIA,
IN UCHAR SubAuthCount,
IN DWORD Rid1,
IN DWORD Rid2
)
{
//
// remove "logon locally" and "shutdown system" from the following accounts
//
LSA_UNICODE_STRING UserRightRemove[2];
RtlInitUnicodeString(&(UserRightRemove[0]), SE_INTERACTIVE_LOGON_NAME);
RtlInitUnicodeString(&(UserRightRemove[1]), SE_SHUTDOWN_NAME);
PSID AccountSid=NULL;
NTSTATUS NtStatus;
NtStatus = RtlAllocateAndInitializeSid (pIA,
SubAuthCount,
Rid1,
Rid2,
0, 0, 0, 0, 0, 0,
&AccountSid);
if ( NT_SUCCESS(NtStatus) ) {
NtStatus = LsaRemoveAccountRights(
PolicyHandle,
AccountSid,
FALSE,
UserRightRemove,
2
);
RtlFreeSid(AccountSid);
}
return(NtStatus);
}
//
// private APIs
//
DWORD
ScepSetupOpenSecurityDatabase(
IN BOOL bSystemOrAdmin
)
{
if ( hSceSetupHandle != NULL ) {
return ERROR_SUCCESS;
}
//
// get the default template name (on local system because setup only
// runs on local system
//
SCESTATUS rc;
BOOL bAdminLogon;
PWSTR DefProfile=NULL;
//
// don't care if error occurs to detect who is currently logged on
// setup always work on local computer so no remoate is supported here
//
if ( bSystemOrAdmin ) {
bAdminLogon = TRUE;
} else {
ScepIsAdminLoggedOn(&bAdminLogon, FALSE);
}
rc = ScepGetProfileSetting(
L"DefaultProfile",
bAdminLogon,
&DefProfile
);
if ( rc != NO_ERROR ) // return is Win32 error code
return(rc);
if (DefProfile == NULL ) {
return(ERROR_FILE_NOT_FOUND);
}
handle_t binding_h;
NTSTATUS NtStatus;
//
// RPC bind to the server (secure is not required)
//
NtStatus = ScepBindRpc(
NULL,
L"scerpc",
0,
&binding_h
);
/*
NtStatus = ScepBindSecureRpc(
NULL,
L"scerpc",
0,
&binding_h
);
*/
if (NT_SUCCESS(NtStatus)){
RpcTryExcept {
//
// should create file if it does not exist
//
rc = SceRpcOpenDatabase(
binding_h,
(wchar_t *)DefProfile,
SCE_OPEN_OPTION_TATTOO,
&hSceSetupHandle
);
rc = ScepSceStatusToDosError(rc);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
//
// Free the binding handle
//
RpcpUnbindRpc( binding_h );
} else {
rc = RtlNtStatusToDosError( NtStatus );
}
ScepFree( DefProfile );
return(rc);
}
DWORD
ScepSetupCloseSecurityDatabase()
{
DWORD rc;
if ( hSceSetupHandle != NULL ) {
//
// close the database, without terminating the jet engine
//
rc = ScepSceStatusToDosError(
SceCloseProfile((PVOID *)&hSceSetupHandle) );
if ( rc != ERROR_SUCCESS ) {
//
// not valid handle, or can't close the database
//
return(rc);
}
}
//
// free other environments, if any
//
hSceSetupHandle = NULL;
return(ERROR_SUCCESS);
}
//
// the RPC callback
//
SCEPR_STATUS
SceClientCallback(
IN DWORD ncbTicks,
IN DWORD ncbTotalTicks,
IN AREAPR cbArea,
IN wchar_t *szcbName OPTIONAL
)
/*
Routine Description:
The RPC client callback routine which is called from the server when
the callback flag is set. This routine is registered in scerpc.idl.
The callbacks are registered to SCE as arguments when calling from setup
or from dcpromo, for progress indicating.
Arguments:
ncbTicks - the ticks has passed since last call back
szcbName - the item name to call back
Return Value:
SCEPR_STATUS
*/
{
//
// the static variables holding callback pointer to client
//
if ( theCallBack != NULL ) {
switch ( CallbackType ) {
case SCE_SETUP_CALLBACK:
//
// callback to setup
//
if ( ncbTicks != (DWORD)-1 ) {
PSCE_NOTIFICATION_CALLBACK_ROUTINE pcb;
pcb = (PSCE_NOTIFICATION_CALLBACK_ROUTINE)theCallBack;
DWORD cbCount;
if ( dwCallbackTotal >= ncbTicks ) {
dwCallbackTotal -= ncbTicks;
cbCount = ncbTicks;
} else {
cbCount = dwCallbackTotal;
dwCallbackTotal = 0;
}
if ( cbCount > 0 ) {
__try {
//
// calls the client procedure with the prarmeters.
//
if ( !((*pcb)(hCallbackWnd,
SCESETUP_NOTIFICATION_TICKS,
0,
ncbTicks)) ) {
return SCESTATUS_SERVICE_NOT_SUPPORT;
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
return(SCESTATUS_INVALID_PARAMETER);
}
}
}
break;
case SCE_DCPROMO_CALLBACK:
//
// callback to dcpromo
//
if ( szcbName ) {
PSCE_PROMOTE_CALLBACK_ROUTINE pcb;
pcb = (PSCE_PROMOTE_CALLBACK_ROUTINE)theCallBack;
__try {
//
// callback to dcpromo process
//
PWSTR Buffer = (PWSTR)ScepAlloc(LPTR, (wcslen(szCallbackPrefix)+wcslen(szcbName)+1)*sizeof(WCHAR));
if ( Buffer ) {
if (wcsstr(szCallbackPrefix, L"%s")) {
//
// LoadString succeeded
//
swprintf(Buffer, szCallbackPrefix, szcbName);
}
else {
wcscpy(Buffer, szCallbackPrefix);
wcscat(Buffer, szcbName);
}
if ( (*pcb)(Buffer) != ERROR_SUCCESS ) {
ScepFree(Buffer);
Buffer = NULL;
return SCESTATUS_SERVICE_NOT_SUPPORT;
}
ScepFree(Buffer);
Buffer = NULL;
} else {
return SCESTATUS_NOT_ENOUGH_RESOURCE;
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
return(SCESTATUS_INVALID_PARAMETER);
}
}
break;
case SCE_AREA_CALLBACK:
//
// callback to SCE UI for area progress
//
PSCE_AREA_CALLBACK_ROUTINE pcb;
pcb = (PSCE_AREA_CALLBACK_ROUTINE)theCallBack;
__try {
//
// callback to UI process
//
if ( !((*pcb)(hCallbackWnd,
(AREA_INFORMATION)cbArea,
ncbTotalTicks,
ncbTicks)) ) {
return SCESTATUS_SERVICE_NOT_SUPPORT;
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
return(SCESTATUS_INVALID_PARAMETER);
}
break;
}
}
return(SCESTATUS_SUCCESS);
}
SCESTATUS
ScepSetupWriteError(
IN LPTSTR LogFileName,
IN PSCE_ERROR_LOG_INFO pErrlog
)
/* ++
Routine Description:
This routine outputs the error message in each node of the SCE_ERROR_LOG_INFO
list to the log file
Arguments:
LogFileName - the log file name
pErrlog - the error list
Return value:
None
-- */
{
if ( !pErrlog ) {
return(SCESTATUS_SUCCESS);
}
HANDLE hFile=INVALID_HANDLE_VALUE;
if ( LogFileName ) {
hFile = CreateFile(LogFileName,
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwBytesWritten;
SetFilePointer (hFile, 0, NULL, FILE_BEGIN);
BYTE TmpBuf[3];
TmpBuf[0] = 0xFF;
TmpBuf[1] = 0xFE;
TmpBuf[2] = 0;
WriteFile (hFile, (LPCVOID)TmpBuf, 2,
&dwBytesWritten,
NULL);
SetFilePointer (hFile, 0, NULL, FILE_END);
}
}
PSCE_ERROR_LOG_INFO pErr;
for ( pErr=pErrlog; pErr != NULL; pErr = pErr->next ) {
if ( pErr->buffer != NULL ) {
ScepSetupWriteOneError( hFile, pErr->rc, pErr->buffer );
}
}
if ( INVALID_HANDLE_VALUE != hFile ) {
CloseHandle(hFile);
}
return(SCESTATUS_SUCCESS);
}
SCESTATUS
ScepSetupWriteOneError(
IN HANDLE hFile,
IN DWORD rc,
IN LPTSTR buf
)
{
LPVOID lpMsgBuf=NULL;
if ( !buf ) {
return(SCESTATUS_SUCCESS);
}
if ( rc != NO_ERROR ) {
//
// get error description of rc
//
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
rc,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
NULL
);
}
if ( INVALID_HANDLE_VALUE != hFile ) {
//
// The log file is initialized
//
if ( lpMsgBuf != NULL )
ScepWriteVariableUnicodeLog( hFile, TRUE, L"%s %s", (PWSTR)lpMsgBuf, buf );
else
ScepWriteSingleUnicodeLog(hFile, TRUE, buf);
}
if ( lpMsgBuf != NULL )
LocalFree(lpMsgBuf);
return(SCESTATUS_SUCCESS);
}
DWORD
SceSetuppLogComponent(
IN DWORD ErrCode,
IN SCESETUP_OBJECT_TYPE ObjType,
IN SCESETUP_OPERATION_TYPE OptType,
IN PWSTR Name,
IN PWSTR SDText OPTIONAL,
IN PWSTR SecondName OPTIONAL
)
{
//
// check if this log should be generated
//
DWORD dwDebugLog=0;
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Secedit"),
TEXT("SetupCompDebugLevel"),
&dwDebugLog
);
if ( dwDebugLog == 0 ) {
return(ERROR_SUCCESS);
}
//
// build the component log file name %windir%\security\logs\scecomp.log
//
WCHAR LogName[MAX_PATH+51];
GetSystemWindowsDirectory(LogName, MAX_PATH);
LogName[MAX_PATH] = L'\0';
wcscat(LogName, L"\\security\\logs\\scecomp.log\0");
HANDLE hFile = CreateFile(LogName,
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if ( INVALID_HANDLE_VALUE != hFile ) {
DWORD dwBytesWritten;
SetFilePointer (hFile, 0, NULL, FILE_BEGIN);
BYTE TmpBuf[3];
TmpBuf[0] = 0xFF;
TmpBuf[1] = 0xFE;
TmpBuf[2] = 0;
WriteFile (hFile, (LPCVOID)TmpBuf, 2,
&dwBytesWritten,
NULL);
SetFilePointer (hFile, 0, NULL, FILE_END);
//
// print a time stamp
//
LARGE_INTEGER CurrentTime;
LARGE_INTEGER SysTime;
TIME_FIELDS TimeFields;
NTSTATUS NtStatus;
NtStatus = NtQuerySystemTime(&SysTime);
RtlSystemTimeToLocalTime (&SysTime,&CurrentTime);
if ( NT_SUCCESS(NtStatus) &&
(CurrentTime.LowPart != 0 || CurrentTime.HighPart != 0) ) {
memset(&TimeFields, 0, sizeof(TIME_FIELDS));
RtlTimeToTimeFields (
&CurrentTime,
&TimeFields
);
if ( TimeFields.Month > 0 && TimeFields.Month <= 12 &&
TimeFields.Day > 0 && TimeFields.Day <= 31 &&
TimeFields.Year > 1600 ) {
ScepWriteVariableUnicodeLog(hFile, FALSE,
L"%02d/%02d/%04d %02d:%02d:%02d",
TimeFields.Month, TimeFields.Day, TimeFields.Year,
TimeFields.Hour, TimeFields.Minute, TimeFields.Second);
} else {
ScepWriteVariableUnicodeLog(hFile, FALSE, L"%08x08x",
CurrentTime.HighPart, CurrentTime.LowPart);
}
} else {
ScepWriteSingleUnicodeLog(hFile, FALSE, L"Unknown time");
}
//
// print operation status code
//
if ( ErrCode ) {
ScepWriteVariableUnicodeLog(hFile, FALSE, L"\tError=%d", ErrCode);
} else {
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\tSucceed");
}
//
// printf operation type
//
switch (OptType) {
case SCESETUP_UPDATE:
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\tUpdate");
break;
case SCESETUP_MOVE:
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\tMove");
break;
default:
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\tUnknown");
break;
}
//
// print object type
//
switch (ObjType) {
case SCESETUP_FILE:
ScepWriteSingleUnicodeLog(hFile, TRUE, L"\tFile");
break;
case SCESETUP_KEY:
ScepWriteSingleUnicodeLog(hFile, TRUE, L"\tKey");
break;
case SCESETUP_SERVICE:
ScepWriteSingleUnicodeLog(hFile, TRUE, L"\tService");
break;
default:
ScepWriteSingleUnicodeLog(hFile, TRUE, L"\tUnknown");
break;
}
__try {
//
// print the name(s)
//
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\t");
if ( SecondName && Name ) {
// Name\tSecondName\n
ScepWriteSingleUnicodeLog(hFile, FALSE, Name);
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\t");
ScepWriteSingleUnicodeLog(hFile, TRUE, SecondName);
} else if ( Name ) {
ScepWriteSingleUnicodeLog(hFile, TRUE, Name);
}
//
// print the SDDL string
//
if ( SDText ) {
ScepWriteSingleUnicodeLog(hFile, FALSE, L"\tSecurity=");
ScepWriteSingleUnicodeLog(hFile, TRUE, SDText);
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
return(ERROR_INVALID_PARAMETER);
}
CloseHandle(hFile);
} else {
return(GetLastError());
}
return(ERROR_SUCCESS);
}
DWORD
WINAPI
SceSetupBackupSecurity(
IN LPTSTR LogFileName OPTIONAL // default to %windir%\security\logs\backup.log
)
{
TCHAR Buffer[MAX_PATH+1];
DWORD rc32;
TCHAR szGenName[MAX_PATH*2], szNewName[MAX_PATH+51];
DWORD eProductType;
eProductType = WhichNTProduct();
Buffer[0] = L'\0';
GetSystemWindowsDirectory(Buffer, MAX_PATH);
Buffer[MAX_PATH] = L'\0';
szNewName[0] = L'\0';
if ( LogFileName == NULL ) {
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\security\\logs\\backup.log\0");
}
(void) InitializeEvents(L"SceCli");
//
// if I am in setup, query the security policy/user rights for any
// policy changes within setup (such as NT4 PDC upgrade where the policy
// filter will fail to save the change)
//
DWORD dwInSetup=0;
DWORD dwUpgraded=0;
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("System\\Setup"),
TEXT("SystemSetupInProgress"),
&dwInSetup
);
if ( dwInSetup ) {
//
// delete the temp local group policy template
//
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\system32\\grouppolicy\\machine\\microsoft\\windows nt\\secedit\\gpttmpl.inf\0");
DeleteFile(szGenName);
ScepRegQueryIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("SetupUpgraded"),
(DWORD *)&dwUpgraded
);
/*
if ( dwUpgraded ) {
//
// in GUI setup, snapshot the system security/user rights
// query the upgrade flag, only query the system (again) when
// it's upgraded, because for the case of NT4 PDC upgrade to NT5
// any back office apps installed in GUI setup (user rights) won't
// get saved to the GPO storage correctly (ProductType is wrong)
//
rc32 = ScepSystemSecurityInSetup(
szNewName, // not used
LogFileName ? LogFileName : szNewName,
0,
SCESETUP_UPGRADE_SYSTEM | SCESETUP_BIND_NO_AUTH,
NULL,
NULL
);
if ( NO_ERROR != rc32 ) {
LogEventAndReport(MyModuleHandle,
LogFileName ? LogFileName : szNewName,
0,
0,
IDS_ERROR_SNAPSHOT_SECURITY,
rc32
);
} else {
LogEventAndReport(MyModuleHandle,
LogFileName ? LogFileName : szNewName,
0,
0,
IDS_SNAPSHOT_SECURITY_POLICY
);
}
}
//
// reset the value
//
ScepRegSetIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("SetupUpgraded"),
0
);
*/
}
//
// open the database
//
rc32 = ScepSetupOpenSecurityDatabase(TRUE);
BOOL bUpgradeNt5 = (BOOL)(dwUpgraded && IsNT5());
if ( NO_ERROR == rc32 ) {
wcscpy(szGenName, Buffer);
wcscat(szGenName, L"\\security\\setup.inf\0");
//
// generate the updated database (for emergency repair)
// %windir%\security\templates\setup security.inf
//
PSCE_ERROR_LOG_INFO pErrlog=NULL;
rc32 = ScepSceStatusToDosError(
SceCopyBaseProfile(
(PVOID)hSceSetupHandle,
SCE_ENGINE_SMP,
(wchar_t *)szGenName,
dwInSetup ?
AREA_ALL :
(AREA_REGISTRY_SECURITY |
AREA_FILE_SECURITY |
AREA_SYSTEM_SERVICE),
&pErrlog
));
ScepSetupWriteError(LogFileName ? LogFileName : szNewName, pErrlog);
ScepFreeErrorLog(pErrlog);
if ( rc32 != NO_ERROR ) {
LogEventAndReport(MyModuleHandle,
LogFileName ? LogFileName : szNewName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_BACKUP_SECURITY,
IDS_ERROR_GENERATE,
rc32,
szGenName,
LogFileName ? LogFileName : szNewName
);
}
if (NO_ERROR == rc32 && bUpgradeNt5) {
//
// when upgrading from win2k, update (merge) "setup security.inf" or "DC security.inf"
// with the information in the backup security template
//
rc32 = ScepUpdateBackupSecurity(szGenName,
Buffer,
(NtProductLanManNt == eProductType)?TRUE:FALSE
);
}
//
// check if we should trigger a policy propagation manually
//
DWORD dwResetOption=0;
if ( dwInSetup && dwUpgraded )
dwResetOption |= SCE_RESET_POLICY_ENFORCE_ATREBOOT;
//
// remove local policies from the database
// for NT4 DC upgrade case, keep the local policy setting until dcpromo
//
if ( dwInSetup && dwUpgraded && !IsNT5() &&
NtProductLanManNt == eProductType )
dwResetOption |= SCE_RESET_POLICY_KEEP_LOCAL;
//
// if it's after dcpromo, need to empty tattoo table
// if LogFileName is NULL and it's not in setup, it's in DC demotion in which case
// we want to leave the tattoo table (w/ reset settings)
//
if ( !dwInSetup && (LogFileName != NULL) )
dwResetOption |= SCE_RESET_POLICY_TATTOO;
DWORD rCode = SceRpcSetupResetLocalPolicy(
(PVOID)hSceSetupHandle,
AREA_ALL,
NULL,
dwResetOption
);
LogEventAndReport(MyModuleHandle,
LogFileName ? LogFileName : szNewName,
0,
0,
IDS_ERROR_REMOVE_DEFAULT_POLICY,
rCode,
dwResetOption
);
//
// close the context
//
ScepSetupCloseSecurityDatabase();
if ( NO_ERROR == rc32 ){
//
// template is always generated, copy it to %windir%\security\templates and
// to %windir%\repair
//
szNewName[0] = L'0';
//
// Load string for the description
//
LoadString( MyModuleHandle,
dwInSetup ? IDS_BACKUP_OUTBOX_DESCRIPTION : IDS_BACKUP_DC_DESCRIPTION,
szNewName,
MAX_PATH
);
//
// re-write descriptoin for there backup files.
//
WritePrivateProfileSection(
L"Profile Description",
NULL,
(LPCTSTR)szGenName);
if ( szNewName[0] ) {
WritePrivateProfileString(
L"Profile Description",
L"Description",
szNewName,
(LPCTSTR)szGenName);
}
//
// copy the file to its destination
//
szNewName[0] = L'0';
wcscpy(szNewName, Buffer);
if ( (!dwInSetup && (LogFileName == NULL)) ||
(dwInSetup && (NtProductLanManNt != eProductType))){
wcscat(szNewName, L"\\security\\templates\\setup security.inf\0");
}
else{
wcscat(szNewName, L"\\security\\templates\\DC security.inf\0");
}
if ( CopyFile( szGenName, szNewName, FALSE ) ) {
LogEvent(MyModuleHandle,
STATUS_SEVERITY_INFORMATIONAL,
SCEEVENT_INFO_BACKUP_SECURITY,
0,
szNewName
);
wcscpy(szNewName, Buffer);
if ( (!dwInSetup && (LogFileName == NULL)) ||
(dwInSetup && (NtProductLanManNt != eProductType))){
wcscat(szNewName, L"\\repair\\secsetup.inf\0");
} else {
wcscat(szNewName, L"\\repair\\secDC.inf\0");
}
CopyFile( szGenName, szNewName, FALSE );
} else {
rc32 = GetLastError();
wcscpy(szNewName, Buffer);
if ( (!dwInSetup && (LogFileName == NULL)) ||
(dwInSetup && (NtProductLanManNt != eProductType))){
wcscat(szNewName, L"\\repair\\secsetup.inf\0");
} else {
wcscat(szNewName, L"\\repair\\secDC.inf\0");
}
if ( CopyFile( szGenName, szNewName, FALSE ) ) {
LogEvent(MyModuleHandle,
STATUS_SEVERITY_WARNING,
SCEEVENT_WARNING_BACKUP_SECURITY,
0,
szNewName
);
rc32 = ERROR_SUCCESS;
} else {
rc32 = GetLastError();
LogEvent(MyModuleHandle,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_BACKUP_SECURITY,
IDS_ERROR_BACKUP,
rc32
);
}
}
DeleteFile(szGenName);
}
} else {
LogEventAndReport(MyModuleHandle,
LogFileName ? LogFileName : szNewName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_BACKUP_SECURITY,
IDS_ERROR_OPEN_DATABASE,
rc32
);
}
if ( dwInSetup ) {
dwThisMachine = eProductType;
if ((dwThisMachine == NtProductServer || dwThisMachine == NtProductWinNt) ||
((dwThisMachine == NtProductLanManNt) && IsNT5())) {
//
// reconfigure file
//
TCHAR szLogName[MAX_PATH+51], szTempName[MAX_PATH+51];
wcscpy(szLogName, Buffer);
wcscat(szLogName, L"\\security\\logs\\scesetup.log\0");
wcscpy(szTempName, Buffer);
wcscat(szTempName, L"\\inf\\syscomp.inf\0");
rc32 = ScepSystemSecurityInSetup(
szTempName,
szLogName,
0,
SCESETUP_RECONFIG_SECURITY | SCESETUP_BIND_NO_AUTH,
NULL,
NULL
);
if ( NO_ERROR != rc32 ) {
LogEventAndReport(MyModuleHandle,
szLogName,
0,
0,
IDS_ERR_RECONFIG_FILES,
rc32
);
}
//
// append syscomp.inf to "setup security.inf" or
// "DC security.inf"
//
PVOID hProfile = NULL;
PSCE_PROFILE_INFO pReConfFile = NULL;
SCESTATUS rcSce = SCESTATUS_SUCCESS;
//
// first export the syscomp.inf data from the database
// so we can get the enviroment variables resolved
// which allows us to do a successful merge with
// setup/DC security.inf
//
wcscpy(szTempName, Buffer);
wcscat(szTempName, L"\\security\\templates\\syscomp.inf\0");
//
// open the database
//
rcSce = ScepSetupOpenSecurityDatabase(TRUE);
if(SCESTATUS_SUCCESS == rcSce){
//
// export syscomp data to a temp file
//
rcSce = SceCopyBaseProfile((PVOID)hSceSetupHandle,
SCE_ENGINE_SMP,
(wchar_t *)szTempName,
AREA_FILE_SECURITY,
NULL
);
if(SCESTATUS_SUCCESS == rcSce){
//
// open the temp file and read the file section
//
rcSce = SceOpenProfile(szTempName,
SCE_INF_FORMAT,
&hProfile
);
if(SCESTATUS_SUCCESS == rcSce){
rcSce = SceGetSecurityProfileInfo(hProfile,
SCE_ENGINE_SCP,
AREA_FILE_SECURITY,
&pReConfFile,
NULL
);
if(SCESTATUS_SUCCESS == rcSce){
//
// append the data to setup/DC security.inf
//
wcscpy(szTempName, Buffer);
if(dwThisMachine == NtProductLanManNt){
wcscat(szTempName, L"\\security\\templates\\DC security.inf\0");
}
else{
wcscat(szTempName, L"\\security\\templates\\setup security.inf\0");
}
rcSce = SceAppendSecurityProfileInfo(szTempName,
AREA_FILE_SECURITY,
pReConfFile,
NULL
);
SceFreeProfileMemory(pReConfFile);
}
SceCloseProfile(&hProfile);
}
//
// delete the temp file
//
wcscpy(szTempName, Buffer);
wcscat(szTempName, L"\\security\\templates\\syscomp.inf\0");
DeleteFile(szTempName);
}
//
// remove local policies from the database
//
(void)SceRpcSetupResetLocalPolicy(
(PVOID)hSceSetupHandle,
AREA_FILE_SECURITY,
NULL,
0
);
ScepSetupCloseSecurityDatabase();
}
if(SCESTATUS_SUCCESS != rcSce){
rc32 = ScepSceStatusToDosError(rcSce);
wcscpy(szTempName, Buffer);
wcscat(szTempName, L"\\security\\templates\\setup security.inf\0");
LogEventAndReport(MyModuleHandle,
szLogName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_BACKUP_SECURITY,
IDS_ERROR_MERGE_BACKUP_SECURITY,
rc32,
szTempName
);
}
}
}
(void) ShutdownEvents();
return(rc32);
}
SCESTATUS
ScepUpdateBackupSecurity(
IN PCTSTR pszSetupInf,
IN PCTSTR pszWindowsFolder,
IN BOOL bIsDC
)
/*
Routine Description:
This routine updates the exisitng setup security.inf or DC security.inf
(depends on if the code runs on a domain controler) based on the information
in the passed in security template.
All areas except file security, registry key security and services security
are "merged" but sections for file and registry keys are only taken from the
new security template file, because in setup upgrade,
all system files/keys/services are re-ACL'ed properly.
Note, this routine should only be called when ugpraded from W2K.
Arguments:
pszSetupInf - the full path name of the temporary setup security template exported from system db
pszWindowsFolder - the windows root path
bIsDC - TRUE - this is a domain controller
Return Value:
SCE error
*/
{
TCHAR szTempName[MAX_PATH + 51] = {0};
TCHAR szNewTemplateName[MAX_PATH + 51] = {0};
PVOID hProfile = NULL;
PSCE_PROFILE_INFO pSetupSecurity = NULL;
SCESTATUS rcSce = SCESTATUS_SUCCESS;
//
// validate parameters
//
if(!pszSetupInf || !pszWindowsFolder){
return SCESTATUS_INVALID_PARAMETER;
}
//
// find which template to update
//
wcscpy(szTempName, pszWindowsFolder);
if(bIsDC){
//
// if DC, update DC Security.inf
//
wcscat(szTempName, TEXT("\\security\\templates\\DC security.inf"));
} else {
//
// if not DC, update Setup Security.inf
//
wcscat(szTempName, TEXT("\\security\\templates\\setup security.inf"));
}
//
// first copy the template to a temp scratch file
//
wcscpy(szNewTemplateName, pszWindowsFolder);
wcscat(szNewTemplateName, TEXT("\\security\\NewSecurity.inf"));
if(!CopyFile(szTempName, szNewTemplateName, FALSE)){
rcSce = ScepDosErrorToSceStatus(GetLastError());
goto ExitHandler;
}
//
// Second, Read all the information of what we secured during
// setup
//
//
// Open the template that was exported from the database table
// we used to secure the system during setup
//
rcSce = SceOpenProfile(pszSetupInf,
SCE_INF_FORMAT,
&hProfile
);
if(SCESTATUS_SUCCESS != rcSce){
goto ExitHandler;
}
//
// read out all the information
//
rcSce = SceGetSecurityProfileInfo(hProfile,
SCE_ENGINE_SCP,
AREA_ALL,
&pSetupSecurity,
NULL
);
if(SCESTATUS_SUCCESS != rcSce){
goto ExitHandler;
}
//
// then append all section except Files, Registry and services sections
// to the scratch template ("setup security" or "DC security" copy)
//
rcSce = SceAppendSecurityProfileInfo(szNewTemplateName,
AREA_SECURITY_POLICY |
AREA_GROUP_MEMBERSHIP |
AREA_PRIVILEGES,
pSetupSecurity,
NULL
);
if(SCESTATUS_SUCCESS != rcSce){
goto ExitHandler;
}
//
// then overwrite the files, registry and services sections.
// because all the information we need is in the upgrade template
// and there is not need to merge those with the old info.
//
rcSce = SceWriteSecurityProfileInfo(szNewTemplateName,
AREA_SYSTEM_SERVICE |
AREA_FILE_SECURITY |
AREA_REGISTRY_SECURITY,
pSetupSecurity,
NULL
);
if(SCESTATUS_SUCCESS != rcSce){
goto ExitHandler;
}
//
// if all that succeeded then copy back the scartch template
// to its original template
//
if(!CopyFile(szNewTemplateName, pszSetupInf, FALSE)){
rcSce = ScepDosErrorToSceStatus(GetLastError());
goto ExitHandler;
}
ExitHandler:
//
// clean up
//
if(hProfile){
SceCloseProfile(&hProfile);
}
if(pSetupSecurity){
SceFreeProfileMemory(pSetupSecurity);
}
DeleteFile(szNewTemplateName);
return ScepSceStatusToDosError(rcSce);
}
DWORD
WINAPI
SceSetupConfigureServices(
IN UINT SetupProductType
)
{
TCHAR Buffer[MAX_PATH+1];
DWORD rc32 = SCESTATUS_SUCCESS;
TCHAR szNewName[MAX_PATH+51];
Buffer[0] = L'\0';
GetSystemWindowsDirectory(Buffer, MAX_PATH);
Buffer[MAX_PATH] = L'\0';
szNewName[0] = L'\0';
wcscpy(szNewName, Buffer);
wcscat(szNewName, L"\\security\\logs\\backup.log\0");
//
// if I am in setup, query the security policy/user rights for any
// policy changes within setup (such as NT4 PDC upgrade where the policy
// filter will fail to save the change)
//
DWORD dwInSetup=0;
DWORD dwUpgraded=0;
ScepRegQueryIntValue(HKEY_LOCAL_MACHINE,
TEXT("System\\Setup"),
TEXT("SystemSetupInProgress"),
&dwInSetup
);
if ( dwInSetup ) {
//
// in GUI setup, snapshot the system security/user rights
// query the upgrade flag, only query the system (again) when
// it's upgraded, because for the case of NT4 PDC upgrade to NT5
// any back office apps installed in GUI setup (user rights) won't
// get saved to the GPO storage correctly (ProductType is wrong)
//
ScepRegQueryIntValue(
HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
TEXT("SetupUpgraded"),
(DWORD *)&dwUpgraded
);
if ( !dwUpgraded ) {
//
// configure service area
//
rc32 = ScepSystemSecurityInSetup(
(SetupProductType == PRODUCT_WORKSTATION) ? L"defltwk.inf" : L"defltsv.inf",
szNewName,
AREA_SYSTEM_SERVICE,
SCESETUP_BACKUP_SECURITY | SCESETUP_BIND_NO_AUTH,
NULL,
NULL
);
}
}
return(rc32);
}
BOOL
pCreateDefaultGPOsInSysvol(
IN LPTSTR DomainDnsName,
IN LPTSTR szSysvolPath,
IN DWORD Options,
IN LPTSTR LogFileName
)
/*++
Routine Description:
Creates the default domain-wide account policy object and the default
policy object for local policies in sysvol.
The GUID to use is queried from registry.
Arguments:
DomainDnsName - the new domain's DNS name, e.g., JINDOM4.ntdev.microsoft.com
Options - the promotion options
LogFileName - the log file for debug info
Return:
WIN32 error
--*/
{
/*
//
// get sysvol share location
//
TCHAR szSysvolPath[MAX_PATH+1];
szSysvolPath[0] = L'\0';
GetEnvironmentVariable( L"SYSVOL",
szSysvolPath,
MAX_PATH);
*/
//
// create \\?\%sysvol%\sysvol\<DnsName>\Policies directory
// the \\?\ is for the case of longer than MAX_PATH chars
//
DWORD Len = 4 + wcslen(szSysvolPath) + wcslen(TEXT("\\sysvol\\Policies\\")) +
wcslen(DomainDnsName);
PWSTR pszPoliciesPath = (PWSTR)ScepAlloc(LPTR, (Len+wcslen(TEXT("\\{}\\MACHINE"))+
STR_GUID_LEN+1)*sizeof(WCHAR));
if ( !pszPoliciesPath ) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
swprintf(pszPoliciesPath, L"\\\\?\\%s\\sysvol\\%s\\Policies\0", szSysvolPath, DomainDnsName);
DWORD Win32rc = ScepSceStatusToDosError(
ScepCreateDirectory(
pszPoliciesPath,
TRUE,
NULL
));
if ( ERROR_SUCCESS == Win32rc ) {
//
// create sub directory for the first GPO GUID1 and machine, user, GPT.ini
//
if ( pCreateSysvolContainerForGPO(STR_DEFAULT_DOMAIN_GPO_GUID,
pszPoliciesPath,
Len) ) {
//
// when it's returned success from the previous
// pszPoliciesPath is already changed to the machine's root
// with the guid info.
//
if ( pCreateOneGroupPolicyObject(
pszPoliciesPath,
TRUE, // domain level
LogFileName) ) {
//
// create sub directory for the second GPO
//
if ( pCreateSysvolContainerForGPO(STR_DEFAULT_DOMAIN_CONTROLLER_GPO_GUID,
pszPoliciesPath,
Len) ) {
//
// when it's returned success from the previous
// pszPoliciesPath is already changed to the machine's root
// with the guid info.
//
if ( pCreateOneGroupPolicyObject(
pszPoliciesPath,
FALSE, // not domain level
LogFileName) ) {
//
// log a entry to the log
//
LogEventAndReport(MyModuleHandle,
LogFileName,
0,
0,
IDS_SUCCESS_DEFAULT_GPO,
L"in sysvol"
);
} else {
Win32rc = GetLastError();
}
} else {
Win32rc = GetLastError();
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_CREATE_DIRECTORY,
Win32rc,
STR_DEFAULT_DOMAIN_CONTROLLER_GPO_GUID
);
}
} else {
Win32rc = GetLastError();
}
} else {
Win32rc = GetLastError();
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_CREATE_DIRECTORY,
Win32rc,
STR_DEFAULT_DOMAIN_GPO_GUID
);
}
} else {
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_CREATE_DIRECTORY,
Win32rc,
pszPoliciesPath
);
}
ScepFree(pszPoliciesPath);
SetLastError( Win32rc );
//
// if this function fails, it will fail DCPROMO and the sysvol directory
// should be cleaned up by dcpromo/ntfrs
//
return ( ERROR_SUCCESS == Win32rc );
}
BOOL
pCreateSysvolContainerForGPO(
IN LPCTSTR strGuid,
IN LPTSTR szPath,
IN DWORD dwStart
)
{
swprintf(szPath+dwStart, L"\\{%s}\\USER", strGuid);
DWORD Win32rc = ScepSceStatusToDosError(
ScepCreateDirectory(
szPath,
TRUE,
NULL
));
if ( ERROR_SUCCESS == Win32rc ) {
//
// the directory for the GUID is created
// now create the GPT.INI
//
swprintf(szPath+dwStart, L"\\{%s}\\GPT.INI", strGuid);
WritePrivateProfileString (TEXT("General"), TEXT("Version"), TEXT("1"),
szPath); // does it work with prefix "\\?\" ?
//
// create the machine directory
// since all the parent directories are already created by the call
// to create USER directory, there is no need to loop again
// call CreateDirectory directly
//
swprintf(szPath+dwStart, L"\\{%s}\\MACHINE", strGuid);
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = FALSE;
if ( CreateDirectory(
szPath,
&sa
) == FALSE ) {
if ( GetLastError() != ERROR_ALREADY_EXISTS ) {
Win32rc = GetLastError();
}
}
}
SetLastError(Win32rc);
return (ERROR_SUCCESS == Win32rc);
}
BOOL
pCreateOneGroupPolicyObject(
IN PWSTR pszGPOSysPath,
IN BOOL bDomainLevel,
IN PWSTR LogFileName
)
/*++
Routine Description:
Creates a group policy object in sysvol.
Arguments:
pszGPOSysPath- the GPO's sysvol path (up to root of machine)
bDomainLevel - create the object for domain level if TRUE, otherwise,
create the GPO for "domain controllers" OU
LogFileName - the dcpromo log file to track info
Return:
TRUE - success
FALSE - fail, use GetLastError()
--*/
{
//
// create the default domain policy object
//
LPTSTR SceTemplateName = (LPTSTR) LocalAlloc(LPTR,(lstrlen(pszGPOSysPath)+
lstrlen(GPTSCE_TEMPLATE)+2)*sizeof(TCHAR));
DWORD Win32rc;
if (SceTemplateName) {
//
// build the template path first
//
lstrcpy(SceTemplateName,pszGPOSysPath);
lstrcat(SceTemplateName,L"\\");
lstrcat(SceTemplateName, GPTSCE_TEMPLATE);
//
// Create the template directory if there isn't one already
//
Win32rc = ScepSceStatusToDosError(
ScepCreateDirectory(
SceTemplateName,
FALSE,
NULL
));
if ( ERROR_SUCCESS == Win32rc ) {
TCHAR pszGPOTempName[MAX_PATH+51];
pszGPOTempName[0] = L'\0';
GetSystemWindowsDirectory(pszGPOTempName, MAX_PATH);
pszGPOTempName[MAX_PATH] = L'\0';
if ( bDomainLevel ) {
//
// create the default domain GPO
// copy template from %windir%\security\FirstDGPO.inf
//
wcscat(pszGPOTempName, L"\\security\\FirstDGPO.inf\0");
} else {
//
// create the default GPO for "domain controllers" OU
// copy template from %windir%\security\FirstOGPO.inf
//
wcscat(pszGPOTempName, L"\\security\\FirstOGPO.inf\0");
}
DWORD rc=ERROR_SUCCESS;
HINF hInf=NULL;
AREA_INFORMATION Area = AREA_SECURITY_POLICY | AREA_PRIVILEGES;
PSCE_PROFILE_INFO pSceInfo=NULL;
rc = SceInfpOpenProfile(
pszGPOTempName,
&hInf
);
if ( SCESTATUS_SUCCESS == rc ) {
//
// do not do sid->name->sid translation in DCPromo (bug 462994)
//
gbClientInDcPromo = TRUE;
//
// load informatin from the template
//
rc = SceInfpGetSecurityProfileInfo(
hInf,
Area,
&pSceInfo,
NULL
);
gbClientInDcPromo = FALSE;
if ( SCESTATUS_SUCCESS != rc ) {
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_GETGPO_FILE_PATH,
rc,
pszGPOTempName
);
}
SceInfpCloseProfile(hInf);
} else {
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_GETGPO_FILE_PATH,
rc,
pszGPOTempName
);
}
if ( ERROR_SUCCESS == rc && pSceInfo ) {
//
// Write to GPO instead of copy, this way the GPO will be unicode.
//
//??? pSceInfo->Type = SCE_ENGINE_SMP;
rc = SceWriteSecurityProfileInfo(SceTemplateName,
Area,
(PSCE_PROFILE_INFO)pSceInfo,
NULL
);
if ( SCESTATUS_SUCCESS != rc ) {
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_GETGPO_FILE_PATH,
rc,
pszGPOTempName
);
}
}
if ( pSceInfo != NULL ) {
SceFreeProfileMemory(pSceInfo);
}
#if 0
if ( !CopyFile( pszGPOTempName,
SceTemplateName,
FALSE ) ) {
Win32rc = GetLastError();
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_COPY_TEMPLATE,
Win32rc,
SceTemplateName
);
}
#endif
DeleteFile(pszGPOTempName);
} else {
LogEventAndReport(MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_CREATE_DIRECTORY,
Win32rc,
SceTemplateName
);
}
LocalFree(SceTemplateName);
} else {
Win32rc = ERROR_NOT_ENOUGH_MEMORY;
LogEventAndReport(
MyModuleHandle,
LogFileName,
STATUS_SEVERITY_ERROR,
SCEEVENT_ERROR_CREATE_GPO,
IDS_ERROR_NO_MEMORY
);
}
SetLastError(Win32rc);
return ( ERROR_SUCCESS == Win32rc);
}
//NT_PRODUCT_TYPE
DWORD
WhichNTProduct()
{
HKEY hKey;
DWORD dwBufLen=32;
TCHAR szProductType[32];
LONG lRet;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
0,
KEY_QUERY_VALUE,
&hKey) != ERROR_SUCCESS) {
// return Unknown
return PRODUCT_UNKNOWN;
}
lRet = RegQueryValueEx(hKey,
TEXT("ProductType"),
NULL,
NULL,
(LPBYTE)szProductType,
&dwBufLen);
RegCloseKey(hKey);
if(lRet != ERROR_SUCCESS) {
// return Unknown
return PRODUCT_UNKNOWN;
}
// check product options, in order of likelihood
if (lstrcmpi(TEXT("WINNT"), szProductType) == 0) {
return NtProductWinNt;
}
if (lstrcmpi(TEXT("SERVERNT"), szProductType) == 0) {
return NtProductServer;
}
if (lstrcmpi(TEXT("LANMANNT"), szProductType) == 0) {
return NtProductLanManNt;
}
// return Unknown
return PRODUCT_UNKNOWN;
}
BOOL
ScepAddAuthUserToLocalGroup()
{
//
// Attempt to add Authenticated Users and Interactive back into Users group.
//
DWORD rc1;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AuthenticatedUsers = NULL;
PSID Interactive = NULL;
WCHAR Name[36];
BOOL b;
LOCALGROUP_MEMBERS_INFO_0 lgrmi0[2];
HMODULE hMod = GetModuleHandle(L"scecli.dll");
LoadString(hMod, IDS_NAME_USERS, Name, 36);
b = AllocateAndInitializeSid (
&NtAuthority,
1,
SECURITY_AUTHENTICATED_USER_RID,
0, 0, 0, 0, 0, 0, 0,
&AuthenticatedUsers
);
if (b) {
lgrmi0[0].lgrmi0_sid = AuthenticatedUsers;
b = AllocateAndInitializeSid (
&NtAuthority,
1,
SECURITY_INTERACTIVE_RID,
0, 0, 0, 0, 0, 0, 0,
&Interactive
);
if (b) {
lgrmi0[1].lgrmi0_sid = Interactive;
rc1 = NetLocalGroupAddMembers(
NULL,
Name,
0,
(PBYTE) lgrmi0,
2
);
}
else {
if ( AuthenticatedUsers ) {
FreeSid( AuthenticatedUsers );
}
return FALSE;
}
if ( AuthenticatedUsers ) {
FreeSid( AuthenticatedUsers );
}
if ( Interactive ) {
FreeSid( Interactive );
}
if ( rc1 != ERROR_SUCCESS && rc1 != ERROR_MEMBER_IN_ALIAS ) {
return FALSE;
}
}
else {
return FALSE;
}
return TRUE;
}
DWORD
SceSysPrep()
{
SCESTATUS rc=0;
handle_t binding_h=NULL;
NTSTATUS NtStatus;
//
// open system database
//
rc = ScepSetupOpenSecurityDatabase(TRUE);
rc = ScepSceStatusToDosError(rc);
if ( ERROR_SUCCESS == rc ) {
RpcTryExcept {
// reset policy
// all tables
rc = SceRpcSetupResetLocalPolicy(
(PVOID)hSceSetupHandle,
AREA_ALL,
NULL,
SCE_RESET_POLICY_SYSPREP
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code (DWORD)
//
rc = RpcExceptionCode();
} RpcEndExcept;
//
// close the database
//
ScepSetupCloseSecurityDatabase();
}
HKEY hKey;
DWORD Interval;
DWORD RegType;
DWORD DataSize;
if ( ERROR_SUCCESS == rc ) {
//
// update local policy version #
// so policy will be propagated at reboot
//
ScepEnforcePolicyPropagation();
}
//
// re-register seclogon.dll to recreate EFS recovery policy
// at first logon
//
HINSTANCE hNotifyDll = LoadLibrary(TEXT("sclgntfy.dll"));
if ( hNotifyDll) {
PFREGISTERSERVER pfRegisterServer = (PFREGISTERSERVER)GetProcAddress(
hNotifyDll,
"DllRegisterServer");
if ( pfRegisterServer ) {
//
// do not care errors - shouldn't fail
//
(void) (*pfRegisterServer)();
}
FreeLibrary(hNotifyDll);
}
if(( rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
EFS_NOTIFY_PATH,
0,
MAXIMUM_ALLOWED,
&hKey
)) == ERROR_SUCCESS ) {
//
// set a flag to registry
// this shouldn't fail since admin logon
//
Interval = 1;
rc = RegSetValueEx( hKey,
TEXT("SystemCloned"),
0,
REG_DWORD,
(BYTE *)&Interval,
4
);
RegCloseKey( hKey );
}
return(rc);
}
DWORD ScepCompareDaclWithStringSD(
IN PCWSTR pcwszSD,
IN PACL pDacl,
OUT PBOOL pbDifferent)
{
DWORD dwRet = ERROR_SUCCESS;
BOOL bDaclPresent, bDaclDefaulted;
PSECURITY_DESCRIPTOR pSD = NULL;
PACL pDaclFromSD = NULL;
if ( !ConvertStringSecurityDescriptorToSecurityDescriptor(
pcwszSD,
SDDL_REVISION_1,
&pSD,
NULL) ) {
dwRet = GetLastError();
}
if ( ERROR_SUCCESS == dwRet ) {
if ( !GetSecurityDescriptorDacl(
pSD,
&bDaclPresent,
&pDaclFromSD,
&bDaclDefaulted) ) {
dwRet = GetLastError();
}
}
if ( ERROR_SUCCESS == dwRet ) {
dwRet = ScepCompareExplicitAcl(
SE_FILE_OBJECT,
TRUE, // IsContainer
pDaclFromSD,
pDacl,
pbDifferent);
}
if ( pSD )
LocalFree(pSD);
return dwRet;
}
DWORD
WINAPI
SceSetupRootSecurity()
/*
Description:
This function should be called in GUI setup after system security is
configured (SceSetupSystemSecurityByName). The function calls to NTMARTA
API to set security on the root of boot partition (where Windows is installed).
This task will take quite long time depending on the size of the drive.
Therefore, setup should call this function in a asynchronous thread.
This function will NOT set security on the root drive if one of the following
conditions is met:
1) FAT partition
2) Security on the root drive was modified by user in a previous install.
This is determined by comparing the security on the root drive to the
default security from NTFS format, NTFS convert tool on both NT4 and
Windows 2000 systems.
*/
{
DWORD rc=NO_ERROR;
WCHAR szRootDir[MAX_PATH+1];
WCHAR szSetupInfFile[MAX_PATH+1];
WCHAR LogFileName[MAX_PATH+51];
UINT DriveType;
DWORD FileSystemFlags;
//
// get the time stamp
//
TCHAR pvBuffer[100];
pvBuffer[0] = L'\0';
ScepGetTimeStampString(pvBuffer);
szRootDir[0] = L'\0';
//
// get the root drive of Windows directory
//
if ( GetSystemWindowsDirectory( szRootDir, MAX_PATH ) == 0 ) {
return(GetLastError());
}
szRootDir[MAX_PATH] = L'\0';
wcscpy(LogFileName, szRootDir);
wcscat(LogFileName, L"\\security\\logs\\SceRoot.log");
//
// attempt to write root SDDL so that it is useful for FAT->NTFS conversion
// if default is different from hardcoded value, it will be overwritten later...
//
//
// insert the root security SDDL into %windir%\security\templates\setup security.inf
// this will be useful for the new API which implements convert behavior.
//
wcscpy(szSetupInfFile, szRootDir);
wcscat(szSetupInfFile, L"\\security\\templates\\setup security.inf");
// the first two letters are X:
szRootDir[2] = L'\\';
szRootDir[3] = L'\0';
//
// independent of future errors/file systemtypr etc., attempt to
// write default root acl to %windir%\security\templates\setup security.inf
// used in FAT->NTFS convert
//
PWSTR pszDefltInfStringToWrite = NULL;
DWORD rcDefltRootBackup = ERROR_SUCCESS;
rcDefltRootBackup = ScepBreakSDDLToMultiFields(
szRootDir,
SDDLRoot,
sizeof(SDDLRoot)+1,
0,
&pszDefltInfStringToWrite
);
if ( rcDefltRootBackup == ERROR_SUCCESS && pszDefltInfStringToWrite) {
if ( !WritePrivateProfileString(szFileSecurity, L"0", pszDefltInfStringToWrite, szSetupInfFile) ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_INFWRITE,
GetLastError(),
SDDLRoot
);
}
ScepFree(pszDefltInfStringToWrite);
}
else {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_INFWRITE,
rcDefltRootBackup,
SDDLRoot
);
}
//
// log the time stamp
//
if ( pvBuffer[0] != L'\0' ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
0,
pvBuffer
);
}
//
// detect if the partition is FAT
//
DriveType = GetDriveType(szRootDir);
if ( DriveType == DRIVE_FIXED ||
DriveType == DRIVE_RAMDISK ) {
if ( GetVolumeInformation(szRootDir,
NULL,
0,
NULL,
NULL,
&FileSystemFlags,
NULL,
0
) == TRUE ) {
if ( !(FileSystemFlags & FS_PERSISTENT_ACLS) ) {
//
// only set security on NTFS partition
//
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_NON_NTFS,
szRootDir
);
return(rc);
}
} else {
//
// something is wrong
//
rc = GetLastError();
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_QUERY_VOLUME,
rc,
szRootDir
);
return rc;
}
} else {
//
// do not set security on remote drives
//
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_NOT_FIXED_VOLUME,
szRootDir
);
return(rc);
}
PSECURITY_DESCRIPTOR pSDSet=NULL, pSDOld=NULL;
DWORD dwSize=0;
SECURITY_INFORMATION SeInfo=0;
PACL pDacl=NULL;
ACCESS_ALLOWED_ACE *pAce=NULL;
SID_IDENTIFIER_AUTHORITY Authority=SECURITY_WORLD_SID_AUTHORITY;
PSID pSid;
BYTE SidEveryone[20];
BOOLEAN tFlag;
BOOLEAN aclPresent;
SECURITY_DESCRIPTOR_CONTROL Control=0;
ULONG Revision;
NTSTATUS NtStatus;
BOOL bDefault;
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_NTFS_VOLUME,
szRootDir
);
//
// It's NTFS volume. Let's convert the security descriptor
//
rc = ConvertTextSecurityDescriptor (SDDLRoot,
&pSDSet,
&dwSize,
&SeInfo
);
if ( rc != NO_ERROR ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_CONVERT,
rc,
SDDLRoot
);
return(rc);
}
if ( !(SeInfo & DACL_SECURITY_INFORMATION) ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_INVALID_SDINFO,
SDDLRoot
);
LocalFree(pSDSet);
return(ERROR_INVALID_PARAMETER);
}
//
// It's NTFS volume. Now get existing security of the root drive
//
rc = GetNamedSecurityInfo(szRootDir,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
NULL,
NULL,
&pDacl,
NULL,
&pSDOld
);
if ( rc == ERROR_SUCCESS && pDacl ) {
//
// Detect if permissions are the default from a clean install or upgrade (NT4 or win2k).
// There are several possible defaults to be found, DC vs srv and wks, and clean NT4 or
// win2k vs upgrades.
//
bDefault=FALSE;
if ( pDacl ) {
PCWSTR rpcwszOldDefaultDacl[] = {
SDDLOldRootDefault1, // everyone - full control (CIOI)
SDDLOldRootDefault2, // admin, system, creator/owner - full(CIOI); everyone - change(CIOI)
SDDLOldRootDefault3, // admin, system, creator/owner - full(CIOI); everyone, server op - change(CIOI)
};
int cOldDefaultDacls = ARRAYSIZE(rpcwszOldDefaultDacl);
for(int i=0; i<cOldDefaultDacls; i++)
{
BOOL bDifferent;
rc = ScepCompareDaclWithStringSD(
rpcwszOldDefaultDacl[i],
pDacl,
&bDifferent);
if ( ERROR_SUCCESS != rc)
break;
if ( FALSE == bDifferent) {
bDefault = TRUE;
break;
}
}
}
if ( ERROR_SUCCESS == rc )
{
if ( bDefault && pSDSet ) {
//
// only set security if it's default
//
RtlGetControlSecurityDescriptor (
pSDSet,
&Control,
&Revision
);
//
// Get DACL address
//
pDacl = NULL;
rc = RtlNtStatusToDosError(
RtlGetDaclSecurityDescriptor(
pSDSet,
&aclPresent,
&pDacl,
&tFlag));
if (rc == NO_ERROR && !aclPresent )
pDacl = NULL;
//
// if error occurs for this one, do not set. return
//
if ( rc == ERROR_SUCCESS ) {
//
// set permission
//
if ( Control & SE_DACL_PROTECTED ) {
SeInfo |= PROTECTED_DACL_SECURITY_INFORMATION;
}
pvBuffer[0] = L'\0';
ScepGetTimeStampString(pvBuffer);
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_SECURITY_DEFAULT,
szRootDir,
pvBuffer
);
rc = SetNamedSecurityInfo(szRootDir,
SE_FILE_OBJECT,
SeInfo,
NULL,
NULL,
pDacl,
NULL
);
pvBuffer[0] = L'\0';
ScepGetTimeStampString(pvBuffer);
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_MARTA_RETURN,
rc,
pvBuffer,
szRootDir
);
} else {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_DACL,
rc
);
}
} else {
//
// convert the old security descriptor to text and log it
//
PWSTR pszOldSDDL=NULL;
PWSTR pszInfStringToWrite = NULL;
DWORD rcRootBackup = ERROR_SUCCESS;
ConvertSecurityDescriptorToText (
pSDOld,
DACL_SECURITY_INFORMATION,
&pszOldSDDL,
&dwSize
);
//
// also, overwrite this SDDL to %windir%\security\templates\setup security.inf
// since this is the "default" root security. This will be used later if
// SCE is invoked to do security configuration during NTFS->FAT->NTFS conversion.
//
if (pszOldSDDL) {
rcRootBackup = ScepBreakSDDLToMultiFields(
szRootDir,
pszOldSDDL,
dwSize,
0,
&pszInfStringToWrite
);
if (rcRootBackup == ERROR_SUCCESS && pszInfStringToWrite) {
if ( !WritePrivateProfileString(szFileSecurity, L"0", pszInfStringToWrite, szSetupInfFile) ) {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_INFWRITE,
GetLastError(),
pszOldSDDL
);
}
ScepFree(pszInfStringToWrite);
} else {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_INFWRITE,
rcRootBackup,
pszOldSDDL
);
}
}
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_SECURITY_MODIFIED,
szRootDir,
pszOldSDDL ? pszOldSDDL : L""
);
if ( pszOldSDDL ) {
LocalFree(pszOldSDDL);
}
}
} else {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_COMPARE_SECURITY,
rc,
szRootDir
);
}
LocalFree(pSDOld);
} else {
LogEventAndReport(MyModuleHandle,
(wchar_t *)LogFileName,
0,
0,
IDS_ROOT_ERROR_QUERY_SECURITY,
rc,
szRootDir
);
}
LocalFree(pSDSet);
return(rc);
}
DWORD
WINAPI
SceEnforceSecurityPolicyPropagation()
{
return(ScepEnforcePolicyPropagation());
}
DWORD
WINAPI
SceConfigureConvertedFileSecurity(
IN PWSTR pszDriveName,
IN DWORD dwConvertDisposition
)
/*++
Routine Description:
Exported API called by convert.exe to configure setup style security for drives converted from FAT to NTFS.
Briefly, this API will
EITHER (dwConvertDisposition == 0)
convert the volume in question immediately (in an asynchronous thread after RPC'ing over to the server)
OR (dwConvertDisposition == 1)
will schedule a conversion to happen at the time of reboot (in an asynchronous thread during reboot).
Scheduling is done by entering pszDriveName(s) in a REG_MULTI_SZ registry value
SCE_ROOT_PATH\FatNtfsConvertedDrives.
Arguments:
pszDriveName - Name of the volume to be converted
dwConvertDisposition - 0 implies volume can be converted immediately
1 implies volume cannot be converted immediately and is scheduled for conversion
Return:
win32 error code
--*/
{
DWORD rc = ERROR_SUCCESS;
if ( pszDriveName == NULL ||
wcslen(pszDriveName) == 0 ||
(dwConvertDisposition != 0 && dwConvertDisposition != 1) ) {
return ERROR_INVALID_PARAMETER;
}
//
// validate drive name - has to end in ":"
//
if ( pszDriveName [wcslen( pszDriveName ) - 1] != L':') {
return ERROR_INVALID_PARAMETER;
}
if (dwConvertDisposition == 0) {
//
// configure setup-style security immediately
// RPC over to scesrv
//
NTSTATUS NtStatus = NO_ERROR;
handle_t binding_h = NULL;
//
// RPC bind to the server - don't use secure RPC
//
NtStatus = ScepBindRpc(
NULL,
L"scerpc",
0,
&binding_h
);
/*
NtStatus = ScepBindSecureRpc(
NULL,
L"scerpc",
0,
&binding_h
);
*/
if (NT_SUCCESS(NtStatus)) {
RpcTryExcept {
//
// make the RPC call
//
rc = SceRpcConfigureConvertedFileSecurityImmediately(
binding_h,
pszDriveName
);
} RpcExcept( I_RpcExceptionFilter( RpcExceptionCode()) ) {
//
// get exception code
//
rc = RpcExceptionCode();
} RpcEndExcept;
//
// Free the binding handle
//
RpcpUnbindRpc( binding_h );
} else {
rc = RtlNtStatusToDosError( NtStatus );
}
}
else if (dwConvertDisposition == 1) {
//
// schedule conversion for reboot time - i.e. enter into MULTI_SZ registry value
//
rc = ScepAppendCreateMultiSzRegValue(HKEY_LOCAL_MACHINE,
SCE_ROOT_PATH,
L"FatNtfsConvertedDrives",
pszDriveName
);
}
return rc;
}
DWORD
ScepBreakSDDLToMultiFields(
IN PWSTR pszObjName,
IN PWSTR pszSDDL,
IN DWORD dwSDDLsize,
IN BYTE ObjStatus,
OUT PWSTR *ppszAdjustedInfLine
)
/*++
Routine Description:
Inf files have a limitation w.r.t. line size - so break up SDDL if need be
Arguments:
pszObjName - name of the object
pszSDDL - SDDL string that might be velry long
dwSDDLsize - size of pszSDDL
ObjStatus - 0/1/2
ppszAdjustedInfLine - ptr to adjusted string
Return:
win32 error code
--*/
{
DWORD rc;
PWSTR Strvalue=NULL;
DWORD nFields;
DWORD *aFieldOffset=NULL;
DWORD i;
DWORD dwObjSize = 0;
if ( pszObjName == NULL ||
pszSDDL == NULL ||
ppszAdjustedInfLine == NULL )
return ERROR_INVALID_PARAMETER;
rc = SceInfpBreakTextIntoMultiFields(pszSDDL, dwSDDLsize, &nFields, &aFieldOffset);
if ( SCESTATUS_SUCCESS != rc ) {
rc = ScepSceStatusToDosError(rc);
goto Done;
}
//
// each extra field will use 3 more chars : ,"<field>"
//
dwObjSize = wcslen(pszObjName)+8 + dwSDDLsize;
if ( nFields ) {
dwObjSize += 3*nFields;
} else {
dwObjSize += 2;
}
//
// allocate the output buffer
//
Strvalue = (PWSTR)ScepAlloc(LMEM_ZEROINIT, (dwObjSize+1) * sizeof(WCHAR) );
if ( Strvalue == NULL ) {
rc = ERROR_NOT_ENOUGH_MEMORY;
goto Done;
}
//
// copy data into the buffer
//
if ( nFields == 0 || !aFieldOffset ) {
swprintf(Strvalue, L"\"%s\",%1d,\"%s\"", pszObjName, ObjStatus, pszSDDL);
} else {
//
// loop through the fields
//
swprintf(Strvalue, L"\"%s\",%1d\0", pszObjName, ObjStatus);
for ( i=0; i<nFields; i++ ) {
if ( aFieldOffset[i] < dwSDDLsize ) {
wcscat(Strvalue, L",\"");
if ( i == nFields-1 ) {
//
// the last field
//
wcscat(Strvalue, pszSDDL+aFieldOffset[i]);
} else {
wcsncat(Strvalue, pszSDDL+aFieldOffset[i],
aFieldOffset[i+1]-aFieldOffset[i]);
}
wcscat(Strvalue, L"\"");
}
}
}
*ppszAdjustedInfLine = Strvalue;
Done:
if ( aFieldOffset ) {
ScepFree(aFieldOffset);
}
return(rc);
}
#ifndef _WIN64
BOOL
GetIsWow64 (
VOID
)
/*++
Routine Description:
Determine if we're running on WOW64 or not.
Arguments:
none
Return value:
TRUE if running under WOW64 (and special Wow64 features available)
--*/
{
ULONG_PTR ul = 0;
NTSTATUS st;
//
// If this call succeeds and sets ul non-zero
// it's a 32-bit process running on Win64
//
st = NtQueryInformationProcess(NtCurrentProcess(),
ProcessWow64Information,
&ul,
sizeof(ul),
NULL);
if (NT_SUCCESS(st) && (0 != ul)) {
// 32-bit code running on Win64
return TRUE;
}
return FALSE;
}
#endif // _WIN64
| 29.103633 | 131 | 0.430843 | [
"object",
"model"
] |
be73fdf4c9a9fc35de867b0b65d8715986c33922 | 18,826 | cpp | C++ | brlycmbd/CrdBrlyNav/PnlBrlyNavAdmin_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyNav/PnlBrlyNavAdmin_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | brlycmbd/CrdBrlyNav/PnlBrlyNavAdmin_blks.cpp | mpsitech/brly-BeamRelay | 481ccb3e83ea6151fb78eba293b44ade62a0ec78 | [
"MIT"
] | null | null | null | /**
* \file PnlBrlyNavAdmin_blks.cpp
* job handler for job PnlBrlyNavAdmin (implementation of blocks)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 11 Jan 2021
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class PnlBrlyNavAdmin::VecVDo
******************************************************************************/
uint PnlBrlyNavAdmin::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butusgviewclick") return BUTUSGVIEWCLICK;
if (s == "butusgnewcrdclick") return BUTUSGNEWCRDCLICK;
if (s == "butusrviewclick") return BUTUSRVIEWCLICK;
if (s == "butusrnewcrdclick") return BUTUSRNEWCRDCLICK;
if (s == "butprsviewclick") return BUTPRSVIEWCLICK;
if (s == "butprsnewcrdclick") return BUTPRSNEWCRDCLICK;
if (s == "butfilviewclick") return BUTFILVIEWCLICK;
if (s == "butfilnewcrdclick") return BUTFILNEWCRDCLICK;
if (s == "butoprviewclick") return BUTOPRVIEWCLICK;
if (s == "butoprnewcrdclick") return BUTOPRNEWCRDCLICK;
if (s == "butptyviewclick") return BUTPTYVIEWCLICK;
if (s == "butptynewcrdclick") return BUTPTYNEWCRDCLICK;
return(0);
};
string PnlBrlyNavAdmin::VecVDo::getSref(
const uint ix
) {
if (ix == BUTUSGVIEWCLICK) return("ButUsgViewClick");
if (ix == BUTUSGNEWCRDCLICK) return("ButUsgNewcrdClick");
if (ix == BUTUSRVIEWCLICK) return("ButUsrViewClick");
if (ix == BUTUSRNEWCRDCLICK) return("ButUsrNewcrdClick");
if (ix == BUTPRSVIEWCLICK) return("ButPrsViewClick");
if (ix == BUTPRSNEWCRDCLICK) return("ButPrsNewcrdClick");
if (ix == BUTFILVIEWCLICK) return("ButFilViewClick");
if (ix == BUTFILNEWCRDCLICK) return("ButFilNewcrdClick");
if (ix == BUTOPRVIEWCLICK) return("ButOprViewClick");
if (ix == BUTOPRNEWCRDCLICK) return("ButOprNewcrdClick");
if (ix == BUTPTYVIEWCLICK) return("ButPtyViewClick");
if (ix == BUTPTYNEWCRDCLICK) return("ButPtyNewcrdClick");
return("");
};
/******************************************************************************
class PnlBrlyNavAdmin::ContIac
******************************************************************************/
PnlBrlyNavAdmin::ContIac::ContIac(
const uint numFLstUsg
, const uint numFLstUsr
, const uint numFLstPrs
, const uint numFLstFil
, const uint numFLstOpr
, const uint numFLstPty
) :
Block()
{
this->numFLstUsg = numFLstUsg;
this->numFLstUsr = numFLstUsr;
this->numFLstPrs = numFLstPrs;
this->numFLstFil = numFLstFil;
this->numFLstOpr = numFLstOpr;
this->numFLstPty = numFLstPty;
mask = {NUMFLSTUSG, NUMFLSTUSR, NUMFLSTPRS, NUMFLSTFIL, NUMFLSTOPR, NUMFLSTPTY};
};
bool PnlBrlyNavAdmin::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacBrlyNavAdmin");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacBrlyNavAdmin";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstUsg", numFLstUsg)) add(NUMFLSTUSG);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstUsr", numFLstUsr)) add(NUMFLSTUSR);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstPrs", numFLstPrs)) add(NUMFLSTPRS);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstFil", numFLstFil)) add(NUMFLSTFIL);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstOpr", numFLstOpr)) add(NUMFLSTOPR);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstPty", numFLstPty)) add(NUMFLSTPTY);
};
return basefound;
};
void PnlBrlyNavAdmin::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacBrlyNavAdmin";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacBrlyNavAdmin";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFLstUsg", numFLstUsg);
writeUintAttr(wr, itemtag, "sref", "numFLstUsr", numFLstUsr);
writeUintAttr(wr, itemtag, "sref", "numFLstPrs", numFLstPrs);
writeUintAttr(wr, itemtag, "sref", "numFLstFil", numFLstFil);
writeUintAttr(wr, itemtag, "sref", "numFLstOpr", numFLstOpr);
writeUintAttr(wr, itemtag, "sref", "numFLstPty", numFLstPty);
xmlTextWriterEndElement(wr);
};
set<uint> PnlBrlyNavAdmin::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (numFLstUsg == comp->numFLstUsg) insert(items, NUMFLSTUSG);
if (numFLstUsr == comp->numFLstUsr) insert(items, NUMFLSTUSR);
if (numFLstPrs == comp->numFLstPrs) insert(items, NUMFLSTPRS);
if (numFLstFil == comp->numFLstFil) insert(items, NUMFLSTFIL);
if (numFLstOpr == comp->numFLstOpr) insert(items, NUMFLSTOPR);
if (numFLstPty == comp->numFLstPty) insert(items, NUMFLSTPTY);
return(items);
};
set<uint> PnlBrlyNavAdmin::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFLSTUSG, NUMFLSTUSR, NUMFLSTPRS, NUMFLSTFIL, NUMFLSTOPR, NUMFLSTPTY};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlBrlyNavAdmin::StatApp
******************************************************************************/
void PnlBrlyNavAdmin::StatApp::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
, const uint ixBrlyVExpstate
, const bool LstUsgAlt
, const bool LstUsrAlt
, const bool LstPrsAlt
, const bool LstFilAlt
, const bool LstOprAlt
, const bool LstPtyAlt
, const uint LstUsgNumFirstdisp
, const uint LstUsrNumFirstdisp
, const uint LstPrsNumFirstdisp
, const uint LstFilNumFirstdisp
, const uint LstOprNumFirstdisp
, const uint LstPtyNumFirstdisp
) {
if (difftag.length() == 0) difftag = "StatAppBrlyNavAdmin";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemAppBrlyNavAdmin";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "srefIxBrlyVExpstate", VecBrlyVExpstate::getSref(ixBrlyVExpstate));
writeBoolAttr(wr, itemtag, "sref", "LstUsgAlt", LstUsgAlt);
writeBoolAttr(wr, itemtag, "sref", "LstUsrAlt", LstUsrAlt);
writeBoolAttr(wr, itemtag, "sref", "LstPrsAlt", LstPrsAlt);
writeBoolAttr(wr, itemtag, "sref", "LstFilAlt", LstFilAlt);
writeBoolAttr(wr, itemtag, "sref", "LstOprAlt", LstOprAlt);
writeBoolAttr(wr, itemtag, "sref", "LstPtyAlt", LstPtyAlt);
writeUintAttr(wr, itemtag, "sref", "LstUsgNumFirstdisp", LstUsgNumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "LstUsrNumFirstdisp", LstUsrNumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "LstPrsNumFirstdisp", LstPrsNumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "LstFilNumFirstdisp", LstFilNumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "LstOprNumFirstdisp", LstOprNumFirstdisp);
writeUintAttr(wr, itemtag, "sref", "LstPtyNumFirstdisp", LstPtyNumFirstdisp);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlBrlyNavAdmin::StatShr
******************************************************************************/
PnlBrlyNavAdmin::StatShr::StatShr(
const bool LstUsgAvail
, const bool ButUsgViewActive
, const bool LstUsrAvail
, const bool ButUsrViewActive
, const bool LstPrsAvail
, const bool ButPrsViewActive
, const bool LstFilAvail
, const bool ButFilViewActive
, const bool LstOprAvail
, const bool ButOprViewActive
, const bool LstPtyAvail
, const bool ButPtyViewActive
) :
Block()
{
this->LstUsgAvail = LstUsgAvail;
this->ButUsgViewActive = ButUsgViewActive;
this->LstUsrAvail = LstUsrAvail;
this->ButUsrViewActive = ButUsrViewActive;
this->LstPrsAvail = LstPrsAvail;
this->ButPrsViewActive = ButPrsViewActive;
this->LstFilAvail = LstFilAvail;
this->ButFilViewActive = ButFilViewActive;
this->LstOprAvail = LstOprAvail;
this->ButOprViewActive = ButOprViewActive;
this->LstPtyAvail = LstPtyAvail;
this->ButPtyViewActive = ButPtyViewActive;
mask = {LSTUSGAVAIL, BUTUSGVIEWACTIVE, LSTUSRAVAIL, BUTUSRVIEWACTIVE, LSTPRSAVAIL, BUTPRSVIEWACTIVE, LSTFILAVAIL, BUTFILVIEWACTIVE, LSTOPRAVAIL, BUTOPRVIEWACTIVE, LSTPTYAVAIL, BUTPTYVIEWACTIVE};
};
void PnlBrlyNavAdmin::StatShr::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StatShrBrlyNavAdmin";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemShrBrlyNavAdmin";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeBoolAttr(wr, itemtag, "sref", "LstUsgAvail", LstUsgAvail);
writeBoolAttr(wr, itemtag, "sref", "ButUsgViewActive", ButUsgViewActive);
writeBoolAttr(wr, itemtag, "sref", "LstUsrAvail", LstUsrAvail);
writeBoolAttr(wr, itemtag, "sref", "ButUsrViewActive", ButUsrViewActive);
writeBoolAttr(wr, itemtag, "sref", "LstPrsAvail", LstPrsAvail);
writeBoolAttr(wr, itemtag, "sref", "ButPrsViewActive", ButPrsViewActive);
writeBoolAttr(wr, itemtag, "sref", "LstFilAvail", LstFilAvail);
writeBoolAttr(wr, itemtag, "sref", "ButFilViewActive", ButFilViewActive);
writeBoolAttr(wr, itemtag, "sref", "LstOprAvail", LstOprAvail);
writeBoolAttr(wr, itemtag, "sref", "ButOprViewActive", ButOprViewActive);
writeBoolAttr(wr, itemtag, "sref", "LstPtyAvail", LstPtyAvail);
writeBoolAttr(wr, itemtag, "sref", "ButPtyViewActive", ButPtyViewActive);
xmlTextWriterEndElement(wr);
};
set<uint> PnlBrlyNavAdmin::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (LstUsgAvail == comp->LstUsgAvail) insert(items, LSTUSGAVAIL);
if (ButUsgViewActive == comp->ButUsgViewActive) insert(items, BUTUSGVIEWACTIVE);
if (LstUsrAvail == comp->LstUsrAvail) insert(items, LSTUSRAVAIL);
if (ButUsrViewActive == comp->ButUsrViewActive) insert(items, BUTUSRVIEWACTIVE);
if (LstPrsAvail == comp->LstPrsAvail) insert(items, LSTPRSAVAIL);
if (ButPrsViewActive == comp->ButPrsViewActive) insert(items, BUTPRSVIEWACTIVE);
if (LstFilAvail == comp->LstFilAvail) insert(items, LSTFILAVAIL);
if (ButFilViewActive == comp->ButFilViewActive) insert(items, BUTFILVIEWACTIVE);
if (LstOprAvail == comp->LstOprAvail) insert(items, LSTOPRAVAIL);
if (ButOprViewActive == comp->ButOprViewActive) insert(items, BUTOPRVIEWACTIVE);
if (LstPtyAvail == comp->LstPtyAvail) insert(items, LSTPTYAVAIL);
if (ButPtyViewActive == comp->ButPtyViewActive) insert(items, BUTPTYVIEWACTIVE);
return(items);
};
set<uint> PnlBrlyNavAdmin::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {LSTUSGAVAIL, BUTUSGVIEWACTIVE, LSTUSRAVAIL, BUTUSRVIEWACTIVE, LSTPRSAVAIL, BUTPRSVIEWACTIVE, LSTFILAVAIL, BUTFILVIEWACTIVE, LSTOPRAVAIL, BUTOPRVIEWACTIVE, LSTPTYAVAIL, BUTPTYVIEWACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlBrlyNavAdmin::Tag
******************************************************************************/
void PnlBrlyNavAdmin::Tag::writeXML(
const uint ixBrlyVLocale
, xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "TagBrlyNavAdmin";
string itemtag;
if (shorttags) itemtag = "Ti";
else itemtag = "TagitemBrlyNavAdmin";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
if (ixBrlyVLocale == VecBrlyVLocale::ENUS) {
writeStringAttr(wr, itemtag, "sref", "Cpt", "Administration module");
writeStringAttr(wr, itemtag, "sref", "CptUsg", "user groups");
writeStringAttr(wr, itemtag, "sref", "CptUsr", "users");
writeStringAttr(wr, itemtag, "sref", "CptPrs", "persons");
writeStringAttr(wr, itemtag, "sref", "CptFil", "files");
writeStringAttr(wr, itemtag, "sref", "CptOpr", "operators");
writeStringAttr(wr, itemtag, "sref", "CptPty", "plane types");
} else if (ixBrlyVLocale == VecBrlyVLocale::DECH) {
writeStringAttr(wr, itemtag, "sref", "Cpt", "Verwaltung");
writeStringAttr(wr, itemtag, "sref", "CptUsg", "Benutzergruppen");
writeStringAttr(wr, itemtag, "sref", "CptUsr", "Benutzer");
writeStringAttr(wr, itemtag, "sref", "CptPrs", "Personen");
writeStringAttr(wr, itemtag, "sref", "CptFil", "Dateien");
writeStringAttr(wr, itemtag, "sref", "CptOpr", "Betreiber");
writeStringAttr(wr, itemtag, "sref", "CptPty", "Flugzeugtypen");
};
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlBrlyNavAdmin::DpchAppData
******************************************************************************/
PnlBrlyNavAdmin::DpchAppData::DpchAppData() :
DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYNAVADMINDATA)
{
};
string PnlBrlyNavAdmin::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlBrlyNavAdmin::DpchAppData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyNavAdminData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
} else {
contiac = ContIac();
};
};
/******************************************************************************
class PnlBrlyNavAdmin::DpchAppDo
******************************************************************************/
PnlBrlyNavAdmin::DpchAppDo::DpchAppDo() :
DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYNAVADMINDO)
{
ixVDo = 0;
};
string PnlBrlyNavAdmin::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlBrlyNavAdmin::DpchAppDo::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
string srefIxVDo;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyNavAdminDo");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) {
ixVDo = VecVDo::getIx(srefIxVDo);
add(IXVDO);
};
} else {
};
};
/******************************************************************************
class PnlBrlyNavAdmin::DpchEngData
******************************************************************************/
PnlBrlyNavAdmin::DpchEngData::DpchEngData(
const ubigint jref
, ContIac* contiac
, Feed* feedFLstFil
, Feed* feedFLstOpr
, Feed* feedFLstPrs
, Feed* feedFLstPty
, Feed* feedFLstUsg
, Feed* feedFLstUsr
, StatShr* statshr
, const set<uint>& mask
) :
DpchEngBrly(VecBrlyVDpch::DPCHENGBRLYNAVADMINDATA, jref)
{
if (find(mask, ALL)) this->mask = {JREF, CONTIAC, FEEDFLSTFIL, FEEDFLSTOPR, FEEDFLSTPRS, FEEDFLSTPTY, FEEDFLSTUSG, FEEDFLSTUSR, STATAPP, STATSHR, TAG};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
if (find(this->mask, FEEDFLSTFIL) && feedFLstFil) this->feedFLstFil = *feedFLstFil;
if (find(this->mask, FEEDFLSTOPR) && feedFLstOpr) this->feedFLstOpr = *feedFLstOpr;
if (find(this->mask, FEEDFLSTPRS) && feedFLstPrs) this->feedFLstPrs = *feedFLstPrs;
if (find(this->mask, FEEDFLSTPTY) && feedFLstPty) this->feedFLstPty = *feedFLstPty;
if (find(this->mask, FEEDFLSTUSG) && feedFLstUsg) this->feedFLstUsg = *feedFLstUsg;
if (find(this->mask, FEEDFLSTUSR) && feedFLstUsr) this->feedFLstUsr = *feedFLstUsr;
if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr;
};
string PnlBrlyNavAdmin::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(FEEDFLSTFIL)) ss.push_back("feedFLstFil");
if (has(FEEDFLSTOPR)) ss.push_back("feedFLstOpr");
if (has(FEEDFLSTPRS)) ss.push_back("feedFLstPrs");
if (has(FEEDFLSTPTY)) ss.push_back("feedFLstPty");
if (has(FEEDFLSTUSG)) ss.push_back("feedFLstUsg");
if (has(FEEDFLSTUSR)) ss.push_back("feedFLstUsr");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlBrlyNavAdmin::DpchEngData::merge(
DpchEngBrly* dpcheng
) {
DpchEngData* src = (DpchEngData*) dpcheng;
if (src->has(JREF)) {jref = src->jref; add(JREF);};
if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);};
if (src->has(FEEDFLSTFIL)) {feedFLstFil = src->feedFLstFil; add(FEEDFLSTFIL);};
if (src->has(FEEDFLSTOPR)) {feedFLstOpr = src->feedFLstOpr; add(FEEDFLSTOPR);};
if (src->has(FEEDFLSTPRS)) {feedFLstPrs = src->feedFLstPrs; add(FEEDFLSTPRS);};
if (src->has(FEEDFLSTPTY)) {feedFLstPty = src->feedFLstPty; add(FEEDFLSTPTY);};
if (src->has(FEEDFLSTUSG)) {feedFLstUsg = src->feedFLstUsg; add(FEEDFLSTUSG);};
if (src->has(FEEDFLSTUSR)) {feedFLstUsr = src->feedFLstUsr; add(FEEDFLSTUSR);};
if (src->has(STATAPP)) add(STATAPP);
if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);};
if (src->has(TAG)) add(TAG);
};
void PnlBrlyNavAdmin::DpchEngData::writeXML(
const uint ixBrlyVLocale
, xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchEngBrlyNavAdminData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/brly");
if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref));
if (has(CONTIAC)) contiac.writeXML(wr);
if (has(FEEDFLSTFIL)) feedFLstFil.writeXML(wr);
if (has(FEEDFLSTOPR)) feedFLstOpr.writeXML(wr);
if (has(FEEDFLSTPRS)) feedFLstPrs.writeXML(wr);
if (has(FEEDFLSTPTY)) feedFLstPty.writeXML(wr);
if (has(FEEDFLSTUSG)) feedFLstUsg.writeXML(wr);
if (has(FEEDFLSTUSR)) feedFLstUsr.writeXML(wr);
if (has(STATAPP)) StatApp::writeXML(wr);
if (has(STATSHR)) statshr.writeXML(wr);
if (has(TAG)) Tag::writeXML(ixBrlyVLocale, wr);
xmlTextWriterEndElement(wr);
};
| 35.587902 | 200 | 0.674546 | [
"vector"
] |
be835341b18eb6acfc04f321dec080e0ae15a0a2 | 3,161 | cpp | C++ | Source/Transform.cpp | chuckeles/metal-pacman | 78f20fff1e2f578932014e349a5e81b1f6eb7d7c | [
"MIT"
] | 1 | 2019-05-10T06:37:54.000Z | 2019-05-10T06:37:54.000Z | Source/Transform.cpp | chuckeles/metal-pacman | 78f20fff1e2f578932014e349a5e81b1f6eb7d7c | [
"MIT"
] | null | null | null | Source/Transform.cpp | chuckeles/metal-pacman | 78f20fff1e2f578932014e349a5e81b1f6eb7d7c | [
"MIT"
] | null | null | null | #include "Transform.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
void Transform::Move(float x, float y, float z, Space space) {
Move(glm::vec3(x, y, z), space);
}
void Transform::Move(glm::vec3 pos, Space space) {
mDirty = true;
switch (space) {
case Space::Local:
mPosition += mRotation * pos;
break;
case Space::Global:
mPosition += pos;
break;
}
}
void Transform::Pitch(float angle, Space space) {
Rotate(glm::vec3(1.f, 0.f, 0.f), angle, space);
}
void Transform::Yaw(float angle, Space space) {
Rotate(glm::vec3(0.f, 1.f, 0.f), angle, space);
}
void Transform::Roll(float angle, Space space) {
Rotate(glm::vec3(0.f, 0.f, 1.f), angle, space);
}
void Transform::Rotate(glm::vec3 axis, float angle, Space space) {
Rotate(glm::angleAxis(angle, axis), space);
}
void Transform::Rotate(Transform::Axis axis, float angle, Transform::Space space) {
switch (axis) {
case Axis::X:
Pitch(angle, space);
break;
case Axis::Y:
Yaw(angle, space);
break;
case Axis::Z:
Roll(angle, space);
break;
}
}
void Transform::Rotate(glm::quat quat, Space space) {
mDirty = true;
glm::quat qnorm = glm::normalize(quat);
switch (space) {
case Space::Local:
mRotation = mRotation * qnorm;
break;
case Space::Global:
mRotation = qnorm * mRotation;
break;
}
}
void Transform::Scale(float x, float y, float z) {
mDirty = true;
mScale *= glm::vec3(x, y, z);
}
void Transform::Scale(float s) {
mDirty = true;
mScale *= glm::vec3(s, s, s);
}
void Transform::SetPosition(float x, float y, float z) {
mDirty = true;
mPosition = glm::vec3(x, y, z);
}
void Transform::SetRotation(float pith, float yaw, float roll) {
mDirty = true;
mRotation = glm::quat(glm::vec3(pith, yaw, roll));
}
void Transform::Attach(std::shared_ptr<Transform> parent) {
mParent = parent;
}
void Transform::Detach() {
mParent = std::shared_ptr<Transform>();
}
const glm::vec3 &Transform::GetPosition() const {
return mPosition;
}
const glm::mat4 &Transform::GetMatrix() {
if (mDirty) {
glm::mat4 position = glm::translate(glm::mat4(), mPosition);
glm::mat4 rotation = glm::mat4_cast(mRotation);
glm::mat4 scale = glm::scale(glm::mat4(), mScale);
mMatrix = position * rotation * scale;
++mVersion;
}
if (mParent) {
if (mDirty || mParent->GetVersion() != mParentVersion) {
mParentVersion = mParent->GetVersion();
mMatrixWithParent = mParent->GetMatrix() * mMatrix;
}
}
else {
return mMatrix;
}
mDirty = false;
return mMatrixWithParent;
}
unsigned long Transform::GetVersion() const {
return mVersion;
}
Transform::Transform() :
Transform(0, 0, 0) {
}
Transform::Transform(float x, float y, float z) :
Transform(glm::vec3(x, y, z)) {
}
Transform::Transform(glm::vec3 pos) :
mPosition(pos), mScale(1, 1, 1) {
}
| 21.951389 | 83 | 0.585574 | [
"transform"
] |
be878c1e0194816a6ae48de9a8eebcef0412c6e4 | 3,550 | cpp | C++ | Source/WebKit/WebProcess/GPU/media/RemoteCDMFactory.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Source/WebKit/WebProcess/GPU/media/RemoteCDMFactory.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Source/WebKit/WebProcess/GPU/media/RemoteCDMFactory.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "RemoteCDMFactory.h"
#if ENABLE(GPU_PROCESS) && ENABLE(ENCRYPTED_MEDIA)
#include "GPUProcessConnection.h"
#include "RemoteCDM.h"
#include "RemoteCDMFactoryProxyMessages.h"
#include "RemoteCDMInstanceSession.h"
#include "WebProcess.h"
#include <WebCore/Settings.h>
namespace WebKit {
using namespace WebCore;
RemoteCDMFactory::RemoteCDMFactory(WebProcess& process)
: m_process(process)
{
}
RemoteCDMFactory::~RemoteCDMFactory() = default;
void RemoteCDMFactory::registerFactory(Vector<CDMFactory*>& factories)
{
factories.append(this);
}
const char* RemoteCDMFactory::supplementName()
{
return "RemoteCDMFactory";
}
GPUProcessConnection& RemoteCDMFactory::gpuProcessConnection()
{
return m_process.ensureGPUProcessConnection();
}
bool RemoteCDMFactory::supportsKeySystem(const String& keySystem)
{
bool supported = false;
gpuProcessConnection().connection().sendSync(Messages::RemoteCDMFactoryProxy::SupportsKeySystem(keySystem), Messages::RemoteCDMFactoryProxy::SupportsKeySystem::Reply(supported), { });
return supported;
}
std::unique_ptr<CDMPrivate> RemoteCDMFactory::createCDM(const String& keySystem)
{
RemoteCDMIdentifier id;
RemoteCDMConfiguration configuration;
gpuProcessConnection().connection().sendSync(Messages::RemoteCDMFactoryProxy::CreateCDM(keySystem), Messages::RemoteCDMFactoryProxy::CreateCDM::Reply(id, configuration), { });
if (!id)
return nullptr;
return RemoteCDM::create(makeWeakPtr(this), WTFMove(id), WTFMove(configuration));
}
void RemoteCDMFactory::addSession(Ref<RemoteCDMInstanceSession>&& session)
{
ASSERT(!m_sessions.contains(session->identifier()));
m_sessions.set(session->identifier(), WTFMove(session));
}
void RemoteCDMFactory::removeSession(RemoteCDMInstanceSessionIdentifier id)
{
ASSERT(m_sessions.contains(id));
m_sessions.remove(id);
}
void RemoteCDMFactory::didReceiveSessionMessage(IPC::Connection& connection, IPC::Decoder& decoder)
{
if (auto* session = m_sessions.get(makeObjectIdentifier<RemoteCDMInstanceSessionIdentifierType>(decoder.destinationID())))
session->didReceiveMessage(connection, decoder);
}
}
#endif
| 34.803922 | 187 | 0.770141 | [
"vector"
] |
be8bd469c1b21d91971199daf00520e2e2efc1a5 | 726 | cpp | C++ | hihocoder/1038.cpp | phiysng/leetcode | 280e8b1a0b45233deb2262ceec85b8174e9b2ced | [
"BSD-3-Clause"
] | 3 | 2019-04-12T19:12:55.000Z | 2020-05-29T07:55:16.000Z | hihocoder/1038.cpp | phiysng/leetcode | 280e8b1a0b45233deb2262ceec85b8174e9b2ced | [
"BSD-3-Clause"
] | null | null | null | hihocoder/1038.cpp | phiysng/leetcode | 280e8b1a0b45233deb2262ceec85b8174e9b2ced | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main(int argc, char const* argv[])
{
int nu, values;
cin >> nu >> values;
vector<int> need(nu + 1), value(nu + 1);
for (size_t i = 1; i < nu + 1; i++) {
cin >> need[i] >> value[i];
}
vector<vector<int>> res(nu + 1, vector<int>(values + 1));
for (int i = 1; i < res.size(); ++i) { // 1-> nu+1
for (int val = 0; val <= values; ++val) {
res[i][val] = res[i - 1][val];
if (val - need[i] >= 0)
res[i][val] = max(res[i][val], res[i - 1][val - need[i]] + value[i]);
}
}
cout << res[nu][values] << endl;
return 0;
}
| 24.2 | 85 | 0.484848 | [
"vector"
] |
be8ccce94e27b398f1bce48d43c0f360ff44082c | 1,101 | cxx | C++ | POSN Camp2/frog_jump-094718.cxx | ParamaaS/ParamaaS-Cpp-code- | a6c78151defe38d1460cde2b005a67be5a1d092d | [
"MIT"
] | null | null | null | POSN Camp2/frog_jump-094718.cxx | ParamaaS/ParamaaS-Cpp-code- | a6c78151defe38d1460cde2b005a67be5a1d092d | [
"MIT"
] | null | null | null | POSN Camp2/frog_jump-094718.cxx | ParamaaS/ParamaaS-Cpp-code- | a6c78151defe38d1460cde2b005a67be5a1d092d | [
"MIT"
] | null | null | null | /*/
- Paramaa Sawanpanyalert -
Lang : c++
/*/
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
#define mp make_pair
#define pb push_back
int n,m,arr[255][255],ard[250][250],c,c2;
int ar[255][255],x,y,disr,disd,nx,ny;
queue<pair<int,int>> q;
main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(c=0;c<n;c++)
{
for(c2=0;c2<m;c2++)
scanf("%d",&arr[c][c2]);
}
for(c=0;c<n;c++)
{
for(c2=0;c2<m;c2++)
scanf("%d",&ard[c][c2]);
}
memset(ar,-1,sizeof ar);
q.push(mp(0,0));
ar[0][0]=0;
while(!q.empty())
{
x=q.front().X;///n
y=q.front().Y;///m
q.pop();
nx=x+ard[x][y];///n
ny=y+arr[x][y];///m
if(nx>=n)
nx%=n;
if(ny>=m)
ny%=m;
/*/
printf(" %d %d %d %d\n",x,y,nx,ny);
for(c=0;c<n;c++)
{
for(c2=0;c2<m;c2++)
printf("%3d",ar[c][c2]);
printf("\n");
}
printf("\n");/*/
if(ar[nx][y]==-1)
{
ar[nx][y]=ar[x][y]+1;
q.push(mp(nx,y));
}
if(ar[x][ny]==-1)
{
ar[x][ny]=ar[x][y]+1;
q.push(mp(x,ny));
}
}
printf("%d\n",ar[n-1][m-1]);
}
}
| 16.938462 | 41 | 0.453224 | [
"3d"
] |
be94976508d42ae6db08ef7e7c1e620dac64a322 | 7,766 | cpp | C++ | src/common/benchmarkdatabase.cpp | pc2/fbench | 0e21704f9e4dd3440b03ee913e058ee3916086f2 | [
"MIT"
] | null | null | null | src/common/benchmarkdatabase.cpp | pc2/fbench | 0e21704f9e4dd3440b03ee913e058ee3916086f2 | [
"MIT"
] | null | null | null | src/common/benchmarkdatabase.cpp | pc2/fbench | 0e21704f9e4dd3440b03ee913e058ee3916086f2 | [
"MIT"
] | 2 | 2020-10-20T14:51:31.000Z | 2020-10-20T15:25:41.000Z | /*****************************************************************************
* @file benchmarkdatabase.cpp
* @class BenchmarkDatabase
*
* <b>Purpose:</b> Track results for multiple benchmarks
* Print statistics of raw results. Generate JSON, XML, CSV
* file for results.
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
******************************************************************************/
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "benchmarkdatabase.h"
#include "resultdatabase.h"
#include "optionparser.h"
#include "benchmarkoptions.h"
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::AddBenchmark()
*
* <b>Purpose:</b> Adds a new benchmark to the benchmark database.
*
* @param benchmark the benchmark name
* @param options options for the current benchmark
* @return Nothing
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*******************************************************************************/
void BenchmarkDatabase::AddBenchmark(const string &benchmark,BenchmarkOptions &options)
{
BenchmarkResult *temp= new BenchmarkResult;
temp->benchmark = benchmark;
temp->options = options;
temp->resultdb = new ResultDatabase;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
BenchmarkResult *i=head;
while(i->next!=NULL)
i=i->next;
i->next=temp;
}
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::AddResult()
*
* <b>Purpose:</b>
*
* @param benchmark benchmark name
* @param test test name
* @param atts
* @param unit measurement unit
* @param value test value
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::AddResult(const string &benchmark,
const string &test,
const string &atts,
const string &unit,
double value)
{
BenchmarkResult *i=head;
while(i!=NULL)
{
if(i->benchmark.compare(benchmark)==0)
{
i->resultdb->AddResult(test,atts,unit,value);
return;
}
i=i->next;
}
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::AddResults()
*
* <b>Purpose:</b>
*
* @param benchmark benchmark name
* @param test test name
* @param atts
* @param unit measurement unit
* @param value test value
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::AddResults(const string &benchmark,
const string &test,
const string &atts,
const string &unit,
const vector<double> &values)
{
BenchmarkResult *i=head;
while(i!=NULL)
{
if(i->benchmark.compare(benchmark)==0)
{
i->resultdb->AddResults(test,atts,unit,values);
return;
}
i=i->next;
}
}
void BenchmarkDatabase::DumpResults()
{
cout<<"printing resluts to ";
if (head->options.dumpJson.length() != 0)
{
cout<<head->options.dumpJson<<endl;
DumpJSON(head->options.dumpJson);
}
else if (head->options.dumpXml.length() != 0)
{
cout<<head->options.dumpXml<<endl;
DumpXML(head->options.dumpXml);
}
else
{
cout<<"output screen"<<endl;
DumpDetailed(std::cout);
}
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::DumpDetailed()
*
* <b>Purpose:</b> Writes the summary results (min/max/stddev/med/mean) to desired output stream
*
* @param out where to print
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::DumpDetailed(ostream &out)
{
BenchmarkResult *i=head;
while(i!=NULL)
{
out<<i->benchmark<<"\t";
//*i->options.DumpDetailed(out);
i->resultdb->DumpDetailed(out);
i=i->next;
}
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::DumpCSV()
*
* <b>Purpose:</b> Writes the summary results (min/max/stddev/med/mean), to CSV file
*
* @param fileName file to be written to
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::DumpCSV(string fileName)
{
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::DumpJSON()
*
* <b>Purpose:</b> Writes the summary results (min/max/stddev/med/mean), to JSON file
*
* @param out file to be written to
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::DumpJSON(string fileName)
{
boost::property_tree::ptree btree;
BenchmarkResult *i=head;
while(i!=NULL)
{
vector<Result> sorted(i->resultdb->results);
sort(sorted.begin(), sorted.end());
auto& x = btree.put_child(i->benchmark, {});
for (int j=0; j<sorted.size(); j++)
{
Result &r = sorted[j];
x.add(r.test+".atts", r.atts);
x.add(r.test+".units", r.unit);
if (r.GetMedian() == FLT_MAX)
x.add(r.test+".Median","N/A");
else
x.add(r.test+".Median",r.GetMedian());
if (r.GetMean() == FLT_MAX)
x.add(r.test+".Mean","N/A");
else
x.add(r.test+".Mean",r.GetMean());
if (r.GetStdDev() == FLT_MAX)
x.add(r.test+".StdDev","N/A");
else
x.add(r.test+".StdDev",r.GetStdDev());
if (r.GetMin() == FLT_MAX)
x.add(r.test+".Min","N/A");
else
x.add(r.test+".Min",r.GetMin());
if (r.GetMax() == FLT_MAX)
x.add(r.test+".Max","N/A");
else
x.add(r.test+".max",r.GetMax());
}
i=i->next;
}
boost::property_tree::write_json(fileName, btree);
}
/*****************************************************************************
* <b>Function:</b> BenchmarkDatabase::DumpXML()
*
* <b>Purpose:</b> Writes the summary results (min/max/stddev/med/mean), to XML file
*
* @param out file to be written to
*
* <b>Modifications:</b>
*
* @author Masood Raeisi Nafchi
* @date Feb 04, 2020
*****************************************************************************/
void BenchmarkDatabase::DumpXML(string fileName)
{
boost::property_tree::ptree btree;
BenchmarkResult *i=head;
while(i!=NULL)
{
vector<Result> sorted(i->resultdb->results);
sort(sorted.begin(), sorted.end());
auto& x = btree.put_child(i->benchmark, {});
for (int j=0; j<sorted.size(); j++)
{
Result &r = sorted[j];
x.add(r.test+".atts", r.atts);
x.add(r.test+".units", r.unit);
if (r.GetMedian() == FLT_MAX)
x.add(r.test+".Median","N/A");
else
x.add(r.test+".Median",r.GetMedian());
if (r.GetMean() == FLT_MAX)
x.add(r.test+".Mean","N/A");
else
x.add(r.test+".Mean",r.GetMean());
if (r.GetStdDev() == FLT_MAX)
x.add(r.test+".StdDev","N/A");
else
x.add(r.test+".StdDev",r.GetStdDev());
if (r.GetMin() == FLT_MAX)
x.add(r.test+".Min","N/A");
else
x.add(r.test+".Min",r.GetMin());
if (r.GetMax() == FLT_MAX)
x.add(r.test+".Max","N/A");
else
x.add(r.test+".max",r.GetMax());
}
i=i->next;
}
boost::property_tree::write_xml(fileName, btree);
}
| 24.971061 | 95 | 0.522148 | [
"vector"
] |
be95c205d94a298435497de8ccf8a171e3d851c7 | 5,760 | cpp | C++ | 1139/main.cpp | Heliovic/PAT_Solutions | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | 2 | 2019-03-18T12:55:38.000Z | 2019-09-07T10:11:26.000Z | 1139/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | 1139/main.cpp | Heliovic/My_PAT_Answer | 7c5dd554654045308f2341713c3e52cc790beb59 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <set>
#include <utility>
#include <algorithm>
#include <queue>
#define MAX_ID 10240
#define MALE 1
#define FEMALE -1
using namespace std;
int gender[MAX_ID];
vector<int> friends[MAX_ID];
int N, M, K;
vector<pair<int, int> > ans;
void MF(int s, int t)
{
//printf("%d\n", id);
queue<vector<int> > q;
vector<int> vec;
vec.push_back(s);
q.push(vec);
while (!q.empty())
{
vector<int> v = q.front();
q.pop();
int sz = v.size();
int id = v[sz - 1];
if (sz == 4)
{
set<int> st;
st.insert(v[0]); st.insert(v[1]); st.insert(v[2]); st.insert(v[3]);
if (st.size() == 4)
ans.push_back(make_pair(v[1], v[2]));
continue;
}
for (int i = 0; i < friends[id].size(); i++)
{
int f = friends[id][i];
if (sz == 3)
{
if (f != t)
continue;
}
else if (sz == 2)
{
if (gender[f] != FEMALE)
continue;
}
else if (sz == 1)
{
if (gender[f] != MALE)
continue;
}
v.push_back(f);
q.push(v);
v.pop_back();
}
}
}
void FM(int s, int t)
{
//printf("%d\n", id);
queue<vector<int> > q;
vector<int> vec;
vec.push_back(s);
q.push(vec);
while (!q.empty())
{
vector<int> v = q.front();
q.pop();
int sz = v.size();
int id = v[sz - 1];
if (sz == 4)
{
set<int> st;
st.insert(v[0]); st.insert(v[1]); st.insert(v[2]); st.insert(v[3]);
if (st.size() == 4)
ans.push_back(make_pair(v[1], v[2]));
continue;
}
for (int i = 0; i < friends[id].size(); i++)
{
int f = friends[id][i];
if (sz == 3)
{
if (f != t)
continue;
}
else if (sz == 2)
{
if (gender[f] != MALE)
continue;
}
else if (sz == 1)
{
if (gender[f] != FEMALE)
continue;
}
v.push_back(f);
q.push(v);
v.pop_back();
}
}
}
void MM(int s, int t)
{
//printf("%d\n", id);
queue<vector<int> > q;
vector<int> vec;
vec.push_back(s);
q.push(vec);
while (!q.empty())
{
vector<int> v = q.front();
q.pop();
int sz = v.size();
int id = v[sz - 1];
if (sz == 4)
{
set<int> st;
st.insert(v[0]); st.insert(v[1]); st.insert(v[2]); st.insert(v[3]);
if (st.size() == 4)
ans.push_back(make_pair(v[1], v[2]));
continue;
}
for (int i = 0; i < friends[id].size(); i++)
{
int f = friends[id][i];
if (sz == 3)
{
if (f != t)
continue;
}
else if (gender[f] != MALE)
continue;
v.push_back(f);
q.push(v);
v.pop_back();
}
}
}
void FF(int s, int t)
{
queue<vector<int> > q;
vector<int> vec;
vec.push_back(s);
q.push(vec);
while (!q.empty())
{
vector<int> v = q.front();
q.pop();
int sz = v.size();
int id = v[sz - 1];
if (sz == 4)
{
set<int> st;
st.insert(v[0]); st.insert(v[1]); st.insert(v[2]); st.insert(v[3]);
if (st.size() == 4)
ans.push_back(make_pair(v[1], v[2]));
continue;
}
for (int i = 0; i < friends[id].size(); i++)
{
int f = friends[id][i];
if (sz == 3)
{
if (f != t)
continue;
}
else if (gender[f] != FEMALE)
continue;
v.push_back(f);
q.push(v);
v.pop_back();
}
}
}
bool cmp(pair<int, int>& p1, pair<int, int>& p2)
{
if (p1.first != p2.first)
return p1.first < p2.first;
return p1.second < p2.second;
}
int main()
{
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
char sbuf[10], tbuf[10];
int s, t;
scanf("%s %s", sbuf, tbuf);
if (sbuf[0] == '-')
{
sscanf(sbuf + 1, "%d", &s);
gender[s] = FEMALE;
}
else
{
sscanf(sbuf, "%d", &s);
gender[s] = MALE;
}
if (tbuf[0] == '-')
{
sscanf(tbuf + 1, "%d", &t);
gender[t] = FEMALE;
}
else
{
sscanf(tbuf, "%d", &t);
gender[t] = MALE;
}
friends[s].push_back(t);
friends[t].push_back(s);
}
scanf("%d", &K);
while (K--)
{
ans.clear();
int s, t;
scanf("%d %d", &s, &t);
s = abs(s);
t = abs(t);
if (gender[s] == MALE)
{
if (gender[t] == MALE)
MM(s, t);
else
MF(s, t);
}
else
{
if (gender[t] == MALE)
FM(s, t);
else
FF(s, t);
}
sort(ans.begin(), ans.end(), cmp);
printf("%d\n", ans.size());
for (int i = 0; i < ans.size(); i++)
{
printf("%04d %04d\n", ans[i].first, ans[i].second);
}
}
return 0;
}
| 21.254613 | 79 | 0.358333 | [
"vector"
] |
be98cb6106d633b137d90c809ac4e8c15bfd74a9 | 19,704 | cpp | C++ | test/vcf/normalize_test.cpp | Jack-Ren1/vcf-validator | 186085059cb5c25b710afc3d4ce68a40be22f96e | [
"Apache-2.0"
] | null | null | null | test/vcf/normalize_test.cpp | Jack-Ren1/vcf-validator | 186085059cb5c25b710afc3d4ce68a40be22f96e | [
"Apache-2.0"
] | null | null | null | test/vcf/normalize_test.cpp | Jack-Ren1/vcf-validator | 186085059cb5c25b710afc3d4ce68a40be22f96e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2017 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "catch/catch.hpp"
#include <vcf/file_structure.hpp>
#include <vcf/normalizer.hpp>
#include "test_utils.hpp"
namespace ebi
{
/**
* This helper function takes a simplified variant (2nd argument, TestMultiRecord) that may be multiallelic, and
* returns its normalization (performed with a user provided function, 1st argument) along with the expected result
* (3rd argument, vector<TestRecord>) in a comparable way (both as vectors of RecordCore). Example:
*
* auto comparison = test_normalization(vcf::normalize, {1000, "T", {"G", "A"}}, {{1000, "T", "G"}, {1000, "T", "A"}});
* CHECK((comparison.first) == (comparison.second));
*/
std::pair<std::vector<vcf::RecordCore>, std::vector<vcf::RecordCore>> test_normalization(
std::function<std::vector<vcf::RecordCore> (const vcf::Record &record)> normalize_function,
TestMultiRecord orig, std::vector<TestRecord> results)
{
try {
std::vector<vcf::RecordCore> expected_normalization;
for (auto result : results) {
expected_normalization.push_back(
{1, "1", result.normalized_pos, result.normalized_reference, result.normalized_alternate});
}
return {normalize_function(build_mock_record(orig)), expected_normalization};
} catch (vcf::Error * e) {
// Catch doesn't seem to understand an exception thrown by a pointer. workaround to see the message: rethrow by value
throw *e;
}
}
TEST_CASE("Record normalization: same length", "[normalize]")
{
SECTION("Single nucleotide polymorphism") {
TestMultiRecord origin{1000, "T", {"G"}};
std::vector<TestRecord> result{{1000, "T", "G"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Different ending") {
TestMultiRecord origin{1000, "TCACCC", {"TGACGG"}};
std::vector<TestRecord> result{{1001, "CACCC", "GACGG"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Same ending") {
TestMultiRecord origin{1000, "TCACCC", {"TGACGC"}};
std::vector<TestRecord> result{{1001, "CACC", "GACG"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
}
TEST_CASE("Record normalization: insertions", "[normalize]")
{
SECTION("Insertions: ambiguous context, 1-base context ambiguous, 1-base insertion")
{
TestMultiRecord origin{1000, "A", {"AA"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1000, "", "A"}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1001, "", "A"}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading context, 1-base context at left, 1-base insertion")
{
TestMultiRecord origin{1000, "T", {"TA"}};
std::vector<TestRecord> result{{1001, "", "A"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: trailing context, 1-base context at right, 1-base insertion")
{
TestMultiRecord origin{1000, "T", {"AT"}};
std::vector<TestRecord> result{{1000, "", "A"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading context, 1-base context, 2-base insertion")
{
TestMultiRecord origin{1000, "A", {"ATC"}};
std::vector<TestRecord> result{{1001, "", "TC"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading context, 2-base context, 1-base insertion")
{
TestMultiRecord origin{1000, "AC", {"ACT"}};
std::vector<TestRecord> result{{1002, "", "T"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading and trailing context")
{
TestMultiRecord origin{1000, "AC", {"ATC"}};
std::vector<TestRecord> result{{1001, "", "T"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading context and trailing ambiguous context (substring)")
{
TestMultiRecord origin{1000, "GT", {"GTT"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1001, "", "T"}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1002, "", "T"}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: leading ambiguous context and trailing context (substring)")
{
TestMultiRecord origin{1000, "TG", {"TTG"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1000, "", "T"}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1001, "", "T"}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: trailing context, 1-base context, 2-base insertion")
{
TestMultiRecord origin{1000, "A", {"TCA"}};
std::vector<TestRecord> result{{1000, "", "TC"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: trailing context, 2-base context, 1-base insertion")
{
TestMultiRecord origin{1000, "TC", {"ATC"}};
std::vector<TestRecord> result{{1000, "", "A"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: no context")
{
TestMultiRecord origin{1000, "TAC", {"CGATT"}};
std::vector<TestRecord> result{{1000, "TAC", "CGATT"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
}
TEST_CASE("Record normalization: deletions", "[normalize]")
{
SECTION("Deletions: ambiguous context, 1-base context ambiguous, 1-base deletion")
{
TestMultiRecord origin{1000, "AA", {"A"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1000, "A", ""}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1001, "A", ""}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading context, 1-base context at left, 1-base deletion")
{
TestMultiRecord origin{1000, "TA", {"T"}};
std::vector<TestRecord> result{{1001, "A", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: trailing context, 1-base context at right, 1-base deletion")
{
TestMultiRecord origin{1000, "AT", {"T"}};
std::vector<TestRecord> result{{1000, "A", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading context, 1-base context, 3-base deletion")
{
TestMultiRecord origin{1000, "GATC", {"G"}};
std::vector<TestRecord> result{{1001, "ATC", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading context, 2-base context, 1-base deletion")
{
TestMultiRecord origin{1000, "GAT", {"GA"}};
std::vector<TestRecord> result{{1002, "T", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading and trailing context")
{
TestMultiRecord origin{1000, "ATC", {"AC"}};
std::vector<TestRecord> result{{1001, "T", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading context and trailing ambiguous context (substring)")
{
TestMultiRecord origin{1000, "GTT", {"GT"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1001, "T", ""}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1002, "T", ""}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: leading ambiguous context and trailing context (substring)")
{
TestMultiRecord origin{1000, "TTG", {"TG"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1000, "T", ""}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1001, "T", ""}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: trailing context, 1-base context, 2-base deletion")
{
TestMultiRecord origin{1000, "ATC", {"C"}};
std::vector<TestRecord> result{{1000, "AT", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Insertions: trailing context, 2-base context, 1-base deletion")
{
TestMultiRecord origin{1000, "ATC", {"TC"}};
std::vector<TestRecord> result{{1000, "A", ""}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Deletions: no context")
{
TestMultiRecord origin{1000, "CGATT", {"TAC"}};
std::vector<TestRecord> result{{1000, "CGATT", "TAC"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
}
TEST_CASE("Record normalization: complex variants", "[normalize]")
{
SECTION("Complex variants: leading context, 1-base context, 2-to-1 bases variation")
{
TestMultiRecord origin{1000, "CAT", {"CG"}};
std::vector<TestRecord> result{{1001, "AT", "G"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Complex variants: trailing context, 1-base context, 2-to-1 bases variation")
{
TestMultiRecord origin{1000, "ATC", {"GC"}};
std::vector<TestRecord> result{{1000, "AT", "G"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
}
TEST_CASE("Record normalization: multiallelic", "[normalize]")
{
SECTION("Multiallelic splitting: same length")
{
TestMultiRecord origin{10040, "T", {"A", "C"}};
std::vector<TestRecord> result{{10040, "T", "A"},
{10040, "T", "C"}};
auto comparison = test_normalization(vcf::normalize, origin, result);
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, result);
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Multiallelic splitting: same length or deletion")
{
TestMultiRecord origin{10040, "TGACGTAACGATT", {"T", "TGACGTAACGGTT", "TGACGTAATAC"}};
auto comparison = test_normalization(vcf::normalize, origin, {
{10040, "TGACGTAACGAT", ""},
{10050, "A", "G"},
{10048, "CGATT", "TAC"}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {
{10041, "GACGTAACGATT", ""},
{10050, "A", "G"},
{10048, "CGATT", "TAC"}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Multiallelic splitting: insertions (substring)")
{
TestMultiRecord origin{1000, "GT", {"GTGT", "GTT"}};
auto comparison = test_normalization(vcf::normalize, origin, {{1000, "", "GT"},
{1001, "", "T"}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1002, "", "GT"},
{1002, "", "T"}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
SECTION("Multiallelic splitting: deletions (substring)")
{
TestMultiRecord origin{1000, "GTT", {"GT", "G"}};
std::vector<TestRecord> result;
auto comparison = test_normalization(vcf::normalize, origin, {{1001, "T", ""},
{1001, "TT", ""}});
CHECK((comparison.first) == (comparison.second));
auto comparison_pad_at_left = test_normalization(vcf::normalize_right_alignment, origin, {{1002, "T", ""},
{1001, "TT", ""}});
CHECK((comparison_pad_at_left.first) == (comparison_pad_at_left.second));
}
}
}
| 51.3125 | 127 | 0.630989 | [
"vector"
] |
be9a94d5e579488d9b363c176c2606427573476b | 517 | cpp | C++ | 142_count_no_of_hops.cpp | swapmali/Must-Do-Coding-Questions-For-Companies-GFG | b68340c150f572c0fad7311af87f79b684060fb9 | [
"MIT"
] | 1 | 2021-02-07T19:50:36.000Z | 2021-02-07T19:50:36.000Z | 142_count_no_of_hops.cpp | swapmali/Must-Do-Coding-Questions-For-Companies-GFG | b68340c150f572c0fad7311af87f79b684060fb9 | [
"MIT"
] | null | null | null | 142_count_no_of_hops.cpp | swapmali/Must-Do-Coding-Questions-For-Companies-GFG | b68340c150f572c0fad7311af87f79b684060fb9 | [
"MIT"
] | 1 | 2021-05-06T15:30:47.000Z | 2021-05-06T15:30:47.000Z | // https://practice.geeksforgeeks.org/problems/count-number-of-hops/0
#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> f(n + 1);
f[0] = 1;
f[1] = 1;
f[2] = 2;
for (int i = 3; i < n + 1; ++i)
f[i] = f[i - 1] + f[i - 2] + f[i - 3];
cout << f[n] << endl;
}
return 0;
} | 15.666667 | 69 | 0.547389 | [
"vector"
] |
be9ca91b0f830eaae9c4dfa77bf560ec3c09a42a | 12,390 | cxx | C++ | SimVascular-master/Code/Source/sv4gui/Modules/svFSI/sv4gui_svFSIJob.cxx | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | SimVascular-master/Code/Source/sv4gui/Modules/svFSI/sv4gui_svFSIJob.cxx | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | SimVascular-master/Code/Source/sv4gui/Modules/svFSI/sv4gui_svFSIJob.cxx | mccsssk2/SimVascularPM3_March2020 | 3cce6cc7be66545bea5dc3915a2db50a3892bf04 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) Stanford University, The Regents of the University of
* California, and others.
*
* All Rights Reserved.
*
* See Copyright-SimVascular.txt for additional details.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "sv4gui_svFSIJob.h"
#include <QFile>
#include <QTextStream>
sv4guisvFSIJob::sv4guisvFSIJob()
: nsd(3)
, timeSteps(1000)
, stepSize("1e-3")
, continuePrevious(false)
, saveInFoder(true)
, restartInc(10)
, resultPrefix("result")
, resultInc(10)
, startSavingStep(1)
, saveAvgResult(true)
, rhoInf(0.2)
, stopFileName("STOP_SIM")
, verbose(true)
, warn(true)
, debug(false)
, remeshing(false)
{
}
sv4guisvFSIJob::sv4guisvFSIJob(const sv4guisvFSIJob &other)
{
*this=other;
}
sv4guisvFSIJob::~sv4guisvFSIJob()
{
}
sv4guisvFSIJob* sv4guisvFSIJob::Clone()
{
return new sv4guisvFSIJob(*this);
}
bool sv4guisvFSIJob::WriteFile(std::string filePath)
{
std::cout << "writing svFSI input file\n";
if(m_Domains.size()<=0 || m_Domains.size()>2)
return false;
QFile file(QString::fromStdString(filePath));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream out(&file);
QString tabS=" ";
QString endL="\n";
QString formatVersion="#Format Version 1.0";
out << formatVersion << endL;
out << "# General simulation parameters" << endL;
out << "# -----------------------------------------------------" << endL;
out << "Number of spatial dimensions: " << nsd << endL;
out << "Number of time steps: " << timeSteps << endL;
out << "Time step size: " << QString::fromStdString(stepSize) << endL;
out << "Continue previous simulation: " << continuePrevious << endL;
out << "Save results in a folder: " << saveInFoder << endL;
out << "Increment in saving restart files: " << restartInc << endL;
out << "Name prefix of saved files: " << QString::fromStdString(resultPrefix) << endL;
out << "Increment in saving files: " << resultInc << endL;
out << "Start saving after time step: " << startSavingStep << endL;
out << "Save averaged results: " << saveAvgResult << endL;
out << "Spectral radius of infinite time step: " << rhoInf << endL;
out << "Searched file name to trigger stop: " << QString::fromStdString(stopFileName) << endL;
out << "Simulation requires remeshing: " << (remeshing?"T":"F") << endL;
out << "Verbose: " << verbose << endL;
out << "Warning: " << warn << endL;
out << "Debug: " << debug << endL << endL;
out << "# Domains" << endL;
out << "#------------------------------------------------------" << endL;
//make sure the first domain is fluid if there are two domains.
std::vector<sv4guisvFSIDomain> domains;
if (m_Domains.size()==1){
for(auto& pair : m_Domains)
{
domains.push_back(pair.second);
}
}
else if (m_Domains.size()==2){
domains.resize(2);
for(auto& pair : m_Domains)
{
if(pair.second.type=="fluid")
domains[0]=pair.second;
else
domains[1]=pair.second;
}
}
int domainID=0;
for(auto& domain : domains)
{
out << "Add mesh: "<< QString::fromStdString(domain.name) <<" {" << endL;
out << tabS << "Mesh file path (vtu): " <<QString::fromStdString(domain.folderName)<< "/" << QString::fromStdString(domain.fileName)<< endL;
domainID++;
for ( auto& faceName : domain.faceNames ) {
out << tabS << "Add face: " << QString::fromStdString(faceName) << " {" << endL;
out << tabS << tabS << "Face file path (vtp): " <<QString::fromStdString(domain.folderName)
<< "/" << QString::fromStdString(domain.faceFolderName)<< "/" << QString::fromStdString(faceName+".vtp")<< endL;
out << tabS << "}" << endL;
}
out << tabS << "Domain: " << domainID << endL;
out << "}" << endL;
}
out << endL;
//add projection
for (sv4guisvFSIeqClass& eq: m_Eqs) {
if(eq.physName=="FSI")
{
for( auto& fbc : eq.faceBCs ) {
sv4guisvFSIbcClass& iBc=fbc.second;
if(iBc.bcType=="Projection")
out << "Add projection: " << iBc.faceName << " { Project from face: " << iBc.projectionFaceName << " }"<< endL;
}
}
}
out << endL;
out << "# Equations" << endL;
out << "#------------------------------------------------------" << endL;
for (sv4guisvFSIeqClass& eq: m_Eqs) {
std::cout << "equation name " << eq.getPhysName().toStdString() << "\n";
out << "Add equation: " << eq.physName << " {" << endL;
out << tabS << "Coupled: " << eq.coupled << endL;
out << tabS << "Min iterations: " << eq.minItr << endL;
out << tabS << "Max iterations: " << eq.maxItr << endL;
out << tabS << "Tolerance: " << eq.tol << endL;
out << tabS << "Residual dB reduction: " << eq.dBr << endL;
if(eq.physName=="fluid")
out << tabS << "Backflow stabilization coefficient: " << eq.backflowStab << endL;
out << endL;
if ( eq.getPhysName() == "FSI" ) {
if(eq.remesher!="None")
{
out << tabS << "Remesher: "<< eq.remesher <<" { " << endL;
for(auto& pair : m_Domains)
{
std::string domainName=pair.first;
sv4guisvFSIDomain& domain=pair.second;
out << tabS << tabS << "Max edge size: " << QString::fromStdString(domainName) << " { val: " << domain.edgeSize <<" }" << endL;
}
out << tabS << tabS << "Min dihedral angle: " << eq.rmMinAngle <<endL;
out << tabS << tabS << "Max radius ratio: " << eq.rmMaxRadiusRatio << endL;
out << tabS << tabS << "Remesh frequency: " << eq.rmFrequency << endL;
out << tabS << tabS << "Frequency for copying data: " << eq.rmCopyFrequency << endL;
out << tabS << "}" << endL << endL;
}
out << tabS << "Domain: 1 { " << endL;
out << tabS << tabS << "Equation: fluid" << endL;
out << tabS << tabS << "Density: " << eq.getPropValue(0) << endL;
out << tabS << tabS << "Viscosity: " << eq.getPropValue(1) << endL;
out << tabS << tabS << "Backflow stabilization coefficient: " << eq.backflowStab << endL;
out << tabS << "}" << endL;
out << endL;
out << tabS << "Domain: 2 { " << endL;
out << tabS << tabS << "Equation: struct" << endL;
out << tabS << tabS << "Constitutive model: " << eq.constitutiveModel << endL;
out << tabS << tabS << "Density: " << eq.getPropValue(2) << endL;
out << tabS << tabS << "Elasticity modulus: " << eq.getPropValue(3) << endL;
out << tabS << tabS << "Poisson ratio: " << eq.getPropValue(4) << endL;
out << tabS << "}" << endL;
} else {
for ( int i=0 ; i < eq.getPropCount() ; i++ ) {
out << tabS << eq.getPropName(i) << ": " << eq.getPropValue(i) << endL ;
}
if(eq.getPhysName()=="struct"){
out << tabS << "Constitutive model: " << eq.constitutiveModel << endL ;
}
}
out << endL;
if(eq.physName!="mesh")
{
out << tabS << "LS type: " << eq.lsType << " {" << endL;
if(eq.lsPreconditioner!="" && eq.lsPreconditioner!="Default")
out << tabS << tabS << "Preconditioner: " <<eq.lsPreconditioner << endL;
out << tabS << tabS << "Max iterations: " <<eq.lsMaxItr << endL;
out << tabS << tabS << "Tolerance: " <<eq.lsTol << endL;
if(eq.lsType=="NS")
{
out << tabS << tabS << "NS-GM max iterations: " <<eq.lsNSGMMaxItr << endL;
out << tabS << tabS << "NS-GM tolerance: " <<eq.lsNSGMTol << endL;
out << tabS << tabS << "NS-CG max iterations: " <<eq.lsNSCGMaxItr << endL;
out << tabS << tabS << "NS-CG tolerance: " <<eq.lsNSCGTol << endL;
}
out << tabS << tabS << "Absolute tolerance: " <<eq.lsAbsoluteTol << endL;
out << tabS << tabS << "Krylov space dimension: " <<eq.lsKrylovDim << endL;
out << tabS << "}" << endL << endL;
}
out << tabS << "Output: Spatial {" << endL;
foreach ( QString outName , eq.getOutputNames() ) {
out << tabS << tabS << outName << ": t" << endL;
}
out << tabS << "}" << endL << endL;
for( auto& fbc : eq.faceBCs ) {
sv4guisvFSIbcClass& iBc=fbc.second;
if(iBc.bcType=="Projection")
continue;
out << tabS << "Add BC: " << iBc.faceName << " {" << endL;
if ( iBc.bcGrp != "" ) {
out << tabS << tabS << "Type: " << iBc.bcGrp << endL;
} else
{
return false;
}
out << tabS << tabS << "Time dependence: " << iBc.bcType << endL;
if ( iBc.bcType == "Steady" ) {
out << tabS << tabS << "Value: " << iBc.g << endL;
} else if ( iBc.bcType == "Unsteady" ) {
out << tabS << tabS << "Temporal values file path: " << iBc.gtFile << endL;
} else if ( iBc.bcType == "Resistance" ) {
out << tabS << tabS << "Value: " << iBc.r << endL;
} else if ( iBc.bcType == "Coupled" ) {
// Noting special is required
} else if ( iBc.bcType == "General" ) {
out << tabS << tabS << "Temporal and spatial values file path: " << iBc.gmFile << endL;
}
out << tabS << tabS << "Profile: " << iBc.profile << endL;
if ( iBc.profile == "User_defined" ) {
out << tabS << tabS << "Spatial profile file path: " << iBc.gxFile << endL;
}
if(iBc.zperm)
out << tabS << tabS << "Zero out perimeter: " << iBc.zperm << endL;
if(iBc.flux)
out << tabS << tabS << "Impose flux: " << iBc.flux << endL;
if(iBc.imposeIntegral)
out << tabS << tabS << "Impose on state variable integral: " << iBc.imposeIntegral << endL;
if(iBc.effectiveDirection.trimmed()!="")
{
QStringList list=iBc.effectiveDirection.trimmed().split(QRegExp("[(),{}-\\s+]"),QString::SkipEmptyParts);
out << tabS << tabS << "Effective direction: (" << list[0] << ", " << list[1] <<", " << list[2] << ")" << endL;
}
out << tabS << "}" << endL << endL;
}
out << "}" << endL;
out << endL;
}
file.close();
return true;
}
//bool sv4guisvFSIJob::ReadFile(std::string filePath)
//{
//}
| 38.71875 | 148 | 0.524455 | [
"mesh",
"vector",
"model"
] |
be9d526da647e15b933e8ea62be3c6cf5aed5bc4 | 6,378 | cpp | C++ | src/debug.cpp | dj1mm/vhdlstuff | 36768a6195991f31a33015fbeb3cf717c5d52ce4 | [
"Unlicense"
] | null | null | null | src/debug.cpp | dj1mm/vhdlstuff | 36768a6195991f31a33015fbeb3cf717c5d52ce4 | [
"Unlicense"
] | null | null | null | src/debug.cpp | dj1mm/vhdlstuff | 36768a6195991f31a33015fbeb3cf717c5d52ce4 | [
"Unlicense"
] | null | null | null |
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "version.h"
// this define is needed before the include format.h. Otherwise will get an
// `undefined reference to `fmt::v8::vformat` compile error
#define FMT_HEADER_ONLY
#include "fmt/args.h"
#include "fmt/format.h"
#include "vhdl/ast.h"
#include "vhdl/lexer.h"
#include "vhdl/library_manager.h"
#include "vhdl/parser.h"
#include "vhdl/binder.h"
#include "vhdl_syntax_debug.h"
#include "args.hxx"
#include "loguru.h"
int debug_tokens(std::string file, bool stats = false)
{
auto zero = std::chrono::high_resolution_clock::now();
std::ifstream content(file);
if (!content.good())
throw std::invalid_argument(fmt::format("Unable to open {}", file));
content.seekg(0, std::ios::end);
auto size = content.tellg();
std::string buffer(size, ' ');
content.seekg(0);
content.read(&buffer[0], size);
auto p = std::filesystem::path(file);
if (p.is_relative()) {
p = std::filesystem::canonical(file);
}
common::stringtable st;
std::vector<common::diagnostic> diags;
auto one = std::chrono::high_resolution_clock::now();
vhdl::lexer lexer(&buffer[0], &buffer[buffer.length()], &st, &diags, p.string());
lexer.scan();
auto two = std::chrono::high_resolution_clock::now();
while (lexer.current_token() != vhdl::token::eof)
{
std::cout << lexer.scan().debug() << "\n";
}
auto three = std::chrono::high_resolution_clock::now();
if (stats)
{
std::cout << "Lexer took: " << std::chrono::duration_cast<std::chrono::microseconds>(two-one).count() << "us"
" / " << std::chrono::duration_cast<std::chrono::milliseconds>(three-two).count() << "ms"
" / " << std::chrono::duration_cast<std::chrono::milliseconds>(three-zero).count() << "ms\n";
}
return diags.size() == 0? 0 : 1 << 2;
}
int debug_analysis(std::string file, std::filesystem::path path, std::string work, bool ast = false, bool stats = false)
{
auto cwd = std::filesystem::current_path();
auto manager = std::make_shared<vhdl::library_manager>(cwd.string());
vhdl::ast tree(path.string(), manager, work);
tree.update();
auto [parse_errors, semantic_errors ] = tree.get_diagnostics();
auto number_of_parse_errors = parse_errors.size();
auto number_of_semantic_errors = semantic_errors.size();
for (auto& it : parse_errors)
{
fmt::dynamic_format_arg_store<fmt::format_context> args;
for (auto& arg : it.args)
{
if (std::holds_alternative<std::string>(arg))
args.push_back(std::get<std::string>(arg));
if (std::holds_alternative<int>(arg))
args.push_back(std::get<int>(arg));
}
std::cout << it.location << "\n";
std::cout << fmt::vformat(it.format, args) << "\n\n";
}
if (ast)
{
vhdl::syntax::vhdl_syntax_debug d(std::cout);
tree.get_main_file()->traverse(d);
}
if (stats)
{
std::cout << number_of_parse_errors << " errors" << "\n";
}
int result = 0;
result |= (number_of_parse_errors == 0 ? 0 : 1 << 2);
// result |= (number_of_semantic_errors == 0 ? 0 : 1 << 3);
return result;
}
int main(int argc, char** argv)
{
loguru::g_stderr_verbosity = loguru::Verbosity_OFF;
loguru::init(argc, argv, "--verbosity");
// make a new ArgumentParser
const std::vector<std::string> arguments{argv + 1, argv + argc};
args::ArgumentParser parser("Debug stuffs");
args::Positional<std::string> f(parser, "file" , "compile this file");
args::ValueFlag<std::string> w(parser, "name" , "work library", { "work"}, "work");
args::ValueFlag<std::string> t(parser, "path" , "write trace to this file", { "trace"});
args::Flag k(parser, "tokens", "debug tokens", { "tokens"});
args::Flag p(parser, "ast" , "debug the parse ast", { "ast"});
args::Flag s(parser, "stats" , "print statistics", {'s', "stats"});
args::Flag v(parser, "version", "output version information", {'v', "version"});
args::HelpFlag h(parser, "help" , "print this help message" , {'h', "help"});
int status = 0;
try
{
parser.ParseArgs(arguments);
if (v)
{
std::cout << "Debugstuff " << things::build_hash << " (" << things::build_branch << ") " << things::build_tag << "\n";
return status;
}
if (!f)
{
throw args::ParseError("File is required");
}
auto path = std::filesystem::path(f.Get());
if (path.is_relative())
{
path = std::filesystem::canonical(path);
}
if (k)
{
return debug_tokens(f.Get(), s);
}
return debug_analysis(f.Get(), path, w.Get(), p, s);
}
catch (const args::Completion& e)
{
LOG_S(ERROR) << e.what();
}
catch (const args::Help&)
{
std::cout << parser;
std::cout << "Build " << things::build_hash << " (" << things::build_branch << ") " << things::build_tag << "\n";
std::cout << "Debug stuffs" << std::endl;
}
catch (const args::ParseError& e)
{
std::cerr << parser;
std::cerr << e.what() << "\n\nDo " << argv[0]
<< " --help for more information" << std::endl;
status = 1;
}
catch (const args::Error& e)
{
std::cerr << parser;
std::cerr << "\n\nThere was an unexpected error. Do " << argv[0]
<< " --help for more information" << std::endl;
status = 1;
}
catch (const std::invalid_argument& e)
{
LOG_S(ERROR) << "Invalid argument exception thrown: " << e.what();
std::cerr << e.what() << std::endl;
status = 1;
}
catch (const std::logic_error& e)
{
LOG_S(ERROR) << "Logic error thrown: " << e.what();
status = 1;
}
catch (const std::exception& e)
{
LOG_S(ERROR) << "Uncaught exception " << e.what();
status = 1;
}
return status;
}
| 30.663462 | 130 | 0.550329 | [
"vector"
] |
bea32e62a4dc9a23ab66165f7a604a1538865726 | 3,213 | cpp | C++ | JanuaEngine/tgcviewer-cpp/TgcViewer/GuiController.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 98 | 2015-01-13T16:23:23.000Z | 2022-02-14T21:51:07.000Z | JanuaEngine/tgcviewer-cpp/TgcViewer/GuiController.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 1 | 2016-06-30T22:07:54.000Z | 2016-06-30T22:07:54.000Z | JanuaEngine/tgcviewer-cpp/TgcViewer/GuiController.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 13 | 2015-08-26T11:19:08.000Z | 2021-07-12T03:41:50.000Z | /////////////////////////////////////////////////////////////////////////////////
// TgcViewer-cpp
//
// Author: Matias Leone
//
/////////////////////////////////////////////////////////////////////////////////
#include "TgcViewer/GuiController.h"
using namespace TgcViewer;
GuiController* GuiController::Instance = NULL;
GuiController::GuiController()
{
}
GuiController::~GuiController()
{
}
void GuiController::newInstance()
{
GuiController::Instance = new GuiController();
}
void GuiController::initGraphics(TgcExample* example)
{
this->currentExample = example;
FastMath::init();
this->logger = new TgcLogger();
//Init engine components
this->windowHandler = new WindowHandler();
string currentDir = this->windowHandler->getCurrentDir();
this->examplesMediaPath = currentDir + "\\tgcviewer-cpp\\Media\\Examples\\";
this->engineMediaPath = currentDir + "\\tgcviewer-cpp\\Media\\TgcViewer\\";
this->renderer = TgcRendererFactory::createRenderer();
this->renderer->init();
this->highResolutionTimer = new HighResolutionTimer();
this->input = new TgcInput();
this->texturesPool = new TgcTexturePool();
this->shaders = this->renderer->createTgcShadersInstance();
this->shaders->loadCommonShaders();
this->fontRenderer = new TgcFontRenderer();
this->debugText = new TgcText2d();
this->userVars = new TgcUserVars();
this->gui = new TgcGui();
this->modifiers = new TgcModifiers();
//Init example
this->highResolutionTimer->reset();
this->currentExample->init();
//Start the engine
this->windowHandler->run();
}
void GuiController::render()
{
this->renderer->beginScene();
//Elapsed time
this->highResolutionTimer->set();
this->elapsedTime = this->highResolutionTimer->frameTime;
int fps = this->highResolutionTimer->fps;
//Update input
this->input->update();
//Update modifiers
this->modifiers->update();
//Render example
this->currentExample->render(elapsedTime);
//Render modifiers
this->modifiers->render();
//Render fps
this->drawText("FPS: " + TgcParserUtils::toString(fps), 2, 2);
//Draw user vars
this->userVars->render();
this->renderer->endScene();
}
void GuiController::shutDown()
{
this->windowHandler->running = false;
}
void GuiController::dispose()
{
this->currentExample->close();
delete this->currentExample;
delete this->input;
this->renderer->shutdown();
delete this->renderer;
this->windowHandler->closeWindow();
delete this->windowHandler;
delete this->highResolutionTimer;
this->modifiers->dispose();
delete this->modifiers;
this->gui->dispose();
delete this->gui;
this->fontRenderer->dispose();
delete this->fontRenderer;
this->logger->dispose();
delete this->logger;
this->shaders->dispose();
delete this->shaders;
this->debugText->dispose();
delete this->debugText;
this->userVars->dispose();
delete this->userVars;
this->texturesPool->clearAll();
delete this->texturesPool;
delete GuiController::Instance;
}
void GuiController::drawText(string text, int x, int y, Color color)
{
this->debugText->text = text;
this->debugText->position = Vector2((float)x, (float)y);
this->debugText->color = color;
this->debugText->updateValues();
this->debugText->render();
}
| 21 | 81 | 0.678494 | [
"render"
] |
bea3f93e00103700b51e61e5cb65d150d3c03863 | 2,144 | cpp | C++ | deepg3d/code/transforms/rotation_z.cpp | eth-sri/3dcertify | bb10f339f80149a9ebc7c07d041b2ef222efb394 | [
"Apache-2.0"
] | 9 | 2021-03-31T20:27:50.000Z | 2022-01-07T21:52:47.000Z | deepg3d/code/transforms/rotation_z.cpp | eth-sri/3dcertify | bb10f339f80149a9ebc7c07d041b2ef222efb394 | [
"Apache-2.0"
] | 2 | 2021-06-21T15:38:07.000Z | 2021-11-08T09:10:09.000Z | deepg3d/code/transforms/rotation_z.cpp | eth-sri/3dcertify | bb10f339f80149a9ebc7c07d041b2ef222efb394 | [
"Apache-2.0"
] | 4 | 2021-07-17T15:04:14.000Z | 2022-02-09T17:51:39.000Z | #include "rotation_z.h"
Point<double>
RotationZTransformation3D::transform(const Point<double> &point,
const std::vector<double> ¶ms) const {
assert(params.size() == 1);
double alpha = params[0];
return {cos(alpha) * point.x - sin(alpha) * point.y,
sin(alpha) * point.x + cos(alpha) * point.y, point.z};
}
Point<Interval>
RotationZTransformation3D::transform(const Point<Interval> &point,
const vector<Interval> ¶ms) const {
assert(params.size() == 1);
Interval alpha = params[0];
return {cos(alpha) * point.x - sin(alpha) * point.y,
sin(alpha) * point.x + cos(alpha) * point.y, point.z};
}
std::tuple<std::vector<Interval>, std::vector<Interval>, std::vector<Interval>>
RotationZTransformation3D::gradTransform(const Point<Interval> &point,
const vector<Interval> ¶ms) const {
assert(params.size() == 1);
Interval alpha = params[0];
return {{-sin(alpha) * point.x - cos(alpha) * point.y},
{cos(alpha) * point.x - sin(alpha) * point.y},
{{0., 0.}}};
}
std::tuple<Interval, Interval, Interval>
RotationZTransformation3D::dx(const Point<Interval> &point,
const vector<Interval> ¶ms) const {
assert(params.size() == 1);
Interval alpha = params[0];
return {cos(alpha), -sin(alpha), {0, 0}};
}
std::tuple<Interval, Interval, Interval>
RotationZTransformation3D::dy(const Point<Interval> &point,
const vector<Interval> ¶ms) const {
assert(params.size() == 1);
Interval alpha = params[0];
return {sin(alpha), cos(alpha), {0, 0}};
}
std::tuple<Interval, Interval, Interval>
RotationZTransformation3D::dz(const Point<Interval> &point,
const vector<Interval> ¶ms) const {
assert(params.size() == 1);
return {{0, 0}, {0, 0}, {1, 1}};
}
SpatialTransformation3D *RotationZTransformation3D::getInverse() {
HyperBox new_domain =
HyperBox({{-this->domain[0].sup, -this->domain[0].inf}});
return new RotationZTransformation3D(new_domain);
}
| 36.338983 | 80 | 0.614272 | [
"vector",
"transform"
] |
bead2c9afce523d8cd875569316120fd2564cc19 | 70,205 | cpp | C++ | src/CQChartsAxis.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 14 | 2018-05-22T15:06:08.000Z | 2022-01-20T12:18:28.000Z | src/CQChartsAxis.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 6 | 2020-09-04T15:49:24.000Z | 2022-01-12T19:06:45.000Z | src/CQChartsAxis.cpp | SammyEnigma/CQCharts | 56433e32c943272b6faaf6771d0652c0507f943e | [
"MIT"
] | 9 | 2019-04-01T13:10:11.000Z | 2022-01-22T01:46:27.000Z | #include <CQChartsAxis.h>
#include <CQChartsPlot.h>
#include <CQChartsView.h>
#include <CQChartsModelUtil.h>
#include <CQChartsEditHandles.h>
#include <CQChartsVariant.h>
#include <CQCharts.h>
#include <CQChartsPaintDevice.h>
#include <CQChartsDrawUtil.h>
#include <CQChartsRotatedText.h>
#include <CQPropertyViewModel.h>
#include <CQPropertyViewItem.h>
#include <CQTclUtil.h>
#include <cstring>
#include <algorithm>
namespace {
int boolFactor(bool b) { return (b ? 1 : -1); }
}
//------
CQChartsAxis::
CQChartsAxis(const Plot *plot, Qt::Orientation direction, double start, double end) :
CQChartsObj(plot->charts()),
CQChartsObjAxesLineData <CQChartsAxis>(this),
CQChartsObjAxesTickLabelTextData<CQChartsAxis>(this),
CQChartsObjAxesLabelTextData <CQChartsAxis>(this),
CQChartsObjAxesMajorGridLineData<CQChartsAxis>(this),
CQChartsObjAxesMinorGridLineData<CQChartsAxis>(this),
CQChartsObjAxesGridFillData <CQChartsAxis>(this),
plot_(plot), direction_(direction),
start_(std::min(start, end)), end_(std::max(start, end)), calcStart_(start), calcEnd_(end)
{
init();
}
CQChartsAxis::
~CQChartsAxis()
{
}
void
CQChartsAxis::
init()
{
setObjectName("axis");
setEditable(true);
//--
Color themeFg (Color::Type::INTERFACE_VALUE, 1);
Color themeGray1(Color::Type::INTERFACE_VALUE, 0.7);
Color themeGray2(Color::Type::INTERFACE_VALUE, 0.3);
Color themeGray3(Color::Type::INTERFACE_VALUE, 0.3);
setAxesLabelTextColor (themeFg);
setAxesTickLabelTextColor(themeFg);
setAxesLinesColor(themeGray1);
// init grid
setAxesMajorGridLinesColor(themeGray2);
setAxesMajorGridLinesDash (LineDash(LineDash::Lengths({2, 2}), 0));
setAxesMinorGridLinesColor(themeGray2);
setAxesMinorGridLinesDash (LineDash(LineDash::Lengths({2, 2}), 0));
setAxesGridFillColor(themeGray3);
setAxesGridFillAlpha(Alpha(0.5));
needsCalc_ = true;
//---
setAxesTickLabelTextFont(Font().decFontSize(4));
}
//---
namespace {
template<typename T>
void swapT(CQChartsAxis *lhs, CQChartsAxis *rhs) {
std::swap(*(T*)(lhs), *(T*)(rhs));
}
}
void
CQChartsAxis::
swap(CQChartsAxis *lhs, CQChartsAxis *rhs)
{
std::swap(lhs->side_ , rhs->side_ );
std::swap(lhs->position_ , rhs->position_ );
std::swap(lhs->valueType_ , rhs->valueType_ );
std::swap(lhs->dataLabels_ , rhs->dataLabels_ );
std::swap(lhs->column_ , rhs->column_ );
std::swap(lhs->formatStr_ , rhs->formatStr_ );
std::swap(lhs->maxFitExtent_, rhs->maxFitExtent_);
std::swap(lhs->labelDisplayed_, rhs->labelDisplayed_);
std::swap(lhs->label_ , rhs->label_ );
std::swap(lhs->userLabel_ , rhs->userLabel_ );
std::swap(lhs->gridLinesDisplayed_, rhs->gridLinesDisplayed_);
std::swap(lhs->gridFillDisplayed_ , rhs->gridFillDisplayed_ );
std::swap(lhs->gridMid_ , rhs->gridMid_ );
std::swap(lhs->gridAbove_, rhs->gridAbove_);
std::swap(lhs->ticksDisplayed_, rhs->ticksDisplayed_);
std::swap(lhs->majorTickLen_ , rhs->majorTickLen_ );
std::swap(lhs->minorTickLen_ , rhs->minorTickLen_ );
std::swap(lhs->tickInside_ , rhs->tickInside_ );
std::swap(lhs->mirrorTicks_ , rhs->mirrorTicks_ );
std::swap(lhs->tickLabelAutoHide_ , rhs->tickLabelAutoHide_ );
std::swap(lhs->tickLabelPlacement_, rhs->tickLabelPlacement_);
std::swap(lhs->start_ , rhs->start_ );
std::swap(lhs->end_ , rhs->end_ );
std::swap(lhs->includeZero_ , rhs->includeZero_ );
std::swap(lhs->allowHtmlLabels_, rhs->allowHtmlLabels_);
std::swap(lhs->maxMajorTicks_ , rhs->maxMajorTicks_ );
std::swap(lhs->tickIncrement_ , rhs->tickIncrement_ );
std::swap(lhs->majorIncrement_ , rhs->majorIncrement_ );
std::swap(lhs->tickSpaces_ , rhs->tickSpaces_ );
std::swap(lhs->tickLabels_ , rhs->tickLabels_ );
std::swap(lhs->requireTickLabel_, rhs->requireTickLabel_);
swapT<CQChartsObjAxesLineData <CQChartsAxis>>(lhs, rhs);
swapT<CQChartsObjAxesTickLabelTextData<CQChartsAxis>>(lhs, rhs);
swapT<CQChartsObjAxesLabelTextData <CQChartsAxis>>(lhs, rhs);
swapT<CQChartsObjAxesMajorGridLineData<CQChartsAxis>>(lhs, rhs);
swapT<CQChartsObjAxesMinorGridLineData<CQChartsAxis>>(lhs, rhs);
swapT<CQChartsObjAxesGridFillData <CQChartsAxis>>(lhs, rhs);
}
//---
CQCharts *
CQChartsAxis::
charts() const
{
return view()->charts();
}
QString
CQChartsAxis::
calcId() const
{
if (isHorizontal())
return plot()->id() + "/xaxis";
else
return plot()->id() + "/yaxis";
}
CQChartsView *
CQChartsAxis::
view()
{
return plot()->view();
}
const CQChartsView *
CQChartsAxis::
view() const
{
return plot()->view();
}
//---
void
CQChartsAxis::
setVisible(bool b)
{
CQChartsUtil::testAndSet(visible_, b, [&]() { redraw(); } );
}
void
CQChartsAxis::
setSelected(bool b)
{
CQChartsUtil::testAndSet(selected_, b, [&]() { emitSelectionChanged(); } );
}
//---
void
CQChartsAxis::
emitSelectionChanged()
{
emit selectionChanged();
}
void
CQChartsAxis::
addProperties(CQPropertyViewModel *model, const QString &path, const PropertyType &propertyTypes)
{
auto addProp = [&](const QString &path, const QString &name, const QString &alias,
const QString &desc, bool hidden=false) {
auto *item = &(model->addProperty(path, this, name, alias)->setDesc(desc));
if (hidden) CQCharts::setItemIsHidden(item);
return item;
};
auto addStyleProp = [&](const QString &path, const QString &name, const QString &alias,
const QString &desc, bool hidden=false) {
auto *item = addProp(path, name, alias, desc, hidden);
CQCharts::setItemIsStyle(item);
return item;
};
//---
if (int(propertyTypes) & int(PropertyType::STATE)) {
addProp(path, "visible" , "", "Axis visible");
addProp(path, "editable" , "", "Axis editable");
}
//---
if (! (int(propertyTypes) & int(PropertyType::ANNOTATION)))
addProp(path, "direction", "", "Axis direction", true)->setEditable(false);
addProp(path, "side" , "", "Axis plot side");
addProp(path, "valueType", "", "Axis value type");
addProp(path, "format" , "", "Axis tick value format string");
addProp(path, "tickIncrement" , "", "Axis tick increment");
addProp(path, "majorIncrement", "", "Axis tick major increment");
if (! (int(propertyTypes) & int(PropertyType::ANNOTATION))) {
addProp(path, "start", "", "Axis start position");
addProp(path, "end" , "", "Axis end position");
}
addProp(path, "includeZero", "", "Axis force include zero", true);
addProp(path, "valueStart", "", "Axis custom start position");
addProp(path, "valueEnd" , "", "Axis custom end position");
addProp(path, "tickLabels" , "", "Indexed Tick Labels", true);
addProp(path, "customTickLabels", "", "Custom Tick Labels", true);
addProp(path, "maxFitExtent", "", "Axis maximum extent percent for auto fit")->
setMinValue(0.0);
//---
if (! (int(propertyTypes) & int(PropertyType::ANNOTATION))) {
auto posPath = path + "/position";
addProp(posPath, "position", "value", "Axis position");
}
//---
if (int(propertyTypes) & int(PropertyType::STROKE)) {
auto linePath = path + "/stroke";
addStyleProp(linePath, "axesLineData" , "style" , "Axis stroke style", true);
addStyleProp(linePath, "axesLines" , "visible", "Axis stroke visible");
addStyleProp(linePath, "axesLinesColor", "color" , "Axis stroke color");
addStyleProp(linePath, "axesLinesAlpha", "alpha" , "Axis stroke alpha");
addStyleProp(linePath, "axesLinesWidth", "width" , "Axis stroke width");
addStyleProp(linePath, "axesLinesDash" , "dash" , "Axis stroke dash");
addStyleProp(linePath, "axesLinesCap" , "cap" , "Axis stroke cap");
//addStyleProp(linePath, "axesLinesJoin" , "join" , "Axis stroke dash");
}
//---
auto ticksPath = path + "/ticks";
addProp(ticksPath, "ticksDisplayed", "lines", "Axis major and/or minor ticks visible");
auto majorTicksPath = ticksPath + "/major";
auto minorTicksPath = ticksPath + "/minor";
addProp(majorTicksPath, "majorTickLen", "length", "Axis major ticks pixel length");
addProp(minorTicksPath, "minorTickLen", "length", "Axis minor ticks pixel length");
//---
auto ticksLabelPath = ticksPath + "/label";
auto ticksLabelTextPath = ticksLabelPath + "/text";
addProp(ticksLabelPath, "tickLabelAutoHide" , "autoHide", "Axis tick label text is auto hide");
addProp(ticksLabelPath, "tickLabelPlacement", "placement", "Axis tick label text placement");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextData" , "style",
"Axis tick label text style", true);
addProp (ticksLabelTextPath, "axesTickLabelTextVisible" , "visible",
"Axis tick label text visible");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextColor" , "color",
"Axis tick label text color");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextAlpha" , "alpha",
"Axis tick label text alpha");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextFont" , "font",
"Axis tick label text font");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextAngle" , "angle",
"Axis tick label text angle");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextContrast" , "contrast",
"Axis tick label text contrast");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextContrastAlpha", "contrastAlpha",
"Axis tick label text contrast alpha");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextClipLength" , "clipLength",
"Axis tick label text clip length");
addStyleProp(ticksLabelTextPath, "axesTickLabelTextClipElide" , "clipElide",
"Axis tick label text clip elide");
addProp(ticksPath, "tickInside" , "inside", "Axis ticks drawn inside plot");
addProp(ticksPath, "mirrorTicks", "mirror", "Axis tick are mirrored on other side of plot");
//---
auto labelPath = path + "/label";
auto labelTextPath = labelPath + "/text";
addProp(labelPath, "scaleLabelFont" , "", "Scale label font to match length");
addProp(labelPath, "scaleLabelExtent", "", "Extent to length for scale label font");
addProp(labelTextPath, "labelStr" , "string" , "Axis label text string");
addProp(labelTextPath, "defLabel" , "defString", "Axis label text default string");
//addProp(labelTextPath, "userLabel", "string" , "Axis label text user string");
addStyleProp(labelTextPath, "axesLabelTextData" , "style",
"Axis label text style", true);
addProp (labelTextPath, "axesLabelTextVisible" , "visible",
"Axis label text visible");
addStyleProp(labelTextPath, "axesLabelTextColor" , "color",
"Axis label text color");
addStyleProp(labelTextPath, "axesLabelTextAlpha" , "alpha",
"Axis label text alpha");
addStyleProp(labelTextPath, "axesLabelTextFont" , "font",
"Axis label text font");
addStyleProp(labelTextPath, "axesLabelTextContrast" , "contrast",
"Axis label text contrast");
addStyleProp(labelTextPath, "axesLabelTextContrastAlpha", "contrastAlpha",
"Axis label text contrast alpha");
addStyleProp(labelTextPath, "axesLabelTextHtml" , "html",
"Axis label text is HTML");
addStyleProp(labelTextPath, "axesLabelTextClipLength" , "clipLength",
"Axis label text clip length");
addStyleProp(labelTextPath, "axesLabelTextClipElide" , "clipElide",
"Axis label text clip elide");
//---
auto gridPath = path + "/grid";
auto gridLinePath = gridPath + "/stroke";
auto gridMajorPath = gridPath + "/major";
auto gridMajorStrokePath = gridMajorPath + "/stroke";
auto gridMajorFillPath = gridMajorPath + "/fill";
auto gridMinorPath = gridPath + "/minor";
auto gridMinorStrokePath = gridMinorPath + "/stroke";
addProp(gridPath, "gridMid" , "middle", "Grid at make tick mid point");
addProp(gridPath, "gridAbove", "above" , "Grid is drawn above axes");
addProp(gridPath, "gridLinesDisplayed", "lines", "Axis major and/or minor grid lines visible");
addProp(gridPath, "gridFillDisplayed" , "fill" , "Axis major and/or minor fill visible");
addStyleProp(gridMajorStrokePath, "axesMajorGridLineData" , "style",
"Axis major grid stroke style", true);
addStyleProp(gridMajorStrokePath, "axesMajorGridLinesColor", "color",
"Axis major grid stroke color");
addStyleProp(gridMajorStrokePath, "axesMajorGridLinesAlpha", "alpha",
"Axis major grid stroke alpha");
addStyleProp(gridMajorStrokePath, "axesMajorGridLinesWidth", "width",
"Axis major grid stroke width");
addStyleProp(gridMajorStrokePath, "axesMajorGridLinesDash" , "dash",
"Axis major grid stroke dash");
addStyleProp(gridMajorStrokePath, "axesMajorGridLinesCap" , "cap",
"Axis major grid stroke cap");
//addStyleProp(gridMajorStrokePath, "axesMajorGridLinesJoin" , "join",
// "Axis major grid stroke join");
addStyleProp(gridMinorStrokePath, "axesMinorGridLineData" , "style",
"Axis minor grid stroke style", true);
addStyleProp(gridMinorStrokePath, "axesMinorGridLinesColor", "color",
"Axis minor grid stroke color");
addStyleProp(gridMinorStrokePath, "axesMinorGridLinesAlpha", "alpha",
"Axis minor grid stroke alpha");
addStyleProp(gridMinorStrokePath, "axesMinorGridLinesWidth", "width",
"Axis minor grid stroke width");
addStyleProp(gridMinorStrokePath, "axesMinorGridLinesDash" , "dash",
"Axis minor grid stroke dash");
addStyleProp(gridMinorStrokePath, "axesMinorGridLinesCap" , "cap",
"Axis minor grid stroke cap");
//addStyleProp(gridMinorStrokePath, "axesMinorGridLinesJoin" , "join",
// "Axis minor grid stroke join");
addStyleProp(gridMajorFillPath, "axesGridFillData" , "style" ,
"Axis grid fill style", true);
addStyleProp(gridMajorFillPath, "axesGridFillColor" , "color" , "Axis grid fill color");
addStyleProp(gridMajorFillPath, "axesGridFillAlpha" , "alpha" , "Axis grid fill alpha");
addStyleProp(gridMajorFillPath, "axesGridFillPattern", "pattern", "Axis grid fill pattern");
}
//---
void
CQChartsAxis::
setRange(double start, double end)
{
start_ = std::min(start, end);
end_ = std::max(start, end);
calcAndRedraw();
}
void
CQChartsAxis::
setValueStart(const OptReal &v)
{
valueStart_ = v;
calcAndRedraw();
}
void
CQChartsAxis::
setValueEnd(const OptReal &v)
{
valueEnd_ = v;
calcAndRedraw();
}
//---
void
CQChartsAxis::
setMajorIncrement(const CQChartsOptInt &i)
{
CQChartsUtil::testAndSet(majorIncrement_, i, [&]() { calcAndRedraw(); } );
}
void
CQChartsAxis::
setTickIncrement(const CQChartsOptInt &i)
{
CQChartsUtil::testAndSet(tickIncrement_, i, [&]() { calcAndRedraw(); } );
}
double
CQChartsAxis::
majorTickIncrement() const
{
return calcIncrement();
}
double
CQChartsAxis::
minorTickIncrement() const
{
return majorTickIncrement()/numMinorTicks();
}
//---
QString
CQChartsAxis::
tickLabelsStr() const
{
QStringList strs;
for (const auto &p : tickLabels_) {
QStringList strs1;
strs1 << CQChartsUtil::realToString(p.first);
strs1 << p.second;
auto str1 = CQTcl::mergeList(strs1);
strs << str1;
}
return CQTcl::mergeList(strs);
}
void
CQChartsAxis::
setTickLabelsStr(const QString &str)
{
QStringList strs;
if (! CQTcl::splitList(str, strs))
return;
for (int i = 0; i < strs.length(); ++i) {
const auto &str1 = strs[i];
QStringList strs1;
if (! CQTcl::splitList(str1, strs1))
continue;
if (strs1.length() < 1)
continue;
bool ok;
int value = strs1[0].toInt(&ok);
if (! ok) continue;
if (strs1.length() > 1)
setTickLabel(value, strs1[1]);
else
setTickLabel(value, strs1[0]);
}
}
void
CQChartsAxis::
clearTickLabels()
{
tickLabels_.clear();
}
void
CQChartsAxis::
setTickLabel(long i, const QString &label)
{
CQChartsUtil::testAndSet(tickLabels_[i], label, [&]() { redraw(); } );
}
bool
CQChartsAxis::
hasTickLabel(long i) const
{
return (tickLabels_.find(i) != tickLabels_.end());
}
const QString &
CQChartsAxis::
tickLabel(long i) const
{
auto p = tickLabels_.find(i);
assert(p != tickLabels_.end());
return (*p).second;
}
//---
QString
CQChartsAxis::
customTickLabelsStr() const
{
QStringList strs;
for (const auto &p : customTickLabels_) {
QStringList strs1;
strs1 << CQChartsUtil::realToString(p.first);
strs1 << p.second;
auto str1 = CQTcl::mergeList(strs1);
strs << str1;
}
return CQTcl::mergeList(strs);
}
void
CQChartsAxis::
setCustomTickLabelsStr(const QString &str)
{
customTickLabels_.clear();
QStringList strs;
if (! CQTcl::splitList(str, strs))
return;
for (int i = 0; i < strs.length(); ++i) {
const auto &str1 = strs[i];
QStringList strs1;
if (! CQTcl::splitList(str1, strs1))
continue;
if (strs1.length() < 1)
continue;
bool ok;
double value = strs1[0].toDouble(&ok);
if (! ok) continue;
if (strs1.length() > 1)
customTickLabels_[value] = strs1[1];
else
customTickLabels_[value] = strs1[0];
}
}
//---
void
CQChartsAxis::
setPosition(const CQChartsOptReal &r)
{
CQChartsUtil::testAndSet(position_, r, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setColumn(const CQChartsColumn &c)
{
CQChartsUtil::testAndSet(column_, c, [&]() { redraw(); } );
}
void
CQChartsAxis::
setDataLabels(bool b)
{
CQChartsUtil::testAndSet(dataLabels_, b, [&]() { redraw(); } );
}
//---
QString
CQChartsAxis::
format() const
{
if (formatStr_.length())
return formatStr_;
#if 0
if (column().isValid()) {
QString typeStr;
if (! plot()->columnTypeStr(column(), typeStr))
return "";
return typeStr;
}
#endif
return "";
}
bool
CQChartsAxis::
setFormat(const QString &formatStr)
{
CQChartsUtil::testAndSet(formatStr_, formatStr, [&]() {
#if 0
if (column().isValid()) {
auto *plot = const_cast<Plot *>(plot_);
if (! plot->setColumnTypeStr(column(), typeStr))
return false;
}
#endif
redraw();
} );
return true;
}
//---
void
CQChartsAxis::
setMaxFitExtent(double r)
{
CQChartsUtil::testAndSet(maxFitExtent_, r, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setLabel(const CQChartsOptString &str)
{
CQChartsUtil::testAndSet(label_, str, [&]() { redraw(); } );
}
void
CQChartsAxis::
setLabelStr(const QString &str)
{
if (label_.stringOr() != str) {
label_.setString(str); redraw();
}
}
void
CQChartsAxis::
setDefLabel(const QString &str, bool notify)
{
if (label_.defValue() != str) {
label_.setDefValue(str);
if (notify)
redraw();
}
}
void
CQChartsAxis::
setUserLabel(const QString &str)
{
CQChartsUtil::testAndSet(userLabel_, str, [&]() { redraw(); } );
}
void
CQChartsAxis::
setScaleLabelFont(bool b)
{
CQChartsUtil::testAndSet(scaleLabelFont_, b, [&]() { redraw(); } );
}
void
CQChartsAxis::
setScaleLabelExtent(const Length &l)
{
CQChartsUtil::testAndSet(scaleLabelExtent_, l, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setGridLinesDisplayed(const GridLinesDisplayed &d)
{
CQChartsUtil::testAndSet(gridLinesDisplayed_, d, [&]() { redraw(); } );
}
void
CQChartsAxis::
setGridFillDisplayed(const GridFillDisplayed &d)
{
CQChartsUtil::testAndSet(gridFillDisplayed_, d, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setGridMid(bool b)
{
CQChartsUtil::testAndSet(gridMid_, b, [&]() { redraw(); } );
}
void
CQChartsAxis::
setGridAbove(bool b)
{
CQChartsUtil::testAndSet(gridAbove_, b, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setTicksDisplayed(const TicksDisplayed &d)
{
CQChartsUtil::testAndSet(ticksDisplayed_, d, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setMajorTickLen(int i)
{
CQChartsUtil::testAndSet(majorTickLen_, i, [&]() { redraw(); } );
}
void
CQChartsAxis::
setMinorTickLen(int i)
{
CQChartsUtil::testAndSet(minorTickLen_, i, [&]() { redraw(); } );
}
void
CQChartsAxis::
setTickInside(bool b)
{
CQChartsUtil::testAndSet(tickInside_, b, [&]() { redraw(); } );
}
void
CQChartsAxis::
setMirrorTicks(bool b)
{
CQChartsUtil::testAndSet(mirrorTicks_, b, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setTickLabelAutoHide(bool b)
{
CQChartsUtil::testAndSet(tickLabelAutoHide_, b, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setTickSpaces(double *tickSpaces, uint numTickSpaces)
{
tickSpaces_.resize(numTickSpaces);
memcpy(&tickSpaces_[0], tickSpaces, numTickSpaces*sizeof(double));
}
//---
void
CQChartsAxis::
setTickLabelPlacement(const CQChartsAxisTickLabelPlacement &p)
{
CQChartsUtil::testAndSet(tickLabelPlacement_, p, [&]() {
emit tickPlacementChanged();
redraw();
} );
}
//---
void
CQChartsAxis::
setIncludeZero(bool b)
{
CQChartsUtil::testAndSet(includeZero_, b, [&]() { updatePlotRange(); } );
}
//---
void
CQChartsAxis::
setAnnotation(bool b)
{
CQChartsUtil::testAndSet(annotation_, b, [&]() { redraw(); } );
}
void
CQChartsAxis::
setAllowHtmlLabels(bool b)
{
CQChartsUtil::testAndSet(allowHtmlLabels_, b, [&]() { redraw(); } );
}
//---
void
CQChartsAxis::
setValueType(const CQChartsAxisValueType &v, bool notify)
{
CQChartsUtil::testAndSet(valueType_, v, [&]() {
needsCalc_ = true;
if (notify) updatePlotRangeAndObjs();
} );
}
//---
void
CQChartsAxis::
calcAndRedraw()
{
needsCalc_ = true;
if (isUpdatesEnabled())
redraw();
}
void
CQChartsAxis::
updateCalc() const
{
if (needsCalc_) {
auto *th = const_cast<CQChartsAxis *>(this);
th->needsCalc_ = false;
th->calc();
}
}
void
CQChartsAxis::
calc()
{
interval_.setStart(valueStart_.realOr(start()));
interval_.setEnd (valueEnd_ .realOr(end ()));
interval_.setIntegral(isIntegral());
interval_.setDate (isDate ());
interval_.setLog (isLog ());
if (majorIncrement().isSet())
interval_.setMajorIncrement(majorIncrement().integer());
else
interval_.setMajorIncrement(0);
if (tickIncrement().isSet())
interval_.setTickIncrement(tickIncrement().integer());
else
interval_.setTickIncrement(0);
numMajorTicks_ = std::max(interval_.calcNumMajor(), 1);
numMinorTicks_ = std::max(interval_.calcNumMinor(), 1);
calcIncrement_ = interval_.calcIncrement();
calcStart_ = interval_.calcStart ();
calcEnd_ = interval_.calcEnd ();
//std::cerr << "numMajorTicks: " << numMajorTicks_ << "\n";
//std::cerr << "numMinorTicks: " << numMinorTicks_ << "\n";
//std::cerr << "calcIncrement: " << calcIncrement() << "\n";
//std::cerr << "calcStart : " << calcStart() << "\n";
//std::cerr << "calcEnd : " << calcEnd() << "\n";
emit ticksChanged();
}
double
CQChartsAxis::
minorIncrement() const
{
if (numMajorTicks() > 0 && numMinorTicks() > 0)
return (calcEnd() - calcStart())/(numMajorTicks()*numMinorTicks());
return 0.0;
}
QString
CQChartsAxis::
valueStr(double pos) const
{
return valueStr(plot(), pos);
}
QString
CQChartsAxis::
valueStr(const Plot *plot, double pos) const
{
using ModelIndex = CQChartsModelIndex;
if (isLog())
pos = plot->expValue(pos);
QVariant valuePos(pos);
if (isIntegral()) {
long ipos = long(pos);
if (hasTickLabel(ipos))
return tickLabel(ipos);
if (isRequireTickLabel())
return "";
valuePos = QVariant(int(ipos));
}
if (formatStr_.length()) {
QString str;
if (CQChartsModelUtil::formatColumnTypeValue(plot->charts(), plot->model().data(),
column(), formatStr_, valuePos, str))
return str;
}
if (column().isValid()) {
QString str;
if (CQChartsModelUtil::formatColumnValue(plot->charts(), plot->model().data(),
column(), valuePos, str))
return str;
if (isDataLabels()) {
int row = int(pos);
QModelIndex parent; // TODO: support parent
ModelIndex columnInd(plot, row, column(), parent);
bool ok;
auto header = plot->modelValue(columnInd, ok);
if (header.isValid()) {
QString headerStr;
CQChartsVariant::toString(header, headerStr);
return headerStr;
}
}
}
if (isIntegral())
return CQChartsUtil::formatInteger(long(pos));
else
return CQChartsUtil::formatReal(pos);
}
void
CQChartsAxis::
updatePlotPosition()
{
auto *plot = const_cast<Plot *>(plot_);
plot->updateMargins();
}
bool
CQChartsAxis::
contains(const Point &p) const
{
if (! isVisible())
return false;
return bbox().inside(p);
}
void
CQChartsAxis::
redraw(bool wait)
{
auto *plot = const_cast<Plot *>(plot_);
if (plot) {
if (wait) {
if (isDrawAll()) {
plot->drawObjs();
}
else {
plot->drawBackground();
plot->drawForeground();
}
}
else {
if (isDrawAll()) {
plot->invalidateLayers();
}
else {
plot->invalidateLayer(CQChartsBuffer::Type::BACKGROUND);
plot->invalidateLayer(CQChartsBuffer::Type::FOREGROUND);
}
}
}
emit appearanceChanged();
}
void
CQChartsAxis::
updatePlotRange()
{
auto *plot = const_cast<Plot *>(plot_);
plot->updateRange();
}
void
CQChartsAxis::
updatePlotRangeAndObjs()
{
auto *plot = const_cast<Plot *>(plot_);
plot->updateRangeAndObjs();
}
CQChartsEditHandles *
CQChartsAxis::
editHandles() const
{
if (! editHandles_) {
auto *th = const_cast<CQChartsAxis *>(this);
th->editHandles_ = std::make_unique<EditHandles>(plot_, EditHandles::Mode::MOVE);
}
return editHandles_.get();
}
//---
bool
CQChartsAxis::
editPress(const Point &p)
{
editHandles()->setDragPos(p);
double apos1, apos2;
calcPos(plot(), apos1, apos2);
setPosition(CQChartsOptReal(apos1));
return true;
}
bool
CQChartsAxis::
editMove(const Point &p)
{
const auto &dragPos = editHandles()->dragPos();
double dx = p.x - dragPos.x;
double dy = p.y - dragPos.y;
double apos;
if (isHorizontal())
apos = position().realOr(0.0) + dy;
else
apos = position().realOr(0.0) + dx;
setPosition(CQChartsOptReal(apos));
editHandles()->setDragPos(p);
redraw(/*wait*/false);
return true;
}
bool
CQChartsAxis::
editMotion(const Point &p)
{
return editHandles()->selectInside(p);
}
void
CQChartsAxis::
editMoveBy(const Point &d)
{
double apos1, apos2;
calcPos(plot(), apos1, apos2);
double apos;
if (isHorizontal())
apos = apos1 + d.y;
else
apos = apos1 + d.x;
setPosition(CQChartsOptReal(apos));
redraw(/*wait*/false);
}
//---
void
CQChartsAxis::
setPen(PenBrush &penBrush, const CQChartsPenData &penData) const
{
plot()->setPen(penBrush, penData);
}
bool
CQChartsAxis::
isDrawGrid() const
{
return (isMajorGridLinesDisplayed() || isMinorGridLinesDisplayed() || isMajorGridFilled());
}
void
CQChartsAxis::
drawGrid(const Plot *plot, PaintDevice *device) const
{
if (! isDrawGrid())
return;
//---
auto dataRange = plot->calcDataRange();
double amin = start();
double amax = end ();
double dmin, dmax;
if (isHorizontal()) {
dmin = dataRange.getYMin();
dmax = dataRange.getYMax();
}
else {
dmin = dataRange.getXMin();
dmax = dataRange.getXMax();
}
auto a1 = windowToPixel(plot, amin, dmin);
auto a2 = windowToPixel(plot, amax, dmax);
//---
device->save();
//---
double inc = calcIncrement();
double inc1 = (isLog() ? plot->expValue(inc) : inc)/numMinorTicks();
//---
// draw fill
if (isMajorGridFilled()) {
auto dataRect = plot->calcDataPixelRect();
device->setClipRect(dataRect);
//---
PenBrush penBrush;
auto fillColor = interpAxesGridFillColor(ColorInd());
plot->setPenBrush(penBrush,
PenData(false), BrushData(true, fillColor, axesGridFillAlpha(), axesGridFillPattern()));
//---
if (numMajorTicks() < maxMajorTicks()) {
double pos1;
if (isDate()) {
pos1 = interval_.interval(0);
if (isGridMid())
pos1 = (pos1 + interval_.interval(1))/2;
}
else {
pos1 = calcStart();
if (isGridMid())
pos1 += inc/2.0;
}
double pos2 = pos1;
for (uint i = 0; i < numMajorTicks() + 1; i++) {
// fill on alternate gaps
if (i & 1) {
if (pos2 >= amin || pos1 <= amax) {
double pos3 = std::max(pos1, amin);
double pos4 = std::min(pos2, amax);
auto pp1 = plot->windowToPixel(Point(pos3, pos1));
auto pp2 = plot->windowToPixel(Point(pos4, pos2));
BBox bbox;
if (isHorizontal())
bbox = BBox(pp1.x, a1.y, pp2.x, a2.y);
else
bbox = BBox(a1.x, pp1.y, a2.x, pp2.y);
CQChartsDrawUtil::setPenBrush(device, penBrush);
device->fillRect(bbox);
}
}
//---
pos1 = pos2;
if (isDate())
pos2 = interval_.interval(int(i + 1));
else
pos2 = pos1 + inc;
}
}
}
//---
// draw grid lines
if (isMajorGridLinesDisplayed() || isMinorGridLinesDisplayed()) {
if (numMajorTicks() < maxMajorTicks()) {
double pos1;
if (isDate()) {
pos1 = interval_.interval(0);
if (isGridMid())
pos1 = (pos1 + interval_.interval(1))/2;
}
else {
pos1 = calcStart();
if (isGridMid())
pos1 += inc/2.0;
}
// TODO: draw minor then major in case of overlap (e.g. log axis)
for (uint i = 0; i < numMajorTicks() + 1; i++) {
// draw major line (grid and tick)
if (pos1 >= amin && pos1 <= amax) {
// draw major grid line if major or minor displayed
if (isMajorGridLinesDisplayed())
drawMajorGridLine(plot, device, pos1, dmin, dmax);
else if (isMinorGridLinesDisplayed())
drawMinorGridLine(plot, device, pos1, dmin, dmax);
}
if (isMinorGridLinesDisplayed()) {
for (uint j = 1; j < numMinorTicks(); j++) {
double pos2 = pos1 + (isLog() ? plot->logValue(j*inc1) : j*inc1);
if (isIntegral() && ! CMathUtil::isInteger(pos2))
continue;
// draw minor grid line
if (pos2 >= amin && pos2 <= amax)
drawMinorGridLine(plot, device, pos2, dmin, dmax);
}
}
//---
if (isDate())
pos1 = interval_.interval(int(i + 1));
else
pos1 += inc;
}
}
}
//---
device->restore();
}
void
CQChartsAxis::
drawAt(double pos, const Plot *plot, PaintDevice *device) const
{
auto *th = const_cast<CQChartsAxis *>(this);
auto position = CQChartsOptReal(pos);
std::swap(th->position_, position);
draw(plot, device);
std::swap(th->position_, position);
}
void
CQChartsAxis::
draw(const Plot *plot, PaintDevice *device, bool usePen, bool forceColor) const
{
usePen_ = usePen;
forceColor_ = forceColor;
savePen_ = device->pen();
//---
fitBBox_ = BBox(); // fit box
fitLBBox_ = BBox(); // label fit box
fitTLBBox_ = BBox(); // tick label fit box
bbox_ = BBox();
//---
double apos1, apos2;
calcPos(plot, apos1, apos2);
double amin = start();
double amax = end ();
if (isHorizontal()) {
bbox_ += Point(amin, apos1);
bbox_ += Point(amax, apos1);
}
else {
bbox_ += Point(apos1, amin);
bbox_ += Point(apos1, amax);
}
fitBBox_ = bbox();
//---
device->save();
//---
// axis line
bool lineVisible = isAxesLines();
if (usePen_)
lineVisible = (savePen_.style() != Qt::NoPen);
if (lineVisible)
drawLine(plot, device, apos1, amin, amax);
//---
double inc = calcIncrement();
double inc1 = (isLog() ? plot->expValue(inc) : inc)/numMinorTicks();
//---
auto mapPos = [&](double pos) {
if (! valueStart_.isSet() && ! valueEnd_.isSet())
return pos;
return CMathUtil::map(pos, valueStart_.realOr(start()), valueEnd_.realOr(end()),
start(), end());
};
//---
double pos1;
if (isDate())
pos1 = interval_.interval(0);
else
pos1 = calcStart();
int tlen2 = majorTickLen();
int tgap = 2;
//---
lbbox_ = BBox();
//---
//lastTickLabelRect_ = BBox();
textPlacer_.clear();
if (customTickLabels_.size()) {
for (const auto &p : customTickLabels_) {
double pos = p.first;
if (pos < amin || pos > amax)
continue;
// draw major line (grid and tick)
if (isMajorTicksDisplayed()) {
drawMajorTickLine(plot, device, apos1, pos, isTickInside());
if (isMirrorTicks())
drawMajorTickLine(plot, device, apos2, pos, ! isTickInside());
}
//---
// draw major tick label
if (isAxesTickLabelTextVisible())
drawTickLabel(plot, device, apos1, pos, pos, isTickInside());
}
}
else if (isRequireTickLabel() && tickLabels_.size()) {
for (const auto &p : tickLabels_) {
double pos = p.first;
if (pos < amin || pos > amax)
continue;
// draw major line (grid and tick)
if (isMajorTicksDisplayed()) {
drawMajorTickLine(plot, device, apos1, pos, isTickInside());
if (isMirrorTicks())
drawMajorTickLine(plot, device, apos2, pos, ! isTickInside());
}
//---
// draw major tick label
if (isAxesTickLabelTextVisible())
drawTickLabel(plot, device, apos1, pos, pos, isTickInside());
}
}
else {
double dt =
(tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN ? -0.5 : 0.0);
if (numMajorTicks() < maxMajorTicks()) {
for (uint i = 0; i < numMajorTicks() + 1; i++) {
double pos2 = pos1 + dt;
double mpos1 = mapPos(pos1);
double mpos2 = mapPos(pos2);
// draw major line (grid and tick)
if (mpos2 >= amin && mpos2 <= amax) {
// draw major tick (or minor tick if major ticks off and minor ones on)
if (isMajorTicksDisplayed()) {
drawMajorTickLine(plot, device, apos1, mpos1, isTickInside());
if (isMirrorTicks())
drawMajorTickLine(plot, device, apos2, mpos1, ! isTickInside());
}
else if (isMinorTicksDisplayed()) {
drawMinorTickLine(plot, device, apos1, mpos1, isTickInside());
if (isMirrorTicks())
drawMinorTickLine(plot, device, apos2, mpos1, ! isTickInside());
}
}
// draw minor tick lines (grid and tick)
if (isMinorTicksDisplayed() && i < numMajorTicks()) {
for (uint j = 1; j < numMinorTicks(); j++) {
double pos2 = pos1 + (isLog() ? plot->logValue(j*inc1) : j*inc1);
if (isIntegral() && ! CMathUtil::isInteger(pos2))
continue;
double mpos2 = mapPos(pos2);
// draw minor tick line
if (mpos2 >= amin && mpos2 <= amax) {
drawMinorTickLine(plot, device, apos1, mpos2, isTickInside());
if (isMirrorTicks())
drawMinorTickLine(plot, device, apos2, mpos2, ! isTickInside());
}
}
}
//---
if (isAxesTickLabelTextVisible()) {
// draw major tick label
double mpos1 = mapPos(pos1);
if (mpos1 >= amin && mpos1 <= amax) {
drawTickLabel(plot, device, apos1, mpos1, pos1, isTickInside());
}
}
//---
if (isDate())
pos1 = interval_.interval(int(i + 1));
else
pos1 += inc;
}
}
}
drawAxisTickLabelDatas(plot, device);
//---
// fix range if not set
if (! lbbox_.isSet()) {
auto a1 = windowToPixel(plot, amin, apos1);
auto a2 = windowToPixel(plot, amax, apos1);
if (isHorizontal()) {
bool isPixelBottom =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertY()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertY());
double dys = (isPixelBottom ? 1 : -1);
a2.y += dys*(tlen2 + tgap);
lbbox_ += Point(a1.x, a1.y);
lbbox_ += Point(a2.x, a2.y);
}
else {
bool isPixelLeft =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertX()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertX());
double dxs = (isPixelLeft ? 1 : -1);
a2.x += dxs*(tlen2 + tgap);
lbbox_ += Point(a1.x, a1.y);
lbbox_ += Point(a2.x, a2.y);
}
}
//---
if (isAxesLabelTextVisible()) {
auto text = userLabel();
bool allowHtml = true;
if (! text.length()) {
text = label().string();
allowHtml = false;
}
if (! text.length())
text = label().defValue();
drawAxisLabel(plot, device, apos1, amin, amax, text, allowHtml);
}
//---
if (plot->showBoxes()) {
plot->drawWindowColorBox(device, bbox(), Qt::blue);
plot->drawColorBox(device, lbbox_, Qt::green);
}
//---
device->restore();
//----
double extent = std::max(maxFitExtent()/100.0, 0.0);
double fitMin = fitBBox_.getMinExtent(isHorizontal());
double fitMax = fitBBox_.getMaxExtent(isHorizontal());
double fitLen = fitMax - fitMin;
auto adjustLabelFitBox = [&](BBox &bbox) {
if (fitLen <= 0) return bbox;
double boxMin = bbox.getMinExtent(isHorizontal());
double boxMax = bbox.getMaxExtent(isHorizontal());
double f1 = (fitMin - boxMin)/fitLen;
double f2 = (boxMax - fitMax)/fitLen;
if (f1 <= extent && f2 <= extent)
return bbox;
auto bbox1 = bbox;
if (f1 > extent)
bbox1.setMinExtent(isHorizontal(), fitMin - extent*fitLen);
if (f2 > extent)
bbox1.setMaxExtent(isHorizontal(), fitMax + extent*fitLen);
bbox1.update();
return bbox1;
};
if (fitTLBBox_.isSet())
fitBBox_ += adjustLabelFitBox(fitTLBBox_);
if (fitLBBox_.isSet())
fitBBox_ += adjustLabelFitBox(fitLBBox_);
//---
usePen_ = false;
forceColor_ = false;
//---
auto *th = const_cast<CQChartsAxis *>(this);
th->rect_ = bbox_;
}
void
CQChartsAxis::
drawEditHandles(PaintDevice *device) const
{
assert(view()->mode() == CQChartsView::Mode::EDIT && isSelected());
setEditHandlesBBox();
editHandles()->draw(device);
}
void
CQChartsAxis::
setEditHandlesBBox() const
{
auto *th = const_cast<CQChartsAxis *>(this);
th->editHandles()->setBBox(this->bbox());
}
void
CQChartsAxis::
getTickLabelsPositions(std::set<int> &positions) const
{
if (numMajorTicks() >= maxMajorTicks())
return;
double pos;
if (isDate())
pos = interval_.interval(0);
else
pos = calcStart();
double inc = calcIncrement();
for (uint i = 0; i < numMajorTicks() + 1; i++) {
positions.insert(int(pos));
if (isDate())
pos = interval_.interval(int(i + 1));
else
pos += inc;
}
}
void
CQChartsAxis::
calcPos(const Plot *plot, double &apos1, double &apos2) const
{
if (position().isSet()) {
apos1 = position().real();
apos2 = apos1;
return;
}
//---
auto dataRange = plot->calcDataRange();
if (dataRange.isSet())
dataRange += plot->extraFitBBox();
else
dataRange = BBox(0.0, 0.0, 1.0, 1.0);
//---
if (isHorizontal()) {
bool isWindowBottom = (side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT);
double ymin = dataRange.getYMin();
double ymax = dataRange.getYMax();
apos1 = (isWindowBottom ? ymin : ymax);
apos2 = (isWindowBottom ? ymax : ymin);
}
else {
bool isWindowLeft = (side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT);
double xmin = dataRange.getXMin();
double xmax = dataRange.getXMax();
apos1 = (isWindowLeft ? xmin : xmax);
apos2 = (isWindowLeft ? xmax : xmin);
}
}
void
CQChartsAxis::
drawLine(const Plot *, PaintDevice *device, double apos, double amin, double amax) const
{
PenBrush penBrush;
setAxesLineDataPen(penBrush.pen, ColorInd());
if (! usePen_)
device->setPen(penBrush.pen);
else
device->setPen(savePen_);
//---
if (isHorizontal())
device->drawLine(Point(amin, apos), Point(amax, apos));
else
device->drawLine(Point(apos, amin), Point(apos, amax));
}
void
CQChartsAxis::
drawMajorGridLine(const Plot *, PaintDevice *device, double apos, double dmin, double dmax) const
{
PenBrush penBrush;
setAxesMajorGridLineDataPen(penBrush.pen, ColorInd());
if (forceColor_)
penBrush.pen.setColor(savePen_.color());
device->setPen(penBrush.pen);
//---
if (isHorizontal())
device->drawLine(Point(apos, dmin), Point(apos, dmax));
else
device->drawLine(Point(dmin, apos), Point(dmax, apos));
}
void
CQChartsAxis::
drawMinorGridLine(const Plot *, PaintDevice *device, double apos, double dmin, double dmax) const
{
PenBrush penBrush;
setAxesMinorGridLineDataPen(penBrush.pen, ColorInd());
if (forceColor_)
penBrush.pen.setColor(savePen_.color());
device->setPen(penBrush.pen);
//---
if (isHorizontal())
device->drawLine(Point(apos, dmin), Point(apos, dmax));
else
device->drawLine(Point(dmin, apos), Point(dmax, apos));
}
void
CQChartsAxis::
drawMajorTickLine(const Plot *plot, PaintDevice *device,
double apos, double tpos, bool inside) const
{
drawTickLine(plot, device, apos, tpos, inside, /*major*/true);
}
void
CQChartsAxis::
drawMinorTickLine(const Plot *plot, PaintDevice *device,
double apos, double tpos, bool inside) const
{
drawTickLine(plot, device, apos, tpos, inside, /*major*/false);
}
void
CQChartsAxis::
drawTickLine(const Plot *plot, PaintDevice *device,
double apos, double tpos, bool inside, bool major) const
{
int tlen = (major ? majorTickLen() : minorTickLen());
Point pp;
if (isHorizontal()) {
if (major && tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
pp = Point(tpos - 0.5, apos);
else
pp = Point(tpos, apos);
}
else {
if (major && tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
pp = Point(apos, tpos - 0.5);
else
pp = Point(apos, tpos);
}
//---
PenBrush penBrush;
setAxesLineDataPen(penBrush.pen, ColorInd());
if (! usePen_)
device->setPen(penBrush.pen);
else
device->setPen(savePen_);
//---
if (isHorizontal()) {
bool isWindowBottom = (side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT);
bool isPixelBottom =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertY()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertY());
int pys = (isPixelBottom ? 1 : -1);
int dt1 = pys*tlen;
double adt1 = plot->pixelToWindowHeight(dt1);
if (inside)
device->drawLine(Point(pp.x, pp.y), Point(pp.x, pp.y + adt1));
else {
device->drawLine(Point(pp.x, pp.y), Point(pp.x, pp.y - adt1));
Point p;
if (isWindowBottom)
p = Point(tpos, apos - adt1);
else
p = Point(tpos, apos + adt1);
bbox_ += p;
fitBBox_ += p;
}
}
else {
bool isWindowLeft = (side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT);
bool isPixelLeft =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertX()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertX());
int pxs = (isPixelLeft ? -1 : 1);
int dt1 = pxs*tlen;
double adt1 = plot->pixelToWindowWidth(dt1);
if (inside)
device->drawLine(Point(pp.x, pp.y), Point(pp.x + adt1, pp.y));
else {
device->drawLine(Point(pp.x, pp.y), Point(pp.x - adt1, pp.y));
Point p;
if (isWindowLeft)
p = Point(apos - adt1, tpos);
else
p = Point(apos + adt1, tpos);
bbox_ += p;
fitBBox_ += p;
}
}
}
void
CQChartsAxis::
drawTickLabel(const Plot *plot, PaintDevice *device,
double apos, double tpos, double value, bool inside) const
{
auto text = valueStr(plot, value);
if (! text.length()) return;
//---
int tgap = 2;
int tlen1 = majorTickLen();
int tlen2 = minorTickLen();
auto pp = windowToPixel(plot, tpos, apos);
//---
plot->setPainterFont(device, axesTickLabelTextFont());
auto angle = axesTickLabelTextAngle();
auto clipLength = plot_->lengthPixelWidth(axesTickLabelTextClipLength());
auto clipElide = axesTickLabelTextClipElide();
QFontMetricsF fm(device->font());
auto text1 = CQChartsDrawUtil::clipTextToLength(text, device->font(), clipLength, clipElide);
double ta = fm.ascent();
double td = fm.descent();
double tw = fm.width(text1); // TODO: support HTML
if (isHorizontal()) {
bool isPixelBottom =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertY()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertY());
double tyo = 0.0;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
tyo = tgap;
else
tyo = tlen1 + tgap;
}
else {
if (inside)
tyo = tgap;
else
tyo = tlen2 + tgap;
}
//---
BBox tbbox;
//bool visible = true;
if (isPixelBottom) {
Qt::Alignment align = Qt::AlignHCenter;
/*
if (! plot->isInvertY())
align |= Qt::AlignTop;
else
align |= Qt::AlignBottom;
*/
align |= Qt::AlignTop;
Point pt(pp.x, pp.y + tyo);
if (angle.isZero()) {
double atw = plot->pixelToWindowWidth (tw);
double wta = plot->pixelToWindowHeight(ta);
double wtd = plot->pixelToWindowHeight(td);
double wth = wta + wtd;
double atm;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
atm = plot->pixelToWindowHeight(tgap);
else
atm = plot->pixelToWindowHeight(tlen1 + tgap);
}
else {
if (inside)
atm = plot->pixelToWindowHeight(tgap);
else
atm = plot->pixelToWindowHeight(tlen2 + tgap);
}
lbbox_ += Point(pt.x, pt.y );
lbbox_ += Point(pt.x, pt.y + (ta + td));
double xpos = 0.0;
double ypos = apos - boolFactor(! plot_->isInvertY())*(wth + atm);
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
xpos = tpos - atw/2;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
xpos = tpos - atw;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
xpos = tpos;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
xpos = tpos - 0.5;
if (! plot_->isInvertY())
tbbox = BBox(xpos, ypos, xpos + atw, ypos + wth);
else
tbbox = BBox(xpos, ypos - wth, xpos + atw, ypos);
}
else {
TextOptions options;
options.angle = angle;
options.align = align;
options.clipLength = clipLength;
options.clipElide = clipElide;
auto rrect = CQChartsRotatedText::calcBBox(pt.x, pt.y, text, device->font(),
options, 0, /*alignBox*/true);
lbbox_ += rrect;
tbbox = plot->pixelToWindow(rrect);
}
#if 0
if (isTickLabelAutoHide()) {
if (lastTickLabelRect_.isSet() && lastTickLabelRect_.overlaps(tbbox))
visible = false;
}
#endif
if (angle.isZero()) {
double ty = pt.y + ta;
Point p;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
p = Point(pt.x - tw/2 , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
p = Point(pt.x - tw , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
p = Point(pt.x , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
p = Point(pt.x - plot->windowToPixelWidth(0.5), ty);
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(p, tbbox, text));
}
else {
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(pt, tbbox, text, angle, align));
}
#if 0
if (plot->showBoxes()) {
if (visible)
plot->drawWindowColorBox(device, tbbox);
}
#endif
#if 0
if (visible)
lastTickLabelRect_ = tbbox;
#endif
}
else {
Qt::Alignment align = Qt::AlignHCenter;
/*
if (! plot->isInvertY())
align |= Qt::AlignBottom;
else
align |= Qt::AlignTop;
*/
align |= Qt::AlignBottom;
Point pt(pp.x, pp.y - tyo);
if (angle.isZero()) {
double atw = plot->pixelToWindowWidth (tw);
double wta = plot->pixelToWindowHeight(ta);
double wtd = plot->pixelToWindowHeight(td);
double wth = wta + wtd;
double atm;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
atm = plot->pixelToWindowHeight(tgap);
else
atm = plot->pixelToWindowHeight(tlen1 + tgap);
}
else {
if (inside)
atm = plot->pixelToWindowHeight(tgap);
else
atm = plot->pixelToWindowHeight(tlen2 + tgap);
}
lbbox_ += Point(pt.x, pt.y );
lbbox_ += Point(pt.x, pt.y - (ta + td));
double xpos = 0.0;
double ypos = apos + boolFactor(! plot_->isInvertY())*atm;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
xpos = tpos - atw/2;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
xpos = tpos - atw;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
xpos = tpos;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
xpos = tpos - 0.5;
if (! plot_->isInvertY())
tbbox = BBox(xpos, ypos, xpos + atw, ypos + wth);
else
tbbox = BBox(xpos, ypos - wth, xpos + atw, ypos);
}
else {
TextOptions options;
options.angle = angle;
options.align = align;
options.clipLength = clipLength;
options.clipElide = clipElide;
auto rrect = CQChartsRotatedText::calcBBox(pt.x, pt.y, text, device->font(),
options, 0, /*alignBox*/true);
lbbox_ += rrect;
tbbox = plot->pixelToWindow(rrect);
}
#if 0
if (isTickLabelAutoHide()) {
if (lastTickLabelRect_.isSet() && lastTickLabelRect_.overlaps(tbbox))
visible = false;
}
#endif
if (angle.isZero()) {
double ty = pt.y - td;
Point p;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
p = Point(pt.x - tw/2 , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
p = Point(pt.x - tw , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
p = Point(pt.x , ty);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
p = Point(pt.x - plot->windowToPixelWidth(0.5), ty);
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(p, tbbox, text));
}
else {
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(pt, tbbox, text, angle, align));
}
#if 0
if (plot->showBoxes()) {
if (visible)
plot->drawWindowColorBox(device, tbbox);
}
#endif
#if 0
if (visible)
lastTickLabelRect_ = tbbox;
#endif
}
bbox_ += tbbox;
fitTLBBox_ += tbbox;
}
else {
bool isPixelLeft =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertX()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertX());
double txo = 0.0;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
txo = tgap;
else
txo = tlen1 + tgap;
}
else {
if (inside)
txo = tgap;
else
txo = tlen2 + tgap;
}
//---
BBox tbbox;
//bool visible = true;
if (isPixelLeft) {
Qt::Alignment align = Qt::AlignVCenter;
/*
if (! plot->isInvertX())
align |= Qt::AlignRight;
else
align |= Qt::AlignLeft;
*/
align |= Qt::AlignRight;
Point pt(pp.x - txo, pp.y);
if (angle.isZero()) {
double atw = plot->pixelToWindowWidth (tw);
double wta = plot->pixelToWindowHeight(ta);
double wtd = plot->pixelToWindowHeight(td);
double wth = wta + wtd;
double atm;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
atm = plot->pixelToWindowWidth(tgap);
else
atm = plot->pixelToWindowWidth(tlen1 + tgap);
}
else {
if (inside)
atm = plot->pixelToWindowWidth(tgap);
else
atm = plot->pixelToWindowWidth(tlen2 + tgap);
}
lbbox_ += Point(pt.x , pt.y);
lbbox_ += Point(pt.x - tw, pt.y);
double xpos = apos - boolFactor(! plot_->isInvertX())*(atw + atm);
double ypos = 0.0;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
ypos = tpos - wth/2;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
ypos = tpos - wth;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
ypos = tpos;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
ypos = tpos - 0.5 - wta;
if (! plot_->isInvertX())
tbbox = BBox(xpos, ypos, xpos + atw, ypos + wth);
else
tbbox = BBox(xpos - atw, ypos, xpos, ypos + wth);
}
else {
TextOptions options;
options.angle = angle;
options.align = align;
options.clipLength = clipLength;
options.clipElide = clipElide;
auto rrect = CQChartsRotatedText::calcBBox(pt.x, pt.y, text, device->font(),
options, 0, /*alignBox*/true);
lbbox_ += rrect;
tbbox = plot->pixelToWindow(rrect);
}
#if 0
if (isTickLabelAutoHide()) {
if (lastTickLabelRect_.isSet() && lastTickLabelRect_.overlaps(tbbox))
visible = false;
}
#endif
if (angle.isZero()) {
double tx = pt.x - tw;
Point p;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
p = Point(tx, pt.y + ta/2);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
p = Point(tx, pt.y + ta );
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
p = Point(tx, pt.y - td );
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
p = Point(tx, pt.y - plot->windowToPixelHeight(0.5) + ta);
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(p, tbbox, text));
}
else {
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(pt, tbbox, text, angle, align));
}
#if 0
if (plot->showBoxes()) {
if (visible)
plot->drawWindowColorBox(device, tbbox);
}
#endif
#if 0
if (visible)
lastTickLabelRect_ = tbbox;
#endif
}
else {
Qt::Alignment align = Qt::AlignVCenter;
/*
if (! isPixelLeft)
align |= Qt::AlignLeft;
else
align |= Qt::AlignRight;
*/
align |= Qt::AlignLeft;
Point pt(pp.x + txo, pp.y);
if (angle.isZero()) {
double atw = plot->pixelToWindowWidth (tw);
double wta = plot->pixelToWindowHeight(ta);
double wtd = plot->pixelToWindowHeight(td);
double wth = wta + wtd;
double atm;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE) {
if (inside)
atm = plot->pixelToWindowWidth(tgap);
else
atm = plot->pixelToWindowWidth(tlen1 + tgap);
}
else {
if (inside)
atm = plot->pixelToWindowWidth(tgap);
else
atm = plot->pixelToWindowWidth(tlen2 + tgap);
}
lbbox_ += Point(pt.x , pt.y);
lbbox_ += Point(pt.x + tw, pt.y);
double xpos = apos + boolFactor(! plot_->isInvertX())*atm;
double ypos = 0.0;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
ypos = tpos - wth/2;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
ypos = tpos - wth;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
ypos = tpos;
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
ypos = tpos - 0.5 - wta;
if (! plot_->isInvertX())
tbbox = BBox(xpos, ypos, xpos + atw, ypos + wth);
else
tbbox = BBox(xpos - atw, ypos, xpos, ypos + wth);
}
else {
TextOptions options;
options.angle = angle;
options.align = align;
options.clipLength = clipLength;
options.clipElide = clipElide;
auto rrect = CQChartsRotatedText::calcBBox(pt.x, pt.y, text, device->font(),
options, 0, /*alignBox*/true);
lbbox_ += rrect;
tbbox = plot->pixelToWindow(rrect);
}
#if 0
if (isTickLabelAutoHide()) {
if (lastTickLabelRect_.isSet() && lastTickLabelRect_.overlaps(tbbox))
visible = false;
}
#endif
if (angle.isZero()) {
double tx = pt.x;
Point p;
if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::MIDDLE)
p = Point(tx, pt.y + ta/2);
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BOTTOM_LEFT)
p = Point(tx, pt.y + ta );
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::TOP_RIGHT)
p = Point(tx, pt.y - td );
else if (tickLabelPlacement().type() == CQChartsAxisTickLabelPlacement::Type::BETWEEN)
p = Point(tx, pt.y - plot->windowToPixelHeight(0.5) + ta);
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(p, tbbox, text));
}
else {
textPlacer_.addDrawText(CQChartsAxisTextPlacer::DrawText(pt, tbbox, text, angle, align));
}
#if 0
if (plot->showBoxes()) {
if (visible)
plot->drawWindowColorBox(device, tbbox);
}
#endif
#if 0
if (visible)
lastTickLabelRect_ = tbbox;
#endif
}
bbox_ += tbbox;
fitTLBBox_ += tbbox;
}
}
void
CQChartsAxis::
drawAxisTickLabelDatas(const Plot *plot, PaintDevice *device) const
{
if (textPlacer_.empty())
return;
// clip overlapping labels
if (isTickLabelAutoHide())
textPlacer_.autoHide();
//---
PenBrush tpenBrush;
auto tc = interpAxesTickLabelTextColor(ColorInd());
plot->setPen(tpenBrush, PenData(true, tc, axesTickLabelTextAlpha()));
if (forceColor_)
tpenBrush.pen.setColor(savePen_.color());
device->setPen(tpenBrush.pen);
//---
// html not supported (axis code controls string)
auto textOptions = axesTickLabelTextOptions(device);
textOptions.angle = Angle();
textOptions.align = Qt::AlignHCenter | Qt::AlignVCenter;
textOptions.html = false;
textPlacer_.draw(device, textOptions, plot->showBoxes());
}
void
CQChartsAxis::
drawAxisLabel(const Plot *plot, PaintDevice *device, double apos,
double amin, double amax, const QString &text, bool allowHtml) const
{
if (! text.length())
return;
//---
int tgap = 2;
auto a1 = windowToPixel(plot, amin, apos);
auto a2 = windowToPixel(plot, amax, apos);
auto a3 = windowToPixel(plot, amin, apos);
//---
PenBrush tpenBrush;
auto tc = interpAxesLabelTextColor(ColorInd());
plot->setPen(tpenBrush, PenData(true, tc, axesLabelTextAlpha()));
if (forceColor_)
tpenBrush.pen.setColor(savePen_.color());
device->setPen(tpenBrush.pen);
plot->setPainterFont(device, axesLabelTextFont());
//---
auto html = ((allowHtml || isAllowHtmlLabels()) && isAxesLabelTextHtml());
if (isScaleLabelFont()) {
TextOptions options;
options.html = html;
auto psize = CQChartsDrawUtil::calcTextSize(text, device->font(), options);
auto len = Length::plot(amax - amin);
double plen = 0.0;
if (isHorizontal())
plen = plot_->lengthPixelWidth (len) + plot_->lengthPixelWidth (scaleLabelExtent());
else
plen = plot_->lengthPixelHeight(len) + plot_->lengthPixelHeight(scaleLabelExtent());
double fontScale = (psize.width() > 0.0 ? plen/psize.width() : 1.0);
if (fontScale < 1.0)
device->setFont(CQChartsUtil::scaleFontSize(device->font(), fontScale));
}
//---
auto clipLength = plot_->lengthPixelWidth(axesLabelTextClipLength());
auto clipElide = axesLabelTextClipElide();
QFontMetricsF fm(device->font());
auto text1 = CQChartsDrawUtil::clipTextToLength(text, device->font(), clipLength, clipElide);
double ta = fm.ascent();
double td = fm.descent();
double tw = 0.0;
if (html) {
TextOptions options;
options.html = true;
tw = CQChartsDrawUtil::calcTextSize(text1, device->font(), options).width();
}
else {
tw = fm.width(text1);
}
BBox bbox;
// draw label
if (isHorizontal()) {
double wfh = plot->pixelToWindowHeight(ta + td);
double axm = (a1.x + a2.x)/2 - tw/2;
bool isPixelBottom =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertY()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertY());
//int pys = (isPixelBottom ? 1 : -1);
double ath;
double atw = plot->pixelToWindowWidth(tw/2);
if (isPixelBottom) {
ath = plot->pixelToWindowHeight((lbbox_.getYMax() - a3.y) + tgap) + wfh;
Point pt(axm, lbbox_.getYMax() + ta + tgap);
// angle, align not supported
// formatted not supported (axis code controls string)
// html supported only for user label or annotation axis
auto textOptions = axesLabelTextOptions(device);
textOptions.angle = Angle();
textOptions.align = Qt::AlignLeft;
textOptions.html = html;
textOptions.clipLength = clipLength;
textOptions.clipElide = clipElide;
if (textOptions.html) {
textOptions.align = Qt::AlignCenter;
auto p1 = plot->pixelToWindow(Point(axm + tw/2, lbbox_.getYMax() + (ta + td)/2.0 + tgap));
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/true);
}
else {
auto p1 = plot->pixelToWindow(pt);
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/false);
}
if (! plot_->isInvertY()) {
bbox += Point((amin + amax)/2 - atw, apos - (ath ));
bbox += Point((amin + amax)/2 + atw, apos - (ath - wfh));
}
else {
bbox += Point((amin + amax)/2 - atw, apos + (ath ));
bbox += Point((amin + amax)/2 + atw, apos + (ath - wfh));
}
fitLBBox_ += Point((amin + amax)/2, apos - (ath ));
fitLBBox_ += Point((amin + amax)/2, apos - (ath - wfh));
}
else {
ath = plot->pixelToWindowHeight((a3.y - lbbox_.getYMin()) + tgap) + wfh;
Point pt(axm, lbbox_.getYMin() - td - tgap);
// angle, align not supported
// formatted not supported (axis code controls string)
// html supported only for user label or annotation axis
auto textOptions = axesLabelTextOptions(device);
textOptions.angle = Angle();
textOptions.align = Qt::AlignLeft;
textOptions.html = html;
textOptions.clipLength = clipLength;
textOptions.clipElide = clipElide;
if (textOptions.html) {
textOptions.align = Qt::AlignCenter;
auto p1 = plot->pixelToWindow(Point(axm + tw/2, lbbox_.getYMin() - (ta + td)/2.0 - tgap));
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/true);
}
else {
auto p1 = plot->pixelToWindow(pt);
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/false);
}
if (! plot_->isInvertY()) {
bbox += Point((amin + amax)/2 - atw, apos + (ath ));
bbox += Point((amin + amax)/2 + atw, apos + (ath - wfh));
}
else {
bbox += Point((amin + amax)/2 - atw, apos - (ath ));
bbox += Point((amin + amax)/2 + atw, apos - (ath - wfh));
}
fitLBBox_ += Point((amin + amax)/2, apos + (ath ));
fitLBBox_ += Point((amin + amax)/2, apos + (ath - wfh));
}
}
else {
double wfa = plot->pixelToWindowWidth(ta);
double wfd = plot->pixelToWindowWidth(td);
double wfh = wfa + wfd;
bool isPixelLeft =
(side().type() == CQChartsAxisSide::Type::BOTTOM_LEFT && ! plot->isInvertX()) ||
(side().type() == CQChartsAxisSide::Type::TOP_RIGHT && plot->isInvertX());
//int pxs = (isPixelLeft ? 1 : -1);
double atw;
double ath = plot->pixelToWindowHeight(tw/2.0);
if (isPixelLeft) {
double aym = (a2.y + a1.y)/2.0 + tw/2.0;
atw = plot->pixelToWindowWidth((a3.x - lbbox_.getXMin()) + tgap) + wfh;
//double tx = lbbox_.getXMin() - tgap - td;
double tx = lbbox_.getXMin() - tgap;
auto textOptions = axesLabelTextOptions(device);
textOptions.angle = Angle(90.0);
textOptions.align = Qt::AlignLeft | Qt::AlignBottom;
textOptions.html = html;
textOptions.clipLength = clipLength;
textOptions.clipElide = clipElide;
if (textOptions.html) {
textOptions.align = Qt::AlignCenter;
auto p1 = plot->pixelToWindow(Point(lbbox_.getXMin() - tgap - (ta + td)/2.0,
(a2.y + a1.y)/2));
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/true);
}
else {
auto p1 = plot->pixelToWindow(Point(tx, aym));
CQChartsRotatedText::draw(device, p1, text, textOptions, /*alignBBox*/false);
}
if (! plot_->isInvertX()) {
bbox += Point(apos - (atw ), (amin + amax)/2 - ath);
bbox += Point(apos - (atw - wfh), (amin + amax)/2 + ath);
}
else {
bbox += Point(apos + (atw ), (amin + amax)/2 - ath);
bbox += Point(apos + (atw - wfh), (amin + amax)/2 + ath);
}
fitLBBox_ += Point(apos - (atw ), (amin + amax)/2);
fitLBBox_ += Point(apos - (atw - wfh), (amin + amax)/2);
}
else {
atw = plot->pixelToWindowWidth((lbbox_.getXMax() - a3.x) + tgap) + wfh;
#if 0
double aym = (a2.y + a1.y)/2 - tw/2;
double tx = lbbox_.getXMax() + tgap + td;
#else
double aym = (a2.y + a1.y)/2 + tw/2;
double tx = lbbox_.getXMax() + tgap + ta + td;
#endif
auto textOptions = axesLabelTextOptions(device);
textOptions.angle = Angle(90.0);
textOptions.align = Qt::AlignLeft | Qt::AlignBottom;
textOptions.html = html;
textOptions.clipLength = clipLength;
textOptions.clipElide = clipElide;
if (textOptions.html) {
textOptions.align = Qt::AlignCenter;
auto p1 = plot->pixelToWindow(Point(lbbox_.getXMax() + tgap + (ta + td)/2.0,
(a2.y + a1.y)/2));
CQChartsDrawUtil::drawTextAtPoint(device, p1, text, textOptions, /*centered*/true);
}
else {
auto p1 = plot->pixelToWindow(Point(tx, aym));
CQChartsRotatedText::draw(device, p1, text, textOptions, /*alignBBox*/false);
}
if (! plot_->isInvertX()) {
bbox += Point(apos + (atw ), (amin + amax)/2 - ath);
bbox += Point(apos + (atw - wfh), (amin + amax)/2 + ath);
}
else {
bbox += Point(apos - (atw ), (amin + amax)/2 - ath);
bbox += Point(apos - (atw - wfh), (amin + amax)/2 + ath);
}
fitLBBox_ += Point(apos + (atw ), (amin + amax)/2);
fitLBBox_ += Point(apos + (atw - wfh), (amin + amax)/2);
}
}
if (plot->showBoxes()) {
plot->drawWindowColorBox(device, bbox);
}
bbox_ += bbox;
}
CQChartsGeom::Point
CQChartsAxis::
windowToPixel(const Plot *plot, double x, double y) const
{
if (isHorizontal())
return plot->windowToPixel(Point(x, y));
else
return plot->windowToPixel(Point(y, x));
}
//---
CQChartsGeom::BBox
CQChartsAxis::
fitBBox() const
{
return fitBBox_;
}
| 24.868934 | 98 | 0.603974 | [
"model"
] |
beae804862e0c7eca0d55b1bbe730f80e275e54f | 3,684 | cpp | C++ | src/FSTable.cpp | pperehozhih/transform-cxx | f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48 | [
"BSD-3-Clause"
] | 4 | 2018-09-16T09:55:22.000Z | 2020-12-19T02:02:40.000Z | src/FSTable.cpp | pperehozhih/transform-cxx | f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48 | [
"BSD-3-Clause"
] | null | null | null | src/FSTable.cpp | pperehozhih/transform-cxx | f630079779e9e3cf6d06dcfc04b3ad0bd99d7e48 | [
"BSD-3-Clause"
] | 2 | 2015-11-24T20:27:35.000Z | 2019-06-04T15:23:30.000Z | /*
* FSTable.cpp
* Transform SWF
*
* Created by smackay on Fri Mar 28 2003.
* Copyright (c) 2001-2003 Flagstone Software Ltd. All rights reserved.
*
* This file is part of the Transform SWF library. You may not use this file except in
* compliance with the terms of the license (the 'License') that accompanied this file.
*
* The Original Code and all software distributed under the License are distributed on an
* 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND Flagstone
* HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY
* RIGHTS. Please see the License for the specific language governing rights and limitations
* under the License.
*/
#include "FSTable.h"
#include "FSInputStream.h"
#include "FSOutputStream.h"
using namespace transform;
namespace transform
{
FSTable::FSTable(FSInputStream* aStream) :
FSActionObject(Table),
values()
{
decodeFromStream(aStream);
}
const char* FSTable::className() const
{
const static char _name[] = "FSTable";
return _name;
}
void FSTable::add(const FSVector<FSString>& anArray)
{
for (FSVector<FSString>::const_iterator i = anArray.begin(); i != anArray.end(); i++)
values.push_back(*i);
}
void FSTable::setValues(const char* anArray[], int size)
{
values.resize(size);
for (int i=0; i<size; i++)
values[i] = FSString(anArray[i]);
}
int FSTable::lengthInStream(FSOutputStream* aStream)
{
FSActionObject::lengthInStream(aStream);
length += 2;
for (FSVector<FSString>::const_iterator i = values.begin(); i != values.end(); i++)
length += (*i).length()+1;
return length;
}
void FSTable::encodeToStream(FSOutputStream* aStream)
{
#ifdef _DEBUG
aStream->startEncoding(className());
#endif
FSActionObject::encodeToStream(aStream);
aStream->write(values.size(), FSStream::UnsignedWord, 16);
#ifdef _DEBUG
aStream->startEncoding("array");
#endif
for (FSVector<FSString>::const_iterator i = values.begin(); i != values.end(); i++)
{
aStream->write((byte*)(*i).c_str(), (*i).length());
aStream->write(0, FSStream::UnsignedWord, 8);
}
#ifdef _DEBUG
aStream->endEncoding("array");
aStream->endEncoding(className());
#endif
}
void FSTable::decodeFromStream(FSInputStream* aStream)
{
#ifdef _DEBUG
aStream->startDecoding(className());
#endif
FSActionObject::decodeFromStream(aStream);
int attributeCount = aStream->read(FSStream::UnsignedWord, 16);
if (attributeCount > 0)
{
#ifdef _DEBUG
aStream->startDecoding("array");
#endif
for (int i=0; i<attributeCount; i++)
{
char* str = aStream->readString();
values.push_back(FSString(str));
delete [] str;
}
#ifdef _DEBUG
aStream->endDecoding("array");
#endif
}
else
{
/*
* Reset the length as Macromedia is using the length of a
* table to hide coded following an empty table.
*/
length = 2;
}
#ifdef _DEBUG
aStream->endDecoding(className());
#endif
}
}
| 28.338462 | 95 | 0.580347 | [
"transform"
] |
beb2f5dad7bcefaff43e36be9b08d73684a0708e | 140,722 | cpp | C++ | chuffed/flatzinc/parser.tab.cpp | aekh/chuffed | 61c52d833f5fc6081bf1e48b4608b36a802135d5 | [
"MIT"
] | null | null | null | chuffed/flatzinc/parser.tab.cpp | aekh/chuffed | 61c52d833f5fc6081bf1e48b4608b36a802135d5 | [
"MIT"
] | null | null | null | chuffed/flatzinc/parser.tab.cpp | aekh/chuffed | 61c52d833f5fc6081bf1e48b4608b36a802135d5 | [
"MIT"
] | null | null | null | /* A Bison parser, made by GNU Bison 3.7.1. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation,
Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual,
especially those whose name start with YY_ or yy_. They are
private implementation details that can be changed or removed. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.7.1"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* First part of user prologue. */
#define YYPARSE_PARAM parm
#define YYLEX_PARAM static_cast<ParserState*>(parm)->yyscanner
#include <iostream>
#include <fstream>
#include <sstream>
#include <chuffed/flatzinc/flatzinc.h>
#include <chuffed/flatzinc/parser.tab.h>
#ifdef HAVE_MMAP
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif
using namespace std;
int yyparse(void*);
int yylex(YYSTYPE*, void* scanner);
int yylex_init (void** scanner);
int yylex_destroy (void* scanner);
int yyget_lineno (void* scanner);
void yyset_extra (void* user_defined ,void* yyscanner );
extern int yydebug;
using namespace FlatZinc;
void yyerror(void* parm, const char *str) {
ParserState* pp = static_cast<ParserState*>(parm);
pp->err << "Error: " << str
<< " in line no. " << yyget_lineno(pp->yyscanner)
<< std::endl;
pp->hadError = true;
}
void yyassert(ParserState* pp, bool cond, const char* str)
{
if (!cond) {
pp->err << "Error: " << str
<< " in line no. " << yyget_lineno(pp->yyscanner)
<< std::endl;
pp->hadError = true;
}
}
/*
* The symbol tables
*
*/
AST::Node* getArrayElement(ParserState* pp, string id, unsigned int offset) {
if (offset > 0) {
vector<int> tmp;
if (pp->intvararrays.get(id, tmp) && offset<= tmp.size())
return new AST::IntVar(tmp[offset-1]);
if (pp->boolvararrays.get(id, tmp) && offset<= tmp.size())
return new AST::BoolVar(tmp[offset-1]);
if (pp->setvararrays.get(id, tmp) && offset<= tmp.size())
return new AST::SetVar(tmp[offset-1]);
if (pp->intvalarrays.get(id, tmp) && offset<= tmp.size())
return new AST::IntLit(tmp[offset-1]);
if (pp->boolvalarrays.get(id, tmp) && offset<= tmp.size())
return new AST::BoolLit(tmp[offset-1]);
vector<AST::SetLit> tmpS;
if (pp->setvalarrays.get(id, tmpS) && offset<= tmpS.size())
return new AST::SetLit(tmpS[offset-1]);
}
pp->err << "Error: array access to " << id << " invalid"
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
return new AST::IntVar(0); // keep things consistent
}
AST::Node* getVarRefArg(ParserState* pp, string id, bool annotation = false) {
int tmp;
if (pp->intvarTable.get(id, tmp))
return new AST::IntVar(tmp);
if (pp->boolvarTable.get(id, tmp))
return new AST::BoolVar(tmp);
if (pp->setvarTable.get(id, tmp))
return new AST::SetVar(tmp);
if (annotation)
return new AST::Atom(id);
pp->err << "Error: undefined variable " << id
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
return new AST::IntVar(0); // keep things consistent
}
void addDomainConstraint(
ParserState* pp, std::string id, AST::Node* var, Option<AST::SetLit* >& dom
) {
if (!dom())
return;
AST::Array* args = new AST::Array(2);
args->a[0] = var;
args->a[1] = dom.some();
pp->domainConstraints.push_back(new ConExpr(id, args));
}
/*
* Initialize the root gecode space
*
*/
void initfg(ParserState* pp) {
#if EXPOSE_INT_LITS
static struct {
const char *int_CMP_reif;
IntRelType irt;
} int_CMP_table[] = {
{ "int_eq_reif", IRT_EQ },
{ "int_ne_reif", IRT_NE },
{ "int_ge_reif", IRT_GE },
{ "int_gt_reif", IRT_GT },
{ "int_le_reif", IRT_LE },
{ "int_lt_reif", IRT_LT }
};
for (int i = 0; i < static_cast<int>(pp->domainConstraints2.size()); ) {
ConExpr& c = *pp->domainConstraints2[i].first;
for (int j = 0; j < 6; ++j)
if (c.id.compare(int_CMP_table[j].int_CMP_reif) == 0) {
if (!c[2]->isBoolVar())
goto not_found;
int k;
for (k = c[2]->getBoolVar(); pp->boolvars[k].second->alias; k = pp->boolvars[k].second->i)
;
BoolVarSpec& boolvar = *static_cast<BoolVarSpec *>(pp->boolvars[k].second);
if (boolvar.alias_var >= 0)
goto not_found;
if (c[0]->isIntVar() && c[1]->isInt(boolvar.alias_val)) {
boolvar.alias_var = c[0]->getIntVar();
boolvar.alias_irt = int_CMP_table[j].irt;
goto found;
}
if (c[1]->isIntVar() && c[0]->isInt(boolvar.alias_val)) {
boolvar.alias_var = c[1]->getIntVar();
boolvar.alias_irt = -int_CMP_table[j].irt;
goto found;
}
}
not_found:
++i;
continue;
found:
delete pp->domainConstraints2[i].first;
delete pp->domainConstraints2[i].second;
pp->domainConstraints2.erase(pp->domainConstraints2.begin() + i);
}
#endif
if (!pp->hadError)
pp->fg = new FlatZincSpace(pp->intvars.size(),
pp->boolvars.size(),
pp->setvars.size());
for (unsigned int i = 0; i < pp->intvars.size(); i++) {
if (!pp->hadError) {
try {
pp->fg->newIntVar(static_cast<IntVarSpec*>(pp->intvars[i].second));
IntVar* newiv = pp->fg->iv[pp->fg->intVarCount-1];
intVarString.insert(std::pair<IntVar*, std::string>(newiv, pp->intvars[i].first));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
if (pp->intvars[i].first[0] != '[') {
delete pp->intvars[i].second;
pp->intvars[i].second = NULL;
}
}
for (unsigned int i = 0; i < pp->boolvars.size(); i++) {
if (!pp->hadError) {
try {
pp->fg->newBoolVar(static_cast<BoolVarSpec*>(pp->boolvars[i].second));
BoolView newiv = pp->fg->bv[pp->fg->boolVarCount-1];
if (pp->boolvars[i].second->assigned)
boolVarString.insert(std::pair<BoolView, std::string>(newiv, "ASSIGNED_AT_ROOT"));
else
boolVarString.insert(std::pair<BoolView, std::string>(newiv, pp->boolvars[i].first));
string label;
label = pp->boolvars[i].first;
label.append("=true");
litString.insert(std::pair<int,std::string>(toInt(newiv.getLit(true)), label));
label = pp->boolvars[i].first;
label.append("=false");
litString.insert(std::pair<int,std::string>(toInt(newiv.getLit(false)), label));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
if (pp->boolvars[i].first[0] != '[') {
delete pp->boolvars[i].second;
pp->boolvars[i].second = NULL;
}
}
for (unsigned int i = 0; i < pp->setvars.size(); i++) {
if (!pp->hadError) {
try {
pp->fg->newSetVar(static_cast<SetVarSpec*>(pp->setvars[i].second));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
if (pp->setvars[i].first[0] != '[') {
delete pp->setvars[i].second;
pp->setvars[i].second = NULL;
}
}
for (unsigned int i = pp->domainConstraints.size(); i--;) {
if (!pp->hadError) {
try {
assert(pp->domainConstraints[i]->args->a.size() == 2);
pp->fg->postConstraint(*pp->domainConstraints[i], NULL);
delete pp->domainConstraints[i];
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
}
#if EXPOSE_INT_LITS
for (int i = 0; i < static_cast<int>(pp->domainConstraints2.size()); ++i) {
if (!pp->hadError) {
try {
pp->fg->postConstraint(*pp->domainConstraints2[i].first, pp->domainConstraints2[i].second);
delete pp->domainConstraints2[i].first;
delete pp->domainConstraints2[i].second;
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
}
#endif
}
AST::Node* arrayOutput(AST::Call* ann) {
AST::Array* a = NULL;
if (ann->args->isArray()) {
a = ann->args->getArray();
} else {
a = new AST::Array(ann->args);
}
std::ostringstream oss;
oss << "array" << a->a.size() << "d(";
for (unsigned int i = 0; i < a->a.size(); i++) {
AST::SetLit* s = a->a[i]->getSet();
if (s->empty())
oss << "{}, ";
else if (s->interval)
oss << s->min << ".." << s->max << ", ";
else {
oss << "{";
for (unsigned int j = 0; j < s->s.size(); j++) {
oss << s->s[j];
if (j < s->s.size()-1)
oss << ",";
}
oss << "}, ";
}
}
if (!ann->args->isArray()) {
a->a[0] = NULL;
delete a;
}
return new AST::String(oss.str());
}
/*
* The main program
*
*/
namespace FlatZinc {
void solve(const std::string& filename, std::ostream& err) {
#ifdef HAVE_MMAP
int fd;
char* data;
struct stat sbuf;
fd = open(filename.c_str(), O_RDONLY);
if (fd == -1) {
err << "Cannot open file " << filename << endl;
exit(0);
}
if (stat(filename.c_str(), &sbuf) == -1) {
err << "Cannot stat file " << filename << endl;
return;
}
data = (char*)mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd,0);
if (data == (caddr_t)(-1)) {
err << "Cannot mmap file " << filename << endl;
return;
}
ParserState pp(data, sbuf.st_size, err);
#else
std::ifstream file;
file.open(filename.c_str());
if (!file.is_open()) {
err << "Cannot open file " << filename << endl;
exit(0);
}
std::string s = string(istreambuf_iterator<char>(file),
istreambuf_iterator<char>());
ParserState pp(s, err);
#endif
yylex_init(&pp.yyscanner);
yyset_extra(&pp, pp.yyscanner);
// yydebug = 1;
yyparse(&pp);
FlatZinc::s->output = pp.getOutput();
FlatZinc::s->setOutput();
if (pp.yyscanner)
yylex_destroy(pp.yyscanner);
if (pp.hadError) abort();
}
void solve(std::istream& is, std::ostream& err) {
std::string s = string(istreambuf_iterator<char>(is),
istreambuf_iterator<char>());
ParserState pp(s, err);
yylex_init(&pp.yyscanner);
yyset_extra(&pp, pp.yyscanner);
// yydebug = 1;
yyparse(&pp);
FlatZinc::s->output = pp.getOutput();
FlatZinc::s->setOutput();
if (pp.yyscanner)
yylex_destroy(pp.yyscanner);
if (pp.hadError) abort();
}
}
# ifndef YY_CAST
# ifdef __cplusplus
# define YY_CAST(Type, Val) static_cast<Type> (Val)
# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val)
# else
# define YY_CAST(Type, Val) ((Type) (Val))
# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val))
# endif
# endif
# ifndef YY_NULLPTR
# if defined __cplusplus
# if 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# else
# define YY_NULLPTR ((void*)0)
# endif
# endif
#include <chuffed/flatzinc/parser.tab.h>
/* Symbol kind. */
enum yysymbol_kind_t
{
YYSYMBOL_YYEMPTY = -2,
YYSYMBOL_YYEOF = 0, /* "end of file" */
YYSYMBOL_YYerror = 1, /* error */
YYSYMBOL_YYUNDEF = 2, /* "invalid token" */
YYSYMBOL_INT_LIT = 3, /* INT_LIT */
YYSYMBOL_BOOL_LIT = 4, /* BOOL_LIT */
YYSYMBOL_FLOAT_LIT = 5, /* FLOAT_LIT */
YYSYMBOL_ID = 6, /* ID */
YYSYMBOL_STRING_LIT = 7, /* STRING_LIT */
YYSYMBOL_VAR = 8, /* VAR */
YYSYMBOL_PAR = 9, /* PAR */
YYSYMBOL_ANNOTATION = 10, /* ANNOTATION */
YYSYMBOL_ANY = 11, /* ANY */
YYSYMBOL_ARRAY = 12, /* ARRAY */
YYSYMBOL_BOOLTOK = 13, /* BOOLTOK */
YYSYMBOL_CASE = 14, /* CASE */
YYSYMBOL_COLONCOLON = 15, /* COLONCOLON */
YYSYMBOL_CONSTRAINT = 16, /* CONSTRAINT */
YYSYMBOL_DEFAULT = 17, /* DEFAULT */
YYSYMBOL_DOTDOT = 18, /* DOTDOT */
YYSYMBOL_ELSE = 19, /* ELSE */
YYSYMBOL_ELSEIF = 20, /* ELSEIF */
YYSYMBOL_ENDIF = 21, /* ENDIF */
YYSYMBOL_ENUM = 22, /* ENUM */
YYSYMBOL_FLOATTOK = 23, /* FLOATTOK */
YYSYMBOL_FUNCTION = 24, /* FUNCTION */
YYSYMBOL_IF = 25, /* IF */
YYSYMBOL_INCLUDE = 26, /* INCLUDE */
YYSYMBOL_INTTOK = 27, /* INTTOK */
YYSYMBOL_LET = 28, /* LET */
YYSYMBOL_MAXIMIZE = 29, /* MAXIMIZE */
YYSYMBOL_MINIMIZE = 30, /* MINIMIZE */
YYSYMBOL_OF = 31, /* OF */
YYSYMBOL_SATISFY = 32, /* SATISFY */
YYSYMBOL_OUTPUT = 33, /* OUTPUT */
YYSYMBOL_PREDICATE = 34, /* PREDICATE */
YYSYMBOL_RECORD = 35, /* RECORD */
YYSYMBOL_SET = 36, /* SET */
YYSYMBOL_SHOW = 37, /* SHOW */
YYSYMBOL_SHOWCOND = 38, /* SHOWCOND */
YYSYMBOL_SOLVE = 39, /* SOLVE */
YYSYMBOL_STRING = 40, /* STRING */
YYSYMBOL_TEST = 41, /* TEST */
YYSYMBOL_THEN = 42, /* THEN */
YYSYMBOL_TUPLE = 43, /* TUPLE */
YYSYMBOL_TYPE = 44, /* TYPE */
YYSYMBOL_VARIANT_RECORD = 45, /* VARIANT_RECORD */
YYSYMBOL_WHERE = 46, /* WHERE */
YYSYMBOL_47_ = 47, /* ';' */
YYSYMBOL_48_ = 48, /* '(' */
YYSYMBOL_49_ = 49, /* ')' */
YYSYMBOL_50_ = 50, /* ',' */
YYSYMBOL_51_ = 51, /* ':' */
YYSYMBOL_52_ = 52, /* '[' */
YYSYMBOL_53_ = 53, /* ']' */
YYSYMBOL_54_ = 54, /* '=' */
YYSYMBOL_55_ = 55, /* '{' */
YYSYMBOL_56_ = 56, /* '}' */
YYSYMBOL_YYACCEPT = 57, /* $accept */
YYSYMBOL_model = 58, /* model */
YYSYMBOL_preddecl_items = 59, /* preddecl_items */
YYSYMBOL_preddecl_items_head = 60, /* preddecl_items_head */
YYSYMBOL_vardecl_items = 61, /* vardecl_items */
YYSYMBOL_vardecl_items_head = 62, /* vardecl_items_head */
YYSYMBOL_constraint_items = 63, /* constraint_items */
YYSYMBOL_constraint_items_head = 64, /* constraint_items_head */
YYSYMBOL_preddecl_item = 65, /* preddecl_item */
YYSYMBOL_pred_arg_list = 66, /* pred_arg_list */
YYSYMBOL_pred_arg_list_head = 67, /* pred_arg_list_head */
YYSYMBOL_pred_arg = 68, /* pred_arg */
YYSYMBOL_pred_arg_type = 69, /* pred_arg_type */
YYSYMBOL_pred_arg_simple_type = 70, /* pred_arg_simple_type */
YYSYMBOL_pred_array_init = 71, /* pred_array_init */
YYSYMBOL_pred_array_init_arg = 72, /* pred_array_init_arg */
YYSYMBOL_vardecl_item = 73, /* vardecl_item */
YYSYMBOL_int_init = 74, /* int_init */
YYSYMBOL_int_init_list = 75, /* int_init_list */
YYSYMBOL_int_init_list_head = 76, /* int_init_list_head */
YYSYMBOL_list_tail = 77, /* list_tail */
YYSYMBOL_int_var_array_literal = 78, /* int_var_array_literal */
YYSYMBOL_float_init = 79, /* float_init */
YYSYMBOL_float_init_list = 80, /* float_init_list */
YYSYMBOL_float_init_list_head = 81, /* float_init_list_head */
YYSYMBOL_float_var_array_literal = 82, /* float_var_array_literal */
YYSYMBOL_bool_init = 83, /* bool_init */
YYSYMBOL_bool_init_list = 84, /* bool_init_list */
YYSYMBOL_bool_init_list_head = 85, /* bool_init_list_head */
YYSYMBOL_bool_var_array_literal = 86, /* bool_var_array_literal */
YYSYMBOL_set_init = 87, /* set_init */
YYSYMBOL_set_init_list = 88, /* set_init_list */
YYSYMBOL_set_init_list_head = 89, /* set_init_list_head */
YYSYMBOL_set_var_array_literal = 90, /* set_var_array_literal */
YYSYMBOL_vardecl_int_var_array_init = 91, /* vardecl_int_var_array_init */
YYSYMBOL_vardecl_bool_var_array_init = 92, /* vardecl_bool_var_array_init */
YYSYMBOL_vardecl_float_var_array_init = 93, /* vardecl_float_var_array_init */
YYSYMBOL_vardecl_set_var_array_init = 94, /* vardecl_set_var_array_init */
YYSYMBOL_constraint_item = 95, /* constraint_item */
YYSYMBOL_solve_item = 96, /* solve_item */
YYSYMBOL_int_ti_expr_tail = 97, /* int_ti_expr_tail */
YYSYMBOL_bool_ti_expr_tail = 98, /* bool_ti_expr_tail */
YYSYMBOL_float_ti_expr_tail = 99, /* float_ti_expr_tail */
YYSYMBOL_set_literal = 100, /* set_literal */
YYSYMBOL_int_list = 101, /* int_list */
YYSYMBOL_int_list_head = 102, /* int_list_head */
YYSYMBOL_bool_list = 103, /* bool_list */
YYSYMBOL_bool_list_head = 104, /* bool_list_head */
YYSYMBOL_float_list = 105, /* float_list */
YYSYMBOL_float_list_head = 106, /* float_list_head */
YYSYMBOL_set_literal_list = 107, /* set_literal_list */
YYSYMBOL_set_literal_list_head = 108, /* set_literal_list_head */
YYSYMBOL_flat_expr_list = 109, /* flat_expr_list */
YYSYMBOL_flat_expr = 110, /* flat_expr */
YYSYMBOL_non_array_expr_opt = 111, /* non_array_expr_opt */
YYSYMBOL_non_array_expr = 112, /* non_array_expr */
YYSYMBOL_non_array_expr_list = 113, /* non_array_expr_list */
YYSYMBOL_non_array_expr_list_head = 114, /* non_array_expr_list_head */
YYSYMBOL_solve_expr = 115, /* solve_expr */
YYSYMBOL_minmax = 116, /* minmax */
YYSYMBOL_annotations = 117, /* annotations */
YYSYMBOL_annotations_head = 118, /* annotations_head */
YYSYMBOL_annotation = 119, /* annotation */
YYSYMBOL_annotation_list = 120, /* annotation_list */
YYSYMBOL_annotation_expr = 121, /* annotation_expr */
YYSYMBOL_ann_non_array_expr = 122 /* ann_non_array_expr */
};
typedef enum yysymbol_kind_t yysymbol_kind_t;
#ifdef short
# undef short
#endif
/* On compilers that do not define __PTRDIFF_MAX__ etc., make sure
<limits.h> and (if available) <stdint.h> are included
so that the code can choose integer types of a good width. */
#ifndef __PTRDIFF_MAX__
# include <limits.h> /* INFRINGES ON USER NAME SPACE */
# if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stdint.h> /* INFRINGES ON USER NAME SPACE */
# define YY_STDINT_H
# endif
#endif
/* Narrow types that promote to a signed type and that can represent a
signed or unsigned integer of at least N bits. In tables they can
save space and decrease cache pressure. Promoting to a signed type
helps avoid bugs in integer arithmetic. */
#ifdef __INT_LEAST8_MAX__
typedef __INT_LEAST8_TYPE__ yytype_int8;
#elif defined YY_STDINT_H
typedef int_least8_t yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef __INT_LEAST16_MAX__
typedef __INT_LEAST16_TYPE__ yytype_int16;
#elif defined YY_STDINT_H
typedef int_least16_t yytype_int16;
#else
typedef short yytype_int16;
#endif
#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__
typedef __UINT_LEAST8_TYPE__ yytype_uint8;
#elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST8_MAX <= INT_MAX)
typedef uint_least8_t yytype_uint8;
#elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX
typedef unsigned char yytype_uint8;
#else
typedef short yytype_uint8;
#endif
#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__
typedef __UINT_LEAST16_TYPE__ yytype_uint16;
#elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST16_MAX <= INT_MAX)
typedef uint_least16_t yytype_uint16;
#elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX
typedef unsigned short yytype_uint16;
#else
typedef int yytype_uint16;
#endif
#ifndef YYPTRDIFF_T
# if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__
# define YYPTRDIFF_T __PTRDIFF_TYPE__
# define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__
# elif defined PTRDIFF_MAX
# ifndef ptrdiff_t
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# endif
# define YYPTRDIFF_T ptrdiff_t
# define YYPTRDIFF_MAXIMUM PTRDIFF_MAX
# else
# define YYPTRDIFF_T long
# define YYPTRDIFF_MAXIMUM LONG_MAX
# endif
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned
# endif
#endif
#define YYSIZE_MAXIMUM \
YY_CAST (YYPTRDIFF_T, \
(YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \
? YYPTRDIFF_MAXIMUM \
: YY_CAST (YYSIZE_T, -1)))
#define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X))
/* Stored state numbers (used for stacks). */
typedef yytype_int16 yy_state_t;
/* State numbers in computations. */
typedef int yy_state_fast_t;
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__))
# else
# define YY_ATTRIBUTE_PURE
# endif
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__))
# else
# define YY_ATTRIBUTE_UNUSED
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__
# define YY_IGNORE_USELESS_CAST_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"")
# define YY_IGNORE_USELESS_CAST_END \
_Pragma ("GCC diagnostic pop")
#endif
#ifndef YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_END
#endif
#define YY_ASSERT(E) ((void) (0 && (E)))
#if 1
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* 1 */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yy_state_t yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (YYSIZEOF (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (YYSIZEOF (yy_state_t) + YYSIZEOF (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYPTRDIFF_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * YYSIZEOF (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / YYSIZEOF (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, YY_CAST (YYSIZE_T, (Count)) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYPTRDIFF_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 7
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 341
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 57
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 66
/* YYNRULES -- Number of rules. */
#define YYNRULES 157
/* YYNSTATES -- Number of states. */
#define YYNSTATES 340
/* YYMAXUTOK -- Last valid token kind. */
#define YYMAXUTOK 301
/* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, with out-of-bounds checking. */
#define YYTRANSLATE(YYX) \
(0 <= (YYX) && (YYX) <= YYMAXUTOK \
? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \
: YYSYMBOL_YYUNDEF)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex. */
static const yytype_int8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
48, 49, 2, 2, 50, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 51, 47,
2, 54, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 52, 2, 53, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 55, 2, 56, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_int16 yyrline[] =
{
0, 486, 486, 488, 490, 493, 494, 498, 503, 511,
512, 516, 521, 529, 530, 537, 539, 541, 544, 545,
548, 551, 552, 553, 554, 557, 558, 559, 560, 563,
564, 567, 568, 575, 607, 638, 645, 677, 703, 713,
726, 783, 834, 842, 896, 909, 922, 930, 945, 949,
964, 988, 991, 997, 1002, 1008, 1010, 1013, 1019, 1023,
1038, 1062, 1065, 1071, 1076, 1083, 1089, 1093, 1108, 1132,
1135, 1141, 1146, 1153, 1156, 1160, 1175, 1199, 1202, 1208,
1213, 1220, 1227, 1230, 1237, 1240, 1247, 1250, 1257, 1260,
1266, 1284, 1305, 1328, 1336, 1353, 1357, 1361, 1367, 1371,
1385, 1386, 1393, 1397, 1406, 1409, 1415, 1420, 1428, 1431,
1437, 1442, 1450, 1453, 1459, 1464, 1472, 1475, 1481, 1487,
1499, 1503, 1510, 1514, 1521, 1524, 1530, 1534, 1538, 1542,
1546, 1595, 1609, 1612, 1618, 1622, 1633, 1654, 1684, 1706,
1707, 1715, 1718, 1724, 1728, 1735, 1740, 1746, 1750, 1757,
1761, 1767, 1771, 1775, 1779, 1783, 1826, 1837
};
#endif
/** Accessing symbol of state STATE. */
#define YY_ACCESSING_SYMBOL(State) YY_CAST (yysymbol_kind_t, yystos[State])
#if 1
/* The user-facing name of the symbol whose (internal) number is
YYSYMBOL. No bounds checking. */
static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED;
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"\"end of file\"", "error", "\"invalid token\"", "INT_LIT", "BOOL_LIT",
"FLOAT_LIT", "ID", "STRING_LIT", "VAR", "PAR", "ANNOTATION", "ANY",
"ARRAY", "BOOLTOK", "CASE", "COLONCOLON", "CONSTRAINT", "DEFAULT",
"DOTDOT", "ELSE", "ELSEIF", "ENDIF", "ENUM", "FLOATTOK", "FUNCTION",
"IF", "INCLUDE", "INTTOK", "LET", "MAXIMIZE", "MINIMIZE", "OF",
"SATISFY", "OUTPUT", "PREDICATE", "RECORD", "SET", "SHOW", "SHOWCOND",
"SOLVE", "STRING", "TEST", "THEN", "TUPLE", "TYPE", "VARIANT_RECORD",
"WHERE", "';'", "'('", "')'", "','", "':'", "'['", "']'", "'='", "'{'",
"'}'", "$accept", "model", "preddecl_items", "preddecl_items_head",
"vardecl_items", "vardecl_items_head", "constraint_items",
"constraint_items_head", "preddecl_item", "pred_arg_list",
"pred_arg_list_head", "pred_arg", "pred_arg_type",
"pred_arg_simple_type", "pred_array_init", "pred_array_init_arg",
"vardecl_item", "int_init", "int_init_list", "int_init_list_head",
"list_tail", "int_var_array_literal", "float_init", "float_init_list",
"float_init_list_head", "float_var_array_literal", "bool_init",
"bool_init_list", "bool_init_list_head", "bool_var_array_literal",
"set_init", "set_init_list", "set_init_list_head",
"set_var_array_literal", "vardecl_int_var_array_init",
"vardecl_bool_var_array_init", "vardecl_float_var_array_init",
"vardecl_set_var_array_init", "constraint_item", "solve_item",
"int_ti_expr_tail", "bool_ti_expr_tail", "float_ti_expr_tail",
"set_literal", "int_list", "int_list_head", "bool_list",
"bool_list_head", "float_list", "float_list_head", "set_literal_list",
"set_literal_list_head", "flat_expr_list", "flat_expr",
"non_array_expr_opt", "non_array_expr", "non_array_expr_list",
"non_array_expr_list_head", "solve_expr", "minmax", "annotations",
"annotations_head", "annotation", "annotation_list", "annotation_expr",
"ann_non_array_expr", YY_NULLPTR
};
static const char *
yysymbol_name (yysymbol_kind_t yysymbol)
{
return yytname[yysymbol];
}
#endif
#ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_int16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 59, 40, 41,
44, 58, 91, 93, 61, 123, 125
};
#endif
#define YYPACT_NINF (-124)
#define yypact_value_is_default(Yyn) \
((Yyn) == YYPACT_NINF)
#define YYTABLE_NINF (-1)
#define yytable_value_is_error(Yyn) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int16 yypact[] =
{
4, 38, 76, 45, 4, 44, 49, -124, 75, 105,
60, 72, -124, 100, 137, 131, 45, 109, 102, 110,
-124, 27, 151, -124, -124, 134, 147, 112, 113, 115,
164, 163, 14, -124, 114, 121, 166, 136, 131, 130,
135, -124, 178, -124, 107, 138, -124, -124, 155, 139,
142, -124, 144, -124, -124, -124, 14, -124, -124, 146,
148, 183, 188, 191, 181, 185, 150, -124, 199, -124,
133, 185, 157, 159, -124, -124, 185, -124, 25, 14,
-124, 27, -124, 202, 158, 206, 156, 208, 160, 185,
185, 185, 211, 61, 161, 196, 212, -124, 84, 214,
-124, 17, -124, -124, 169, 209, -124, -24, -124, -124,
-124, -124, 218, -124, -124, -124, -124, 172, 172, 172,
167, 210, -124, -124, 54, -124, 61, 137, -124, -124,
-124, -124, 56, 61, 185, 210, -124, -124, 177, 56,
-124, 36, -124, -124, 179, -124, -124, -124, 119, 56,
228, 25, 203, 185, 56, -124, -124, -124, 205, 230,
61, 18, -124, 74, 182, -124, -124, 189, 56, -124,
186, 192, 185, 84, 185, -124, 193, -124, -124, -124,
-124, 71, 172, -124, 106, -124, 55, 194, 195, 61,
-124, -124, 56, 197, -124, 56, -124, -124, -124, -124,
241, 107, -124, -124, 132, 198, 200, 216, 201, -124,
-124, -124, -124, -124, -124, 204, -124, 222, 207, 215,
219, 248, 249, 14, 250, -124, 14, 253, 254, 255,
185, 185, 220, 185, 221, 185, 185, 185, 213, 223,
256, 224, 257, 225, 226, 227, 217, 231, 185, 232,
185, 233, -124, 234, -124, 235, -124, 261, 268, 236,
137, 237, 143, -124, 12, -124, 1, -124, 229, 146,
239, 148, 242, 240, 243, -124, -124, 244, -124, 245,
238, -124, 247, -124, 251, 252, -124, 258, -124, 259,
263, -124, -124, -124, -124, 48, -124, 89, -124, 271,
-124, 143, -124, 272, -124, 12, -124, 273, -124, 1,
-124, 210, -124, 262, 264, 265, -124, 266, 270, -124,
269, -124, 274, -124, 275, -124, -124, 48, -124, 286,
-124, 89, -124, -124, -124, -124, -124, 276, -124, -124
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
3, 0, 0, 7, 4, 0, 0, 1, 0, 0,
0, 0, 95, 0, 104, 11, 8, 0, 0, 0,
5, 16, 0, 98, 100, 0, 104, 0, 0, 0,
0, 0, 0, 106, 0, 55, 0, 0, 12, 0,
0, 9, 0, 6, 0, 0, 27, 28, 0, 0,
55, 18, 0, 24, 25, 97, 0, 110, 114, 55,
55, 0, 0, 0, 0, 141, 0, 96, 56, 105,
141, 141, 0, 0, 13, 10, 141, 23, 0, 0,
15, 56, 17, 0, 0, 56, 0, 56, 0, 141,
141, 141, 0, 0, 0, 142, 0, 107, 0, 0,
91, 0, 2, 14, 0, 0, 31, 0, 29, 26,
19, 20, 0, 111, 99, 115, 101, 124, 124, 124,
0, 152, 151, 153, 155, 157, 0, 104, 154, 143,
146, 149, 0, 0, 141, 127, 126, 128, 130, 132,
129, 0, 120, 122, 0, 140, 139, 93, 0, 0,
0, 0, 0, 141, 0, 33, 34, 35, 0, 0,
0, 0, 147, 0, 0, 38, 144, 0, 0, 134,
0, 55, 141, 0, 141, 136, 137, 94, 37, 32,
30, 0, 124, 125, 0, 103, 0, 155, 0, 0,
150, 102, 0, 0, 123, 56, 133, 90, 121, 92,
0, 0, 21, 36, 0, 0, 0, 0, 0, 145,
156, 148, 39, 131, 135, 0, 22, 0, 0, 0,
0, 0, 0, 0, 0, 138, 0, 0, 0, 0,
141, 141, 0, 141, 0, 141, 141, 141, 0, 0,
0, 0, 0, 82, 84, 86, 0, 0, 141, 0,
141, 0, 40, 0, 41, 0, 42, 108, 112, 0,
104, 88, 51, 83, 69, 85, 61, 87, 0, 55,
0, 55, 0, 0, 0, 43, 48, 49, 53, 0,
55, 66, 67, 71, 0, 55, 58, 59, 63, 0,
55, 45, 109, 46, 113, 116, 44, 77, 89, 0,
57, 56, 52, 0, 73, 56, 70, 0, 65, 56,
62, 0, 118, 0, 55, 75, 79, 0, 55, 74,
0, 54, 0, 72, 0, 64, 47, 56, 117, 0,
81, 56, 78, 50, 68, 60, 119, 0, 80, 76
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int16 yypgoto[] =
{
-124, -124, -124, -124, -124, -124, -124, -124, 293, -124,
-124, 260, -124, -43, -124, 149, 285, 2, -124, -124,
-50, -124, -4, -124, -124, -124, 3, -124, -124, -124,
-25, -124, -124, -124, -124, -124, -124, -124, 278, -124,
-1, 103, 117, -90, -123, -124, -124, 52, -124, 53,
-124, -124, -124, 145, -107, -112, -124, -124, -124, -124,
-57, -124, -88, 165, -124, 162
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 2, 3, 4, 15, 16, 37, 38, 5, 49,
50, 51, 52, 53, 107, 108, 17, 278, 279, 280,
69, 263, 288, 289, 290, 267, 283, 284, 285, 265,
316, 317, 318, 298, 252, 254, 256, 275, 39, 72,
54, 28, 29, 140, 34, 35, 268, 59, 270, 60,
313, 314, 141, 142, 155, 143, 170, 171, 177, 148,
94, 95, 162, 163, 130, 131
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int16 yytable[] =
{
82, 77, 18, 128, 164, 129, 286, 287, 27, 86,
88, 156, 157, 100, 101, 18, 281, 8, 282, 104,
165, 121, 122, 123, 187, 125, 151, 169, 105, 152,
8, 66, 117, 118, 119, 44, 128, 178, 1, 45,
46, 12, 183, 128, 6, 166, 145, 146, 8, 147,
47, 311, 106, 9, 12, 84, 193, 10, 11, 135,
136, 137, 138, 48, 121, 122, 123, 124, 125, 14,
128, 128, 12, 127, 8, 203, 7, 167, 109, 201,
212, 13, 14, 214, 46, 172, 173, 135, 136, 137,
138, 20, 311, 22, 47, 315, 182, 21, 12, 128,
14, 211, 160, 127, 209, 189, 161, 48, 8, 8,
8, 127, 30, 126, 204, 197, 127, 199, 23, 205,
46, 196, 175, 31, 189, 176, 14, 190, 24, 206,
47, 32, 12, 12, 12, 8, 139, 273, 202, 127,
33, 25, 207, 48, 127, 23, 276, 36, 93, 277,
33, 57, 58, 42, 55, 24, 41, 43, 216, 12,
26, 14, 14, 61, 62, 56, 63, 64, 217, 65,
67, 68, 70, 238, 239, 71, 241, 74, 243, 244,
245, 98, 75, 208, 76, 99, 79, 26, 80, 89,
78, 259, 81, 261, 90, 83, 85, 91, 87, 92,
93, 96, 97, 218, 102, 312, 103, 319, 111, 112,
113, 133, 114, 115, 120, 132, 116, 144, 134, 292,
158, 294, 232, 149, 153, 234, 154, 150, 159, 168,
302, 179, 174, 185, 181, 306, 184, 336, 191, 194,
310, 319, 195, 192, 215, 200, 161, 223, 210, 221,
213, 222, 224, 226, 230, 231, 233, 225, 227, 235,
236, 237, 248, 250, 328, 57, 228, 246, 332, 257,
229, 240, 242, 58, 320, 322, 324, 247, 249, 251,
253, 255, 291, 258, 260, 262, 264, 266, 301, 337,
272, 274, 293, 296, 295, 297, 299, 19, 300, 303,
180, 40, 305, 321, 304, 325, 338, 219, 323, 269,
307, 271, 308, 309, 327, 326, 73, 329, 198, 330,
331, 220, 333, 188, 0, 186, 0, 334, 335, 339,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 110
};
static const yytype_int16 yycheck[] =
{
50, 44, 3, 93, 127, 93, 5, 6, 9, 59,
60, 118, 119, 70, 71, 16, 4, 3, 6, 76,
132, 3, 4, 5, 6, 7, 50, 139, 3, 53,
3, 32, 89, 90, 91, 8, 126, 149, 34, 12,
13, 27, 154, 133, 6, 133, 29, 30, 3, 32,
23, 3, 27, 8, 27, 56, 168, 12, 13, 3,
4, 5, 6, 36, 3, 4, 5, 6, 7, 55,
160, 161, 27, 55, 3, 182, 0, 134, 79, 8,
192, 36, 55, 195, 13, 49, 50, 3, 4, 5,
6, 47, 3, 18, 23, 6, 153, 48, 27, 189,
55, 189, 48, 55, 49, 50, 52, 36, 3, 3,
3, 55, 52, 52, 8, 172, 55, 174, 13, 13,
13, 171, 3, 51, 50, 6, 55, 53, 23, 23,
23, 31, 27, 27, 27, 3, 52, 260, 181, 55,
3, 36, 36, 36, 55, 13, 3, 16, 15, 6,
3, 4, 5, 51, 3, 23, 47, 47, 201, 27,
55, 55, 55, 51, 51, 31, 51, 3, 36, 6,
56, 50, 6, 230, 231, 39, 233, 47, 235, 236,
237, 48, 47, 184, 6, 52, 31, 55, 49, 6,
52, 248, 50, 250, 6, 51, 50, 6, 50, 18,
15, 51, 3, 204, 47, 295, 47, 297, 6, 51,
4, 15, 56, 5, 3, 54, 56, 3, 6, 269,
53, 271, 223, 54, 6, 226, 54, 18, 18, 52,
280, 3, 53, 3, 31, 285, 31, 327, 56, 53,
290, 331, 50, 54, 3, 52, 52, 31, 53, 51,
53, 51, 51, 31, 6, 6, 6, 53, 51, 6,
6, 6, 6, 6, 314, 4, 51, 54, 318, 52,
51, 51, 51, 5, 3, 3, 3, 54, 54, 54,
54, 54, 53, 52, 52, 52, 52, 52, 50, 3,
54, 54, 53, 53, 52, 52, 52, 4, 53, 52,
151, 16, 50, 301, 53, 309, 331, 204, 305, 257,
52, 258, 53, 50, 50, 53, 38, 52, 173, 53,
50, 204, 53, 161, -1, 160, -1, 53, 53, 53,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 81
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_int8 yystos[] =
{
0, 34, 58, 59, 60, 65, 6, 0, 3, 8,
12, 13, 27, 36, 55, 61, 62, 73, 97, 65,
47, 48, 18, 13, 23, 36, 55, 97, 98, 99,
52, 51, 31, 3, 101, 102, 16, 63, 64, 95,
73, 47, 51, 47, 8, 12, 13, 23, 36, 66,
67, 68, 69, 70, 97, 3, 31, 4, 5, 104,
106, 51, 51, 51, 3, 6, 97, 56, 50, 77,
6, 39, 96, 95, 47, 47, 6, 70, 52, 31,
49, 50, 77, 51, 97, 50, 77, 50, 77, 6,
6, 6, 18, 15, 117, 118, 51, 3, 48, 52,
117, 117, 47, 47, 117, 3, 27, 71, 72, 97,
68, 6, 51, 4, 56, 5, 56, 117, 117, 117,
3, 3, 4, 5, 6, 7, 52, 55, 100, 119,
121, 122, 54, 15, 6, 3, 4, 5, 6, 52,
100, 109, 110, 112, 3, 29, 30, 32, 116, 54,
18, 50, 53, 6, 54, 111, 111, 111, 53, 18,
48, 52, 119, 120, 101, 112, 119, 117, 52, 112,
113, 114, 49, 50, 53, 3, 6, 115, 112, 3,
72, 31, 117, 112, 31, 3, 120, 6, 122, 50,
53, 56, 54, 112, 53, 50, 77, 117, 110, 117,
52, 8, 70, 111, 8, 13, 23, 36, 97, 49,
53, 119, 112, 53, 112, 3, 70, 36, 97, 98,
99, 51, 51, 31, 51, 53, 31, 51, 51, 51,
6, 6, 97, 6, 97, 6, 6, 6, 117, 117,
51, 117, 51, 117, 117, 117, 54, 54, 6, 54,
6, 54, 91, 54, 92, 54, 93, 52, 52, 117,
52, 117, 52, 78, 52, 86, 52, 82, 103, 104,
105, 106, 54, 101, 54, 94, 3, 6, 74, 75,
76, 4, 6, 83, 84, 85, 5, 6, 79, 80,
81, 53, 77, 53, 77, 52, 53, 52, 90, 52,
53, 50, 77, 52, 53, 50, 77, 52, 53, 50,
77, 3, 100, 107, 108, 6, 87, 88, 89, 100,
3, 74, 3, 83, 3, 79, 53, 50, 77, 52,
53, 50, 77, 53, 53, 53, 100, 3, 87, 53
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_int8 yyr1[] =
{
0, 57, 58, 59, 59, 60, 60, 61, 61, 62,
62, 63, 63, 64, 64, 65, 66, 66, 67, 67,
68, 69, 69, 69, 69, 70, 70, 70, 70, 71,
71, 72, 72, 73, 73, 73, 73, 73, 73, 73,
73, 73, 73, 73, 73, 73, 73, 73, 74, 74,
74, 75, 75, 76, 76, 77, 77, 78, 79, 79,
79, 80, 80, 81, 81, 82, 83, 83, 83, 84,
84, 85, 85, 86, 87, 87, 87, 88, 88, 89,
89, 90, 91, 91, 92, 92, 93, 93, 94, 94,
95, 95, 95, 96, 96, 97, 97, 97, 98, 98,
99, 99, 100, 100, 101, 101, 102, 102, 103, 103,
104, 104, 105, 105, 106, 106, 107, 107, 108, 108,
109, 109, 110, 110, 111, 111, 112, 112, 112, 112,
112, 112, 113, 113, 114, 114, 115, 115, 115, 116,
116, 117, 117, 118, 118, 119, 119, 120, 120, 121,
121, 122, 122, 122, 122, 122, 122, 122
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_int8 yyr2[] =
{
0, 2, 5, 0, 1, 2, 3, 0, 1, 2,
3, 0, 1, 2, 3, 5, 0, 2, 1, 3,
3, 6, 7, 2, 1, 1, 3, 1, 1, 1,
3, 1, 3, 6, 6, 6, 8, 6, 6, 8,
13, 13, 13, 15, 15, 15, 15, 17, 1, 1,
4, 0, 2, 1, 3, 0, 1, 3, 1, 1,
4, 0, 2, 1, 3, 3, 1, 1, 4, 0,
2, 1, 3, 3, 1, 1, 4, 0, 2, 1,
3, 3, 0, 2, 0, 2, 0, 2, 0, 2,
6, 3, 6, 3, 4, 1, 3, 3, 1, 4,
1, 4, 3, 3, 0, 2, 1, 3, 0, 2,
1, 3, 0, 2, 1, 3, 0, 2, 1, 3,
1, 3, 1, 3, 0, 2, 1, 1, 1, 1,
1, 4, 0, 2, 1, 3, 1, 1, 4, 1,
1, 0, 1, 2, 3, 4, 1, 1, 3, 1,
3, 1, 1, 1, 1, 1, 4, 1
};
enum { YYENOMEM = -2 };
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (parm, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Backward compatibility with an undocumented macro.
Use YYerror or YYUNDEF. */
#define YYERRCODE YYUNDEF
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
# ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
# endif
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Kind, Value, parm); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*-----------------------------------.
| Print this symbol's value on YYO. |
`-----------------------------------*/
static void
yy_symbol_value_print (FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, void *parm)
{
FILE *yyoutput = yyo;
YYUSE (yyoutput);
YYUSE (parm);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yykind < YYNTOKENS)
YYPRINT (yyo, yytoknum[yykind], *yyvaluep);
# endif
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yykind);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*---------------------------.
| Print this symbol on YYO. |
`---------------------------*/
static void
yy_symbol_print (FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, void *parm)
{
YYFPRINTF (yyo, "%s %s (",
yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind));
yy_symbol_value_print (yyo, yykind, yyvaluep, parm);
YYFPRINTF (yyo, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yy_state_t *yybottom, yy_state_t *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yy_state_t *yyssp, YYSTYPE *yyvsp,
int yyrule, void *parm)
{
int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %d):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
YY_ACCESSING_SYMBOL (+yyssp[yyi + 1 - yynrhs]),
&yyvsp[(yyi + 1) - (yynrhs)], parm);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, parm); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args) ((void) 0)
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
/* Context of a parse error. */
typedef struct
{
yy_state_t *yyssp;
yysymbol_kind_t yytoken;
} yypcontext_t;
/* Put in YYARG at most YYARGN of the expected tokens given the
current YYCTX, and return the number of tokens stored in YYARG. If
YYARG is null, return the number of expected tokens (guaranteed to
be less than YYNTOKENS). Return YYENOMEM on memory exhaustion.
Return 0 if there are more than YYARGN expected tokens, yet fill
YYARG up to YYARGN. */
static int
yypcontext_expected_tokens (const yypcontext_t *yyctx,
yysymbol_kind_t yyarg[], int yyargn)
{
/* Actual size of YYARG. */
int yycount = 0;
int yyn = yypact[+*yyctx->yyssp];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYSYMBOL_YYerror
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (!yyarg)
++yycount;
else if (yycount == yyargn)
return 0;
else
yyarg[yycount++] = YY_CAST (yysymbol_kind_t, yyx);
}
}
if (yyarg && yycount == 0 && 0 < yyargn)
yyarg[0] = YYSYMBOL_YYEMPTY;
return yycount;
}
#ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen(S) (YY_CAST (YYPTRDIFF_T, strlen (S)))
# else
/* Return the length of YYSTR. */
static YYPTRDIFF_T
yystrlen (const char *yystr)
{
YYPTRDIFF_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
#endif
#ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
#endif
#ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYPTRDIFF_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYPTRDIFF_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
else
goto append;
append:
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (yyres)
return yystpcpy (yyres, yystr) - yyres;
else
return yystrlen (yystr);
}
#endif
static int
yy_syntax_error_arguments (const yypcontext_t *yyctx,
yysymbol_kind_t yyarg[], int yyargn)
{
/* Actual size of YYARG. */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yyctx->yytoken != YYSYMBOL_YYEMPTY)
{
int yyn;
if (yyarg)
yyarg[yycount] = yyctx->yytoken;
++yycount;
yyn = yypcontext_expected_tokens (yyctx,
yyarg ? yyarg + 1 : yyarg, yyargn - 1);
if (yyn == YYENOMEM)
return YYENOMEM;
else
yycount += yyn;
}
return yycount;
}
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return -1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return YYENOMEM if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYPTRDIFF_T *yymsg_alloc, char **yymsg,
const yypcontext_t *yyctx)
{
enum { YYARGS_MAX = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat: reported tokens (one for the "unexpected",
one per "expected"). */
yysymbol_kind_t yyarg[YYARGS_MAX];
/* Cumulated lengths of YYARG. */
YYPTRDIFF_T yysize = 0;
/* Actual size of YYARG. */
int yycount = yy_syntax_error_arguments (yyctx, yyarg, YYARGS_MAX);
if (yycount == YYENOMEM)
return YYENOMEM;
switch (yycount)
{
#define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
default: /* Avoid compiler warnings. */
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
#undef YYCASE_
}
/* Compute error message size. Don't count the "%s"s, but reserve
room for the terminator. */
yysize = yystrlen (yyformat) - 2 * yycount + 1;
{
int yyi;
for (yyi = 0; yyi < yycount; ++yyi)
{
YYPTRDIFF_T yysize1
= yysize + yytnamerr (YY_NULLPTR, yytname[yyarg[yyi]]);
if (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)
yysize = yysize1;
else
return YYENOMEM;
}
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return -1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yytname[yyarg[yyi++]]);
yyformat += 2;
}
else
{
++yyp;
++yyformat;
}
}
return 0;
}
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg,
yysymbol_kind_t yykind, YYSTYPE *yyvaluep, void *parm)
{
YYUSE (yyvaluep);
YYUSE (parm);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yykind);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (void *parm)
{
/* Lookahead token kind. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs = 0;
yy_state_fast_t yystate = 0;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus = 0;
/* Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* Their size. */
YYPTRDIFF_T yystacksize = YYINITDEPTH;
/* The state stack: array, bottom, top. */
yy_state_t yyssa[YYINITDEPTH];
yy_state_t *yyss = yyssa;
yy_state_t *yyssp = yyss;
/* The semantic value stack: array, bottom, top. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs = yyvsa;
YYSTYPE *yyvsp = yyvs;
int yyn;
/* The return value of yyparse. */
int yyresult;
/* Lookahead symbol kind. */
yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYPTRDIFF_T yymsg_alloc = sizeof yymsgbuf;
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
YYDPRINTF ((stderr, "Starting parse\n"));
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
/*--------------------------------------------------------------------.
| yysetstate -- set current state (the top of the stack) to yystate. |
`--------------------------------------------------------------------*/
yysetstate:
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
YY_ASSERT (0 <= yystate && yystate < YYNSTATES);
YY_IGNORE_USELESS_CAST_BEGIN
*yyssp = YY_CAST (yy_state_t, yystate);
YY_IGNORE_USELESS_CAST_END
YY_STACK_PRINT (yyss, yyssp);
if (yyss + yystacksize - 1 <= yyssp)
#if !defined yyoverflow && !defined YYSTACK_RELOCATE
goto yyexhaustedlab;
#else
{
/* Get the current used size of the three stacks, in elements. */
YYPTRDIFF_T yysize = yyssp - yyss + 1;
# if defined yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
yy_state_t *yyss1 = yyss;
YYSTYPE *yyvs1 = yyvs;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * YYSIZEOF (*yyssp),
&yyvs1, yysize * YYSIZEOF (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
# else /* defined YYSTACK_RELOCATE */
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yy_state_t *yyss1 = yyss;
union yyalloc *yyptr =
YY_CAST (union yyalloc *,
YYSTACK_ALLOC (YY_CAST (YYSIZE_T, YYSTACK_BYTES (yystacksize))));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YY_IGNORE_USELESS_CAST_BEGIN
YYDPRINTF ((stderr, "Stack size increased to %ld\n",
YY_CAST (long, yystacksize)));
YY_IGNORE_USELESS_CAST_END
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
#endif /* !defined yyoverflow && !defined YYSTACK_RELOCATE */
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either empty, or end-of-input, or a valid lookahead. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token\n"));
yychar = yylex (&yylval, YYLEX_PARAM);
}
if (yychar <= YYEOF)
{
yychar = YYEOF;
yytoken = YYSYMBOL_YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else if (yychar == YYerror)
{
/* The scanner already issued an error message, process directly
to error recovery. But do not keep the error token as
lookahead, it is too special and may lead us to an endless
loop in error recovery. */
yychar = YYUNDEF;
yytoken = YYSYMBOL_YYerror;
goto yyerrlab1;
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Discard the shifted token. */
yychar = YYEMPTY;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 7: /* vardecl_items: %empty */
{
#if !EXPOSE_INT_LITS
initfg(static_cast<ParserState*>(parm));
#endif
}
break;
case 8: /* vardecl_items: vardecl_items_head */
{
#if !EXPOSE_INT_LITS
initfg(static_cast<ParserState*>(parm));
#endif
}
break;
case 11: /* constraint_items: %empty */
{
#if EXPOSE_INT_LITS
initfg(static_cast<ParserState*>(parm));
#endif
}
break;
case 12: /* constraint_items: constraint_items_head */
{
#if EXPOSE_INT_LITS
initfg(static_cast<ParserState*>(parm));
#endif
}
break;
case 33: /* vardecl_item: VAR int_ti_expr_tail ':' ID annotations non_array_expr_opt */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, !(yyvsp[-4].oSet)() || !(yyvsp[-4].oSet).some()->empty(), "Empty var int domain.");
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("output_var");
pp->intvarTable.put((yyvsp[-2].sValue), pp->intvars.size());
if (print) {
pp->output(std::string((yyvsp[-2].sValue)), new AST::IntVar(pp->intvars.size()));
}
bool introduced = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("var_is_introduced");
bool looks_introduced = (strncmp((yyvsp[-2].sValue), "X_INTRODUCED_", 13) == 0);
if ((yyvsp[0].oArg)()) {
AST::Node* arg = (yyvsp[0].oArg).some();
if (arg->isInt()) {
pp->intvars.push_back(varspec((yyvsp[-2].sValue),
new IntVarSpec(arg->getInt(),print,introduced,looks_introduced)));
} else if (arg->isIntVar()) {
pp->intvars.push_back(varspec((yyvsp[-2].sValue),
new IntVarSpec(Alias(arg->getIntVar()),print,introduced,looks_introduced)));
} else {
yyassert(pp, false, "Invalid var int initializer.");
}
if (!pp->hadError)
addDomainConstraint(pp, "set_in",
new AST::IntVar(pp->intvars.size()-1), (yyvsp[-4].oSet));
delete arg;
} else {
pp->intvars.push_back(varspec((yyvsp[-2].sValue), new IntVarSpec((yyvsp[-4].oSet),print,introduced,looks_introduced)));
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 34: /* vardecl_item: VAR bool_ti_expr_tail ':' ID annotations non_array_expr_opt */
{
ParserState* pp = static_cast<ParserState*>(parm);
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("output_var");
pp->boolvarTable.put((yyvsp[-2].sValue), pp->boolvars.size());
if (print) {
pp->output(std::string((yyvsp[-2].sValue)), new AST::BoolVar(pp->boolvars.size()));
}
bool introduced = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("var_is_introduced");
bool looks_introduced = (strncmp((yyvsp[-2].sValue), "X_INTRODUCED_", 13) == 0);
if ((yyvsp[0].oArg)()) {
AST::Node* arg = (yyvsp[0].oArg).some();
if (arg->isBool()) {
pp->boolvars.push_back(varspec((yyvsp[-2].sValue),
new BoolVarSpec(arg->getBool(),print,introduced,looks_introduced)));
} else if (arg->isBoolVar()) {
pp->boolvars.push_back(varspec((yyvsp[-2].sValue),
new BoolVarSpec(Alias(arg->getBoolVar()),print,introduced,looks_introduced)));
} else {
yyassert(pp, false, "Invalid var bool initializer.");
}
if (!pp->hadError)
addDomainConstraint(pp, "set_in",
new AST::BoolVar(pp->boolvars.size()-1), (yyvsp[-4].oSet));
delete arg;
} else {
pp->boolvars.push_back(varspec((yyvsp[-2].sValue), new BoolVarSpec((yyvsp[-4].oSet),print,introduced,looks_introduced)));
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 35: /* vardecl_item: VAR float_ti_expr_tail ':' ID annotations non_array_expr_opt */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, false, "Floats not supported.");
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 36: /* vardecl_item: VAR SET OF int_ti_expr_tail ':' ID annotations non_array_expr_opt */
{
ParserState* pp = static_cast<ParserState*>(parm);
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("output_var");
pp->setvarTable.put((yyvsp[-2].sValue), pp->setvars.size());
if (print) {
pp->output(std::string((yyvsp[-2].sValue)), new AST::SetVar(pp->setvars.size()));
}
bool introduced = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasAtom("var_is_introduced");
bool looks_introduced = (strncmp((yyvsp[-2].sValue), "X_INTRODUCED_", 13) == 0);
if ((yyvsp[0].oArg)()) {
AST::Node* arg = (yyvsp[0].oArg).some();
if (arg->isSet()) {
pp->setvars.push_back(varspec((yyvsp[-2].sValue),
new SetVarSpec(arg->getSet(),print,introduced,looks_introduced)));
} else if (arg->isSetVar()) {
pp->setvars.push_back(varspec((yyvsp[-2].sValue),
new SetVarSpec(Alias(arg->getSetVar()),print,introduced,looks_introduced)));
delete arg;
} else {
yyassert(pp, false, "Invalid var set initializer.");
delete arg;
}
if (!pp->hadError)
addDomainConstraint(pp, "set_subset",
new AST::SetVar(pp->setvars.size()-1), (yyvsp[-4].oSet));
} else {
pp->setvars.push_back(varspec((yyvsp[-2].sValue), new SetVarSpec((yyvsp[-4].oSet),print,introduced,looks_introduced)));
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 37: /* vardecl_item: int_ti_expr_tail ':' ID annotations '=' non_array_expr */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, !(yyvsp[-5].oSet)() || !(yyvsp[-5].oSet).some()->empty(), "Empty int domain.");
yyassert(pp, (yyvsp[0].arg)->isInt(), "Invalid int initializer.");
int i = -1;
bool isInt = (yyvsp[0].arg)->isInt(i);
if ((yyvsp[-5].oSet)() && isInt) {
AST::SetLit* sl = (yyvsp[-5].oSet).some();
if (sl->interval) {
yyassert(pp, i >= sl->min && i <= sl->max, "Empty int domain.");
} else {
bool found = false;
for (unsigned int j = 0; j < sl->s.size(); j++) {
if (sl->s[j] == i) {
found = true;
break;
}
}
yyassert(pp, found, "Empty int domain.");
}
}
pp->intvals.put((yyvsp[-3].sValue), i);
delete (yyvsp[-2].argVec);
free((yyvsp[-3].sValue));
}
break;
case 38: /* vardecl_item: BOOLTOK ':' ID annotations '=' non_array_expr */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, (yyvsp[0].arg)->isBool(), "Invalid bool initializer.");
if ((yyvsp[0].arg)->isBool()) {
pp->boolvals.put((yyvsp[-3].sValue), (yyvsp[0].arg)->getBool());
}
delete (yyvsp[-2].argVec);
free((yyvsp[-3].sValue));
}
break;
case 39: /* vardecl_item: SET OF int_ti_expr_tail ':' ID annotations '=' non_array_expr */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, !(yyvsp[-5].oSet)() || !(yyvsp[-5].oSet).some()->empty(), "Empty set domain.");
yyassert(pp, (yyvsp[0].arg)->isSet(), "Invalid set initializer.");
AST::SetLit* set = NULL;
if ((yyvsp[0].arg)->isSet())
set = (yyvsp[0].arg)->getSet();
pp->setvals.put((yyvsp[-3].sValue), *set);
delete set;
delete (yyvsp[-2].argVec);
free((yyvsp[-3].sValue));
}
break;
case 40: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF VAR int_ti_expr_tail ':' ID annotations vardecl_int_var_array_init */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, (yyvsp[-10].iValue) == 1, "Arrays must start at 1");
if (!pp->hadError) {
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasCall("output_array");
vector<int> vars((yyvsp[-8].iValue));
yyassert(pp, !(yyvsp[-4].oSet)() || !(yyvsp[-4].oSet).some()->empty(), "Empty var int domain.");
if (!pp->hadError) {
if ((yyvsp[0].oVarSpecVec)()) {
vector<VarSpec*>* vsv = (yyvsp[0].oVarSpecVec).some();
yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[-8].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError) {
for (int i = 0; i < (yyvsp[-8].iValue); i++) {
IntVarSpec* ivsv = static_cast<IntVarSpec*>((*vsv)[i]);
if (ivsv->alias) {
vars[i] = ivsv->i;
} else {
vars[i] = pp->intvars.size();
pp->intvars.push_back(varspec((yyvsp[-2].sValue), ivsv));
}
if (!pp->hadError && (yyvsp[-4].oSet)()) {
Option<AST::SetLit*> opt =
Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[-4].oSet).some()));
addDomainConstraint(pp, "set_in", new AST::IntVar(vars[i]), opt);
}
}
}
delete vsv;
} else {
IntVarSpec* ispec = new IntVarSpec((yyvsp[-4].oSet),print,!print,false);
string arrayname = "["; arrayname += (yyvsp[-2].sValue);
for (int i = 0; i < (yyvsp[-8].iValue)-1; i++) {
vars[i] = pp->intvars.size();
pp->intvars.push_back(varspec(arrayname, ispec));
}
vars[(yyvsp[-8].iValue)-1] = pp->intvars.size();
pp->intvars.push_back(varspec((yyvsp[-2].sValue), ispec));
}
}
if (print) {
AST::Array* a = new AST::Array();
a->a.push_back(arrayOutput((yyvsp[-1].argVec)->getCall("output_array")));
AST::Array* output = new AST::Array();
for (int i = 0; i < (yyvsp[-8].iValue); i++)
output->a.push_back(new AST::IntVar(vars[i]));
a->a.push_back(output);
a->a.push_back(new AST::String(")"));
pp->output(std::string((yyvsp[-2].sValue)), a);
}
pp->intvararrays.put((yyvsp[-2].sValue), vars);
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 41: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF VAR bool_ti_expr_tail ':' ID annotations vardecl_bool_var_array_init */
{
ParserState* pp = static_cast<ParserState*>(parm);
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasCall("output_array");
yyassert(pp, (yyvsp[-10].iValue) == 1, "Arrays must start at 1");
if (!pp->hadError) {
vector<int> vars((yyvsp[-8].iValue));
if ((yyvsp[0].oVarSpecVec)()) {
vector<VarSpec*>* vsv = (yyvsp[0].oVarSpecVec).some();
yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[-8].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError) {
for (int i = 0; i < (yyvsp[-8].iValue); i++) {
BoolVarSpec* bvsv = static_cast<BoolVarSpec*>((*vsv)[i]);
if (bvsv->alias)
vars[i] = bvsv->i;
else {
vars[i] = pp->boolvars.size();
pp->boolvars.push_back(varspec((yyvsp[-2].sValue), (*vsv)[i]));
}
if (!pp->hadError && (yyvsp[-4].oSet)()) {
Option<AST::SetLit*> opt =
Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[-4].oSet).some()));
addDomainConstraint(pp, "set_in", new AST::BoolVar(vars[i]), opt);
}
}
}
delete vsv;
} else {
for (int i = 0; i < (yyvsp[-8].iValue); i++) {
vars[i] = pp->boolvars.size();
pp->boolvars.push_back(varspec((yyvsp[-2].sValue),
new BoolVarSpec((yyvsp[-4].oSet),print,!print,false)));
}
}
if (print) {
AST::Array* a = new AST::Array();
a->a.push_back(arrayOutput((yyvsp[-1].argVec)->getCall("output_array")));
AST::Array* output = new AST::Array();
for (int i = 0; i < (yyvsp[-8].iValue); i++)
output->a.push_back(new AST::BoolVar(vars[i]));
a->a.push_back(output);
a->a.push_back(new AST::String(")"));
pp->output(std::string((yyvsp[-2].sValue)), a);
}
pp->boolvararrays.put((yyvsp[-2].sValue), vars);
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 42: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF VAR float_ti_expr_tail ':' ID annotations vardecl_float_var_array_init */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, false, "Floats not supported.");
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 43: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF VAR SET OF int_ti_expr_tail ':' ID annotations vardecl_set_var_array_init */
{
ParserState* pp = static_cast<ParserState*>(parm);
bool print = (yyvsp[-1].argVec) && (yyvsp[-1].argVec)->hasCall("output_array");
yyassert(pp, (yyvsp[-12].iValue) == 1, "Arrays must start at 1");
if (!pp->hadError) {
vector<int> vars((yyvsp[-10].iValue));
if ((yyvsp[0].oVarSpecVec)()) {
vector<VarSpec*>* vsv = (yyvsp[0].oVarSpecVec).some();
yyassert(pp, vsv->size() == static_cast<unsigned int>((yyvsp[-10].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError) {
for (int i = 0; i < (yyvsp[-10].iValue); i++) {
SetVarSpec* svsv = static_cast<SetVarSpec*>((*vsv)[i]);
if (svsv->alias)
vars[i] = svsv->i;
else {
vars[i] = pp->setvars.size();
pp->setvars.push_back(varspec((yyvsp[-2].sValue), (*vsv)[i]));
}
if (!pp->hadError && (yyvsp[-4].oSet)()) {
Option<AST::SetLit*> opt =
Option<AST::SetLit*>::some(new AST::SetLit(*(yyvsp[-4].oSet).some()));
addDomainConstraint(pp, "set_subset", new AST::SetVar(vars[i]), opt);
}
}
}
delete vsv;
} else {
SetVarSpec* ispec = new SetVarSpec((yyvsp[-4].oSet),print,!print, false);
string arrayname = "["; arrayname += (yyvsp[-2].sValue);
for (int i = 0; i < (yyvsp[-10].iValue)-1; i++) {
vars[i] = pp->setvars.size();
pp->setvars.push_back(varspec(arrayname, ispec));
}
vars[(yyvsp[-10].iValue)-1] = pp->setvars.size();
pp->setvars.push_back(varspec((yyvsp[-2].sValue), ispec));
}
if (print) {
AST::Array* a = new AST::Array();
a->a.push_back(arrayOutput((yyvsp[-1].argVec)->getCall("output_array")));
AST::Array* output = new AST::Array();
for (int i = 0; i < (yyvsp[-10].iValue); i++)
output->a.push_back(new AST::SetVar(vars[i]));
a->a.push_back(output);
a->a.push_back(new AST::String(")"));
pp->output(std::string((yyvsp[-2].sValue)), a);
}
pp->setvararrays.put((yyvsp[-2].sValue), vars);
}
delete (yyvsp[-1].argVec);
free((yyvsp[-2].sValue));
}
break;
case 44: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF int_ti_expr_tail ':' ID annotations '=' '[' int_list ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, (yyvsp[-12].iValue) == 1, "Arrays must start at 1");
yyassert(pp, (yyvsp[-1].setValue)->size() == static_cast<unsigned int>((yyvsp[-10].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError)
pp->intvalarrays.put((yyvsp[-5].sValue), *(yyvsp[-1].setValue));
delete (yyvsp[-1].setValue);
free((yyvsp[-5].sValue));
delete (yyvsp[-4].argVec);
}
break;
case 45: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF BOOLTOK ':' ID annotations '=' '[' bool_list ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, (yyvsp[-12].iValue) == 1, "Arrays must start at 1");
yyassert(pp, (yyvsp[-1].setValue)->size() == static_cast<unsigned int>((yyvsp[-10].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError)
pp->boolvalarrays.put((yyvsp[-5].sValue), *(yyvsp[-1].setValue));
delete (yyvsp[-1].setValue);
free((yyvsp[-5].sValue));
delete (yyvsp[-4].argVec);
}
break;
case 46: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF FLOATTOK ':' ID annotations '=' '[' float_list ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, false, "Floats not supported.");
delete (yyvsp[-4].argVec);
free((yyvsp[-5].sValue));
}
break;
case 47: /* vardecl_item: ARRAY '[' INT_LIT DOTDOT INT_LIT ']' OF SET OF int_ti_expr_tail ':' ID annotations '=' '[' set_literal_list ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
yyassert(pp, (yyvsp[-14].iValue) == 1, "Arrays must start at 1");
yyassert(pp, (yyvsp[-1].setValueList)->size() == static_cast<unsigned int>((yyvsp[-12].iValue)),
"Initializer size does not match array dimension");
if (!pp->hadError)
pp->setvalarrays.put((yyvsp[-5].sValue), *(yyvsp[-1].setValueList));
delete (yyvsp[-1].setValueList);
delete (yyvsp[-4].argVec);
free((yyvsp[-5].sValue));
}
break;
case 48: /* int_init: INT_LIT */
{
(yyval.varSpec) = new IntVarSpec((yyvsp[0].iValue), false, true, false);
}
break;
case 49: /* int_init: ID */
{
int v = 0;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->intvarTable.get((yyvsp[0].sValue), v))
(yyval.varSpec) = new IntVarSpec(Alias(v), false, true, false);
else {
pp->err << "Error: undefined identifier " << (yyvsp[0].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new IntVarSpec(0,false,true,false); // keep things consistent
}
free((yyvsp[0].sValue));
}
break;
case 50: /* int_init: ID '[' INT_LIT ']' */
{
vector<int> v;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->intvararrays.get((yyvsp[-3].sValue), v)) {
yyassert(pp,static_cast<unsigned int>((yyvsp[-1].iValue)) > 0 &&
static_cast<unsigned int>((yyvsp[-1].iValue)) <= v.size(),
"array access out of bounds");
if (!pp->hadError)
(yyval.varSpec) = new IntVarSpec(Alias(v[(yyvsp[-1].iValue)-1]),false,true,false);
else
(yyval.varSpec) = new IntVarSpec(0,false,true,false); // keep things consistent
} else {
pp->err << "Error: undefined array identifier " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new IntVarSpec(0,false,true,false); // keep things consistent
}
free((yyvsp[-3].sValue));
}
break;
case 51: /* int_init_list: %empty */
{
(yyval.varSpecVec) = new vector<VarSpec*>(0);
}
break;
case 52: /* int_init_list: int_init_list_head list_tail */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 53: /* int_init_list_head: int_init */
{
(yyval.varSpecVec) = new vector<VarSpec*>(1);
(*(yyval.varSpecVec))[0] = (yyvsp[0].varSpec);
}
break;
case 54: /* int_init_list_head: int_init_list_head ',' int_init */
{
(yyval.varSpecVec) = (yyvsp[-2].varSpecVec);
(yyval.varSpecVec)->push_back((yyvsp[0].varSpec));
}
break;
case 57: /* int_var_array_literal: '[' int_init_list ']' */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 58: /* float_init: FLOAT_LIT */
{
(yyval.varSpec) = new FloatVarSpec((yyvsp[0].dValue),false,true,false);
}
break;
case 59: /* float_init: ID */
{
int v = 0;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->floatvarTable.get((yyvsp[0].sValue), v))
(yyval.varSpec) = new FloatVarSpec(Alias(v),false,true,false);
else {
pp->err << "Error: undefined identifier " << (yyvsp[0].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new FloatVarSpec(0.0,false,true,false);
}
free((yyvsp[0].sValue));
}
break;
case 60: /* float_init: ID '[' INT_LIT ']' */
{
vector<int> v;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->floatvararrays.get((yyvsp[-3].sValue), v)) {
yyassert(pp,static_cast<unsigned int>((yyvsp[-1].iValue)) > 0 &&
static_cast<unsigned int>((yyvsp[-1].iValue)) <= v.size(),
"array access out of bounds");
if (!pp->hadError)
(yyval.varSpec) = new FloatVarSpec(Alias(v[(yyvsp[-1].iValue)-1]),false,true,false);
else
(yyval.varSpec) = new FloatVarSpec(0.0,false,true,false);
} else {
pp->err << "Error: undefined array identifier " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new FloatVarSpec(0.0,false,true,false);
}
free((yyvsp[-3].sValue));
}
break;
case 61: /* float_init_list: %empty */
{
(yyval.varSpecVec) = new vector<VarSpec*>(0);
}
break;
case 62: /* float_init_list: float_init_list_head list_tail */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 63: /* float_init_list_head: float_init */
{
(yyval.varSpecVec) = new vector<VarSpec*>(1);
(*(yyval.varSpecVec))[0] = (yyvsp[0].varSpec);
}
break;
case 64: /* float_init_list_head: float_init_list_head ',' float_init */
{
(yyval.varSpecVec) = (yyvsp[-2].varSpecVec);
(yyval.varSpecVec)->push_back((yyvsp[0].varSpec));
}
break;
case 65: /* float_var_array_literal: '[' float_init_list ']' */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 66: /* bool_init: BOOL_LIT */
{
(yyval.varSpec) = new BoolVarSpec((yyvsp[0].iValue),false,true,false);
}
break;
case 67: /* bool_init: ID */
{
int v = 0;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->boolvarTable.get((yyvsp[0].sValue), v))
(yyval.varSpec) = new BoolVarSpec(Alias(v),false,true,false);
else {
pp->err << "Error: undefined identifier " << (yyvsp[0].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new BoolVarSpec(false,false,true,false);
}
free((yyvsp[0].sValue));
}
break;
case 68: /* bool_init: ID '[' INT_LIT ']' */
{
vector<int> v;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->boolvararrays.get((yyvsp[-3].sValue), v)) {
yyassert(pp,static_cast<unsigned int>((yyvsp[-1].iValue)) > 0 &&
static_cast<unsigned int>((yyvsp[-1].iValue)) <= v.size(),
"array access out of bounds");
if (!pp->hadError)
(yyval.varSpec) = new BoolVarSpec(Alias(v[(yyvsp[-1].iValue)-1]),false,true,false);
else
(yyval.varSpec) = new BoolVarSpec(false,false,true,false);
} else {
pp->err << "Error: undefined array identifier " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new BoolVarSpec(false,false,true,false);
}
free((yyvsp[-3].sValue));
}
break;
case 69: /* bool_init_list: %empty */
{
(yyval.varSpecVec) = new vector<VarSpec*>(0);
}
break;
case 70: /* bool_init_list: bool_init_list_head list_tail */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 71: /* bool_init_list_head: bool_init */
{
(yyval.varSpecVec) = new vector<VarSpec*>(1);
(*(yyval.varSpecVec))[0] = (yyvsp[0].varSpec);
}
break;
case 72: /* bool_init_list_head: bool_init_list_head ',' bool_init */
{
(yyval.varSpecVec) = (yyvsp[-2].varSpecVec);
(yyval.varSpecVec)->push_back((yyvsp[0].varSpec));
}
break;
case 73: /* bool_var_array_literal: '[' bool_init_list ']' */
{ (yyval.varSpecVec) = (yyvsp[-1].varSpecVec); }
break;
case 74: /* set_init: set_literal */
{
(yyval.varSpec) = new SetVarSpec(Option<AST::SetLit*>::some((yyvsp[0].setLit)),false,true,false);
}
break;
case 75: /* set_init: ID */
{
ParserState* pp = static_cast<ParserState*>(parm);
int v = 0;
if (pp->setvarTable.get((yyvsp[0].sValue), v))
(yyval.varSpec) = new SetVarSpec(Alias(v),false,true,false);
else {
pp->err << "Error: undefined identifier " << (yyvsp[0].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new SetVarSpec(Alias(0),false,true,false);
}
free((yyvsp[0].sValue));
}
break;
case 76: /* set_init: ID '[' INT_LIT ']' */
{
vector<int> v;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->setvararrays.get((yyvsp[-3].sValue), v)) {
yyassert(pp,static_cast<unsigned int>((yyvsp[-1].iValue)) > 0 &&
static_cast<unsigned int>((yyvsp[-1].iValue)) <= v.size(),
"array access out of bounds");
if (!pp->hadError)
(yyval.varSpec) = new SetVarSpec(Alias(v[(yyvsp[-1].iValue)-1]),false,true,false);
else
(yyval.varSpec) = new SetVarSpec(Alias(0),false,true,false);
} else {
pp->err << "Error: undefined array identifier " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
(yyval.varSpec) = new SetVarSpec(Alias(0),false,true,false);
}
free((yyvsp[-3].sValue));
}
break;
case 77: /* set_init_list: %empty */
{
(yyval.varSpecVec) = new vector<VarSpec*>(0);
}
break;
case 78: /* set_init_list: set_init_list_head list_tail */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 79: /* set_init_list_head: set_init */
{
(yyval.varSpecVec) = new vector<VarSpec*>(1);
(*(yyval.varSpecVec))[0] = (yyvsp[0].varSpec);
}
break;
case 80: /* set_init_list_head: set_init_list_head ',' set_init */
{
(yyval.varSpecVec) = (yyvsp[-2].varSpecVec);
(yyval.varSpecVec)->push_back((yyvsp[0].varSpec));
}
break;
case 81: /* set_var_array_literal: '[' set_init_list ']' */
{
(yyval.varSpecVec) = (yyvsp[-1].varSpecVec);
}
break;
case 82: /* vardecl_int_var_array_init: %empty */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none();
}
break;
case 83: /* vardecl_int_var_array_init: '=' int_var_array_literal */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[0].varSpecVec));
}
break;
case 84: /* vardecl_bool_var_array_init: %empty */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none();
}
break;
case 85: /* vardecl_bool_var_array_init: '=' bool_var_array_literal */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[0].varSpecVec));
}
break;
case 86: /* vardecl_float_var_array_init: %empty */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none();
}
break;
case 87: /* vardecl_float_var_array_init: '=' float_var_array_literal */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[0].varSpecVec));
}
break;
case 88: /* vardecl_set_var_array_init: %empty */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::none();
}
break;
case 89: /* vardecl_set_var_array_init: '=' set_var_array_literal */
{
(yyval.oVarSpecVec) = Option<vector<VarSpec*>* >::some((yyvsp[0].varSpecVec));
}
break;
case 90: /* constraint_item: CONSTRAINT ID '(' flat_expr_list ')' annotations */
{
ParserState *pp = static_cast<ParserState*>(parm);
#if EXPOSE_INT_LITS
pp->domainConstraints2.push_back(std::pair<ConExpr*, AST::Node*>(new ConExpr((yyvsp[-4].sValue), (yyvsp[-2].argVec)), (yyvsp[0].argVec)));
#else
ConExpr c((yyvsp[-4].sValue), (yyvsp[-2].argVec));
if (!pp->hadError) {
try {
pp->fg->postConstraint(c, (yyvsp[0].argVec));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
delete (yyvsp[0].argVec);
#endif
free((yyvsp[-4].sValue));
}
break;
case 91: /* constraint_item: CONSTRAINT ID annotations */
{
ParserState *pp = static_cast<ParserState*>(parm);
AST::Array* args = new AST::Array(2);
args->a[0] = getVarRefArg(pp,(yyvsp[-1].sValue));
args->a[1] = new AST::BoolLit(true);
#if EXPOSE_INT_LITS
pp->domainConstraints2.push_back(std::pair<ConExpr*, AST::Node*>(new ConExpr("bool_eq", args), (yyvsp[0].argVec)));
#else
ConExpr c("bool_eq", args);
if (!pp->hadError) {
try {
pp->fg->postConstraint(c, (yyvsp[0].argVec));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
delete (yyvsp[0].argVec);
#endif
free((yyvsp[-1].sValue));
}
break;
case 92: /* constraint_item: CONSTRAINT ID '[' INT_LIT ']' annotations */
{
ParserState *pp = static_cast<ParserState*>(parm);
AST::Array* args = new AST::Array(2);
args->a[0] = getArrayElement(pp,(yyvsp[-4].sValue),(yyvsp[-2].iValue));
args->a[1] = new AST::BoolLit(true);
#if EXPOSE_INT_LITS
pp->domainConstraints2.push_back(std::pair<ConExpr*, AST::Node*>(new ConExpr("bool_eq", args), (yyvsp[0].argVec)));
#else
ConExpr c("bool_eq", args);
if (!pp->hadError) {
try {
pp->fg->postConstraint(c, (yyvsp[0].argVec));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
delete (yyvsp[0].argVec);
#endif
free((yyvsp[-4].sValue));
}
break;
case 93: /* solve_item: SOLVE annotations SATISFY */
{
ParserState *pp = static_cast<ParserState*>(parm);
if (!pp->hadError) {
pp->fg->solve((yyvsp[-1].argVec));
}
delete (yyvsp[-1].argVec);
}
break;
case 94: /* solve_item: SOLVE annotations minmax solve_expr */
{
ParserState *pp = static_cast<ParserState*>(parm);
if (!pp->hadError) {
if ((yyvsp[-1].bValue))
pp->fg->minimize((yyvsp[0].iValue),(yyvsp[-2].argVec));
else
pp->fg->maximize((yyvsp[0].iValue),(yyvsp[-2].argVec));
}
delete (yyvsp[-2].argVec);
}
break;
case 95: /* int_ti_expr_tail: INTTOK */
{
(yyval.oSet) = Option<AST::SetLit* >::none();
}
break;
case 96: /* int_ti_expr_tail: '{' int_list '}' */
{
(yyval.oSet) = Option<AST::SetLit* >::some(new AST::SetLit(*(yyvsp[-1].setValue)));
}
break;
case 97: /* int_ti_expr_tail: INT_LIT DOTDOT INT_LIT */
{
(yyval.oSet) = Option<AST::SetLit* >::some(new AST::SetLit((yyvsp[-2].iValue), (yyvsp[0].iValue)));
}
break;
case 98: /* bool_ti_expr_tail: BOOLTOK */
{
(yyval.oSet) = Option<AST::SetLit* >::none();
}
break;
case 99: /* bool_ti_expr_tail: '{' bool_list_head list_tail '}' */
{
bool haveTrue = false;
bool haveFalse = false;
for (int i = (yyvsp[-2].setValue)->size(); i--;) {
haveTrue |= ((*(yyvsp[-2].setValue))[i] == 1);
haveFalse |= ((*(yyvsp[-2].setValue))[i] == 0);
}
delete (yyvsp[-2].setValue);
(yyval.oSet) = Option<AST::SetLit* >::some(
new AST::SetLit(!haveFalse,haveTrue));
}
break;
case 102: /* set_literal: '{' int_list '}' */
{
(yyval.setLit) = new AST::SetLit(*(yyvsp[-1].setValue));
}
break;
case 103: /* set_literal: INT_LIT DOTDOT INT_LIT */
{
(yyval.setLit) = new AST::SetLit((yyvsp[-2].iValue), (yyvsp[0].iValue));
}
break;
case 104: /* int_list: %empty */
{
(yyval.setValue) = new vector<int>(0);
}
break;
case 105: /* int_list: int_list_head list_tail */
{
(yyval.setValue) = (yyvsp[-1].setValue);
}
break;
case 106: /* int_list_head: INT_LIT */
{
(yyval.setValue) = new vector<int>(1);
(*(yyval.setValue))[0] = (yyvsp[0].iValue);
}
break;
case 107: /* int_list_head: int_list_head ',' INT_LIT */
{
(yyval.setValue) = (yyvsp[-2].setValue);
(yyval.setValue)->push_back((yyvsp[0].iValue));
}
break;
case 108: /* bool_list: %empty */
{
(yyval.setValue) = new vector<int>(0);
}
break;
case 109: /* bool_list: bool_list_head list_tail */
{
(yyval.setValue) = (yyvsp[-1].setValue);
}
break;
case 110: /* bool_list_head: BOOL_LIT */
{
(yyval.setValue) = new vector<int>(1);
(*(yyval.setValue))[0] = (yyvsp[0].iValue);
}
break;
case 111: /* bool_list_head: bool_list_head ',' BOOL_LIT */
{
(yyval.setValue) = (yyvsp[-2].setValue);
(yyval.setValue)->push_back((yyvsp[0].iValue));
}
break;
case 112: /* float_list: %empty */
{
(yyval.floatSetValue) = new vector<double>(0);
}
break;
case 113: /* float_list: float_list_head list_tail */
{
(yyval.floatSetValue) = (yyvsp[-1].floatSetValue);
}
break;
case 114: /* float_list_head: FLOAT_LIT */
{
(yyval.floatSetValue) = new vector<double>(1);
(*(yyval.floatSetValue))[0] = (yyvsp[0].dValue);
}
break;
case 115: /* float_list_head: float_list_head ',' FLOAT_LIT */
{
(yyval.floatSetValue) = (yyvsp[-2].floatSetValue);
(yyval.floatSetValue)->push_back((yyvsp[0].dValue));
}
break;
case 116: /* set_literal_list: %empty */
{
(yyval.setValueList) = new vector<AST::SetLit>(0);
}
break;
case 117: /* set_literal_list: set_literal_list_head list_tail */
{
(yyval.setValueList) = (yyvsp[-1].setValueList);
}
break;
case 118: /* set_literal_list_head: set_literal */
{
(yyval.setValueList) = new vector<AST::SetLit>(1);
(*(yyval.setValueList))[0] = *(yyvsp[0].setLit);
delete (yyvsp[0].setLit);
}
break;
case 119: /* set_literal_list_head: set_literal_list_head ',' set_literal */
{
(yyval.setValueList) = (yyvsp[-2].setValueList);
(yyval.setValueList)->push_back(*(yyvsp[0].setLit));
delete (yyvsp[0].setLit);
}
break;
case 120: /* flat_expr_list: flat_expr */
{
(yyval.argVec) = new AST::Array((yyvsp[0].arg));
}
break;
case 121: /* flat_expr_list: flat_expr_list ',' flat_expr */
{
(yyval.argVec) = (yyvsp[-2].argVec);
(yyval.argVec)->append((yyvsp[0].arg));
}
break;
case 122: /* flat_expr: non_array_expr */
{
(yyval.arg) = (yyvsp[0].arg);
}
break;
case 123: /* flat_expr: '[' non_array_expr_list ']' */
{
(yyval.arg) = (yyvsp[-1].argVec);
}
break;
case 124: /* non_array_expr_opt: %empty */
{
(yyval.oArg) = Option<AST::Node*>::none();
}
break;
case 125: /* non_array_expr_opt: '=' non_array_expr */
{
(yyval.oArg) = Option<AST::Node*>::some((yyvsp[0].arg));
}
break;
case 126: /* non_array_expr: BOOL_LIT */
{
(yyval.arg) = new AST::BoolLit((yyvsp[0].iValue));
}
break;
case 127: /* non_array_expr: INT_LIT */
{
(yyval.arg) = new AST::IntLit((yyvsp[0].iValue));
}
break;
case 128: /* non_array_expr: FLOAT_LIT */
{
(yyval.arg) = new AST::FloatLit((yyvsp[0].dValue));
}
break;
case 129: /* non_array_expr: set_literal */
{
(yyval.arg) = (yyvsp[0].setLit);
}
break;
case 130: /* non_array_expr: ID */
{
vector<int> as;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->intvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::IntVar(as[i]);
(yyval.arg) = ia;
} else if (pp->boolvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::BoolVar(as[i]);
(yyval.arg) = ia;
} else if (pp->setvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::SetVar(as[i]);
(yyval.arg) = ia;
} else {
std::vector<int> is;
std::vector<AST::SetLit> isS;
int ival = 0;
bool bval = false;
if (pp->intvalarrays.get((yyvsp[0].sValue), is)) {
AST::Array *v = new AST::Array(is.size());
for (int i = is.size(); i--;)
v->a[i] = new AST::IntLit(is[i]);
(yyval.arg) = v;
} else if (pp->boolvalarrays.get((yyvsp[0].sValue), is)) {
AST::Array *v = new AST::Array(is.size());
for (int i = is.size(); i--;)
v->a[i] = new AST::BoolLit(is[i]);
(yyval.arg) = v;
} else if (pp->setvalarrays.get((yyvsp[0].sValue), isS)) {
AST::Array *v = new AST::Array(isS.size());
for (int i = isS.size(); i--;)
v->a[i] = new AST::SetLit(isS[i]);
(yyval.arg) = v;
} else if (pp->intvals.get((yyvsp[0].sValue), ival)) {
(yyval.arg) = new AST::IntLit(ival);
} else if (pp->boolvals.get((yyvsp[0].sValue), bval)) {
(yyval.arg) = new AST::BoolLit(bval);
} else {
(yyval.arg) = getVarRefArg(pp,(yyvsp[0].sValue));
}
}
free((yyvsp[0].sValue));
}
break;
case 131: /* non_array_expr: ID '[' non_array_expr ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
int i = -1;
yyassert(pp, (yyvsp[-1].arg)->isInt(i), "Non-integer array index.");
if (!pp->hadError)
(yyval.arg) = getArrayElement(static_cast<ParserState*>(parm),(yyvsp[-3].sValue),i);
else
(yyval.arg) = new AST::IntLit(0); // keep things consistent
free((yyvsp[-3].sValue));
}
break;
case 132: /* non_array_expr_list: %empty */
{
(yyval.argVec) = new AST::Array(0);
}
break;
case 133: /* non_array_expr_list: non_array_expr_list_head list_tail */
{
(yyval.argVec) = (yyvsp[-1].argVec);
}
break;
case 134: /* non_array_expr_list_head: non_array_expr */
{
(yyval.argVec) = new AST::Array((yyvsp[0].arg));
}
break;
case 135: /* non_array_expr_list_head: non_array_expr_list_head ',' non_array_expr */
{
(yyval.argVec) = (yyvsp[-2].argVec);
(yyval.argVec)->append((yyvsp[0].arg));
}
break;
case 136: /* solve_expr: INT_LIT */
{
ParserState *pp = static_cast<ParserState*>(parm);
// Create a new variable in the parser and append at the end
const int i = pp->intvars.size();
const std::string objname = "X_INTRODUCED_CHUFFEDOBJ";
pp->intvarTable.put(objname, i);
pp->intvars.push_back(varspec(objname,
new IntVarSpec((yyvsp[0].iValue),false,true,false)));
if (pp->fg != NULL) {
// Add a new IntVar to the FlatZincSpace if it was already created
try {
pp->fg->newIntVar(static_cast<IntVarSpec*>(pp->intvars[i].second));
IntVar* newiv = pp->fg->iv[pp->fg->intVarCount-1];
intVarString.insert(std::pair<IntVar*, std::string>(newiv, pp->intvars[i].first));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
(yyval.iValue) = i;
}
break;
case 137: /* solve_expr: ID */
{
ParserState *pp = static_cast<ParserState*>(parm);
int tmp = -1;
// Check whether the Objective variable is an integer constant
if (pp->intvals.get((yyvsp[0].sValue), tmp) && !pp->intvarTable.get((yyvsp[0].sValue), (yyval.iValue))) {
// Create a new variable in the parser and append at the end
const int i = pp->intvars.size();
pp->intvarTable.put((yyvsp[0].sValue), i);
pp->intvars.push_back(varspec((yyvsp[0].sValue),
new IntVarSpec(tmp,false,true,false)));
if (pp->fg != NULL) {
// Add a new IntVar to the FlatZincSpace if it was already created
try {
pp->fg->newIntVar(static_cast<IntVarSpec*>(pp->intvars[i].second));
IntVar* newiv = pp->fg->iv[pp->fg->intVarCount-1];
intVarString.insert(std::pair<IntVar*, std::string>(newiv, pp->intvars[i].first));
} catch (FlatZinc::Error& e) {
yyerror(pp, e.toString().c_str());
}
}
}
if (!pp->intvarTable.get((yyvsp[0].sValue), (yyval.iValue))) {
pp->err << "Error: unknown integer variable " << (yyvsp[0].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
}
free((yyvsp[0].sValue));
}
break;
case 138: /* solve_expr: ID '[' INT_LIT ']' */
{
vector<int> tmp;
ParserState *pp = static_cast<ParserState*>(parm);
if (!pp->intvararrays.get((yyvsp[-3].sValue), tmp)) {
pp->err << "Error: unknown integer variable array " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
}
if ((yyvsp[-1].iValue) == 0 || static_cast<unsigned int>((yyvsp[-1].iValue)) > tmp.size()) {
pp->err << "Error: array index out of bounds for array " << (yyvsp[-3].sValue)
<< " in line no. "
<< yyget_lineno(pp->yyscanner) << std::endl;
pp->hadError = true;
} else {
(yyval.iValue) = tmp[(yyvsp[-1].iValue)-1];
}
free((yyvsp[-3].sValue));
}
break;
case 141: /* annotations: %empty */
{
(yyval.argVec) = NULL;
}
break;
case 142: /* annotations: annotations_head */
{
(yyval.argVec) = (yyvsp[0].argVec);
}
break;
case 143: /* annotations_head: COLONCOLON annotation */
{
(yyval.argVec) = new AST::Array((yyvsp[0].arg));
}
break;
case 144: /* annotations_head: annotations_head COLONCOLON annotation */
{
(yyval.argVec) = (yyvsp[-2].argVec);
(yyval.argVec)->append((yyvsp[0].arg));
}
break;
case 145: /* annotation: ID '(' annotation_list ')' */
{
(yyval.arg) = new AST::Call((yyvsp[-3].sValue), AST::extractSingleton((yyvsp[-1].arg)));
free((yyvsp[-3].sValue));
}
break;
case 146: /* annotation: annotation_expr */
{
(yyval.arg) = (yyvsp[0].arg);
}
break;
case 147: /* annotation_list: annotation */
{
(yyval.arg) = new AST::Array((yyvsp[0].arg));
}
break;
case 148: /* annotation_list: annotation_list ',' annotation */
{
(yyval.arg) = (yyvsp[-2].arg);
(yyval.arg)->append((yyvsp[0].arg));
}
break;
case 149: /* annotation_expr: ann_non_array_expr */
{
(yyval.arg) = (yyvsp[0].arg);
}
break;
case 150: /* annotation_expr: '[' annotation_list ']' */
{
(yyval.arg) = (yyvsp[-1].arg);
}
break;
case 151: /* ann_non_array_expr: BOOL_LIT */
{
(yyval.arg) = new AST::BoolLit((yyvsp[0].iValue));
}
break;
case 152: /* ann_non_array_expr: INT_LIT */
{
(yyval.arg) = new AST::IntLit((yyvsp[0].iValue));
}
break;
case 153: /* ann_non_array_expr: FLOAT_LIT */
{
(yyval.arg) = new AST::FloatLit((yyvsp[0].dValue));
}
break;
case 154: /* ann_non_array_expr: set_literal */
{
(yyval.arg) = (yyvsp[0].setLit);
}
break;
case 155: /* ann_non_array_expr: ID */
{
vector<int> as;
ParserState* pp = static_cast<ParserState*>(parm);
if (pp->intvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::IntVar(as[i]);
(yyval.arg) = ia;
} else if (pp->boolvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::BoolVar(as[i]);
(yyval.arg) = ia;
} else if (pp->setvararrays.get((yyvsp[0].sValue), as)) {
AST::Array *ia = new AST::Array(as.size());
for (int i = as.size(); i--;)
ia->a[i] = new AST::SetVar(as[i]);
(yyval.arg) = ia;
} else {
std::vector<int> is;
int ival = 0;
bool bval = false;
if (pp->intvalarrays.get((yyvsp[0].sValue), is)) {
AST::Array *v = new AST::Array(is.size());
for (int i = is.size(); i--;)
v->a[i] = new AST::IntLit(is[i]);
(yyval.arg) = v;
} else if (pp->boolvalarrays.get((yyvsp[0].sValue), is)) {
AST::Array *v = new AST::Array(is.size());
for (int i = is.size(); i--;)
v->a[i] = new AST::BoolLit(is[i]);
(yyval.arg) = v;
} else if (pp->intvals.get((yyvsp[0].sValue), ival)) {
(yyval.arg) = new AST::IntLit(ival);
} else if (pp->boolvals.get((yyvsp[0].sValue), bval)) {
(yyval.arg) = new AST::BoolLit(bval);
} else {
(yyval.arg) = getVarRefArg(pp,(yyvsp[0].sValue),true);
}
}
free((yyvsp[0].sValue));
}
break;
case 156: /* ann_non_array_expr: ID '[' ann_non_array_expr ']' */
{
ParserState* pp = static_cast<ParserState*>(parm);
int i = -1;
yyassert(pp, (yyvsp[-1].arg)->isInt(i), "Non-integer array index.");
if (!pp->hadError)
(yyval.arg) = getArrayElement(static_cast<ParserState*>(parm),(yyvsp[-3].sValue),i);
else
(yyval.arg) = new AST::IntLit(0); // keep things consistent
free((yyvsp[-3].sValue));
}
break;
case 157: /* ann_non_array_expr: STRING_LIT */
{
(yyval.arg) = new AST::String((yyvsp[0].sValue));
free((yyvsp[0].sValue));
}
break;
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", YY_CAST (yysymbol_kind_t, yyr1[yyn]), &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
{
const int yylhs = yyr1[yyn] - YYNTOKENS;
const int yyi = yypgoto[yylhs] + *yyssp;
yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp
? yytable[yyi]
: yydefgoto[yylhs]);
}
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
{
yypcontext_t yyctx
= {yyssp, yytoken};
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx);
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == -1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = YY_CAST (char *,
YYSTACK_ALLOC (YY_CAST (YYSIZE_T, yymsg_alloc)));
if (yymsg)
{
yysyntax_error_status
= yysyntax_error (&yymsg_alloc, &yymsg, &yyctx);
yymsgp = yymsg;
}
else
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = YYENOMEM;
}
}
yyerror (parm, yymsgp);
if (yysyntax_error_status == YYENOMEM)
goto yyexhaustedlab;
}
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, parm);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers when the user code never invokes YYERROR and the
label yyerrorlab therefore never appears in user code. */
if (0)
YYERROR;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
/* Pop stack until we find a state that shifts the error token. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYSYMBOL_YYerror;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYSYMBOL_YYerror)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
YY_ACCESSING_SYMBOL (yystate), yyvsp, parm);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", YY_ACCESSING_SYMBOL (yyn), yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if 1
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (parm, YY_("memory exhausted"));
yyresult = 2;
goto yyreturn;
#endif
/*-------------------------------------------------------.
| yyreturn -- parsing is finished, clean up and return. |
`-------------------------------------------------------*/
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, parm);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
YY_ACCESSING_SYMBOL (+*yyssp), yyvsp, parm);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
return yyresult;
}
| 38.270873 | 150 | 0.494677 | [
"vector",
"model"
] |
bec03e07038db885b4eb9369011066923fca0f15 | 9,227 | cpp | C++ | hydra/blocks/old/hubbardmodeldetail.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | hydra/blocks/old/hubbardmodeldetail.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | hydra/blocks/old/hubbardmodeldetail.cpp | awietek/hydra | 724a101500e308e91186a5cd6c5c520d8b343a6c | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Alexander Wietek - 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 <hydra/utils/complex.h>
#include "hubbardmodeldetail.h"
namespace hydra {
namespace detail {
template <class coeff_t>
void set_hubbard_terms(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &hoppings,
std::vector<coeff_t> &hopping_amplitudes,
std::vector<std::pair<int, int>> ¤ts,
std::vector<coeff_t> ¤t_amplitudes,
std::vector<std::pair<int, int>> &interactions,
std::vector<double> &interaction_strengths,
std::vector<int> &onsites,
std::vector<double> &onsite_potentials,
std::vector<std::pair<int, int>> &szszs,
std::vector<double> &szsz_amplitudes,
std::vector<std::pair<int, int>> &exchanges,
std::vector<coeff_t> &exchange_amplitudes, double &U) {
set_hoppings<coeff_t>(bondlist, couplings, hoppings, hopping_amplitudes);
set_currents<coeff_t>(bondlist, couplings, currents, current_amplitudes);
set_interactions(bondlist, couplings, interactions, interaction_strengths);
set_onsites(bondlist, couplings, onsites, onsite_potentials);
set_U(couplings, U);
set_szszs(bondlist, couplings, szszs, szsz_amplitudes);
set_exchanges<coeff_t>(bondlist, couplings, exchanges, exchange_amplitudes);
}
template <>
void set_hoppings<double>(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &hoppings,
std::vector<double> &hopping_amplitudes) {
BondList hopping_list = bondlist.bonds_of_type("HUBBARDHOP");
for (auto bond : hopping_list) {
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
hoppings.push_back({s1, s2});
double c = ForceReal<double>(
couplings[bond.coupling()], true,
"Warning: deprecating imaginary part of hopping (real Hubbard)!");
hopping_amplitudes.push_back(c);
}
}
template <>
void set_hoppings<complex>(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &hoppings,
std::vector<complex> &hopping_amplitudes) {
BondList hopping_list = bondlist.bonds_of_type("HUBBARDHOP");
for (auto bond : hopping_list) {
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
hoppings.push_back({s1, s2});
complex c = couplings[bond.coupling()];
hopping_amplitudes.push_back(c);
}
}
template <>
void set_currents<double>(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> ¤ts,
std::vector<double> ¤t_amplitudes) {
BondList current_list = bondlist.bonds_of_type("HUBBARDCURRENT");
for (auto bond : current_list) {
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
currents.push_back({s1, s2});
assert(couplings.is_real(bond.coupling())); // current be real
double c = couplings.real(bond.coupling());
current_amplitudes.push_back(c);
}
}
template <>
void set_currents<complex>(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> ¤ts,
std::vector<complex> ¤t_amplitudes) {
BondList current_list = bondlist.bonds_of_type("HUBBARDCURRENT");
for (auto bond : current_list) {
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
currents.push_back({s1, s2});
assert(couplings.is_real(bond.coupling())); // current be real
complex c = complex(0., couplings.real(bond.coupling()));
current_amplitudes.push_back(c);
}
}
void set_interactions(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &interactions,
std::vector<double> &interaction_strengths) {
BondList interaction_list = bondlist.bonds_of_type("HUBBARDV");
for (auto bond : interaction_list) {
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
interactions.push_back({s1, s2});
assert(couplings.is_real(bond.coupling())); // V be real
interaction_strengths.push_back(couplings.real(bond.coupling()));
}
}
void set_onsites(BondList bondlist, Couplings couplings,
std::vector<int> &onsites,
std::vector<double> &onsite_potentials) {
BondList onsites_list = bondlist.bonds_of_type("HUBBARDMU");
for (auto bond : onsites_list)
if (couplings.defined(bond.coupling())) {
assert(bond.sites().size() == 1);
int s1 = bond.sites()[0];
onsites.push_back(s1);
assert(couplings.is_real(bond.coupling())); // mu be real
onsite_potentials.push_back(couplings.real(bond.coupling()));
}
}
void set_U(Couplings couplings, double &U) {
if (couplings.defined("U")) {
assert(couplings.is_real("U")); // U be real
U = couplings.real("U");
} else
U = 0.;
}
void set_szszs(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &szszs,
std::vector<double> &szsz_amplitudes) {
BondList szsz_list = bondlist.bonds_of_type("HEISENBERG");
for (auto bond : szsz_list) {
assert(bond.sites().size() == 2);
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
szszs.push_back({s1, s2});
double c = ForceReal<double>(
couplings[bond.coupling()], true,
"Warning: deprecating imaginary part of Heisenberg (real Hubbard)!");
szsz_amplitudes.push_back(c);
}
szsz_list = bondlist.bonds_of_type("SZSZ");
for (auto bond : szsz_list) {
assert(bond.sites().size() == 2);
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
szszs.push_back({s1, s2});
double c = ForceReal<double>(
couplings[bond.coupling()], true,
"Warning: deprecating imaginary part of Heisenberg (real Hubbard)!");
szsz_amplitudes.push_back(c);
}
}
template <class coeff_t>
void set_exchanges(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &exchanges,
std::vector<coeff_t> &exchange_amplitudes) {
BondList exchange_list = bondlist.bonds_of_type("HEISENBERG");
for (auto bond : exchange_list) {
assert(bond.sites().size() == 2);
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
exchanges.push_back({s1, s2});
coeff_t c = ForceReal<coeff_t>(
couplings[bond.coupling()], true,
"Warning: deprecating imaginary part of Heisenberg (real Hubbard)!");
exchange_amplitudes.push_back(c);
}
exchange_list = bondlist.bonds_of_type("EXCHANGEXY");
for (auto bond : exchange_list) {
assert(bond.sites().size() == 2);
int s1 = bond.sites()[0];
int s2 = bond.sites()[1];
exchanges.push_back({s1, s2});
coeff_t c = ForceReal<coeff_t>(
couplings[bond.coupling()], true,
"Warning: deprecating imaginary part of Heisenberg (real Hubbard)!");
exchange_amplitudes.push_back(c);
}
}
template void
set_hubbard_terms<double>(BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &hoppings,
std::vector<double> &hopping_amplitudes,
std::vector<std::pair<int, int>> ¤ts,
std::vector<double> ¤t_amplitudes,
std::vector<std::pair<int, int>> &interactions,
std::vector<double> &interaction_strengths,
std::vector<int> &onsites,
std::vector<double> &onsite_potentials,
std::vector<std::pair<int, int>> &szszs,
std::vector<double> &szsz_amplitudes,
std::vector<std::pair<int, int>> &exchanges,
std::vector<double> &exchange_amplitudes, double &U);
template void set_hubbard_terms<complex>(
BondList bondlist, Couplings couplings,
std::vector<std::pair<int, int>> &hoppings,
std::vector<complex> &hopping_amplitudes,
std::vector<std::pair<int, int>> ¤ts,
std::vector<complex> ¤t_amplitudes,
std::vector<std::pair<int, int>> &interactions,
std::vector<double> &interaction_strengths, std::vector<int> &onsites,
std::vector<double> &onsite_potentials,
std::vector<std::pair<int, int>> &szszs,
std::vector<double> &szsz_amplitudes,
std::vector<std::pair<int, int>> &exchanges,
std::vector<complex> &exchange_amplitudes, double &U);
} // namespace detail
} // namespace hydra
| 40.292576 | 79 | 0.631083 | [
"vector"
] |
bec65c1126171bae2f179751f00bfb491c9cb22c | 4,055 | cpp | C++ | lib/CodeGen/Primitives/TypenamePrimitive.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 80 | 2015-02-19T21:38:57.000Z | 2016-05-25T06:53:12.000Z | lib/CodeGen/Primitives/TypenamePrimitive.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 8 | 2015-02-20T09:47:20.000Z | 2015-11-13T07:49:17.000Z | lib/CodeGen/Primitives/TypenamePrimitive.cpp | scross99/locic | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | [
"MIT"
] | 6 | 2015-02-20T11:26:19.000Z | 2016-04-13T14:30:39.000Z | #include <assert.h>
#include <stdexcept>
#include <string>
#include <vector>
#include <llvm-abi/ABI.hpp>
#include <llvm-abi/ABITypeInfo.hpp>
#include <llvm-abi/Type.hpp>
#include <llvm-abi/TypeBuilder.hpp>
#include <locic/CodeGen/ArgInfo.hpp>
#include <locic/CodeGen/ConstantGenerator.hpp>
#include <locic/CodeGen/Debug.hpp>
#include <locic/CodeGen/Function.hpp>
#include <locic/CodeGen/FunctionCallInfo.hpp>
#include <locic/CodeGen/GenABIType.hpp>
#include <locic/CodeGen/GenVTable.hpp>
#include <locic/CodeGen/Interface.hpp>
#include <locic/CodeGen/InternalContext.hpp>
#include <locic/CodeGen/IREmitter.hpp>
#include <locic/CodeGen/Module.hpp>
#include <locic/CodeGen/Primitive.hpp>
#include <locic/CodeGen/Primitives.hpp>
#include <locic/CodeGen/Primitives/TypenamePrimitive.hpp>
#include <locic/CodeGen/Routines.hpp>
#include <locic/CodeGen/SizeOf.hpp>
#include <locic/CodeGen/Support.hpp>
#include <locic/CodeGen/Template.hpp>
#include <locic/CodeGen/TypeGenerator.hpp>
#include <locic/CodeGen/UnwindAction.hpp>
#include <locic/CodeGen/VTable.hpp>
#include <locic/Support/MethodID.hpp>
namespace locic {
namespace CodeGen {
TypenamePrimitive::TypenamePrimitive(const AST::TypeInstance& typeInstance)
: typeInstance_(typeInstance) {
(void) typeInstance_;
}
bool TypenamePrimitive::isSizeAlwaysKnown(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return true;
}
bool TypenamePrimitive::isSizeKnownInThisModule(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return true;
}
bool TypenamePrimitive::hasCustomDestructor(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return false;
}
bool TypenamePrimitive::hasCustomMove(const TypeInfo& /*typeInfo*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return false;
}
llvm_abi::Type TypenamePrimitive::getABIType(Module& module,
const llvm_abi::TypeBuilder& /*abiTypeBuilder*/,
llvm::ArrayRef<AST::Value> /*templateArguments*/) const {
return typeInfoType(module);
}
llvm::Value* TypenamePrimitive::emitMethod(IREmitter& irEmitter,
const MethodID methodID,
llvm::ArrayRef<AST::Value> typeTemplateArguments,
llvm::ArrayRef<AST::Value> /*functionTemplateArguments*/,
PendingResultArray args,
llvm::Value* /*resultPtr*/) const {
auto& function = irEmitter.function();
auto& module = irEmitter.module();
const auto& constantGenerator = irEmitter.constantGenerator();
switch (methodID) {
case METHOD_ALIGNMASK: {
const auto abiType = this->getABIType(module,
module.abiTypeBuilder(),
typeTemplateArguments);
return constantGenerator.getSizeTValue(module.abi().typeInfo().getTypeRequiredAlign(abiType).asBytes() - 1);
}
case METHOD_SIZEOF: {
const auto abiType = this->getABIType(module,
module.abiTypeBuilder(),
typeTemplateArguments);
return constantGenerator.getSizeTValue(module.abi().typeInfo().getTypeAllocSize(abiType).asBytes());
}
case METHOD_IMPLICITCOPY:
case METHOD_COPY:
case METHOD_MOVE:
return args[0].resolveWithoutBind(function);
case METHOD_DESTROY:
(void) args[0].resolveWithoutBind(function);
return ConstantGenerator(module).getVoidUndef();
default:
llvm_unreachable("Unknown typename primitive method.");
}
}
}
}
| 36.531532 | 113 | 0.623921 | [
"vector"
] |
beccedb1b00b6b6c0cc50d7d603ad6a17539e1d9 | 1,260 | hpp | C++ | lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/cell_updater_3d.hpp | GalaxyHunters/Vivid | f724e5671b650433d0c26319c86231bd3b246e4e | [
"BSD-3-Clause"
] | null | null | null | lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/cell_updater_3d.hpp | GalaxyHunters/Vivid | f724e5671b650433d0c26319c86231bd3b246e4e | [
"BSD-3-Clause"
] | 222 | 2018-07-25T18:13:57.000Z | 2021-10-10T14:54:04.000Z | lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/three_dimensional/cell_updater_3d.hpp | GalaxyHunters/Vivid | f724e5671b650433d0c26319c86231bd3b246e4e | [
"BSD-3-Clause"
] | 2 | 2018-07-29T09:39:40.000Z | 2018-08-25T19:17:49.000Z | /*! \file cell_updater_3d.hpp
\brief Abstract class for cell update scheme
\author Almog Yalinewich
*/
#ifndef CELL_UPDATER_HPP
#define CELL_UPDATER_HPP 1
#include "computational_cell.hpp"
#include "conserved_3d.hpp"
#include "../../3D/GeometryCommon/Tessellation3D.hpp"
#include "../two_dimensional/computational_cell_2d.hpp"
#include "../common/equation_of_state.hpp"
//! \brief Abstract clas for cell update scheme
class CellUpdater3D
{
public:
/*! \brief Calculates the computational cell
\param res The new cells given as output
\param extensives The extensive conserved variables
\param eos Equation of state
\param tess The tessellation
\param tracerstickernames The names of the tracers and stickers
\return Computational cell
*/
virtual void operator() (vector<ComputationalCell3D> &res, EquationOfState const& eos,
const Tessellation3D& tess,vector<Conserved3D>& extensives,TracerStickerNames const& tracerstickernames)const = 0;
//! \brief Class destructor
virtual ~CellUpdater3D(void);
};
/*!
\brief Calculates velocity from extensive in SR
\param cell The extensive variable
\param G The adiabatic index
\return The velocity
*/
double GetVelocity(Conserved3D const& cell, double G);
#endif // CELL_UPDATER_HPP
| 29.302326 | 116 | 0.77381 | [
"vector",
"3d"
] |
bee2fbe0b1259b406b9494bbc55abdb91071a3ba | 5,477 | cpp | C++ | src/Core/Animation/DualQuaternionSkinning.cpp | Yasoo31/Radium-Engine | e22754d0abe192207fd946509cbd63c4f9e52dd4 | [
"Apache-2.0"
] | 78 | 2017-12-01T12:23:22.000Z | 2022-03-31T05:08:09.000Z | src/Core/Animation/DualQuaternionSkinning.cpp | neurodiverseEsoteric/Radium-Engine | ebebc29d889a9d32e0637e425e589e403d8edef8 | [
"Apache-2.0"
] | 527 | 2017-09-25T13:05:32.000Z | 2022-03-31T18:47:44.000Z | src/Core/Animation/DualQuaternionSkinning.cpp | neurodiverseEsoteric/Radium-Engine | ebebc29d889a9d32e0637e425e589e403d8edef8 | [
"Apache-2.0"
] | 48 | 2018-01-04T22:08:08.000Z | 2022-03-03T08:13:41.000Z | #include <Core/Animation/DualQuaternionSkinning.hpp>
#include <Core/Animation/SkinningData.hpp>
namespace Ra {
namespace Core {
namespace Animation {
DQList computeDQ( const Pose& pose, const Sparse& weight ) {
CORE_ASSERT( ( pose.size() == size_t( weight.cols() ) ), "pose/weight size mismatch." );
DQList DQ( weight.rows(),
DualQuaternion( Quaternion( 0, 0, 0, 0 ), Quaternion( 0, 0, 0, 0 ) ) );
// Stores the first non-zero quaternion for each vertex.
std::vector<uint> firstNonZero( weight.rows(), std::numeric_limits<uint>::max() );
// Contains the converted dual quaternions from the pose
std::vector<DualQuaternion> poseDQ( pose.size() );
// Loop through all transforms Tj
for ( int j = 0; j < weight.outerSize(); ++j )
{
poseDQ[j] = DualQuaternion( pose[j] );
// Count how many vertices are influenced by the given transform
const int nonZero = weight.col( j ).nonZeros();
Sparse::InnerIterator it0( weight, j );
#pragma omp parallel for
// This for loop is here just because OpenMP wants classic for loops.
// Since we cannot iterate directly through the non-zero elements using the InnerIterator,
// we initialize an InnerIterator to the first element and then we increase it nz times.
/*
* This crappy piece of code was done in order to avoid the critical section
* DQ[i] += wq;
*
* that was occurring when parallelizing the main for loop.
*
* NOTE: this could be definitely improved by using std::thread
*/
// Loop through all vertices vi who depend on Tj
for ( int nz = 0; nz < nonZero; ++nz )
{
Sparse::InnerIterator itn = it0 + Eigen::Index( nz );
const uint i = itn.row();
const Scalar w = itn.value();
firstNonZero[i] = std::min( firstNonZero[i], uint( j ) );
const Scalar sign =
Ra::Core::Math::signNZ( poseDQ[j].getQ0().dot( poseDQ[firstNonZero[i]].getQ0() ) );
const auto wq = poseDQ[j] * w * sign;
DQ[i] += wq;
}
}
// Normalize all dual quats.
#pragma omp parallel for
for ( int i = 0; i < int( DQ.size() ); ++i )
{
DQ[i].normalize();
}
return DQ;
}
// alternate naive version, for reference purposes.
// See Kavan , Collins, Zara and O'Sullivan, 2008
DQList computeDQ_naive( const Pose& pose, const Sparse& weight ) {
CORE_ASSERT( ( pose.size() == size_t( weight.cols() ) ), "pose/weight size mismatch." );
DQList DQ( weight.rows(),
DualQuaternion( Quaternion( 0, 0, 0, 0 ), Quaternion( 0, 0, 0, 0 ) ) );
std::vector<DualQuaternion> poseDQ( pose.size() );
// 1. Convert all transforms to DQ
#pragma omp parallel for
for ( int j = 0; j < weight.cols(); ++j )
{
poseDQ[j] = DualQuaternion( pose[j] );
}
// 2. for all vertices, blend the dual quats.
for ( int i = 0; i < weight.rows(); ++i )
{
int firstNonZero = -1;
for ( uint j = 0; j < weight.cols(); ++j )
{
const Scalar& w = weight.coeff( i, j );
if ( w == 0 ) { continue; }
if ( firstNonZero < 0 ) { firstNonZero = j; }
// Flip the dual quaternion sign according to the dot product with the first non-null
// dual quat see Algorithm 2 in section 4.1 of the paper.
Scalar sign =
Ra::Core::Math::signNZ( poseDQ[j].getQ0().dot( poseDQ[firstNonZero].getQ0() ) );
DQ[i] += sign * w * poseDQ[j];
}
}
// 3. renormalize all dual quats.
#pragma omp parallel for
for ( int i = 0; i < int( DQ.size() ); ++i )
{
DQ[i].normalize();
}
return DQ;
}
Vector3Array applyDualQuaternions( const DQList& DQ, const Vector3Array& vertices ) {
Vector3Array out( vertices.size(), Vector3::Zero() );
#pragma omp parallel for
for ( int i = 0; i < int( vertices.size() ); ++i )
{
out[i] = DQ[i].transform( vertices[i] );
}
return out;
}
void dualQuaternionSkinning( const SkinningRefData& refData,
const Vector3Array& tangents,
const Vector3Array& bitangents,
SkinningFrameData& frameData ) {
// prepare the pose w.r.t. the bind matrices and the mesh tranform
auto pose = frameData.m_skeleton.getPose( HandleArray::SpaceType::MODEL );
#pragma omp parallel for
for ( int i = 0; i < int( frameData.m_skeleton.size() ); ++i )
{
pose[i] = refData.m_meshTransformInverse * pose[i] * refData.m_bindMatrices[i];
}
// compute the dual quaternion for each vertex
const auto DQ = computeDQ( pose, refData.m_weights );
// apply DQS
const auto& vertices = refData.m_referenceMesh.vertices();
const auto& normals = refData.m_referenceMesh.normals();
#pragma omp parallel for
for ( int i = 0; i < int( frameData.m_currentPosition.size() ); ++i )
{
const auto& DQi = DQ[i];
frameData.m_currentPosition[i] = DQi.transform( vertices[i] );
frameData.m_currentNormal[i] = DQi.rotate( normals[i] );
frameData.m_currentTangent[i] = DQi.rotate( tangents[i] );
frameData.m_currentBitangent[i] = DQi.rotate( bitangents[i] );
}
}
} // namespace Animation
} // namespace Core
} // namespace Ra
| 36.513333 | 99 | 0.585357 | [
"mesh",
"vector",
"model",
"transform"
] |
beec95f4a6e578e2207104fe750abda9b69a0227 | 1,554 | cpp | C++ | _codeforces/191C/191c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | _codeforces/191C/191c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | _codeforces/191C/191c.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <iostream>
#include <vector>
using namespace std;
const int maxn = 200005;
const int maxlg = 22;
int n, k, level[maxn], anc[maxlg][maxn], mars[maxn];
vector <int> g[maxn];
inline void dfs(int node, int father) {
anc[0][node] = father;
level[node] = level[father] + 1;
for(auto it : g[node])
if(it != father)
dfs(it, node);
}
inline void dfssolve(int node, int father) {
for(auto it : g[node])
if(it != father) {
dfssolve(it, node);
mars[node] += mars[it];
}
}
inline int lca(int x, int y) {
if(level[x] < level[y])
swap(x, y);
int diff = level[x] - level[y];
for(int i = 0 ; (1 << i) <= diff ; ++ i)
if(diff & (1 << i))
x = anc[i][x];
if(x == y)
return x;
for(int i = maxlg - 1 ; i >= 0 ; -- i)
if(anc[i][x] != anc[i][y]) {
x = anc[i][x];
y = anc[i][y];
}
return anc[0][x];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("191c.in", "r", stdin);
freopen("191c.out", "w", stdout);
#endif
vector<pair<int, int> > edges;
cin >> n;
for(int i = 1 ; i < n ; ++ i) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
edges.push_back(make_pair(x, y));
}
dfs(1, 0);
for(int i = 1 ; i < maxlg ; ++ i)
for(int j = 1 ; j <= n ; ++ j)
anc[i][j] = anc[i - 1][anc[i - 1][j]];
cin >> k;
for(int i = 1 ; i <= k ; ++ i) {
int x, y;
cin >> x >> y;
++ mars[x];
++ mars[y];
mars[lca(x, y)] -= 2;
}
dfssolve(1, 0);
mars[1] = 0;
for(auto it : edges) {
int x = it.first;
int y = it.second;
if(level[x] < level[y])
swap(x, y);
cout << mars[x] << ' ';
}
}
| 18.722892 | 52 | 0.513514 | [
"vector"
] |
beed288776010d36171f5b9bef4f2ffd20bd4875 | 2,265 | cpp | C++ | 2019/0420_tenka1-2019/D.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 7 | 2019-03-24T14:06:29.000Z | 2020-09-17T21:16:36.000Z | 2019/0420_tenka1-2019/D.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | null | null | null | 2019/0420_tenka1-2019/D.cpp | kazunetakahashi/atcoder | 16ce65829ccc180260b19316e276c2fcf6606c53 | [
"MIT"
] | 1 | 2020-07-22T17:27:09.000Z | 2020-07-22T17:27:09.000Z | #define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2019-4-20 21:08:04
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
const ll M = 998244353;
int N;
int a[310];
int S = 0;
ll dp[310][90010];
ll DP[310][90010];
int main()
{
cin >> N;
for (auto i = 0; i < N; i++)
{
cin >> a[i];
S += a[i];
}
fill(&dp[0][0], &dp[0][0] + 310 * 90010, 0);
dp[0][0] = 1;
for (auto i = 0; i < N; i++)
{
for (auto v = 0; v < 90010; v++)
{
if (dp[i][v] == 0)
{
continue;
}
dp[i + 1][v + a[i]] += dp[i][v];
dp[i + 1][v + a[i]] %= M;
dp[i + 1][v] += 2 * dp[i][v];
dp[i + 1][v] %= M;
}
}
ll K = 0;
for (auto v = (S + 1) / 2; v <= S; v++)
{
K += dp[N][v];
}
fill(&DP[0][0], &DP[0][0] + 310 * 90010, 0);
DP[0][0] = 1;
for (auto i = 0; i < N; i++)
{
for (auto v = 0; v < 90010; v++)
{
if (DP[i][v] == 0)
{
continue;
}
DP[i + 1][v + a[i]] += DP[i][v];
DP[i + 1][v + a[i]] %= M;
DP[i + 1][v] += DP[i][v];
DP[i + 1][v] %= M;
}
}
ll L = 0;
if (S % 2 == 0)
{
L = DP[N][S / 2];
}
ll ans = 1;
for (auto i = 0; i < N; i++)
{
ans *= 3LL;
ans %= M;
}
ans += M - (3 * K) % M;
ans %= M;
ans += 3 * L;
ans %= M;
cout << ans << endl;
} | 20.972222 | 103 | 0.4883 | [
"vector"
] |
beee50397d8fde35592f38e151976f4d78b5b1eb | 5,125 | cpp | C++ | hedcuter/code/hedcut.cpp | FaezDabestani/hedcut | bd653ea88a3b52586be10ed4a9d52d276bfbd646 | [
"MIT"
] | null | null | null | hedcuter/code/hedcut.cpp | FaezDabestani/hedcut | bd653ea88a3b52586be10ed4a9d52d276bfbd646 | [
"MIT"
] | null | null | null | hedcuter/code/hedcut.cpp | FaezDabestani/hedcut | bd653ea88a3b52586be10ed4a9d52d276bfbd646 | [
"MIT"
] | null | null | null | #include "hedcut.h"
#include <time.h>
Hedcut::Hedcut()
{
//control flags
disk_size = 1; //if uniform_disk_size is true, all disks have radius=disk_size,
//othewise, the largest disks will have their radii=disk_size
deviation = 7;
uniform_disk_size = false; //true if all disks have the same size. disk_size is used when uniform_disk_size is true.
collision = true; //true if disks are allowed to collide
black_disk = false; //true if all disks are black ONLY
//cvt control flags
cvt_iteration_limit = 100; //max number of iterations when building cvf
max_site_displacement = 1.01f; //max tolerable site displacement in each iteration.
average_termination = false;
gpu = false;
subpixels = 1;
debug = false;
}
bool Hedcut::build(cv::Mat & input_image, int n)
{
cv::Mat grayscale;
cv::cvtColor(input_image, grayscale, CV_BGR2GRAY);
//sample n points
std::vector<cv::Point2d> pts;
sample_initial_points(grayscale, n, pts);
//initialize cvt
CVT cvt;
cvt.iteration_limit = this->cvt_iteration_limit;
cvt.max_site_displacement = this->max_site_displacement;
cvt.average_termination = this->average_termination;
cvt.gpu = this->gpu;
cvt.subpixels = this->subpixels;
cvt.debug = this->debug;
clock_t startTime, endTime;
startTime = clock();
//compute weighted centroidal voronoi tessellation
if (cvt.gpu)
cvt.compute_weighted_cvt_GPU(input_image, pts);
else
cvt.compute_weighted_cvt(grayscale, pts); //*****
endTime = clock();
std::cout << "Total time: "<< ((double)(endTime - startTime)) / CLOCKS_PER_SEC << std::endl;
if (debug) cv::waitKey();
//create disks
create_disks(input_image, cvt);
return true;
}
void Hedcut::sample_initial_points(cv::Mat & img, int n, std::vector<cv::Point2d> & pts)
{
//create n points that spread evenly that are in areas of black points...
int count = 0;
std::default_random_engine generator;
std::exponential_distribution<double> distribution(deviation);
cv::RNG rng_uniform(time(NULL));
cv::RNG rng_gaussian(time(NULL));
cv::Mat visited(img.size(), CV_8U, cv::Scalar::all(0)); //all unvisited
while (count < n)
{
//generate a random point
int c = (int)floor(img.size().width*rng_uniform.uniform(0.f, 1.f));
int r = (int)floor(img.size().height*rng_uniform.uniform(0.f, 1.f));
//decide to keep basic on a probability (black has higher probability)
float value = img.at<uchar>(r, c)*1.0/255; //black:0, white:1
//float gr = fabs(rng_gaussian.gaussian(0.8));
float gr = (float)abs(distribution(generator));
if ( value < gr && visited.at<uchar>(r, c) ==0) //keep
{
count++;
pts.push_back(cv::Point(r, c));
visited.at<uchar>(r,c)=1;
}
}
if (debug)
{
cv::Mat tmp = img.clone();
for (auto& c : pts)
{
cv::circle(tmp, cv::Point(c.y, c.x), 2, CV_RGB(0, 0, 255), -1);
}
cv::imshow("samples", tmp);
cv::waitKey();
}
}
inline float distance(cv::Point p1, cv::Point p2) {
return (sqrt(pow(p1.x - p2.x,2)+ pow(p1.y - p2.y, 2)));
}
void Hedcut::create_disks(cv::Mat & img, CVT & cvt)
{
cv::Mat grayscale;
cv::cvtColor(img, grayscale, CV_BGR2GRAY);
disks.clear();
//create disks from cvt
for (auto& cell : cvt.getCells())
{
//compute avg intensity
unsigned int total = 0;
unsigned int r = 0, g = 0, b = 0;
for (auto & resizedPix : cell.coverage)
{
cv::Point pix(resizedPix.x / subpixels, resizedPix.y / subpixels);
total += grayscale.at<uchar>(pix.x, pix.y);
r += img.at<cv::Vec3b>(pix.x, pix.y)[2];
g += img.at<cv::Vec3b>(pix.x, pix.y)[1];
b += img.at<cv::Vec3b>(pix.x, pix.y)[0];
}
float avg_v = floor(total * 1.0f/ cell.coverage.size());
r = floor(r / cell.coverage.size());
g = floor(g / cell.coverage.size());
b = floor(b / cell.coverage.size());
cv::Point2d up_pos = cell.site,
down_pos = cell.site,
left_pos = cell.site,
right_pos = cell.site;
if (!uniform_disk_size) {
for (auto& c : cell.coverage){
if (c.y - left_pos.y < std::numeric_limits<float>::epsilon()) {
if (c.x <= left_pos.x) {
left_pos = c;
}
else if (right_pos.x <= c.x) {
right_pos = c;
}
}
else if (c.x - left_pos.x < std::numeric_limits<float>::epsilon()) {
if (c.y <= left_pos.y) {
up_pos = c;
}
else if (right_pos.y <= c.y) {
down_pos = c;
}
}
}
float diameter;
if(collision){
diameter = std::max(distance(right_pos , left_pos), distance(up_pos , down_pos));
}
else{
diameter = std::min(distance(right_pos , left_pos), distance(up_pos , down_pos));
}
if(diameter <10)
disk_size = diameter;
else disk_size = 5;
}
//create a disk
HedcutDisk disk;
disk.center.x = cell.site.y; //x = col
disk.center.y = cell.site.x; //y = row
disk.color = (black_disk) ? cv::Scalar::all(0) : cv::Scalar(r, g, b, 0.0);
disk.radius = (uniform_disk_size) ? disk_size : (100 * disk_size / (avg_v + 100));
//remember
this->disks.push_back(disk);
}//end for cell
//done
}
| 26.554404 | 117 | 0.628878 | [
"vector"
] |
beefb1815f6c6ff27049831155f6be3b41abdd44 | 3,541 | cc | C++ | backends/npu/kernels/where_index_kernel.cc | Aganlengzi/PaddleCustomDevice | 0aa0d2e1b2e5db556777604e6fe851a7d0697456 | [
"Apache-2.0"
] | null | null | null | backends/npu/kernels/where_index_kernel.cc | Aganlengzi/PaddleCustomDevice | 0aa0d2e1b2e5db556777604e6fe851a7d0697456 | [
"Apache-2.0"
] | null | null | null | backends/npu/kernels/where_index_kernel.cc | Aganlengzi/PaddleCustomDevice | 0aa0d2e1b2e5db556777604e6fe851a7d0697456 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2022 PaddlePaddle 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 "kernels/funcs/npu_funcs.h"
#include "kernels/funcs/npu_op_runner.h"
namespace custom_kernel {
template <typename T, typename Context>
void WhereIndexKernel(const Context& dev_ctx,
const phi::DenseTensor& condition,
phi::DenseTensor* out) {
auto dims = condition.dims();
const int rank = dims.size();
const aclrtStream& stream = dev_ctx.stream();
// Run Cast and ReduceSum to get 0 dim of Out
phi::DenseTensor booled_cond;
if (condition.dtype() != phi::DataType::BOOL) {
booled_cond.Resize(dims);
auto bool_type = ConvertToNpuDtype(phi::DataType::BOOL);
booled_cond.Resize(dims);
dev_ctx.template Alloc<bool>(&booled_cond);
const auto& booled_runner =
NpuOpRunner("Cast",
{condition},
{booled_cond},
{{"dst_type", static_cast<int32_t>(bool_type)}});
booled_runner.Run(stream, true);
} else {
booled_cond = condition;
}
phi::DenseTensor casted_cond;
auto dst_dtype = ConvertToNpuDtype(phi::DataType::INT64);
casted_cond.Resize(dims);
dev_ctx.template Alloc<int64_t>(&casted_cond);
const auto& cast_runner =
NpuOpRunner("Cast",
{booled_cond},
{casted_cond},
{{"dst_type", static_cast<int>(dst_dtype)}});
cast_runner.Run(stream, true);
phi::DenseTensor sumed_true_num;
sumed_true_num.Resize({1});
dev_ctx.template Alloc<int64_t>(&sumed_true_num);
phi::DenseTensor cond_axes;
cond_axes.Resize({dims.size()});
dev_ctx.template Alloc<int>(&cond_axes);
std::vector<int> axes_vec;
for (int i = 0; i < dims.size(); ++i) {
axes_vec.push_back(i);
}
custom_kernel::TensorFromVector(dev_ctx, axes_vec, dev_ctx, &cond_axes);
const auto& sum_runner = NpuOpRunner("ReduceSum",
{casted_cond, cond_axes},
{sumed_true_num},
{{"keep_dims", false}});
sum_runner.Run(stream, true);
phi::DenseTensor local_true_num;
TensorCopy(dev_ctx, sumed_true_num, true, &local_true_num, phi::CPUPlace());
auto true_num = *local_true_num.data<int64_t>();
out->Resize(phi::make_ddim({true_num, rank}));
dev_ctx.template Alloc<int64_t>(out);
if (true_num == 0) {
return;
}
phi::DenseTensorMeta out_meta = {
out->dtype(), out->dims(), phi::DataLayout::kAnyLayout};
out->set_meta(out_meta);
NpuOpRunner runner{"Where", {condition}, {*out}};
runner.Run(stream);
}
} // namespace custom_kernel
PD_REGISTER_PLUGIN_KERNEL(where_index,
ascend,
ALL_LAYOUT,
custom_kernel::WhereIndexKernel,
bool,
int,
int64_t,
float,
double) {}
| 34.378641 | 78 | 0.620164 | [
"vector"
] |
bef507265d29a0f4847813bd6e692377209d7df1 | 4,929 | hpp | C++ | src/fleury/reachable_vertices_from.hpp | CppPhil/graph_algorithms | 6742fccf83a85fd7b1e500ac495b35c7d0670b84 | [
"Unlicense"
] | null | null | null | src/fleury/reachable_vertices_from.hpp | CppPhil/graph_algorithms | 6742fccf83a85fd7b1e500ac495b35c7d0670b84 | [
"Unlicense"
] | null | null | null | src/fleury/reachable_vertices_from.hpp | CppPhil/graph_algorithms | 6742fccf83a85fd7b1e500ac495b35c7d0670b84 | [
"Unlicense"
] | null | null | null | #ifndef INCG_GP_FLEURY_REACHABLE_VERTICES_FROM_HPP
#define INCG_GP_FLEURY_REACHABLE_VERTICES_FROM_HPP
#include "../directed_graph.hpp" // gp::DirectedGraph
#include "../vertex.hpp" // gp::Vertex
#include <cinttypes> // UINT64_C
#include <ciso646> // not
#include <cstdint> // std::uint64_t
#include <pl/algo/ranged_algorithms.hpp> // pl::algo::transform
#include <pl/annotations.hpp> // PL_NODISCARD
#include <unordered_map> // std::unordered_map
namespace gp {
namespace fleury {
namespace detail {
/*!
* \tparam VertexIdentifier The type of which instances are used to uniquely
* identify vertices in the graph.
* \tparam VertexData The type of the data stored on a vertex in the graph.
* \tparam EdgeIdentifier The type of which instances are used to uniquely
* identify edges in the graph.
* \tparam EdgeData The type of the data stored on an edge in the graph.
* \param graph The graph to operate on.
* \param vertex The vertex for which to determine the amount of reachable
* vertices.
* \param isVisited In-out parameter to keep track of which vertices are
* already visited and which aren't.
* \return The amount of vertices reachable from vertex.
* \note This is an implementation function. It is not to be called directly
* from client code.
**/
template<
typename VertexIdentifier,
typename VertexData,
typename EdgeIdentifier,
typename EdgeData>
PL_NODISCARD std::uint64_t reachableVerticesFromImpl(
const DirectedGraph<VertexIdentifier, VertexData, EdgeIdentifier, EdgeData>&
graph,
const VertexIdentifier& vertex,
std::unordered_map<VertexIdentifier, bool>& isVisited)
{
// Type aliases
using graph_type
= DirectedGraph<VertexIdentifier, VertexData, EdgeIdentifier, EdgeData>;
using edge_type = typename graph_type::edge_type;
isVisited[vertex] = true; // We're visiting it right now.
std::uint64_t count{UINT64_C(1)}; // Every vertex can at least reach itself.
// For all the reachables
const std::vector<const edge_type*> outbounds{graph.outboundEdges(vertex)};
const std::vector<VertexIdentifier> reachables{[&outbounds] {
std::vector<VertexIdentifier> result(
outbounds.size(), VertexIdentifier{});
pl::algo::transform(
outbounds, result.begin(), [](const edge_type* currentEdge) {
return currentEdge->target();
});
return result;
}()};
for (const VertexIdentifier& reachable : reachables) {
// If we haven't already visited it -> recurse (Depth First Search).
if (not isVisited[reachable]) {
count += reachableVerticesFromImpl(graph, reachable, isVisited);
}
}
// Done.
return count;
}
} // namespace detail
/*!
* \tparam VertexIdentifier The type of which instances are used to uniquely
* identify vertices in the graph.
* \tparam VertexData The type of the data stored on a vertex in the graph.
* \tparam EdgeIdentifier The type of which instances are used to uniquely
* identify edges in the graph.
* \tparam EdgeData The type of the data stored on an edge in the graph.
* \param graph The graph to operate on.
* \param vertex The vertex in the graph given for which to determine
* the amount of reachable vertices.
* \return The amount (number) of vertices reachable from the vertex given.
* (This includes the vertex itself (vertices can always at least
* reach themselves))
* \note Complexity is linear in the amount of edges in the graph.
* \warning The vertex must be a vertex of the graph given!
*
* The entry point for the user into this algorithm.
* Uses a DFS (depth first search) to count the amount of vertices
* that can be reached from the vertex given in the given graph.
**/
template<
typename VertexIdentifier,
typename VertexData,
typename EdgeIdentifier,
typename EdgeData>
PL_NODISCARD std::uint64_t reachableVerticesFrom(
const DirectedGraph<VertexIdentifier, VertexData, EdgeIdentifier, EdgeData>&
graph,
const VertexIdentifier& vertex)
{
// Set up isVisited map
std::unordered_map<VertexIdentifier, bool> isVisited{};
// By default all vertices in the graph must be considered non-visited.
for (const auto& v : graph.vertices()) {
isVisited.emplace(v.identifier(), false);
}
// Branch into the recursive algorithm.
return ::gp::fleury::detail::reachableVerticesFromImpl(
graph, vertex, isVisited);
}
} // namespace fleury
} // namespace gp
#endif // INCG_GP_FLEURY_REACHABLE_VERTICES_FROM_HPP
| 41.420168 | 80 | 0.664638 | [
"vector",
"transform"
] |
bef711ea4b56f94abbcd8d510f475a825b411d9b | 3,047 | cpp | C++ | Release/samples/granada/oauth2-server/src/business/message.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null | Release/samples/granada/oauth2-server/src/business/message.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null | Release/samples/granada/oauth2-server/src/business/message.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null | /**
* Copyright (c) <2016> granada <afernandez@cookinapps.io>
*
* This source code is licensed under the MIT license.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Message
* Class for creating, editing and deleting users' messages.
*
*/
#include "message.h"
namespace granada{
Message::Message(std::shared_ptr<granada::cache::CacheHandler>& cache){
cache_ = cache;
n_generator_ = std::unique_ptr<utility::nonce_generator>(new utility::nonce_generator(16));
}
void Message::Create(const std::string username, const std::string& message){
std::string message_id = utility::conversions::to_utf8string(n_generator_->generate());
if (cache_->Exists("message:" + username + ":" + message_id)){
Create(username,message);
}else{
cache_->Write("message:" + username + ":" + message_id, "key", message_id);
cache_->Write("message:" + username + ":" + message_id, "text", message);
}
}
bool Message::Edit(const std::string username, const std::string& message_id, const std::string& message){
if (cache_->Exists("message:" + username + ":" + message_id)){
cache_->Write("message:" + username + ":" + message_id, "text", message);
return true;
}
return false;
}
void Message::Delete(const std::string username, const std::string& message_id){
cache_->Destroy("message:" + username + ":" + message_id);
}
std::string Message::List(const std::string username){
std::string message_list = "";
std::vector<std::string> keys;
cache_->Match("message:" + username + ":*", keys);
for (auto it = keys.begin(); it != keys.end(); ++it){
if (it != keys.begin()){
message_list += ",";
}
message_list = message_list + "{\"key\":\"" + cache_->Read(*it, "key") + "\",\"text\":\"" + cache_->Read(*it, "text") + "\"}";
}
message_list = "[" + message_list + "]";
return message_list;
}
}
| 40.626667 | 133 | 0.653101 | [
"vector"
] |
bef76e64c80bbb5e013f41bafa5d8dbd2e726165 | 1,386 | cxx | C++ | src/Cxx/Images/RTAnalyticSource.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Images/RTAnalyticSource.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Images/RTAnalyticSource.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkImageActor.h>
#include <vtkImageMapper3D.h>
#include <vtkImageData.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkRTAnalyticSource.h>
int main(int, char*[])
{
vtkSmartPointer<vtkRTAnalyticSource> analyticSource =
vtkSmartPointer<vtkRTAnalyticSource>::New();
analyticSource->SetWholeExtent(-10,10, -10,10, 0,0);
vtkSmartPointer<vtkImageActor> imageActor =
vtkSmartPointer<vtkImageActor>::New();
imageActor->GetMapper()->SetInputConnection(
analyticSource->GetOutputPort());
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> interactor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkInteractorStyleImage> style =
vtkSmartPointer<vtkInteractorStyleImage>::New();
interactor->SetInteractorStyle( style );
interactor->SetRenderWindow(renderWindow);
// Setup both renderers
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
renderer->SetBackground(1,0,0);
renderWindow->AddRenderer(renderer);
renderer->AddActor(imageActor);
renderer->ResetCamera();
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
| 27.72 | 57 | 0.765512 | [
"render"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.