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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db5fb05ddd87b183a9e87137550d199c4fd1b371 | 8,024 | cpp | C++ | src/Launcher.cpp | pierotofy/glassomium | 27bbfc172501c9553e2ba769526399c166d2e992 | [
"Apache-2.0"
] | 8 | 2015-06-02T20:57:55.000Z | 2020-02-09T21:50:34.000Z | src/Launcher.cpp | pierotofy/glassomium | 27bbfc172501c9553e2ba769526399c166d2e992 | [
"Apache-2.0"
] | 2 | 2016-02-11T15:23:41.000Z | 2017-03-16T13:35:11.000Z | src/Launcher.cpp | pierotofy/glassomium | 27bbfc172501c9553e2ba769526399c166d2e992 | [
"Apache-2.0"
] | 5 | 2015-06-03T09:00:49.000Z | 2019-11-17T12:02:22.000Z | /*
Glassomium - web-based TUIO-enabled window manager
http://www.glassomium.org
Copyright 2012 The Glassomium Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Launcher.h"
#include "Appinfo.h"
#include "Utils.h"
Launcher::Launcher(){
// Find available resolutions
std::vector<sf::VideoMode> videoModes = sf::VideoMode::getFullscreenModes();
for (unsigned int i = 0; i < videoModes.size(); i++){
if (videoModes[i].bitsPerPixel != 32) continue; // Avoid duplicates
stringstream ss;
Resolution res;
res.width = videoModes[i].width;
res.height = videoModes[i].height;
ss << res.width << "x" << res.height;
res.printable = ss.str();
availableResolutions.push_back(res);
}
if (availableResolutions.size() > 0){
run();
}else{
cerr << "No screen resolutions are available; make sure your video card driver is properly installed and enabled." << endl;
exit(EXIT_FAILURE);
}
}
void Launcher::run() {
const float WINDOW_WIDTH = 480.0f;
const float WINDOW_HEIGHT = 320.0f;
// Create SFML's window.
renderWindow = new sf::RenderWindow( sf::VideoMode( (int)WINDOW_WIDTH, (int)WINDOW_HEIGHT ), APP_NAME " " APP_VERSION, sf::Style::Titlebar );
// Load icon
sf::Image icon;
icon.loadFromFile("icon.png");
renderWindow->setIcon(32, 32, icon.getPixelsPtr());
// Load splash screen
sf::Image splashImage;
splashImage.loadFromFile("splash.png");
// OK and exit buttons
sfg::Button::Ptr launchButton( sfg::Button::Create( "Launch!" ) );
launchButton->GetSignal( sfg::Widget::OnLeftClick ).Connect( &Launcher::LaunchButton_Click, this );
sfg::Button::Ptr exitButton( sfg::Button::Create( "Exit" ) );
exitButton->GetSignal( sfg::Widget::OnLeftClick ).Connect( &Launcher::ExitButton_Click, this );
// Create layout
sfg::Table::Ptr table( sfg::Table::Create() );
table->SetRequisition(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT));
// Splash image
table->Attach( sfg::Image::Create(splashImage), sf::Rect<sf::Uint32>( 0, 0, 3, 1 ), sfg::Table::FILL, sfg::Table::FILL );
// Options
// Resolution
resolutionComboBox = sfg::ComboBox::Create();
for (unsigned int i = 0; i < availableResolutions.size(); i++){
resolutionComboBox->AppendItem(availableResolutions[i].printable);
}
resolutionComboBox->SelectItem(0);
table->Attach( sfg::Label::Create( "Resolution:" ), sf::Rect<sf::Uint32>( 0, 1, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->Attach( resolutionComboBox, sf::Rect<sf::Uint32>( 1, 1, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL );
// Aspect ratio
/*
aspectRatioComboBox = sfg::ComboBox::Create();
aspectRatioComboBox->AppendItem( "4:3" );
aspectRatioComboBox->AppendItem( "16:9" );
Resolution selectedRes = availableResolutions[0];
if (selectedRes.width % 4 == 0 && selectedRes.height % 3 == 0){
aspectRatioComboBox->SelectItem(0);
}else{
aspectRatioComboBox->SelectItem(1);
}
table->Attach( sfg::Label::Create( "Aspect ratio:" ), sf::Rect<sf::Uint32>( 0, 2, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->Attach( aspectRatioComboBox, sf::Rect<sf::Uint32>( 1, 2, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL );
*/
// Debug
debugChkBox = sfg::CheckButton::Create("");
debugChkBox->SetActive(true);
table->Attach( sfg::Label::Create( "Debug:" ), sf::Rect<sf::Uint32>( 0, 2, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->Attach( debugChkBox, sf::Rect<sf::Uint32>( 1, 2, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL );
// Full screen
fullscreenChkBox = sfg::CheckButton::Create("");
fullscreenChkBox->SetActive(true);
table->Attach( sfg::Label::Create( "Fullscreen:" ), sf::Rect<sf::Uint32>( 0, 3, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->Attach( fullscreenChkBox, sf::Rect<sf::Uint32>( 1, 3, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL );
// Notice
table->Attach( sfg::Label::Create("To access more options launch the program from a console: glassomium --help"), sf::Rect<sf::Uint32>( 0, 4, 3, 1 ), sfg::Table::FILL, sfg::Table::FILL );
// Launch/exit buttons
table->Attach( exitButton, sf::Rect<sf::Uint32>( 0, 5, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->Attach( launchButton, sf::Rect<sf::Uint32>( 2, 5, 1, 1 ), sfg::Table::FILL, sfg::Table::FILL );
table->SetRowSpacing(0, 20.0f);
table->SetRowSpacing(1, 10.0f);
table->SetRowSpacing(2, 10.0f);
table->SetRowSpacing(3, 20.0f);
table->SetRowSpacing(4, 20.0f);
// Create a window and add the box layouter to it. Also set the window's title.
sfg::Window::Ptr window( sfg::Window::Create(sfg::Window::BACKGROUND) );
window->Add( table );
// Create a desktop and add the window to it.
sfg::Desktop desktop;
desktop.Add( window );
desktop.SetProperty<sf::Color>("Window", "BackgroundColor", sf::Color(0xb9, 0xd6, 0xf7));
desktop.SetProperty<sf::Color>("Label", "Color", sf::Color::Black);
desktop.SetProperty<sf::Color>("Button", "BackgroundColor", sf::Color(0x7a, 0xaf, 0xef));
desktop.SetProperty<float>("Button", "BorderWidth", 1.0f);
desktop.SetProperty<sf::Color>("Button", "BorderColor", sf::Color(0x10, 0x10, 0x10));
desktop.SetProperty<sf::Color>("Button", "Color", sf::Color::Black);
desktop.SetProperty<sf::Color>("ComboBox", "BackgroundColor", sf::Color(0x7a, 0xaf, 0xef));
desktop.SetProperty<sf::Color>("ComboBox", "HighlightedColor", sf::Color::White);
desktop.SetProperty<sf::Color>("ComboBox", "ArrowColor", sf::Color::Black);
desktop.SetProperty<sf::Color>("ComboBox", "Color", sf::Color::Black);
desktop.SetProperty<sf::Color>("ComboBox", "BorderColor", sf::Color::Black);
desktop.SetProperty<sf::Color>("CheckButton", "BackgroundColor", sf::Color(0x7a, 0xaf, 0xef));
desktop.SetProperty<sf::Color>("CheckButton", "CheckColor", sf::Color::Black);
desktop.SetProperty<sf::Color>("CheckButton", "Color", sf::Color::Black);
desktop.SetProperty<sf::Color>("CheckButton", "BorderColor", sf::Color::Black);
// We're not using SFML to render anything in this program, so reset OpenGL
// states. Otherwise we wouldn't see anything.
renderWindow->resetGLStates();
// Main loop!
sf::Event event;
sf::Clock clock;
while( renderWindow->isOpen() ) {
// Event processing.
while( renderWindow->pollEvent( event ) ) {
desktop.HandleEvent( event );
// If window is about to be closed, leave program.
if( event.type == sf::Event::Closed ) {
renderWindow->close();
}
if ( event.type == sf::Event::MouseWheelMoved){
resolutionComboBox->SelectItem(resolutionComboBox->GetSelectedItem() - event.mouseWheel.delta);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
resolutionComboBox->SelectItem(resolutionComboBox->GetSelectedItem() - 1);
}else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
resolutionComboBox->SelectItem(resolutionComboBox->GetSelectedItem() + 1);
}else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)){
ExitButton_Click();
}else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return)){
LaunchButton_Click();
}
}
// Update SFGUI with elapsed seconds since last call.
desktop.Update( clock.restart().asSeconds() );
// Rendering.
renderWindow->clear();
sfgui.Display( *renderWindow );
renderWindow->display();
}
}
void Launcher::LaunchButton_Click() {
renderWindow->close();
}
void Launcher::ExitButton_Click() {
exit(EXIT_SUCCESS);
}
Launcher::~Launcher(){
RELEASE_SAFELY(renderWindow);
}
| 36.807339 | 188 | 0.677343 | [
"render",
"vector"
] |
db603654b5aa53ead67754cc06d77debe56c6f70 | 10,829 | cpp | C++ | third_party/libunwindstack/tests/RegsTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,847 | 2020-03-24T19:01:42.000Z | 2022-03-31T13:18:57.000Z | third_party/libunwindstack/tests/RegsTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 1,100 | 2020-03-24T19:41:13.000Z | 2022-03-31T14:27:09.000Z | third_party/libunwindstack/tests/RegsTest.cpp | tufeigunchu/orbit | 407354cf7c9159ff7e3177c603a6850b95509e3a | [
"BSD-2-Clause"
] | 228 | 2020-03-25T05:32:08.000Z | 2022-03-31T11:27:39.000Z | /*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 <stdint.h>
#include <gtest/gtest.h>
#include <unwindstack/Elf.h>
#include <unwindstack/ElfInterface.h>
#include <unwindstack/MapInfo.h>
#include <unwindstack/Object.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsMips.h>
#include <unwindstack/RegsMips64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include "ElfFake.h"
#include "RegsFake.h"
#include "utils/MemoryFake.h"
namespace unwindstack {
class RegsTest : public ::testing::Test {
protected:
void SetUp() override {
memory_ = new MemoryFake;
elf_.reset(new ElfFake(memory_));
elf_interface_ = new ElfInterfaceFake(elf_->memory());
elf_->FakeSetInterface(elf_interface_);
}
ElfInterfaceFake* elf_interface_;
MemoryFake* memory_;
std::unique_ptr<ElfFake> elf_;
};
TEST_F(RegsTest, regs32) {
RegsImplFake<uint32_t> regs32(50);
ASSERT_EQ(50U, regs32.total_regs());
uint32_t* raw = reinterpret_cast<uint32_t*>(regs32.RawData());
for (size_t i = 0; i < 50; i++) {
raw[i] = 0xf0000000 + i;
}
regs32.set_pc(0xf0120340);
regs32.set_sp(0xa0ab0cd0);
for (size_t i = 0; i < 50; i++) {
ASSERT_EQ(0xf0000000U + i, regs32[i]) << "Failed comparing register " << i;
}
ASSERT_EQ(0xf0120340U, regs32.pc());
ASSERT_EQ(0xa0ab0cd0U, regs32.sp());
regs32[32] = 10;
ASSERT_EQ(10U, regs32[32]);
}
TEST_F(RegsTest, regs64) {
RegsImplFake<uint64_t> regs64(30);
ASSERT_EQ(30U, regs64.total_regs());
uint64_t* raw = reinterpret_cast<uint64_t*>(regs64.RawData());
for (size_t i = 0; i < 30; i++) {
raw[i] = 0xf123456780000000UL + i;
}
regs64.set_pc(0xf123456780102030UL);
regs64.set_sp(0xa123456780a0b0c0UL);
for (size_t i = 0; i < 30; i++) {
ASSERT_EQ(0xf123456780000000U + i, regs64[i]) << "Failed reading register " << i;
}
ASSERT_EQ(0xf123456780102030UL, regs64.pc());
ASSERT_EQ(0xa123456780a0b0c0UL, regs64.sp());
regs64[8] = 10;
ASSERT_EQ(10U, regs64[8]);
}
TEST_F(RegsTest, rel_pc) {
EXPECT_EQ(4U, GetPcAdjustment(0x10, elf_.get(), ARCH_ARM64));
EXPECT_EQ(4U, GetPcAdjustment(0x4, elf_.get(), ARCH_ARM64));
EXPECT_EQ(0U, GetPcAdjustment(0x3, elf_.get(), ARCH_ARM64));
EXPECT_EQ(0U, GetPcAdjustment(0x2, elf_.get(), ARCH_ARM64));
EXPECT_EQ(0U, GetPcAdjustment(0x1, elf_.get(), ARCH_ARM64));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_ARM64));
EXPECT_EQ(1U, GetPcAdjustment(0x100, elf_.get(), ARCH_X86));
EXPECT_EQ(1U, GetPcAdjustment(0x2, elf_.get(), ARCH_X86));
EXPECT_EQ(1U, GetPcAdjustment(0x1, elf_.get(), ARCH_X86));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_X86));
EXPECT_EQ(1U, GetPcAdjustment(0x100, elf_.get(), ARCH_X86_64));
EXPECT_EQ(1U, GetPcAdjustment(0x2, elf_.get(), ARCH_X86_64));
EXPECT_EQ(1U, GetPcAdjustment(0x1, elf_.get(), ARCH_X86_64));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_X86_64));
EXPECT_EQ(8U, GetPcAdjustment(0x10, elf_.get(), ARCH_MIPS));
EXPECT_EQ(8U, GetPcAdjustment(0x8, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x7, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x6, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x5, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x4, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x3, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x2, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x1, elf_.get(), ARCH_MIPS));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_MIPS));
EXPECT_EQ(8U, GetPcAdjustment(0x10, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(8U, GetPcAdjustment(0x8, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x7, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x6, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x5, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x4, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x3, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x2, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x1, elf_.get(), ARCH_MIPS64));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_MIPS64));
}
TEST_F(RegsTest, rel_pc_arm) {
// Check fence posts.
elf_->FakeSetLoadBias(0);
EXPECT_EQ(2U, GetPcAdjustment(0x5, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x4, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x3, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x2, elf_.get(), ARCH_ARM));
EXPECT_EQ(0U, GetPcAdjustment(0x1, elf_.get(), ARCH_ARM));
EXPECT_EQ(0U, GetPcAdjustment(0x0, elf_.get(), ARCH_ARM));
elf_->FakeSetLoadBias(0x100);
EXPECT_EQ(0U, GetPcAdjustment(0x1, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x2, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0xff, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x105, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x104, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x103, elf_.get(), ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x102, elf_.get(), ARCH_ARM));
EXPECT_EQ(0U, GetPcAdjustment(0x101, elf_.get(), ARCH_ARM));
EXPECT_EQ(0U, GetPcAdjustment(0x100, elf_.get(), ARCH_ARM));
// Check thumb instructions handling.
elf_->FakeSetLoadBias(0);
memory_->SetData32(0x2000, 0);
EXPECT_EQ(2U, GetPcAdjustment(0x2005, elf_.get(), ARCH_ARM));
memory_->SetData32(0x2000, 0xe000f000);
EXPECT_EQ(4U, GetPcAdjustment(0x2005, elf_.get(), ARCH_ARM));
elf_->FakeSetLoadBias(0x400);
memory_->SetData32(0x2100, 0);
EXPECT_EQ(2U, GetPcAdjustment(0x2505, elf_.get(), ARCH_ARM));
memory_->SetData32(0x2100, 0xf111f111);
EXPECT_EQ(4U, GetPcAdjustment(0x2505, elf_.get(), ARCH_ARM));
}
TEST_F(RegsTest, elf_invalid) {
MapInfo map_info(nullptr, nullptr, 0x1000, 0x2000, 0, 0, "");
Elf* invalid_elf = new Elf(nullptr);
map_info.set_object(invalid_elf);
EXPECT_EQ(0x500U, invalid_elf->GetRelPc(0x1500, &map_info));
EXPECT_EQ(2U, GetPcAdjustment(0x500U, invalid_elf, ARCH_ARM));
EXPECT_EQ(2U, GetPcAdjustment(0x511U, invalid_elf, ARCH_ARM));
EXPECT_EQ(0x600U, invalid_elf->GetRelPc(0x1600, &map_info));
EXPECT_EQ(4U, GetPcAdjustment(0x600U, invalid_elf, ARCH_ARM64));
EXPECT_EQ(0x700U, invalid_elf->GetRelPc(0x1700, &map_info));
EXPECT_EQ(1U, GetPcAdjustment(0x700U, invalid_elf, ARCH_X86));
EXPECT_EQ(0x800U, invalid_elf->GetRelPc(0x1800, &map_info));
EXPECT_EQ(1U, GetPcAdjustment(0x800U, invalid_elf, ARCH_X86_64));
EXPECT_EQ(0x900U, invalid_elf->GetRelPc(0x1900, &map_info));
EXPECT_EQ(8U, GetPcAdjustment(0x900U, invalid_elf, ARCH_MIPS));
EXPECT_EQ(0xa00U, invalid_elf->GetRelPc(0x1a00, &map_info));
EXPECT_EQ(8U, GetPcAdjustment(0xa00U, invalid_elf, ARCH_MIPS64));
}
TEST_F(RegsTest, arm_verify_sp_pc) {
RegsArm arm;
uint32_t* regs = reinterpret_cast<uint32_t*>(arm.RawData());
regs[13] = 0x100;
regs[15] = 0x200;
EXPECT_EQ(0x100U, arm.sp());
EXPECT_EQ(0x200U, arm.pc());
}
TEST_F(RegsTest, arm64_verify_sp_pc) {
RegsArm64 arm64;
uint64_t* regs = reinterpret_cast<uint64_t*>(arm64.RawData());
regs[31] = 0xb100000000ULL;
regs[32] = 0xc200000000ULL;
EXPECT_EQ(0xb100000000U, arm64.sp());
EXPECT_EQ(0xc200000000U, arm64.pc());
}
TEST_F(RegsTest, x86_verify_sp_pc) {
RegsX86 x86;
uint32_t* regs = reinterpret_cast<uint32_t*>(x86.RawData());
regs[4] = 0x23450000;
regs[8] = 0xabcd0000;
EXPECT_EQ(0x23450000U, x86.sp());
EXPECT_EQ(0xabcd0000U, x86.pc());
}
TEST_F(RegsTest, x86_64_verify_sp_pc) {
RegsX86_64 x86_64;
uint64_t* regs = reinterpret_cast<uint64_t*>(x86_64.RawData());
regs[7] = 0x1200000000ULL;
regs[16] = 0x4900000000ULL;
EXPECT_EQ(0x1200000000U, x86_64.sp());
EXPECT_EQ(0x4900000000U, x86_64.pc());
}
TEST_F(RegsTest, mips_verify_sp_pc) {
RegsMips mips;
uint32_t* regs = reinterpret_cast<uint32_t*>(mips.RawData());
regs[29] = 0x100;
regs[32] = 0x200;
EXPECT_EQ(0x100U, mips.sp());
EXPECT_EQ(0x200U, mips.pc());
}
TEST_F(RegsTest, mips64_verify_sp_pc) {
RegsMips64 mips64;
uint64_t* regs = reinterpret_cast<uint64_t*>(mips64.RawData());
regs[29] = 0xb100000000ULL;
regs[32] = 0xc200000000ULL;
EXPECT_EQ(0xb100000000U, mips64.sp());
EXPECT_EQ(0xc200000000U, mips64.pc());
}
TEST_F(RegsTest, arm64_strip_pac_mask) {
RegsArm64 arm64;
arm64.SetPseudoRegister(Arm64Reg::ARM64_PREG_RA_SIGN_STATE, 1);
arm64.SetPACMask(0x007fff8000000000ULL);
arm64.set_pc(0x0020007214bb3a04ULL);
EXPECT_EQ(0x0000007214bb3a04ULL, arm64.pc());
}
TEST_F(RegsTest, arm64_fallback_pc) {
RegsArm64 arm64;
arm64.SetPACMask(0x007fff8000000000ULL);
arm64.set_pc(0x0020007214bb3a04ULL);
arm64.fallback_pc();
EXPECT_EQ(0x0000007214bb3a04ULL, arm64.pc());
}
TEST_F(RegsTest, machine_type) {
RegsArm arm_regs;
EXPECT_EQ(ARCH_ARM, arm_regs.Arch());
RegsArm64 arm64_regs;
EXPECT_EQ(ARCH_ARM64, arm64_regs.Arch());
RegsX86 x86_regs;
EXPECT_EQ(ARCH_X86, x86_regs.Arch());
RegsX86_64 x86_64_regs;
EXPECT_EQ(ARCH_X86_64, x86_64_regs.Arch());
RegsMips mips_regs;
EXPECT_EQ(ARCH_MIPS, mips_regs.Arch());
RegsMips64 mips64_regs;
EXPECT_EQ(ARCH_MIPS64, mips64_regs.Arch());
}
template <typename RegisterType>
void clone_test(Regs* regs) {
RegisterType* register_values = reinterpret_cast<RegisterType*>(regs->RawData());
int num_regs = regs->total_regs();
for (int i = 0; i < num_regs; ++i) {
register_values[i] = i;
}
std::unique_ptr<Regs> clone(regs->Clone());
ASSERT_EQ(regs->total_regs(), clone->total_regs());
RegisterType* clone_values = reinterpret_cast<RegisterType*>(clone->RawData());
for (int i = 0; i < num_regs; ++i) {
EXPECT_EQ(register_values[i], clone_values[i]);
EXPECT_NE(®ister_values[i], &clone_values[i]);
}
}
TEST_F(RegsTest, clone) {
std::vector<std::unique_ptr<Regs>> regs;
regs.emplace_back(new RegsArm());
regs.emplace_back(new RegsArm64());
regs.emplace_back(new RegsX86());
regs.emplace_back(new RegsX86_64());
regs.emplace_back(new RegsMips());
regs.emplace_back(new RegsMips64());
for (auto& r : regs) {
if (r->Is32Bit()) {
clone_test<uint32_t>(r.get());
} else {
clone_test<uint64_t>(r.get());
}
}
}
} // namespace unwindstack
| 33.526316 | 85 | 0.720011 | [
"object",
"vector"
] |
db76aff0d96820b8ce55812f15e8ec9aa88eb70f | 13,615 | hpp | C++ | src/emu6502/mos6502.hpp | macsimbodnar/emu | 017bac23e38269065f2229dae89d92e788aeee73 | [
"MIT"
] | 3 | 2019-10-01T12:20:10.000Z | 2021-03-02T15:31:46.000Z | src/emu6502/mos6502.hpp | macsimbodnar/emu | 017bac23e38269065f2229dae89d92e788aeee73 | [
"MIT"
] | null | null | null | src/emu6502/mos6502.hpp | macsimbodnar/emu | 017bac23e38269065f2229dae89d92e788aeee73 | [
"MIT"
] | null | null | null | #pragma once
#include "common.hpp"
#include "util.hpp"
#include <functional>
#include <stdint.h>
#include <vector>
#define STACK_POINTER_DEFAULT 0xFD
#define PROCESSOR_STATUS_DEFAULT 0x24
#define INITIAL_ADDRESS 0xFFFC
#define STACK_OFFSET 0x0100
#define BRK_PCL 0xFFFE
#define BRK_PCH 0xFFFF
class MOS6502 {
public:
explicit MOS6502(mem_access_callback mem_acc_clb, void *usr_data);
bool clock(); // Clock signal
void reset(); // Reset signal
void irq(); // Interrupt signal
void nmi(); // Non-maskable interrupt signal
// Set the PC to specific memory address.
// NOTE(max): debug/test
void set_PC(uint16_t address);
// Return the struct containing the current processor status.
// NOTE(max): debug/test
p_state_t get_status();
// Set the callback used for log. Not mandatory
void set_log_callback(log_callback);
public:
/********************************************************
* REGISTERS / FLAGS *
********************************************************/
uint8_t A = 0x00; // Accumulator
uint8_t X = 0x00; // X Register
uint8_t Y = 0x00; // Y Register
uint8_t P = PROCESSOR_STATUS_DEFAULT;
// Processor STATUS [N][O][-][B][D][I][Z][C]
// | | | | | | | |
// | | | | | | | +- Carry
// | | | | | | +-- Zero
// | | | | | +--- Interrupt Disable
// | | | | +---- Decimal
// | | +--+----- No CPU effect, see: the B flag
// | +-------- Overflow
// +--------- Negative
uint8_t S = STACK_POINTER_DEFAULT; // Stack pointer
uint16_t PC = 0x0000; // Program counter
/********************************************************
* DATA STRUCTURES *
********************************************************/
enum status_flag_t { // Processor Status Register BITMASKs
N = (1 << 7), // N: NEGATIVE 1 = Neg
O = (1 << 6), // O: OVERFLOW 1 = True
U = (1 << 5), // - UNUSED stay on 1
B = (1 << 4), // B: BRK COMMAND
D = (1 << 3), // D: DECIMAL MODE 1 = True
I = (1 << 2), // I: IRQ DISABLE 1 = Disable
Z = (1 << 1), // Z: ZERO: 1 = Result Zero
C = (1 << 0) // C: CARRY 1 = True
};
typedef void (MOS6502::*operation_t)(void);
typedef void (MOS6502::*addrmode_t)(void);
typedef void (*micro_op_t)(MOS6502 *self);
struct instruction_t { // INSTRUCTION
const std::string name;
const operation_t operation;
const addrmode_t addrmode;
const unsigned int cycles;
const unsigned int instruction_bytes;
};
/********************************************************
* NEEDED TO WORK *
********************************************************/
// Callback used to access the memory
mem_access_callback mem_access = nullptr;
// User passed like first argument to the mem_access
void *user_data = nullptr;
uint8_t opcode; // Current opcode
const instruction_t *instruction; // Current instruction
uint8_t data_bus; // Data currently on the bus
uint16_t address_bus = INITIAL_ADDRESS; // Current abbsolute address
uint16_t relative_adderess; // Current abbsolute address
// Is True when the current instruction is used with accumulator
// addressing(the current data is fetched from or written to the A register)
bool accumulator_addressing = false;
uint16_t tmp_buff; // Temporary 16-bit buffer
uint16_t hi;
uint16_t lo;
uint32_t cycles = 0;
int64_t time; // Time that this cycle take to execute in ms
// The vector containing the opcode and addressing fuctions and info.
// The vector is 256 size long and the opcode byte match the correct
// addressing mode and function
static const std::vector<instruction_t> opcode_table;
Queue<micro_op_t, 10> microcode_q;
/********************************************************
* DEBUG / TEST *
* NOTE(max): used only for debug and test. *
********************************************************/
uint16_t PC_executed; // Address of the last executed opcode
uint8_t arg1; // Argument 1 of the last executed opcode
uint8_t arg2; // Argument 2 of the last executed opcode
// Callback used to log. Can be setted by set_log_callback()
log_callback log_func = nullptr;
/********************************************************
* UTIL FUNCTIONS *
********************************************************/
void set_flag(const status_flag_t flag, const bool val);
bool read_flag(const status_flag_t flag);
void mem_read();
void mem_write();
bool is_read_instruction();
public:
void log(const std::string &msg);
/********************************************************
* ADDRESSING MODES *
********************************************************/
// clang-format off
void ACC(); // (???)Accumulator addressing: 1-byte instruction on accumulator
void IMM(); // #$BB (IMM)Immediate address: the 2d byte of instruction is the operand
void ABS(); // $LLHH (ABS)Abbsolute addressing: the 2d byte of instruction is the 8 low order bits of the address, 3d is the 8 high order bits (64k total addresses)
void ZPI(); // $LL (ZP0)Zero page addressing: fetch only the 2d byte of the instruction. Assuming the high byte is 0
void ZPX(); // $LL,X (ZPX)Indexed zero page addressing X: the X register is added to the 2d byte. The high byte is 0. No carry is added to high byte, so no page overlapping
void ZPY(); // $LL,Y (ZPY)Indexed zero page addressing Y: Same as in ZPX but with Y register
void ABX(); // $LLHH,X (ABX)Indexed abbsolute addressing X: Adding to X the one absolute address
void ABY(); // $LLHH,X (ABY)Indexed abbsolute addressing Y: Same as in ABX but with Y register
void IMP(); // (IMP)Implied addressing: The address is implicit in the opcode
void REL(); // $BB (REL)Relative addressing: The 2d byte is the branch offset. If the branch is taken, the new address will the the current PC plus the offset.
// The offset is a signed byte, so it can jump a maximum of 127 bytes forward, or 128 bytes backward
void IIX(); // ($LL,X) (IZX)Indexed indirect addressing: The 2d byte is added to the X discarding the carry.
// The result point to the ZERO PAGE address which contains the low order byte of the effective address,
// the next memory location on PAGE ZERO contains the high order byte of the effective address.
// ex: [LDA ($20,X)] (where is X = $04). X is added so $20 -> $24. Then fetch the $24 -> 0024: 7421.
// The fetched 2171 (little endian) from the memory location 0024 is the actual address to be used to load the content into the register A.
// So id in $2171: 124 then A = 124
// formula: target_address = (X + opcode[1]) & 0xFF
void IIY(); // ($LL),Y (IZY)Indirect indexed addressing: Y is applied to the indirectly fetched address.
// ex: [LDA ($86),Y] (where in $0086: 28 40). First fetch the address located at $0086, add that address to the Y register to get
// the final address. So the address will be $4028 (little endian) and Y is $10 then the final address is
// $4038 ad A will be loaded with the content of the address $4038
void IND(); // ($LLHH) (IND)Absolute indirect: The 2d byte contain the low byte of address, the 3d byte contain the high byte of the address.
// The loaded address contain the low byte fo the final addrss and the followed the high byte of the final address
/********************************************************
* INSTRUCTION SET *
********************************************************/
void ADC(); // Add memory to A with Carry
void AND(); // "AND" memory with accumulator
void ASL(); // Shift LEFT 1 bit (memory or A)
void BCC(); // Branch on Carry Clear
void BCS(); // Branch on Carry Set
void BEQ(); // Branch on Result Zero
void BIT(); // Test Bits in Memory with A
void BMI(); // Branch on Result Minus
void BNE(); // Branch on Result not Zero
void BPL(); // Branch on Result Plus
void BRK(); // Force Break
void BVC(); // Branch on Overflow Clear
void BVS(); // Branch on Overflow Set
void CLC(); // Clear Carry Flag
void CLD(); // Clear Decimal Mode
void CLI(); // Clear Interrupt Disable Bit
void CLV(); // Clear Overflow Flag
void CMP(); // Compare Memory and accumulator
void CPX(); // Compare Memory and X
void CPY(); // Compare Memory and Y
void DEC(); // Decrement Memory by 1
void DEX(); // Decrement Index X by 1
void DEY(); // Decrement Index Y by 1
void EOR(); // "Exclusive-OR" Memory with A
void INC(); // Increment Memory by 1
void INX(); // Increment Index X by 1
void INY(); // Increment Index by 1
void JMP(); // Jump to New Location
void JSR(); // Jump to New Location Saving Return Address
void LDA(); // Load A with the Memory
void LDX(); // Load X with the Memory
void LDY(); // Load Y with the Memory
void LSR(); // Shift 1 bit RIGHT (Memory or A)
void NOP(); // No Operation
void NO2(); // No Operation (this one take 2 instruction to execute)
void ORA(); // "OR" Memory with the A
void PHA(); // Push A on Stack
void PHP(); // Push P on Stack
void PLA(); // Pull A from Stack
void PLP(); // Pull P from Stack
void ROL(); // Rotate 1 bit LEFT (Memory or Accumulator)
void ROR(); // Rotate 1 bit RIGHT (Memory or Accumulator)
void RTI(); // Return from Interrupt
void RTS(); // Return from Subroutine
void SBC(); // Subtract Memory from Accumulator with Borrow
void SEC(); // Set Carry Flag
void SED(); // Set Decimal Mode
void SEI(); // Set Interrupt Disable Status
void STA(); // Store A in Memory
void STX(); // Store Index X in Memory
void STY(); // Store Index Y in Memory
void TAX(); // Transfer A to Index X
void TAY(); // Transfer A to Index Y
void TSX(); // Transfer S (Stack Pointer) to Index X
void TXA(); // Transfer Index X to A
void TXS(); // Transfer Index X to Stack Register
void TYA(); // Transfer Index Y to A
/********************************************************
* ILLEGAL INST SET *
********************************************************/
void LAX(); // Loads a value from an absolute address in memory and stores it in A and X at the same time
void SAX(); // Stores the bitwise AND of A and X. As with STA and STX, no flags are affected.
void DCP(); // Equivalent to DEC value then CMP value, except supporting more addressing modes. LDA #$FF followed by DCP can be used to check if the decrement underflows, which is useful for multi-byte decrements.
void ISB(); // ISC // Equivalent to INC value then SBC value, except supporting more addressing modes.
void SLO(); // Equivalent to ASL value then ORA value, except supporting more addressing modes. LDA #0 followed by SLO is an efficient way to shift a variable while also loading it in A.
void RLA(); // Equivalent to ROL value then AND value, except supporting more addressing modes. LDA #$FF followed by RLA is an efficient way to rotate a variable while also loading it in A.
void SRE(); // Equivalent to LSR value then EOR value, except supporting more addressing modes. LDA #0 followed by SRE is an efficient way to shift a variable while also loading it in A.
void RRA(); // Equivalent to ROR value then ADC value, except supporting more addressing modes. Essentially this computes A + value / 2, where value is 9-bit and the division is rounded up.
void XXX(); // Illegal instruction
// clang-format on
}; | 52.976654 | 223 | 0.517885 | [
"vector",
"3d"
] |
db81d8b20943e6f53053bc42dfa2a4212e5ba9bc | 2,351 | cpp | C++ | test/util/merge_lines.test.cpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | test/util/merge_lines.test.cpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | test/util/merge_lines.test.cpp | followtherider/mapbox-gl-native | 62b56b799a7d4fcd1a8f151eed878054b862da5b | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #include <mbgl/test/util.hpp>
#include <mbgl/layout/merge_lines.hpp>
#include <mbgl/layout/symbol_feature.hpp>
const std::u32string aaa = U"a";
const std::u32string bbb = U"b";
TEST(MergeLines, SameText) {
// merges lines with the same text
std::vector<mbgl::SymbolFeature> input1 = {
{ {{{0, 0}, {1, 0}, {2, 0}}}, aaa, {}, 0 },
{ {{{4, 0}, {5, 0}, {6, 0}}}, bbb, {}, 0 },
{ {{{8, 0}, {9, 0}}}, aaa, {}, 0 },
{ {{{2, 0}, {3, 0}, {4, 0}}}, aaa, {}, 0 },
{ {{{6, 0}, {7, 0}, {8, 0}}}, aaa, {}, 0 },
{ {{{5, 0}, {6, 0}}}, aaa, {}, 0 }
};
const std::vector<mbgl::SymbolFeature> expected1 = {
{ {{{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}}}, aaa, {}, 0 },
{ {{{4, 0}, {5, 0}, {6, 0}}}, bbb, {}, 0 },
{ {{{5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 }
};
mbgl::util::mergeLines(input1);
for (int i = 0; i < 6; i++) {
EXPECT_TRUE(input1[i].geometry == expected1[i].geometry);
}
}
TEST(MergeLines, BothEnds) {
// mergeLines handles merge from both ends
std::vector<mbgl::SymbolFeature> input2 = {
{ {{{0, 0}, {1, 0}, {2, 0}}}, aaa, {}, 0 },
{ {{{4, 0}, {5, 0}, {6, 0}}}, aaa, {}, 0 },
{ {{{2, 0}, {3, 0}, {4, 0}}}, aaa, {}, 0 }
};
const std::vector<mbgl::SymbolFeature> expected2 = {
{ {{{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 }
};
mbgl::util::mergeLines(input2);
for (int i = 0; i < 3; i++) {
EXPECT_TRUE(input2[i].geometry == expected2[i].geometry);
}
}
TEST(MergeLines, CircularLines) {
// mergeLines handles circular lines
std::vector<mbgl::SymbolFeature> input3 = {
{ {{{0, 0}, {1, 0}, {2, 0}}}, aaa, {}, 0 },
{ {{{2, 0}, {3, 0}, {4, 0}}}, aaa, {}, 0 },
{ {{{4, 0}, {0, 0}}}, aaa, {}, 0 }
};
const std::vector<mbgl::SymbolFeature> expected3 = {
{ {{{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}, {0, 0}}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 },
{ {{}}, aaa, {}, 0 }
};
mbgl::util::mergeLines(input3);
for (int i = 0; i < 3; i++) {
EXPECT_TRUE(input3[i].geometry == expected3[i].geometry);
}
}
| 30.532468 | 83 | 0.407912 | [
"geometry",
"vector"
] |
db882b3b6505a93410d0b86fff92786ab8b65277 | 3,462 | cpp | C++ | Marlin/src/gcode/config/M301.cpp | violigon/3DPrinter-DE2LV | 5c8960f07085cc11d232a52cb029aa92533287bd | [
"MIT"
] | null | null | null | Marlin/src/gcode/config/M301.cpp | violigon/3DPrinter-DE2LV | 5c8960f07085cc11d232a52cb029aa92533287bd | [
"MIT"
] | null | null | null | Marlin/src/gcode/config/M301.cpp | violigon/3DPrinter-DE2LV | 5c8960f07085cc11d232a52cb029aa92533287bd | [
"MIT"
] | null | null | null | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(PIDTEMP)
#include "../gcode.h"
#include "../../module/temperature.h"
/**
* M301: Set PID parameters P I D (and optionally C, L)
*
* E[extruder] Default: 0
*
* P[float] Kp term
* I[float] Ki term (unscaled)
* D[float] Kd term (unscaled)
*
* With PID_EXTRUSION_SCALING:
*
* C[float] Kc term
* L[int] LPQ length
*
* With PID_FAN_SCALING:
*
* F[float] Kf term
*/
void GcodeSuite::M301() {
// multi-extruder PID patch: M301 updates or prints a single extruder's PID values
// default behavior (omitting E parameter) is to update for extruder 0 only
int8_t e = E_TERN0(parser.byteval('E', -1)); // extruder being updated
if (!parser.seen("PID" TERN_(PID_EXTRUSION_SCALING, "CL") TERN_(PID_FAN_SCALING, "F")))
return M301_report(true E_OPTARG(e));
if (e == -1) e = 0;
if (e < HOTENDS) { // catch bad input value
if (parser.seenval('P')) PID_PARAM(Kp, e) = parser.value_float();
if (parser.seenval('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
if (parser.seenval('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
#if ENABLED(PID_EXTRUSION_SCALING)
if (parser.seenval('C')) PID_PARAM(Kc, e) = parser.value_float();
if (parser.seenval('L')) thermalManager.lpq_len = parser.value_int();
NOMORE(thermalManager.lpq_len, LPQ_MAX_LEN);
NOLESS(thermalManager.lpq_len, 0);
#endif
#if ENABLED(PID_FAN_SCALING)
if (parser.seenval('F')) PID_PARAM(Kf, e) = parser.value_float();
#endif
thermalManager.updatePID();
}
else
SERIAL_ERROR_MSG(STR_INVALID_EXTRUDER);
}
void GcodeSuite::M301_report(const bool forReplay/*=true*/ E_OPTARG(const int8_t eindex/*=-1*/)) {
report_heading(forReplay, PSTR(STR_HOTEND_PID));
IF_DISABLED(HAS_MULTI_EXTRUDER, constexpr int8_t eindex = -1);
HOTEND_LOOP() {
if (e == eindex || eindex == -1) {
report_echo_start(forReplay);
SERIAL_ECHOPGM_P(
#if ENABLED(PID_PARAMS_PER_HOTEND)
PSTR(" M301 E"), e, SP_P_STR
#else
PSTR(" M301 P")
#endif
, PID_PARAM(Kp, e)
, PSTR(" I"), unscalePID_i(PID_PARAM(Ki, e))
, PSTR(" D"), unscalePID_d(PID_PARAM(Kd, e))
);
#if ENABLED(PID_EXTRUSION_SCALING)
SERIAL_ECHOPGM_P(SP_C_STR, PID_PARAM(Kc, e));
if (e == 0) SERIAL_ECHOPGM(" L", thermalManager.lpq_len);
#endif
#if ENABLED(PID_FAN_SCALING)
SERIAL_ECHOPGM(" F", PID_PARAM(Kf, e));
#endif
SERIAL_EOL();
}
}
}
#endif // PIDTEMP
| 31.472727 | 98 | 0.655113 | [
"3d"
] |
db8d735b2d1d846f15033427131d08d15a171522 | 18,857 | cc | C++ | printing/backend/win_helper.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | printing/backend/win_helper.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | printing/backend/win_helper.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 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 "printing/backend/win_helper.h"
#include <algorithm>
#include "base/file_version_info.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_comptr.h"
#include "printing/backend/print_backend.h"
#include "printing/backend/print_backend_consts.h"
#include "printing/backend/printing_info_win.h"
namespace {
typedef HRESULT (WINAPI* PTOpenProviderProc)(PCWSTR printer_name,
DWORD version,
HPTPROVIDER* provider);
typedef HRESULT (WINAPI* PTGetPrintCapabilitiesProc)(HPTPROVIDER provider,
IStream* print_ticket,
IStream* capabilities,
BSTR* error_message);
typedef HRESULT (WINAPI* PTConvertDevModeToPrintTicketProc)(
HPTPROVIDER provider,
ULONG devmode_size_in_bytes,
PDEVMODE devmode,
EPrintTicketScope scope,
IStream* print_ticket);
typedef HRESULT (WINAPI* PTConvertPrintTicketToDevModeProc)(
HPTPROVIDER provider,
IStream* print_ticket,
EDefaultDevmodeType base_devmode_type,
EPrintTicketScope scope,
ULONG* devmode_byte_count,
PDEVMODE* devmode,
BSTR* error_message);
typedef HRESULT (WINAPI* PTMergeAndValidatePrintTicketProc)(
HPTPROVIDER provider,
IStream* base_ticket,
IStream* delta_ticket,
EPrintTicketScope scope,
IStream* result_ticket,
BSTR* error_message);
typedef HRESULT (WINAPI* PTReleaseMemoryProc)(PVOID buffer);
typedef HRESULT (WINAPI* PTCloseProviderProc)(HPTPROVIDER provider);
typedef HRESULT (WINAPI* StartXpsPrintJobProc)(
const LPCWSTR printer_name,
const LPCWSTR job_name,
const LPCWSTR output_file_name,
HANDLE progress_event,
HANDLE completion_event,
UINT8* printable_pages_on,
UINT32 printable_pages_on_count,
IXpsPrintJob** xps_print_job,
IXpsPrintJobStream** document_stream,
IXpsPrintJobStream** print_ticket_stream);
PTOpenProviderProc g_open_provider_proc = NULL;
PTGetPrintCapabilitiesProc g_get_print_capabilities_proc = NULL;
PTConvertDevModeToPrintTicketProc g_convert_devmode_to_print_ticket_proc = NULL;
PTConvertPrintTicketToDevModeProc g_convert_print_ticket_to_devmode_proc = NULL;
PTMergeAndValidatePrintTicketProc g_merge_and_validate_print_ticket_proc = NULL;
PTReleaseMemoryProc g_release_memory_proc = NULL;
PTCloseProviderProc g_close_provider_proc = NULL;
StartXpsPrintJobProc g_start_xps_print_job_proc = NULL;
HRESULT StreamFromPrintTicket(const std::string& print_ticket,
IStream** stream) {
DCHECK(stream);
HRESULT hr = CreateStreamOnHGlobal(NULL, TRUE, stream);
if (FAILED(hr)) {
return hr;
}
ULONG bytes_written = 0;
(*stream)->Write(print_ticket.c_str(),
base::checked_cast<ULONG>(print_ticket.length()),
&bytes_written);
DCHECK(bytes_written == print_ticket.length());
LARGE_INTEGER pos = {0};
ULARGE_INTEGER new_pos = {0};
(*stream)->Seek(pos, STREAM_SEEK_SET, &new_pos);
return S_OK;
}
const char kXpsTicketTemplate[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<psf:PrintTicket "
"xmlns:psf='"
"http://schemas.microsoft.com/windows/2003/08/printing/printschemaframework' "
"xmlns:psk="
"'http://schemas.microsoft.com/windows/2003/08/printing/printschemakeywords' "
"version='1'>"
"<psf:Feature name='psk:PageOutputColor'>"
"<psf:Option name='psk:%s'>"
"</psf:Option>"
"</psf:Feature>"
"</psf:PrintTicket>";
const char kXpsTicketColor[] = "Color";
const char kXpsTicketMonochrome[] = "Monochrome";
} // namespace
namespace printing {
bool XPSModule::Init() {
static bool initialized = InitImpl();
return initialized;
}
bool XPSModule::InitImpl() {
HMODULE prntvpt_module = LoadLibrary(L"prntvpt.dll");
if (prntvpt_module == NULL)
return false;
g_open_provider_proc = reinterpret_cast<PTOpenProviderProc>(
GetProcAddress(prntvpt_module, "PTOpenProvider"));
if (!g_open_provider_proc) {
NOTREACHED();
return false;
}
g_get_print_capabilities_proc = reinterpret_cast<PTGetPrintCapabilitiesProc>(
GetProcAddress(prntvpt_module, "PTGetPrintCapabilities"));
if (!g_get_print_capabilities_proc) {
NOTREACHED();
return false;
}
g_convert_devmode_to_print_ticket_proc =
reinterpret_cast<PTConvertDevModeToPrintTicketProc>(
GetProcAddress(prntvpt_module, "PTConvertDevModeToPrintTicket"));
if (!g_convert_devmode_to_print_ticket_proc) {
NOTREACHED();
return false;
}
g_convert_print_ticket_to_devmode_proc =
reinterpret_cast<PTConvertPrintTicketToDevModeProc>(
GetProcAddress(prntvpt_module, "PTConvertPrintTicketToDevMode"));
if (!g_convert_print_ticket_to_devmode_proc) {
NOTREACHED();
return false;
}
g_merge_and_validate_print_ticket_proc =
reinterpret_cast<PTMergeAndValidatePrintTicketProc>(
GetProcAddress(prntvpt_module, "PTMergeAndValidatePrintTicket"));
if (!g_merge_and_validate_print_ticket_proc) {
NOTREACHED();
return false;
}
g_release_memory_proc =
reinterpret_cast<PTReleaseMemoryProc>(
GetProcAddress(prntvpt_module, "PTReleaseMemory"));
if (!g_release_memory_proc) {
NOTREACHED();
return false;
}
g_close_provider_proc =
reinterpret_cast<PTCloseProviderProc>(
GetProcAddress(prntvpt_module, "PTCloseProvider"));
if (!g_close_provider_proc) {
NOTREACHED();
return false;
}
return true;
}
HRESULT XPSModule::OpenProvider(const base::string16& printer_name,
DWORD version,
HPTPROVIDER* provider) {
return g_open_provider_proc(printer_name.c_str(), version, provider);
}
HRESULT XPSModule::GetPrintCapabilities(HPTPROVIDER provider,
IStream* print_ticket,
IStream* capabilities,
BSTR* error_message) {
return g_get_print_capabilities_proc(provider,
print_ticket,
capabilities,
error_message);
}
HRESULT XPSModule::ConvertDevModeToPrintTicket(HPTPROVIDER provider,
ULONG devmode_size_in_bytes,
PDEVMODE devmode,
EPrintTicketScope scope,
IStream* print_ticket) {
return g_convert_devmode_to_print_ticket_proc(provider,
devmode_size_in_bytes,
devmode,
scope,
print_ticket);
}
HRESULT XPSModule::ConvertPrintTicketToDevMode(
HPTPROVIDER provider,
IStream* print_ticket,
EDefaultDevmodeType base_devmode_type,
EPrintTicketScope scope,
ULONG* devmode_byte_count,
PDEVMODE* devmode,
BSTR* error_message) {
return g_convert_print_ticket_to_devmode_proc(provider,
print_ticket,
base_devmode_type,
scope,
devmode_byte_count,
devmode,
error_message);
}
HRESULT XPSModule::MergeAndValidatePrintTicket(HPTPROVIDER provider,
IStream* base_ticket,
IStream* delta_ticket,
EPrintTicketScope scope,
IStream* result_ticket,
BSTR* error_message) {
return g_merge_and_validate_print_ticket_proc(provider,
base_ticket,
delta_ticket,
scope,
result_ticket,
error_message);
}
HRESULT XPSModule::ReleaseMemory(PVOID buffer) {
return g_release_memory_proc(buffer);
}
HRESULT XPSModule::CloseProvider(HPTPROVIDER provider) {
return g_close_provider_proc(provider);
}
ScopedXPSInitializer::ScopedXPSInitializer() : initialized_(false) {
if (!XPSModule::Init())
return;
// Calls to XPS APIs typically require the XPS provider to be opened with
// PTOpenProvider. PTOpenProvider calls CoInitializeEx with
// COINIT_MULTITHREADED. We have seen certain buggy HP printer driver DLLs
// that call CoInitializeEx with COINIT_APARTMENTTHREADED in the context of
// PTGetPrintCapabilities. This call fails but the printer driver calls
// CoUninitialize anyway. This results in the apartment being torn down too
// early and the msxml DLL being unloaded which in turn causes code in
// unidrvui.dll to have a dangling pointer to an XML document which causes a
// crash. To protect ourselves from such drivers we make sure we always have
// an extra CoInitialize (calls to CoInitialize/CoUninitialize are
// refcounted).
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
// If this succeeded we are done because the PTOpenProvider call will provide
// the extra refcount on the apartment. If it failed because someone already
// called CoInitializeEx with COINIT_APARTMENTTHREADED, we try the other model
// to provide the additional refcount (since we don't know which model buggy
// printer drivers will use).
if (!SUCCEEDED(hr))
hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
DCHECK(SUCCEEDED(hr));
initialized_ = true;
}
ScopedXPSInitializer::~ScopedXPSInitializer() {
if (initialized_)
CoUninitialize();
initialized_ = false;
}
bool XPSPrintModule::Init() {
static bool initialized = InitImpl();
return initialized;
}
bool XPSPrintModule::InitImpl() {
HMODULE xpsprint_module = LoadLibrary(L"xpsprint.dll");
if (xpsprint_module == NULL)
return false;
g_start_xps_print_job_proc = reinterpret_cast<StartXpsPrintJobProc>(
GetProcAddress(xpsprint_module, "StartXpsPrintJob"));
if (!g_start_xps_print_job_proc) {
NOTREACHED();
return false;
}
return true;
}
HRESULT XPSPrintModule::StartXpsPrintJob(
const LPCWSTR printer_name,
const LPCWSTR job_name,
const LPCWSTR output_file_name,
HANDLE progress_event,
HANDLE completion_event,
UINT8* printable_pages_on,
UINT32 printable_pages_on_count,
IXpsPrintJob** xps_print_job,
IXpsPrintJobStream** document_stream,
IXpsPrintJobStream** print_ticket_stream) {
return g_start_xps_print_job_proc(printer_name,
job_name,
output_file_name,
progress_event,
completion_event,
printable_pages_on,
printable_pages_on_count,
xps_print_job,
document_stream,
print_ticket_stream);
}
bool InitBasicPrinterInfo(HANDLE printer, PrinterBasicInfo* printer_info) {
DCHECK(printer);
DCHECK(printer_info);
if (!printer)
return false;
PrinterInfo2 info_2;
if (!info_2.Init(printer))
return false;
printer_info->printer_name = base::WideToUTF8(info_2.get()->pPrinterName);
if (info_2.get()->pComment) {
printer_info->printer_description =
base::WideToUTF8(info_2.get()->pComment);
}
if (info_2.get()->pLocation) {
printer_info->options[kLocationTagName] =
base::WideToUTF8(info_2.get()->pLocation);
}
if (info_2.get()->pDriverName) {
printer_info->options[kDriverNameTagName] =
base::WideToUTF8(info_2.get()->pDriverName);
}
printer_info->printer_status = info_2.get()->Status;
std::string driver_info = GetDriverInfo(printer);
if (!driver_info.empty())
printer_info->options[kDriverInfoTagName] = driver_info;
return true;
}
std::string GetDriverInfo(HANDLE printer) {
DCHECK(printer);
std::string driver_info;
if (!printer)
return driver_info;
DriverInfo6 info_6;
if (!info_6.Init(printer))
return driver_info;
std::string info[4];
if (info_6.get()->pName)
info[0] = base::WideToUTF8(info_6.get()->pName);
if (info_6.get()->pDriverPath) {
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(
base::FilePath(info_6.get()->pDriverPath)));
if (version_info.get()) {
info[1] = base::WideToUTF8(version_info->file_version());
info[2] = base::WideToUTF8(version_info->product_name());
info[3] = base::WideToUTF8(version_info->product_version());
}
}
for (size_t i = 0; i < arraysize(info); ++i) {
std::replace(info[i].begin(), info[i].end(), ';', ',');
driver_info.append(info[i]);
if (i < arraysize(info) - 1)
driver_info.append(";");
}
return driver_info;
}
scoped_ptr<DEVMODE, base::FreeDeleter> XpsTicketToDevMode(
const base::string16& printer_name,
const std::string& print_ticket) {
scoped_ptr<DEVMODE, base::FreeDeleter> dev_mode;
printing::ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized()) {
// TODO(sanjeevr): Handle legacy proxy case (with no prntvpt.dll)
return dev_mode.Pass();
}
printing::ScopedPrinterHandle printer;
if (!printer.OpenPrinter(printer_name.c_str()))
return dev_mode.Pass();
base::win::ScopedComPtr<IStream> pt_stream;
HRESULT hr = StreamFromPrintTicket(print_ticket, pt_stream.Receive());
if (FAILED(hr))
return dev_mode.Pass();
HPTPROVIDER provider = NULL;
hr = printing::XPSModule::OpenProvider(printer_name, 1, &provider);
if (SUCCEEDED(hr)) {
ULONG size = 0;
DEVMODE* dm = NULL;
// Use kPTJobScope, because kPTDocumentScope breaks duplex.
hr = printing::XPSModule::ConvertPrintTicketToDevMode(provider,
pt_stream,
kUserDefaultDevmode,
kPTJobScope,
&size,
&dm,
NULL);
if (SUCCEEDED(hr)) {
// Correct DEVMODE using DocumentProperties. See documentation for
// PTConvertPrintTicketToDevMode.
dev_mode = CreateDevMode(printer, dm);
printing::XPSModule::ReleaseMemory(dm);
}
printing::XPSModule::CloseProvider(provider);
}
return dev_mode.Pass();
}
scoped_ptr<DEVMODE, base::FreeDeleter> CreateDevModeWithColor(
HANDLE printer,
const base::string16& printer_name,
bool color) {
scoped_ptr<DEVMODE, base::FreeDeleter> default_ticket =
CreateDevMode(printer, NULL);
if (!default_ticket)
return default_ticket.Pass();
if ((default_ticket->dmFields & DM_COLOR) &&
((default_ticket->dmColor == DMCOLOR_COLOR) == color)) {
return default_ticket.Pass();
}
default_ticket->dmFields |= DM_COLOR;
default_ticket->dmColor = color ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
DriverInfo6 info_6;
if (!info_6.Init(printer))
return default_ticket.Pass();
const DRIVER_INFO_6* p = info_6.get();
// Only HP known to have issues.
if (!p->pszMfgName || wcscmp(p->pszMfgName, L"HP") != 0)
return default_ticket.Pass();
// Need XPS for this workaround.
printing::ScopedXPSInitializer xps_initializer;
if (!xps_initializer.initialized())
return default_ticket.Pass();
const char* xps_color = color ? kXpsTicketColor : kXpsTicketMonochrome;
std::string xps_ticket = base::StringPrintf(kXpsTicketTemplate, xps_color);
scoped_ptr<DEVMODE, base::FreeDeleter> ticket =
printing::XpsTicketToDevMode(printer_name, xps_ticket);
if (!ticket)
return default_ticket.Pass();
return ticket.Pass();
}
scoped_ptr<DEVMODE, base::FreeDeleter> CreateDevMode(HANDLE printer,
DEVMODE* in) {
LONG buffer_size = DocumentProperties(
NULL, printer, const_cast<wchar_t*>(L""), NULL, NULL, 0);
if (buffer_size < static_cast<int>(sizeof(DEVMODE)))
return scoped_ptr<DEVMODE, base::FreeDeleter>();
scoped_ptr<DEVMODE, base::FreeDeleter> out(
reinterpret_cast<DEVMODE*>(malloc(buffer_size)));
DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER;
if (DocumentProperties(
NULL, printer, const_cast<wchar_t*>(L""), out.get(), in, flags) !=
IDOK) {
return scoped_ptr<DEVMODE, base::FreeDeleter>();
}
CHECK_GE(buffer_size, out.get()->dmSize + out.get()->dmDriverExtra);
return out.Pass();
}
scoped_ptr<DEVMODE, base::FreeDeleter> PromptDevMode(
HANDLE printer,
const base::string16& printer_name,
DEVMODE* in,
HWND window,
bool* canceled) {
LONG buffer_size =
DocumentProperties(window,
printer,
const_cast<wchar_t*>(printer_name.c_str()),
NULL,
NULL,
0);
if (buffer_size < static_cast<int>(sizeof(DEVMODE)))
return scoped_ptr<DEVMODE, base::FreeDeleter>();
scoped_ptr<DEVMODE, base::FreeDeleter> out(
reinterpret_cast<DEVMODE*>(malloc(buffer_size)));
DWORD flags = (in ? (DM_IN_BUFFER) : 0) | DM_OUT_BUFFER | DM_IN_PROMPT;
LONG result = DocumentProperties(window,
printer,
const_cast<wchar_t*>(printer_name.c_str()),
out.get(),
in,
flags);
if (canceled)
*canceled = (result == IDCANCEL);
if (result != IDOK)
return scoped_ptr<DEVMODE, base::FreeDeleter>();
CHECK_GE(buffer_size, out.get()->dmSize + out.get()->dmDriverExtra);
return out.Pass();
}
} // namespace printing
| 35.986641 | 80 | 0.632974 | [
"model"
] |
db900a5092ed79db81cd4cee69efe2dfe8468470 | 19,657 | hpp | C++ | src/simd/vector_div.hpp | tum-db/partitioned-filters | 56c20102715a442cbec9ecb732d41de15b31c828 | [
"MIT"
] | 5 | 2021-08-16T17:48:45.000Z | 2022-03-10T22:53:54.000Z | src/simd/vector_div.hpp | tum-db/partitioned-filters | 56c20102715a442cbec9ecb732d41de15b31c828 | [
"MIT"
] | null | null | null | src/simd/vector_div.hpp | tum-db/partitioned-filters | 56c20102715a442cbec9ecb732d41de15b31c828 | [
"MIT"
] | null | null | null | #pragma once
namespace filters::simd {
template<size_t divisor, typename Vector>
forceinline
static Vector div(const Vector ÷nd) {
if constexpr (math::is_power_of_two(divisor)) {
return dividend >> math::const_log2(divisor);
} else if constexpr (not Vector::avx) {
return Vector(dividend.vector / divisor);
} else {
if constexpr (divisor % 3 == 0 and math::is_power_of_two(divisor / 3)) {
return dividend.mulh32(Vector(2863311531)) >> (1 + math::const_log2(divisor / 3));
} else if constexpr (divisor % 5 == 0 and math::is_power_of_two(divisor / 5)) {
return dividend.mulh32(Vector(3435973837)) >> (2 + math::const_log2(divisor / 5));
} else if constexpr (divisor == 7) {
Vector quotient = dividend.mulh32(Vector(613566757));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 2;
} else if constexpr (divisor % 9 == 0 and math::is_power_of_two(divisor / 9)) {
return dividend.mulh32(Vector(954437177)) >> (1 + math::const_log2(divisor / 9));
} else if constexpr (divisor % 11 == 0 and math::is_power_of_two(divisor / 11)) {
return dividend.mulh32(Vector(3123612579)) >> (3 + math::const_log2(divisor / 11));
} else if constexpr (divisor % 13 == 0 and math::is_power_of_two(divisor / 13)) {
return dividend.mulh32(Vector(1321528399)) >> (2 + math::const_log2(divisor / 13));
} else if constexpr (divisor == 14) {
return (dividend >> 1).mulh32(Vector(2454267027)) >> 2;
} else if constexpr (divisor % 15 == 0 and math::is_power_of_two(divisor / 15)) {
return dividend.mulh32(Vector(2290649225)) >> (3 + math::const_log2(divisor / 15));
} else if constexpr (divisor % 17 == 0 and math::is_power_of_two(divisor / 17)) {
return dividend.mulh32(Vector(4042322161)) >> (4 + math::const_log2(divisor / 17));
} else if constexpr (divisor == 19) {
Vector quotient = dividend.mulh32(Vector(2938661835));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 4;
} else if constexpr (divisor == 21) {
Vector quotient = dividend.mulh32(Vector(2249744775));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 4;
} else if constexpr (divisor % 23 == 0 and math::is_power_of_two(divisor / 23)) {
return dividend.mulh32(Vector(2987803337)) >> (4 + math::const_log2(divisor / 23));
} else if constexpr (divisor % 25 == 0 and math::is_power_of_two(divisor / 25)) {
return dividend.mulh32(Vector(1374389535)) >> (3 + math::const_log2(divisor / 25));
} else if constexpr (divisor == 27) {
Vector quotient = dividend.mulh32(Vector(795364315));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 4;
} else if constexpr (divisor == 28) {
return (dividend >> 2).mulh32(Vector(613566757));
} else if constexpr (divisor % 29 == 0 and math::is_power_of_two(divisor / 29)) {
return dividend.mulh32(Vector(2369637129)) >> (4 + math::const_log2(divisor / 29));
} else if constexpr (divisor == 31) {
Vector quotient = dividend.mulh32(Vector(138547333));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 4;
} else if constexpr (divisor % 33 == 0 and math::is_power_of_two(divisor / 33)) {
return dividend.mulh32(Vector(1041204193)) >> (3 + math::const_log2(divisor / 33));
} else if constexpr (divisor == 35) {
Vector quotient = dividend.mulh32(Vector(3558687189));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor == 37) {
Vector quotient = dividend.mulh32(Vector(3134165325));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor == 38) {
return (dividend >> 1).mulh32(Vector(1808407283)) >> 3;
} else if constexpr (divisor == 39) {
Vector quotient = dividend.mulh32(Vector(2753184165));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor % 41 == 0 and math::is_power_of_two(divisor / 41)) {
return dividend.mulh32(Vector(3352169597)) >> (5 + math::const_log2(divisor / 41));
} else if constexpr (divisor == 42) {
return (dividend >> 1).mulh32(Vector(818089009)) >> 2;
} else if constexpr (divisor % 43 == 0 and math::is_power_of_two(divisor / 43)) {
return dividend.mulh32(Vector(799063683)) >> (3 + math::const_log2(divisor / 43));
} else if constexpr (divisor == 45) {
Vector quotient = dividend.mulh32(Vector(1813430637));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor % 47 == 0 and math::is_power_of_two(divisor / 47)) {
return dividend.mulh32(Vector(2924233053)) >> (5 + math::const_log2(divisor / 47));
} else if constexpr (divisor % 49 == 0 and math::is_power_of_two(divisor / 49)) {
return dividend.mulh32(Vector(1402438301)) >> (4 + math::const_log2(divisor / 49));
} else if constexpr (divisor % 51 == 0 and math::is_power_of_two(divisor / 51)) {
return dividend.mulh32(Vector(2694881441)) >> (5 + math::const_log2(divisor / 51));
} else if constexpr (divisor == 53) {
Vector quotient = dividend.mulh32(Vector(891408307));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor == 54) {
return (dividend >> 1).mulh32(Vector(1272582903)) >> 3;
} else if constexpr (divisor == 55) {
Vector quotient = dividend.mulh32(Vector(702812831));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor == 56) {
return (dividend >> 3).mulh32(Vector(613566757));
} else if constexpr (divisor == 57) {
Vector quotient = dividend.mulh32(Vector(527452125));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor % 59 == 0 and math::is_power_of_two(divisor / 59)) {
return dividend.mulh32(Vector(582368447)) >> (3 + math::const_log2(divisor / 59));
} else if constexpr (divisor % 61 == 0 and math::is_power_of_two(divisor / 61)) {
return dividend.mulh32(Vector(1126548799)) >> (4 + math::const_log2(divisor / 61));
} else if constexpr (divisor == 62) {
return (dividend >> 1).mulh32(Vector(2216757315)) >> 4;
} else if constexpr (divisor == 63) {
Vector quotient = dividend.mulh32(Vector(68174085));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 5;
} else if constexpr (divisor % 65 == 0 and math::is_power_of_two(divisor / 65)) {
return dividend.mulh32(Vector(4228890877)) >> (6 + math::const_log2(divisor / 65));
} else if constexpr (divisor % 67 == 0 and math::is_power_of_two(divisor / 67)) {
return dividend.mulh32(Vector(128207979)) >> (1 + math::const_log2(divisor / 67));
} else if constexpr (divisor % 69 == 0 and math::is_power_of_two(divisor / 69)) {
return dividend.mulh32(Vector(1991868891)) >> (5 + math::const_log2(divisor / 69));
} else if constexpr (divisor == 70) {
return (dividend >> 1).mulh32(Vector(3926827243)) >> 5;
} else if constexpr (divisor % 71 == 0 and math::is_power_of_two(divisor / 71)) {
return dividend.mulh32(Vector(3871519817)) >> (6 + math::const_log2(divisor / 71));
} else if constexpr (divisor == 73) {
Vector quotient = dividend.mulh32(Vector(3235934265));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 74) {
return (dividend >> 1).mulh32(Vector(3714566311)) >> 5;
} else if constexpr (divisor % 75 == 0 and math::is_power_of_two(divisor / 75)) {
return dividend.mulh32(Vector(458129845)) >> (3 + math::const_log2(divisor / 75));
} else if constexpr (divisor == 76) {
return (dividend >> 2).mulh32(Vector(452101821)) >> 1;
} else if constexpr (divisor % 77 == 0 and math::is_power_of_two(divisor / 77)) {
return dividend.mulh32(Vector(892460737)) >> (4 + math::const_log2(divisor / 77));
} else if constexpr (divisor == 78) {
return (dividend >> 1).mulh32(Vector(3524075731)) >> 5;
} else if constexpr (divisor % 79 == 0 and math::is_power_of_two(divisor / 79)) {
return dividend.mulh32(Vector(3479467177)) >> (6 + math::const_log2(divisor / 79));
} else if constexpr (divisor % 81 == 0 and math::is_power_of_two(divisor / 81)) {
return dividend.mulh32(Vector(3393554407)) >> (6 + math::const_log2(divisor / 81));
} else if constexpr (divisor % 83 == 0 and math::is_power_of_two(divisor / 83)) {
return dividend.mulh32(Vector(827945503)) >> (4 + math::const_log2(divisor / 83));
} else if constexpr (divisor == 84) {
return (dividend >> 2).mulh32(Vector(818089009)) >> 2;
} else if constexpr (divisor % 85 == 0 and math::is_power_of_two(divisor / 85)) {
return dividend.mulh32(Vector(3233857729)) >> (6 + math::const_log2(divisor / 85));
} else if constexpr (divisor % 87 == 0 and math::is_power_of_two(divisor / 87)) {
return dividend.mulh32(Vector(789879043)) >> (4 + math::const_log2(divisor / 87));
} else if constexpr (divisor % 89 == 0 and math::is_power_of_two(divisor / 89)) {
return dividend.mulh32(Vector(3088515809)) >> (6 + math::const_log2(divisor / 89));
} else if constexpr (divisor == 90) {
return (dividend >> 1).mulh32(Vector(3054198967)) >> 5;
} else if constexpr (divisor == 91) {
Vector quotient = dividend.mulh32(Vector(1746305385));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor % 93 == 0 and math::is_power_of_two(divisor / 93)) {
return dividend.mulh32(Vector(2955676419)) >> (6 + math::const_log2(divisor / 93));
} else if constexpr (divisor == 95) {
Vector quotient = dividend.mulh32(Vector(1491936009));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 97) {
Vector quotient = dividend.mulh32(Vector(1372618415));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor % 99 == 0 and math::is_power_of_two(divisor / 99)) {
return dividend.mulh32(Vector(2776544515)) >> (6 + math::const_log2(divisor / 99));
} else if constexpr (divisor == 101) {
Vector quotient = dividend.mulh32(Vector(1148159575));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 103) {
Vector quotient = dividend.mulh32(Vector(1042467791));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 105) {
Vector quotient = dividend.mulh32(Vector(940802361));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 106) {
return (dividend >> 1).mulh32(Vector(1296593901)) >> 4;
} else if constexpr (divisor == 107) {
Vector quotient = dividend.mulh32(Vector(842937507));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 108) {
return (dividend >> 2).mulh32(Vector(1272582903)) >> 3;
} else if constexpr (divisor == 109) {
Vector quotient = dividend.mulh32(Vector(748664025));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 110) {
return (dividend >> 1).mulh32(Vector(156180629)) >> 1;
} else if constexpr (divisor == 111) {
Vector quotient = dividend.mulh32(Vector(657787785));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 112) {
return (dividend >> 4).mulh32(Vector(613566758));
} else if constexpr (divisor == 113) {
Vector quotient = dividend.mulh32(Vector(570128403));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 114) {
return (dividend >> 1).mulh32(Vector(2411209711)) >> 5;
} else if constexpr (divisor == 115) {
Vector quotient = dividend.mulh32(Vector(485518043));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 117) {
Vector quotient = dividend.mulh32(Vector(403800345));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor % 119 == 0 and math::is_power_of_two(divisor / 119)) {
return dividend.mulh32(Vector(1154949189)) >> (5 + math::const_log2(divisor / 119));
} else if constexpr (divisor == 121) {
Vector quotient = dividend.mulh32(Vector(248469183));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 123) {
Vector quotient = dividend.mulh32(Vector(174592167));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor == 124) {
return (dividend >> 2).mulh32(Vector(554189329)) >> 2;
} else if constexpr (divisor % 125 == 0 and math::is_power_of_two(divisor / 125)) {
return dividend.mulh32(Vector(274877907)) >> (3 + math::const_log2(divisor / 125));
} else if constexpr (divisor == 126) {
return (dividend >> 1).mulh32(Vector(2181570691)) >> 5;
} else if constexpr (divisor == 127) {
Vector quotient = dividend.mulh32(Vector(33818641));
Vector temp = (dividend - quotient) >> 1;
return (quotient + temp) >> 6;
} else if constexpr (divisor % 129 == 0 and math::is_power_of_two(divisor / 129)) {
return dividend.mulh32(Vector(266354561)) >> (3 + math::const_log2(divisor / 129));
} else if constexpr (divisor % 131 == 0 and math::is_power_of_two(divisor / 131)) {
return dividend.mulh32(Vector(4196609267)) >> (7 + math::const_log2(divisor / 131));
} else if constexpr (divisor % 133 == 0 and math::is_power_of_two(divisor / 133)) {
return dividend.mulh32(Vector(4133502361)) >> (7 + math::const_log2(divisor / 133));
} else if constexpr (divisor % 135 == 0 and math::is_power_of_two(divisor / 135)) {
return dividend.mulh32(Vector(4072265289)) >> (7 + math::const_log2(divisor / 135));
} else if constexpr (divisor % 137 == 0 and math::is_power_of_two(divisor / 137)) {
return dividend.mulh32(Vector(125400505)) >> (2 + math::const_log2(divisor / 137));
} else if constexpr (divisor % 139 == 0 and math::is_power_of_two(divisor / 139)) {
return dividend.mulh32(Vector(1977538899)) >> (6 + math::const_log2(divisor / 139));
} else if constexpr (divisor == 140) {
return (dividend >> 2).mulh32(Vector(981706811)) >> 3;
} else if constexpr (divisor % 141 == 0 and math::is_power_of_two(divisor / 141)) {
return dividend.mulh32(Vector(974744351)) >> (5 + math::const_log2(divisor / 141));
} else if constexpr (divisor % 143 == 0 and math::is_power_of_two(divisor / 143)) {
return dividend.mulh32(Vector(3844446251)) >> (7 + math::const_log2(divisor / 143));
} else if constexpr (divisor % 145 == 0 and math::is_power_of_two(divisor / 145)) {
return dividend.mulh32(Vector(3791419407)) >> (7 + math::const_log2(divisor / 145));
} else if constexpr (divisor == 146) {
return (dividend >> 1).mulh32(Vector(3765450781)) >> 6;
} else if constexpr (divisor % 147 == 0 and math::is_power_of_two(divisor / 147)) {
return dividend.mulh32(Vector(3739835469)) >> (7 + math::const_log2(divisor / 147));
} else if constexpr (divisor == 148) {
return (dividend >> 2).mulh32(Vector(464320789)) >> 2;
} else if constexpr (divisor % 149 == 0 and math::is_power_of_two(divisor / 149)) {
return dividend.mulh32(Vector(3689636335)) >> (7 + math::const_log2(divisor / 149));
} else {
throw std::runtime_error{"not supported: " + std::to_string(divisor)};
}
}
}
template<size_t divisor, typename Vector>
forceinline
static Vector mod(const Vector ÷nd) {
if constexpr (math::is_power_of_two(divisor)) {
return dividend & Vector(divisor - 1);
} else if constexpr (not Vector::avx) {
return Vector(dividend.vector % divisor);
} else {
const Vector div = simd::div<divisor>(dividend);
return dividend - div * Vector(divisor);
}
}
template<size_t divisor, typename Vector>
forceinline
static void div_mod(const Vector ÷nd, Vector &div, Vector &mod) {
if constexpr (math::is_power_of_two(divisor)) {
div = dividend >> math::const_log2(divisor);
mod = dividend & Vector(divisor - 1);
} else if constexpr (not Vector::avx) {
div = Vector(dividend.vector / divisor);
mod = Vector(dividend.vector % divisor);
} else {
div = simd::div<divisor>(dividend);
mod = dividend - div * Vector(divisor);
}
}
} | 65.963087 | 100 | 0.552933 | [
"vector"
] |
db94cc4c0ccba7a226137c87853efd539680bee8 | 1,687 | cpp | C++ | calculus/accept.cpp | lilissun/spa | d44974c51017691ff4ada29c212c54bb0ee931c2 | [
"Apache-2.0"
] | null | null | null | calculus/accept.cpp | lilissun/spa | d44974c51017691ff4ada29c212c54bb0ee931c2 | [
"Apache-2.0"
] | null | null | null | calculus/accept.cpp | lilissun/spa | d44974c51017691ff4ada29c212c54bb0ee931c2 | [
"Apache-2.0"
] | 1 | 2020-04-24T02:28:32.000Z | 2020-04-24T02:28:32.000Z | //
// accept.cpp
// calculus
//
// Created by Li Li on 9/5/15.
// Copyright (c) 2015 Lilissun. All rights reserved.
//
#include "accept.h"
#include "common/iostream.h"
#include "common/debug.h"
#include "symbolic/term.h"
#include "symbolic/tuple.h"
#include "symbolic/number.h"
#include "symbolic/nonce.h"
#include "symbolic/name.h"
#include "expression.h"
#include "tuple.h"
#include "name.h"
#include "state.h"
#include "program.h"
namespace cal {
Accept::~Accept()
{
delete _name;
delete _arguments;
delete _timestamp;
delete _next_process;
}
void Accept::execute(Program *program, const State *state, std::vector<tim::Rule *> &rules) const
{
State *next_state = state->clone();
auto arguments = _arguments->evaluate_tuple(program, next_state);
auto timestamp = next_state->get_global_timestamp(_timestamp->name())->clone();
ASSERT(timestamp->type() == sym::TermType::TERM_NUMBER);
auto accept_event = program->accept_event(_name->name(), next_state->get_identity()->clone(), arguments, timestamp);
rules.push_back(next_state->construct_rule(accept_event));
_next_process->execute(program, next_state, rules);
delete next_state;
}
void Accept::info(const size_t depth, std::ostream &os) const
{
os << com::tabs(process_tab_size, depth) << process_engage << process_space;
os << process_accept << process_space;
_name->info(os);
_arguments->info(os);
os << process_at;
_timestamp->info(os);
os << process_endline << std::endl;
_next_process->info(depth, os);
}
} | 29.086207 | 124 | 0.639004 | [
"vector"
] |
db9d5000f751b4c90e04a6c0ef6f236920156228 | 14,194 | cpp | C++ | stromx/cvimgproc/Undistort.cpp | uboot/stromx-opencv | c7de6353905fee8870f8bf700363e0868ab17b78 | [
"Apache-2.0"
] | null | null | null | stromx/cvimgproc/Undistort.cpp | uboot/stromx-opencv | c7de6353905fee8870f8bf700363e0868ab17b78 | [
"Apache-2.0"
] | null | null | null | stromx/cvimgproc/Undistort.cpp | uboot/stromx-opencv | c7de6353905fee8870f8bf700363e0868ab17b78 | [
"Apache-2.0"
] | null | null | null | #include "stromx/cvimgproc/Undistort.h"
#include "stromx/cvimgproc/Locale.h"
#include "stromx/cvimgproc/Utility.h"
#include <stromx/cvsupport/Image.h>
#include <stromx/cvsupport/Matrix.h>
#include <stromx/cvsupport/Utilities.h>
#include <stromx/runtime/DataContainer.h>
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataComposite.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/ReadAccess.h>
#include <stromx/runtime/VariantComposite.h>
#include <stromx/runtime/WriteAccess.h>
#include <opencv2/imgproc/imgproc.hpp>
namespace stromx
{
namespace cvimgproc
{
const std::string Undistort::PACKAGE(STROMX_CVIMGPROC_PACKAGE_NAME);
const runtime::Version Undistort::VERSION(STROMX_CVIMGPROC_VERSION_MAJOR, STROMX_CVIMGPROC_VERSION_MINOR, STROMX_CVIMGPROC_VERSION_PATCH);
const std::string Undistort::TYPE("Undistort");
Undistort::Undistort()
: runtime::OperatorKernel(TYPE, PACKAGE, VERSION, setupInitParameters()),
m_cameraMatrix(cvsupport::Matrix::eye(3, 3, runtime::Matrix::FLOAT_32)),
m_distCoeffs(cvsupport::Matrix::zeros(1, 5, runtime::Matrix::FLOAT_32)),
m_dataFlow()
{
}
const runtime::DataRef Undistort::getParameter(unsigned int id) const
{
switch(id)
{
case PARAMETER_CAMERA_MATRIX:
return m_cameraMatrix;
case PARAMETER_DIST_COEFFS:
return m_distCoeffs;
case PARAMETER_DATA_FLOW:
return m_dataFlow;
default:
throw runtime::WrongParameterId(id, *this);
}
}
void Undistort::setParameter(unsigned int id, const runtime::Data& value)
{
try
{
switch(id)
{
case PARAMETER_CAMERA_MATRIX:
{
const runtime::Matrix & castedValue = runtime::data_cast<runtime::Matrix>(value);
if(! castedValue.variant().isVariant(runtime::Variant::FLOAT_MATRIX))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkMatrixValue(castedValue, m_cameraMatrixParameter, *this);
m_cameraMatrix = castedValue;
}
break;
case PARAMETER_DIST_COEFFS:
{
const runtime::Matrix & castedValue = runtime::data_cast<runtime::Matrix>(value);
if(! castedValue.variant().isVariant(runtime::Variant::FLOAT_MATRIX))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkMatrixValue(castedValue, m_distCoeffsParameter, *this);
m_distCoeffs = castedValue;
}
break;
case PARAMETER_DATA_FLOW:
{
const runtime::Enum & castedValue = runtime::data_cast<runtime::Enum>(value);
if(! castedValue.variant().isVariant(runtime::Variant::ENUM))
{
throw runtime::WrongParameterType(parameter(id), *this);
}
cvsupport::checkEnumValue(castedValue, m_dataFlowParameter, *this);
m_dataFlow = castedValue;
}
break;
default:
throw runtime::WrongParameterId(id, *this);
}
}
catch(runtime::BadCast&)
{
throw runtime::WrongParameterType(parameter(id), *this);
}
}
const std::vector<const runtime::Parameter*> Undistort::setupInitParameters()
{
std::vector<const runtime::Parameter*> parameters;
m_dataFlowParameter = new runtime::EnumParameter(PARAMETER_DATA_FLOW);
m_dataFlowParameter->setAccessMode(runtime::Parameter::NONE_WRITE);
m_dataFlowParameter->setTitle(L_("Data flow"));
m_dataFlowParameter->add(runtime::EnumDescription(runtime::Enum(MANUAL), L_("Manual")));
m_dataFlowParameter->add(runtime::EnumDescription(runtime::Enum(ALLOCATE), L_("Allocate")));
parameters.push_back(m_dataFlowParameter);
return parameters;
}
const std::vector<const runtime::Parameter*> Undistort::setupParameters()
{
std::vector<const runtime::Parameter*> parameters;
switch(int(m_dataFlow))
{
case(MANUAL):
{
m_cameraMatrixParameter = new runtime::MatrixParameter(PARAMETER_CAMERA_MATRIX, runtime::Variant::FLOAT_MATRIX);
m_cameraMatrixParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_cameraMatrixParameter->setTitle(L_("Camera matrix"));
m_cameraMatrixParameter->setRows(3);
m_cameraMatrixParameter->setCols(3);
parameters.push_back(m_cameraMatrixParameter);
m_distCoeffsParameter = new runtime::MatrixParameter(PARAMETER_DIST_COEFFS, runtime::Variant::FLOAT_MATRIX);
m_distCoeffsParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_distCoeffsParameter->setTitle(L_("Distortion coefficients"));
m_distCoeffsParameter->setRows(1);
m_distCoeffsParameter->setCols(5);
parameters.push_back(m_distCoeffsParameter);
}
break;
case(ALLOCATE):
{
m_cameraMatrixParameter = new runtime::MatrixParameter(PARAMETER_CAMERA_MATRIX, runtime::Variant::FLOAT_MATRIX);
m_cameraMatrixParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_cameraMatrixParameter->setTitle(L_("Camera matrix"));
m_cameraMatrixParameter->setRows(3);
m_cameraMatrixParameter->setCols(3);
parameters.push_back(m_cameraMatrixParameter);
m_distCoeffsParameter = new runtime::MatrixParameter(PARAMETER_DIST_COEFFS, runtime::Variant::FLOAT_MATRIX);
m_distCoeffsParameter->setAccessMode(runtime::Parameter::ACTIVATED_WRITE);
m_distCoeffsParameter->setTitle(L_("Distortion coefficients"));
m_distCoeffsParameter->setRows(1);
m_distCoeffsParameter->setCols(5);
parameters.push_back(m_distCoeffsParameter);
}
break;
}
return parameters;
}
const std::vector<const runtime::Input*> Undistort::setupInputs()
{
std::vector<const runtime::Input*> inputs;
switch(int(m_dataFlow))
{
case(MANUAL):
{
m_srcDescription = new runtime::Input(INPUT_SRC, runtime::Variant::IMAGE);
m_srcDescription->setTitle(L_("Source"));
inputs.push_back(m_srcDescription);
m_dstDescription = new runtime::Input(INPUT_DST, runtime::Variant::IMAGE);
m_dstDescription->setTitle(L_("Destination"));
inputs.push_back(m_dstDescription);
}
break;
case(ALLOCATE):
{
m_srcDescription = new runtime::Input(INPUT_SRC, runtime::Variant::IMAGE);
m_srcDescription->setTitle(L_("Source"));
inputs.push_back(m_srcDescription);
}
break;
}
return inputs;
}
const std::vector<const runtime::Output*> Undistort::setupOutputs()
{
std::vector<const runtime::Output*> outputs;
switch(int(m_dataFlow))
{
case(MANUAL):
{
runtime::Output* dst = new runtime::Output(OUTPUT_DST, runtime::Variant::IMAGE);
dst->setTitle(L_("Destination"));
outputs.push_back(dst);
}
break;
case(ALLOCATE):
{
runtime::Output* dst = new runtime::Output(OUTPUT_DST, runtime::Variant::IMAGE);
dst->setTitle(L_("Destination"));
outputs.push_back(dst);
}
break;
}
return outputs;
}
void Undistort::initialize()
{
runtime::OperatorKernel::initialize(setupInputs(), setupOutputs(), setupParameters());
}
void Undistort::execute(runtime::DataProvider & provider)
{
switch(int(m_dataFlow))
{
case(MANUAL):
{
runtime::Id2DataPair srcInMapper(INPUT_SRC);
runtime::Id2DataPair dstInMapper(INPUT_DST);
provider.receiveInputData(srcInMapper && dstInMapper);
const runtime::Data* srcData = 0;
runtime::Data* dstData = 0;
runtime::ReadAccess srcReadAccess;
runtime::DataContainer inContainer = dstInMapper.data();
runtime::WriteAccess writeAccess(inContainer);
dstData = &writeAccess.get();
if(srcInMapper.data() == inContainer)
{
throw runtime::InputError(INPUT_SRC, *this, "Can not operate in place.");
}
else
{
srcReadAccess = runtime::ReadAccess(srcInMapper.data());
srcData = &srcReadAccess.get();
}
if(! srcData->variant().isVariant(m_srcDescription->variant()))
{
throw runtime::InputError(INPUT_SRC, *this, "Wrong input data variant.");
}
if(! dstData->variant().isVariant(m_dstDescription->variant()))
{
throw runtime::InputError(INPUT_DST, *this, "Wrong input data variant.");
}
const runtime::Image* srcCastedData = runtime::data_cast<runtime::Image>(srcData);
runtime::Image * dstCastedData = runtime::data_cast<runtime::Image>(dstData);
dstCastedData->initializeImage(srcCastedData->width(), srcCastedData->height(), srcCastedData->stride(), dstCastedData->data(), srcCastedData->pixelType());
cv::Mat srcCvData = cvsupport::getOpenCvMat(*srcCastedData);
cv::Mat dstCvData = cvsupport::getOpenCvMat(*dstCastedData);
cv::Mat cameraMatrixCvData = cvsupport::getOpenCvMat(m_cameraMatrix);
cv::Mat distCoeffsCvData = cvsupport::getOpenCvMat(m_distCoeffs);
cv::undistort(srcCvData, dstCvData, cameraMatrixCvData, distCoeffsCvData);
runtime::DataContainer dstOutContainer = inContainer;
runtime::Id2DataPair dstOutMapper(OUTPUT_DST, dstOutContainer);
provider.sendOutputData(dstOutMapper);
}
break;
case(ALLOCATE):
{
runtime::Id2DataPair srcInMapper(INPUT_SRC);
provider.receiveInputData(srcInMapper);
const runtime::Data* srcData = 0;
runtime::ReadAccess srcReadAccess;
srcReadAccess = runtime::ReadAccess(srcInMapper.data());
srcData = &srcReadAccess.get();
if(! srcData->variant().isVariant(m_srcDescription->variant()))
{
throw runtime::InputError(INPUT_SRC, *this, "Wrong input data variant.");
}
const runtime::Image* srcCastedData = runtime::data_cast<runtime::Image>(srcData);
cv::Mat srcCvData = cvsupport::getOpenCvMat(*srcCastedData);
cv::Mat dstCvData;
cv::Mat cameraMatrixCvData = cvsupport::getOpenCvMat(m_cameraMatrix);
cv::Mat distCoeffsCvData = cvsupport::getOpenCvMat(m_distCoeffs);
cv::undistort(srcCvData, dstCvData, cameraMatrixCvData, distCoeffsCvData);
runtime::Image* dstCastedData = new cvsupport::Image(dstCvData);
runtime::DataContainer dstOutContainer = runtime::DataContainer(dstCastedData);
runtime::Id2DataPair dstOutMapper(OUTPUT_DST, dstOutContainer);
dstCastedData->initializeImage(dstCastedData->width(), dstCastedData->height(), dstCastedData->stride(), dstCastedData->data(), srcCastedData->pixelType());
provider.sendOutputData(dstOutMapper);
}
break;
}
}
} // cvimgproc
} // stromx
| 44.63522 | 176 | 0.515781 | [
"vector"
] |
dba3d0b793abebbcc3c1c6e774551d56d1e65783 | 3,935 | cpp | C++ | samples/OfflineRendererSample/OfflineRendererApplication.cpp | flygod1159/MxEngine | 20af09a63368acbf1fe674566deb73f8dd7f85b3 | [
"BSD-3-Clause"
] | 669 | 2020-07-01T17:22:12.000Z | 2022-03-31T02:48:17.000Z | samples/OfflineRendererSample/OfflineRendererApplication.cpp | MomoDeve/MomoEngine | f762ac9036f7f5519bc72e28f33f259e4699293b | [
"BSD-3-Clause"
] | 17 | 2020-07-09T16:39:40.000Z | 2021-12-08T03:11:57.000Z | samples/OfflineRendererSample/OfflineRendererApplication.cpp | MomoDeve/MomoEngine | f762ac9036f7f5519bc72e28f33f259e4699293b | [
"BSD-3-Clause"
] | 42 | 2020-08-03T18:53:40.000Z | 2022-03-18T06:27:56.000Z | #include <MxEngine.h>
namespace OfflineRendererSample
{
using namespace MxEngine;
/*
this sample shows how to render one big screenshot of a scene and save it to disk
although it is possible to just resize camera render texture,
such image will be bound by gpu memory. To avoid this, here we render image in multiple frames
tile-by-tile using frustrum camera projection. Resulting image size is (viewportSize * texturesPerRaw)
*/
class OfflineRendererApplication : public Application
{
// Configure this parameters as you wish //
VectorInt2 viewportSize{ 1920, 1080 };//7680, 4320 };
size_t texturesPerRow = 4;
float imageSize = 1.0f / (float)texturesPerRow;
///////////////////////////////////////////
using TextureArray = MxVector<Image>;
TextureArray textures;
public:
virtual void OnCreate() override
{
// create camera with frustrum mode enabled
auto cameraObject = MxObject::Create();
auto controller = cameraObject->AddComponent<CameraController>();
controller->SetDirection(Vector3(0.0f, -0.333f, 1.0f));
controller->SetCameraType(CameraType::FRUSTRUM);
auto skybox = cameraObject->AddComponent<Skybox>();
skybox->CubeMap = AssetManager::LoadCubeMap("Resources/dawn.jpg"_id);
skybox->Irradiance = AssetManager::LoadCubeMap("Resources/dawn_irradiance.jpg"_id);
skybox->SetIntensity(0.1f);
Rendering::SetViewport(controller);
Rendering::ResizeViewport(viewportSize.x, viewportSize.y);
// create yellow cube as main rendering target
auto cubeObject = MxObject::Create();
cubeObject->LocalTransform.Translate(MakeVector3(0.0f, -1.0f, 3.0f));
cubeObject->LocalTransform.RotateY(45.0f);
auto meshSource = cubeObject->AddComponent<MeshSource>(Primitives::CreateCube());
auto meshRenderer = cubeObject->AddComponent<MeshRenderer>();
auto yellowColor = MakeVector3(1.0f, 0.7f, 0.0f);
meshRenderer->GetMaterial()->BaseColor = yellowColor;
// create global light
auto lightObject = MxObject::Create();
auto dirLight = lightObject->AddComponent<DirectionalLight>();
dirLight->Direction = MakeVector3(0.5f, 1.0f, -0.1f);
dirLight->SetIntensity(1.0f);
dirLight->IsFollowingViewport = true;
}
virtual void OnUpdate() override
{
static int frameCount = 0;
// we determine current tile by frames passed. Total number of frames should be texturesPerRow^2
auto& cam = Rendering::GetViewport()->GetCamera<FrustrumCamera>();
cam.SetProjectionForTile(frameCount % texturesPerRow, frameCount / texturesPerRow, texturesPerRow, imageSize);
if (frameCount != 0) // avoid submitting empty texture, as on zero frame there is no image rendered
{
auto texture = Rendering::GetViewport()->GetRenderTexture();
textures.push_back(texture->GetRawTextureData());
}
if (frameCount == texturesPerRow * texturesPerRow) // when we reach last frame, get image data and convert it to png format
{
auto result = ImageManager::CombineImages(textures, texturesPerRow);
auto png = ImageConverter::ConvertImagePNG(result);
File file("Resources/scene.png", File::WRITE | File::BINARY);
file.WriteBytes(png.data(), png.size());
this->CloseApplication();
}
frameCount++;
}
virtual void OnDestroy() override { }
};
}
int main()
{
MxEngine::LaunchFromSourceDirectory();
OfflineRendererSample::OfflineRendererApplication app;
app.Run();
return 0;
} | 42.771739 | 135 | 0.625159 | [
"render"
] |
dba8936ee9646c2627fdcd472a9abc0e30492851 | 528 | cpp | C++ | laboratorio-de-programacao/Turma 2021.1/classroomA.cpp | gustavo-mendel/my-college-projects | ccc1285e1a6863312e275f973e728de231a9458a | [
"MIT"
] | 3 | 2021-08-18T01:59:50.000Z | 2021-08-28T00:19:07.000Z | laboratorio-de-programacao/Turma 2021.1/classroomA.cpp | gustavo-mendel/my-college-projects | ccc1285e1a6863312e275f973e728de231a9458a | [
"MIT"
] | 4 | 2021-03-09T18:39:47.000Z | 2021-03-26T00:01:56.000Z | laboratorio-de-programacao/Turma 2021.1/classroomA.cpp | gustavo-mendel/my-college-projects | ccc1285e1a6863312e275f973e728de231a9458a | [
"MIT"
] | 1 | 2022-03-20T14:54:09.000Z | 2022-03-20T14:54:09.000Z | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n, a;
cin >> n;
vector<int> vet;
int joias = 0;
for (int i=0; i<n; i++) {
cin >> a;
if (a == 0 or a == 7 or a == 11 or a == 14 or a == 17 or a == 19) {
joias++;
vet.push_back(a);
}
}
if (joias == 6) {
cout << "Vingadores Avante\n";
}
else if (joias > 0 and joias < 6) {
for (int i=0; i<vet.size(); i++) {
cout << vet.at(i) << " ";
} puts("");
cout << "Vingadores Atencao\n";
}
else {
cout << "Pizza\n";
}
} | 14.27027 | 69 | 0.492424 | [
"vector"
] |
dbad9576c129cc3e1c178cfbd2af66abffebaf42 | 6,032 | hpp | C++ | cvaux/cvaux.hpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | cvaux/cvaux.hpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | cvaux/cvaux.hpp | hoozh/emcv | e61b1d5ad16c255f0306d0e9feb8f32e3a92d97f | [
"BSD-3-Clause"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License For Embedded Computer Vision Library
//
// Copyright (c) 2008, EMCV Project,
// Copyright (c) 2000-2007, Intel Corporation,
// All rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * 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 copyright holders nor the names of their 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.
//
// Contributors:
// * Shiqi Yu (Shenzhen Institute of Advanced Technology, Chinese Academy of Sciences)
#ifndef __CVAUX_HPP__
#define __CVAUX_HPP__
#ifdef __cplusplus
/****************************************************************************************\
* Image class *
\****************************************************************************************/
class CV_EXPORTS CvCamShiftTracker
{
public:
CvCamShiftTracker();
virtual ~CvCamShiftTracker();
/**** Characteristics of the object that are calculated by track_object method *****/
float get_orientation() const // orientation of the object in degrees
{ return m_box.angle; }
float get_length() const // the larger linear size of the object
{ return m_box.size.height; }
float get_width() const // the smaller linear size of the object
{ return m_box.size.width; }
CvPoint2D32f get_center() const // center of the object
{ return m_box.center; }
CvRect get_window() const // bounding rectangle for the object
{ return m_comp.rect; }
/*********************** Tracking parameters ************************/
int get_threshold() const // thresholding value that applied to back project
{ return m_threshold; }
int get_hist_dims( int* dims = 0 ) const // returns number of histogram dimensions and sets
{ return m_hist ? cvGetDims( m_hist->bins, dims ) : 0; }
int get_min_ch_val( int channel ) const // get the minimum allowed value of the specified channel
{ return m_min_ch_val[channel]; }
int get_max_ch_val( int channel ) const // get the maximum allowed value of the specified channel
{ return m_max_ch_val[channel]; }
// set initial object rectangle (must be called before initial calculation of the histogram)
bool set_window( CvRect window)
{ m_comp.rect = window; return true; }
bool set_threshold( int threshold ) // threshold applied to the histogram bins
{ m_threshold = threshold; return true; }
bool set_hist_bin_range( int dim, int min_val, int max_val );
bool set_hist_dims( int c_dims, int* dims );// set the histogram parameters
bool set_min_ch_val( int channel, int val ) // set the minimum allowed value of the specified channel
{ m_min_ch_val[channel] = val; return true; }
bool set_max_ch_val( int channel, int val ) // set the maximum allowed value of the specified channel
{ m_max_ch_val[channel] = val; return true; }
/************************ The processing methods *********************************/
// update object position
virtual bool track_object( const IplImage* cur_frame );
// update object histogram
virtual bool update_histogram( const IplImage* cur_frame );
// reset histogram
virtual void reset_histogram();
/************************ Retrieving internal data *******************************/
// get back project image
virtual IplImage* get_back_project()
{ return m_back_project; }
#ifndef _TMS320C6X
float query( int* bin ) const
{ return m_hist ? cvQueryHistValue_nD( m_hist, bin ) : 0.f; }
#endif
protected:
// internal method for color conversion: fills m_color_planes group
virtual void color_transform( const IplImage* img );
CvHistogram* m_hist;
CvBox2D m_box;
CvConnectedComp m_comp;
float m_hist_ranges_data[CV_MAX_DIM][2];
float* m_hist_ranges[CV_MAX_DIM];
int m_min_ch_val[CV_MAX_DIM];
int m_max_ch_val[CV_MAX_DIM];
int m_threshold;
IplImage* m_color_planes[CV_MAX_DIM];
IplImage* m_back_project;
IplImage* m_temp;
IplImage* m_mask;
};
#endif /* __cplusplus */
#endif /* __CVAUX_HPP__ */
/* End of file. */
| 40.483221 | 108 | 0.645391 | [
"object"
] |
dbb324bb2559b0d368865764c5f9c1be6ff5c58a | 11,048 | cpp | C++ | src/Scaleform.cpp | clayne/moreHUDSE | 7481da354c9a2100235892c96787b96d09049b63 | [
"MIT"
] | null | null | null | src/Scaleform.cpp | clayne/moreHUDSE | 7481da354c9a2100235892c96787b96d09049b63 | [
"MIT"
] | null | null | null | src/Scaleform.cpp | clayne/moreHUDSE | 7481da354c9a2100235892c96787b96d09049b63 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "Scaleform.h"
#include "AHZScaleform.h"
#include "SKSE/API.h"
#include "AHZPapyrusMoreHud.h"
#include "HashUtil.h"
namespace Scaleform
{
class SKSEScaleform_InstallHooks : public RE::GFxFunctionHandler
{
public:
void Call([[maybe_unused]] Params& a_params) override
{
}
};
class SKSEScaleform_GetTargetObjectData : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessTargetObject(ref, a_params);
}
};
class SKSEScaleform_GetPlayerData : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
CAHZScaleform::ProcessPlayerData(a_params);
}
};
class SKSEScaleform_GetIsPlayerInCombat : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
a_params.retVal->SetBoolean(CAHZPlayerInfo::GetIsInCombat());
}
};
class SKSEScaleform_GetTargetEffects : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessTargetEffects(ref, a_params);
}
};
class SKSEScaleform_GetIsBookAndWasRead : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
// If the target is not valid or it can't be picked up by the player
if (!ref.isValid) {
a_params.retVal->SetBoolean(false);
return;
}
a_params.retVal->SetBoolean(ref.bookRead);
}
};
class SKSEScaleform_GetArmorWeightClassString : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessArmorClass(ref, a_params);
}
};
class SKSEScaleform_GetValueToWeightString : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessValueToWeight(ref, a_params);
}
};
class SKSEScaleform_GetTargetWarmthRating : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
a_params.retVal->SetNumber(ref.armorWarmthRating);
}
};
class SKSEScaleform_AHZLog : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
assert(a_params.argCount);
logger::trace("{}", a_params.args[0].GetString());
}
};
class SKSEScaleform_GetBookSkillString : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessBookSkill(ref, a_params);
}
};
class SKSEScaleform_GetIsValidTarget : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
CAHZScaleform::ProcessValidTarget(ref, a_params);
}
};
class SKSEScaleform_GetEnemyInformation : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
CAHZScaleform::ProcessEnemyInformation(a_params);
}
};
class SKSEScaleform_IsAKnownEnchantedItem : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
const auto ref = CAHZTarget::Singleton().GetTarget();
// If the target is not valid or it can't be picked up by the player
if (!ref.isValid) {
a_params.retVal->SetNumber(0);
return;
}
a_params.retVal->SetNumber(static_cast<uint32_t>(ref.enchantmentType));
}
};
class SKSEScaleform_IsTargetInFormList : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
assert(a_params.args);
assert(a_params.argCount);
if (a_params.args[0].GetType() == RE::GFxValue::ValueType::kString) {
const auto ref = CAHZTarget::Singleton().GetTarget();
// If the target is not valid then say false
if (!ref.isValid) {
a_params.retVal->SetBoolean(false);
return;
}
auto keyName = string(a_params.args[0].GetString());
a_params.retVal->SetBoolean(PapyrusMoreHud::HasForm(keyName, ref.formId));
return;
}
a_params.retVal->SetBoolean(false);
return;
}
};
class SKSEScaleform_GetFormIcons : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
a_params.movie->CreateArray(a_params.retVal);
const auto ref = CAHZTarget::Singleton().GetTarget();
// If the target is not valid then return an empty array
if (!ref.isValid) {
a_params.retVal->SetArraySize(0);
return;
}
auto formId = ref.formId;
auto customIcons = PapyrusMoreHud::GetFormIcons(formId);
if (!customIcons.empty()) {
RE::GFxValue entry;
a_params.retVal->SetArraySize(static_cast<uint32_t>(customIcons.size()));
auto idx = 0;
for (auto& ci : customIcons) {
entry.SetString(ci);
a_params.retVal->SetElement(idx++, entry);
}
} else {
a_params.retVal->SetArraySize(0);
}
}
};
class SKSEScaleform_IsTargetInIconList : public RE::GFxFunctionHandler
{
public:
void Call(Params& a_params) override
{
assert(a_params.args);
assert(a_params.argCount);
if (a_params.args[0].GetType() == RE::GFxValue::ValueType::kString) {
auto iconName = string(a_params.args[0].GetString());
const auto ref = CAHZTarget::Singleton().GetTarget();
// If the target is not valid then say false
if (!ref.isValid) {
a_params.retVal->SetBoolean(false);
return;
}
auto name = ref.name;
// Can't get the name for the crc
if (name.empty()) {
a_params.retVal->SetBoolean(false);
return;
}
auto hash = static_cast<int32_t>(SKSE::HashUtil::CRC32(name.c_str(), ref.formId & 0x00FFFFFF));
auto resultIconName = string(PapyrusMoreHud::GetIconName(hash));
if (!resultIconName.length()) {
a_params.retVal->SetBoolean(false);
return;
}
a_params.retVal->SetBoolean(resultIconName == iconName);
return;
}
a_params.retVal->SetBoolean(false);
}
};
typedef std::map<const std::type_info*, RE::GFxFunctionHandler*> FunctionHandlerCache;
static FunctionHandlerCache g_functionHandlerCache;
template <typename T>
void RegisterFunction(RE::GFxValue* dst, RE::GFxMovieView* movie, const char* name)
{
// either allocate the object or retrieve an existing instance from the cache
RE::GFxFunctionHandler* fn = nullptr;
// check the cache
FunctionHandlerCache::iterator iter = g_functionHandlerCache.find(&typeid(T));
if (iter != g_functionHandlerCache.end())
fn = iter->second;
if (!fn) {
// not found, allocate a new one
fn = new T;
// add it to the cache
// cache now owns the object as far as refcounting goes
g_functionHandlerCache[&typeid(T)] = fn;
}
// create the function object
RE::GFxValue fnValue;
movie->CreateFunction(&fnValue, fn);
// register it
dst->SetMember(name, fnValue);
}
auto RegisterScaleformFunctions(RE::GFxMovieView* a_view, RE::GFxValue* a_root) -> bool
{
RegisterFunction<SKSEScaleform_InstallHooks>(a_root, a_view, "InstallHooks");
RegisterFunction<SKSEScaleform_GetTargetObjectData>(a_root, a_view, "GetTargetObjectData");
RegisterFunction<SKSEScaleform_GetPlayerData>(a_root, a_view, "GetPlayerData");
RegisterFunction<SKSEScaleform_GetIsValidTarget>(a_root, a_view, "GetIsValidTarget");
RegisterFunction<SKSEScaleform_GetIsPlayerInCombat>(a_root, a_view, "GetIsPlayerInCombat");
RegisterFunction<SKSEScaleform_GetTargetEffects>(a_root, a_view, "GetTargetEffects");
RegisterFunction<SKSEScaleform_GetIsBookAndWasRead>(a_root, a_view, "GetIsBookAndWasRead");
RegisterFunction<SKSEScaleform_GetArmorWeightClassString>(a_root, a_view, "GetArmorWeightClassString");
RegisterFunction<SKSEScaleform_GetBookSkillString>(a_root, a_view, "GetBookSkillString");
RegisterFunction<SKSEScaleform_GetValueToWeightString>(a_root, a_view, "GetValueToWeightString");
RegisterFunction<SKSEScaleform_GetTargetWarmthRating>(a_root, a_view, "GetTargetWarmthRating");
RegisterFunction<SKSEScaleform_GetEnemyInformation>(a_root, a_view, "GetEnemyInformation");
RegisterFunction<SKSEScaleform_IsAKnownEnchantedItem>(a_root, a_view, "IsAKnownEnchantedItem");
RegisterFunction<SKSEScaleform_IsTargetInFormList>(a_root, a_view, "IsTargetInFormList");
RegisterFunction<SKSEScaleform_IsTargetInIconList>(a_root, a_view, "IsTargetInIconList");
RegisterFunction<SKSEScaleform_GetFormIcons>(a_root, a_view, "GetFormIcons");
RegisterFunction<SKSEScaleform_AHZLog>(a_root, a_view, "AHZLog");
return true;
}
void RegisterCallbacks()
{
auto scaleform = SKSE::GetScaleformInterface();
scaleform->Register(RegisterScaleformFunctions, "AHZmoreHUDPlugin");
logger::info("Registered all scaleform callbacks");
}
}
| 34.962025 | 112 | 0.587075 | [
"object"
] |
dbb5b4189f6ba9681ce5f0050878091d22389fd8 | 4,825 | hpp | C++ | src/cpp/f00316_poolpagemanager.hpp | ilackarms/voxelquest | 8e79cd27f540bdba0f52d7d184c17b59cfcb0cac | [
"MIT"
] | 428 | 2016-08-03T21:09:24.000Z | 2022-02-02T05:43:12.000Z | src/cpp/f00316_poolpagemanager.hpp | ctsrc/vqisosmall | 0e1dcd52999c7a797b5087ae5e04e25b41e619a3 | [
"MIT"
] | 9 | 2016-08-04T05:04:43.000Z | 2016-08-06T22:50:22.000Z | src/cpp/f00316_poolpagemanager.hpp | ctsrc/vqisosmall | 0e1dcd52999c7a797b5087ae5e04e25b41e619a3 | [
"MIT"
] | 56 | 2016-08-04T23:24:32.000Z | 2020-09-27T22:44:23.000Z |
class PoolPageManager {
public:
PoolPageManager() {
}
// int poolItemsCreated;
// bool isCPU;
// list<int> pagePoolIds;
// vector<intPair> orderedIds;
// vector<PooledResource *> pagePoolItems;
// Singleton* singleton;
// GameWorld* gw;
// bool isEntity;
// int sizeX;
// int sizeY;
// void init(
// Singleton* _singleton,
// bool _isEntity,
// bool _isCPU,
// int _sizeX,
// int _sizeY
// ) {
// isEntity = _isEntity;
// poolItemsCreated = 0;
// isCPU = _isCPU;
// singleton = _singleton;
// gw = singleton->gw;
// sizeX = _sizeX;
// sizeY = _sizeY;
// }
// float getMaxMem() {
// if (isCPU) {
// return MAX_CPU_MEM;
// }
// else {
// if (isEntity) {
// // TODO: FIX THIS
// return MAX_GPU_MEM*20.0f;
// }
// else {
// return MAX_GPU_MEM;
// }
// }
// }
// float getTotMemUsed() {
// if (isCPU) {
// return TOT_CPU_MEM_USAGE;
// }
// else {
// return TOT_GPU_MEM_USAGE;
// }
// }
// void reorderIds()
// {
// int i;
// int j;
// int oidSize = orderedIds.size();
// int oidSizeM1 = oidSize - 1;
// intPair id0;
// intPair id1;
// int tempId;
// int tot0;
// int tot1;
// bool doSwap;
// GamePage *gp0;
// GamePage *gp1;
// for (i = 0; i < oidSizeM1; i++)
// {
// for (j = i + 1; j < oidSize; j++ )
// {
// id0 = orderedIds[i];
// id1 = orderedIds[j];
// if ( pairIsNeg(id0) || pairIsNeg(id1))
// {
// }
// else
// {
// gp0 = gw->getPageAtIndex(id0.v1);
// gp1 = gw->getPageAtIndex(id1.v1);
// if (gp0 == NULL || gp1 == NULL)
// {
// }
// else
// {
// tot0 = gp0->offsetInPages.getFZ();
// tot1 = gp1->offsetInPages.getFZ();
// if (tot0 == tot1)
// {
// tot0 = gp0->offsetInPages.getFY();
// tot1 = gp1->offsetInPages.getFY();
// if (tot0 == tot1)
// {
// tot1 = gp1->offsetInPages.getFX();
// tot0 = gp0->offsetInPages.getFX();
// if (tot0 == tot1)
// {
// doSwap = false;
// }
// else
// {
// doSwap = tot0 > tot1;
// }
// }
// else
// {
// doSwap = tot0 > tot1;
// }
// }
// else
// {
// doSwap = tot0 > tot1;
// }
// if (doSwap)
// {
// orderedIds[i] = id1;
// orderedIds[j] = id0;
// }
// }
// }
// }
// }
// }
// int findFurthestPageId()
// {
// int longestInd = 0;
// int i;
// float longestDis = 0.0f;
// float testDis;
// FIVector4 tempVec;
// GamePage *gp;
// GamePage *bestGP = NULL;
// for (i = 0; i < pagePoolItems.size(); i++)
// {
// gp = gw->getPageAtIndex(pagePoolItems[i]->usedById.v1);
// if (gp == NULL)
// {
// }
// else
// {
// tempVec.copyFrom(&(gw->camPagePos));
// gp->offsetInPages.wrapDistance(&tempVec, singleton->worldSizeInPages.getIX());
// testDis = gp->offsetInPages.distance( &(tempVec) );
// if (testDis > longestDis)
// {
// longestDis = testDis;
// longestInd = i;
// bestGP = gp;
// }
// }
// }
// return longestInd;
// }
// int requestPoolId(int blockId, int pageId)
// {
// int toFreeId;
// intPair usedById;
// int i;
// if (getTotMemUsed() < getMaxMem())
// {
// pagePoolItems.push_back( new PooledResource() );
// pagePoolItems.back()->init(singleton, isCPU, sizeX, sizeY);
// toFreeId = poolItemsCreated;
// pagePoolIds.push_front(toFreeId);
// orderedIds.push_back(intPair());
// orderedIds.back().v0 = blockId;
// orderedIds.back().v1 = pageId;
// poolItemsCreated++;
// }
// else
// {
// toFreeId = findFurthestPageId();
// usedById = pagePoolItems[toFreeId]->usedById;
// GamePage *consumingPage;
// if ( pairIsNeg(usedById) )
// {
// // this pooledItem is already free
// }
// else
// {
// // free this pooledItem from the page that is consuming it and give it to the requesting page
// consumingPage = gw->getPageAtIndex(usedById.v1);
// if (consumingPage == NULL)
// {
// // page was deleted already
// }
// else
// {
// consumingPage->unbindGPUResources();
// }
// }
// for (i = 0; i < orderedIds.size(); i++)
// {
// if ( pairIsEqual(orderedIds[i], usedById) )
// {
// orderedIds[i].v0 = blockId;
// orderedIds[i].v1 = pageId;
// break;
// }
// }
// pagePoolIds.remove(toFreeId);
// pagePoolIds.push_front(toFreeId);
// }
// pagePoolItems[toFreeId]->usedById.v0 = blockId;
// pagePoolItems[toFreeId]->usedById.v1 = pageId;
// //reorderIds();
// return toFreeId;
// }
};
| 16.580756 | 100 | 0.498446 | [
"vector"
] |
dbb635524885d35ffb3359c1e30b2442a317a1ef | 2,200 | hpp | C++ | include/bliss.hpp | yunseo-h68/bliss | 1eaafd7bbc117f3b39f0900956db7ab7b085d941 | [
"MIT"
] | 1 | 2020-07-27T06:20:32.000Z | 2020-07-27T06:20:32.000Z | include/bliss.hpp | yunseo-h68/bliss | 1eaafd7bbc117f3b39f0900956db7ab7b085d941 | [
"MIT"
] | null | null | null | include/bliss.hpp | yunseo-h68/bliss | 1eaafd7bbc117f3b39f0900956db7ab7b085d941 | [
"MIT"
] | null | null | null | #ifndef BLISS_H
#define BLISS_H
#include <string>
#include <vector>
class BlissExec {
public:
BlissExec();
~BlissExec();
std::string name();
std::string description();
virtual BlissExec* set_name(std::string name);
virtual BlissExec* set_description(std::string description);
virtual void Exec(){}
private:
std::string name_;
std::string description_;
};
class BlissOption : public BlissExec {
public:
BlissOption();
BlissOption(std::string name);
~BlissOption();
std::string name_short();
virtual BlissOption* set_name(std::string name);
BlissOption* set_name_short(std::string name_short);
virtual BlissOption* set_description(std::string description);
private:
std::string name_short_;
};
class BlissCommand : public BlissExec {
public:
BlissCommand();
BlissCommand(std::string name);
~BlissCommand();
std::string usage();
int options_count();
virtual BlissCommand* set_name(std::string name);
virtual BlissCommand* set_description(std::string description);
virtual BlissCommand* set_usage(std::string usage);
BlissOption* GetOptionByIndex(int index);
BlissOption* GetOptionByName(std::string name);
BlissOption* GetOptionByNameShort(std::string name_short);
virtual BlissCommand* AddOption(BlissOption* option);
virtual BlissCommand* DeleteOptionByName(std::string name);
private:
std::string usage_;
std::vector<BlissOption*> options_;
};
class BlissApp : public BlissCommand {
public:
BlissApp();
BlissApp(std::string name);
~BlissApp();
int subcommands_count();
virtual BlissApp* set_name(std::string name);
virtual BlissApp* set_description(std::string description);
virtual BlissApp* set_usage(std::string usage);
virtual BlissApp* AddOption(BlissOption* option);
virtual BlissApp* DeleteOptionByName(std::string name);
BlissApp* AddSubcommand(BlissCommand* subcommand);
BlissApp* DeleteSubcommandByName(std::string name);
BlissCommand* GetSubcommandByIndex(int index);
BlissCommand* GetSubcommandByName(std::string name);
void PrintHelp();
virtual void Exec();
private:
std::vector<BlissCommand*> subcommands_;
};
int bliss_run(BlissApp* app, int argc, char* argv[]);
#endif
| 26.829268 | 65 | 0.745909 | [
"vector"
] |
dbb75e7e7e69999962db5dadb4be8786ad37ca33 | 6,406 | cpp | C++ | SCA/src/ClippedGaussianSampling.cpp | JooseRajamaeki/TVCG18 | ddc73f422c267b1c38ede3ba20046efff46a6d74 | [
"MIT"
] | 6 | 2019-09-23T09:00:32.000Z | 2022-01-09T11:10:49.000Z | SCA/src/ClippedGaussianSampling.cpp | JooseRajamaeki/TVCG18 | ddc73f422c267b1c38ede3ba20046efff46a6d74 | [
"MIT"
] | null | null | null | SCA/src/ClippedGaussianSampling.cpp | JooseRajamaeki/TVCG18 | ddc73f422c267b1c38ede3ba20046efff46a6d74 | [
"MIT"
] | null | null | null | /*
Part of Aalto University Game Tools. See LICENSE.txt for licensing info.
*/
#include "ClippedGaussianSampling.h"
#include <math.h>
#include <vector>
#include "Mathutils.h"
#include <algorithm>
#include <assert.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace AaltoGames
{
class ClippedGaussianSampler{
public:
//Contructor, sets the default parameters
ClippedGaussianSampler();
//Sample a Gaussian random number between minValue and maxValue with the given mean and stdev.
float sample(float mean, float stdev, float minValue, float maxValue );
private:
//Lookup table for the standard normal distribution cdf values.
std::vector<float> standardCdfTable;
//Lookup table for the uniform distribution to inverse standardNormal distribution
std::vector<float> inverseStandardCdfTable;
//The interval for the computation of the inverse cdf lookup table values
float deltaInverse;
//Lower limit for standardCdfTable
float lowLim;
//The interval for the computation of the cdf lookup table values
float delta;
//The upper limit for standardCdfTable
float upLim;
//standardCdfTable has the values from N(X < lowLim) to N(X < upLim). The values are computed with the interval dX = delta.
//This function computes the standard normal distribution cdf values to the table standardCdfTable
void computeCdfTable(void);
//This function computes the inverse standard normal distribution cdf values to the table standardCdfTable
void computeinverseCdfTable(void);
//If x ~ N(mean,stdDev) the function returns y ~ N(0,1)
float nonstandardToStandard(float x,float mean, float stdDev);
//If x ~ N(0,1) the function returns y ~ N(mean,stdDev)
float standardToNonstandard(float x,float mean, float stdDev);
};
//This function computes the standard normal distribution cdf values to the table standardCdfTable
//standardCdfTable has the values from N(X < lowLim) to N(X < upLim). The values are computed with the interval dX = delta.
void ClippedGaussianSampler::computeCdfTable(void){
standardCdfTable.clear();
inverseStandardCdfTable.clear();
float temp = 0.0;
float uniTemp =0.0;
float scalingConst = 1.0f/sqrtf(2.0f*(float)M_PI);
for (float position = lowLim; position < upLim; position = position + delta){
temp += delta*scalingConst*expf(-0.5f*position*position);
while(uniTemp < temp){
inverseStandardCdfTable.push_back(position-delta);
uniTemp += deltaInverse;
}
standardCdfTable.push_back(temp);
}
}
//Contructor, sets the default parameters
ClippedGaussianSampler::ClippedGaussianSampler(){
//Lower limit for standardCdfTable
lowLim = -6.0;
//The upper limit for standardCdfTable
upLim = 6.0;
//The interval for the computation of the values
delta = 1.0/256.0;
deltaInverse = 1.0/2048.0;
standardCdfTable.clear();
inverseStandardCdfTable.clear();
}
//If x ~ N(mean,stdDev) the function returns y ~ N(0,1)
float ClippedGaussianSampler::nonstandardToStandard(float x,float mean, float stdDev){
return (x-mean)/stdDev;
}
//If x ~ N(0,1) the function returns y ~ N(mean,stdDev)
float ClippedGaussianSampler::standardToNonstandard(float x,float mean, float stdDev){
return (mean + x*stdDev);
}
//Clamp x between lower limit lowLim and upper limit upLim.
float clamp(float x, float lowLim, float upLim){
assert(lowLim <= upLim);
return std::max(lowLim,std::min(upLim,x));
}
//Sample a Gaussian random number between minValue and maxValue with the given mean and stdev. This is done using cdf inverting.
float ClippedGaussianSampler::sample(float mean, float stdev, float minValue, float maxValue ){
if (stdev==0)
return mean;
//If the lookup table is empty, populate it.
if (standardCdfTable.empty()){
computeCdfTable();
}
//Map the values to be used with standard normal distribution
float minValStd = nonstandardToStandard(minValue,mean,stdev);
float maxValStd = nonstandardToStandard(maxValue,mean,stdev);
//Find the indices of the places corresponding to the minimum and maximum allowed value
int minPlace = (int)ceil( (minValStd - lowLim)/delta );
int maxPlace = (int)floor( (maxValStd - lowLim)/delta );
//Find the standard normal distribution cdf values corresponding to the minimum and maximum allowed value
minValStd = standardCdfTable[clipMinMaxi(minPlace,0,(int)(standardCdfTable.size()-1))];
maxValStd = standardCdfTable[clipMinMaxi(maxPlace,0,(int)(standardCdfTable.size()-1))];
float transRand, position;
//Sample a uniformly distributed random number from interval [0,1]
transRand = ((float) rand() / (RAND_MAX));
//Scale the random number appropriately
transRand = (maxValStd - minValStd)*transRand + minValStd;
int invCdfIndex = (int)(transRand/deltaInverse);
invCdfIndex=clipMinMaxi(invCdfIndex,0,inverseStandardCdfTable.size()-1); //to avoid index out of bounds errors on the next line
position = inverseStandardCdfTable[invCdfIndex];
//Scale position properly to obtain a truncated Gaussian random number from the originally specified normal distribution
transRand = standardToNonstandard(position,mean,stdev);
////Position will correspond to the sampled value in standard normal distribution
//float position = lowLim;
////Index for the cdf lookup table
//int temp = 0;
////The table size
//int tabSize = standardCdfTable.size();
////Find the standard normal distribution cdf value that is greater than the sampled and scaled uniformly distributed random number transRand.
//while (standardCdfTable[temp] < transRand && temp < tabSize){
// temp++;
//};
////Transform position to a truncated gaussian random number
//position = position + temp*delta;
//Test that the number fullfils the requirements
//AALTO_ASSERT1(transRand >= minValue);
//AALTO_ASSERT1(transRand <= maxValue);
//Clamp just in case of some floating point imprecision or the bounds being outside the tabled range
transRand = clipMinMaxf(transRand,minValue,maxValue);
//Return the value
return transRand;
}
static ClippedGaussianSampler s_sampler;
float randGaussianClipped( float mean, float stdev, float minValue, float maxValue )
{
return s_sampler.sample(mean,stdev,minValue,maxValue);
}
float randGaussian( float mean, float stdev)
{
return s_sampler.sample(mean,stdev,mean-stdev*10.0f,mean+stdev*10.0f);
}
} | 34.256684 | 144 | 0.747424 | [
"vector",
"transform"
] |
dbb8e303582f7e713e637d7c00da4321f3257a42 | 19,626 | cpp | C++ | ZeroEngine/Core/ModulePhysics.cpp | Germanins6/Zero-Engine | db0dacdf2951700c94b41d32db3bac99b04a110a | [
"MIT"
] | null | null | null | ZeroEngine/Core/ModulePhysics.cpp | Germanins6/Zero-Engine | db0dacdf2951700c94b41d32db3bac99b04a110a | [
"MIT"
] | 7 | 2020-10-05T21:56:42.000Z | 2020-12-30T18:22:07.000Z | ZeroEngine/Core/ModulePhysics.cpp | Germanins6/Zero-Engine | db0dacdf2951700c94b41d32db3bac99b04a110a | [
"MIT"
] | 1 | 2021-01-10T20:46:28.000Z | 2021-01-10T20:46:28.000Z | #include "ModulePhysics.h"
#include "Application.h"
#include "PrimitivesGL.h"
#include "p2Defs.h"
#ifndef _DEBUG
# pragma comment(lib, "Core/physx/libx86/_release/PhysX_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXCommon_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXExtensions_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXFoundation_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXPvdSDK_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXCharacterKinematic_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/SceneQuery_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXCooking_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXVehicle_static_32.lib")
# else
# pragma comment(lib, "Core/physx/libx86/_debug/PhysX_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXCommon_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXExtensions_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXFoundation_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXPvdSDK_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXCharacterKinematic_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/SceneQuery_static_32.lib")
# pragma comment(lib, "Core/physx/libx86/_debug/PhysXCooking_32.lib")
# pragma comment(lib, "Core/physx/libx86/_release/PhysXVehicle_static_32.lib")
# endif // _DEBUG
using namespace physx;
#define MAX_NUM_MESH_VEC3S 1024
#define MAX_NUM_ACTOR_SHAPES 128
static PxVec3 gVertexBuffer[MAX_NUM_MESH_VEC3S];
ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled) {
mFoundation = nullptr;
mPhysics = nullptr;
mPvd = nullptr;
mCooking = nullptr;
mMaterial = nullptr;
mScene = nullptr;
mDispatcher = nullptr;
gravity = float3(0.0f,-9.81f, 0.0f);
}
ModulePhysics::~ModulePhysics() {
}
bool ModulePhysics::Init() {
//Initialize PhysX mFoundation
#pragma region Foundation_Initialize
static PxDefaultErrorCallback mErrorCallback;
mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, mAllocator, mErrorCallback);
if (!mFoundation)
LOG("PxCreateFoundation failed!")
else
LOG("PxCreateFoundation Created: Succesfully inited PhysX");
#pragma endregion Foundation_Initialize
//Initialize physics
#pragma region Physics_Initialize
bool recordMemoryAllocations = true;
mPvd = PxCreatePvd(*mFoundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate("hello", 5425, 10);
mPvd->connect(*transport, PxPvdInstrumentationFlag::eALL);
mPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *mFoundation, PxTolerancesScale(), recordMemoryAllocations, mPvd);
if (!mPhysics)
LOG("PxCreatePhysics failed!")
else
LOG("PxCreatePhysics Sucessfull");
#pragma endregion Physics_Initialize
//Initialize Cooking
#pragma region Cooking_Initialize
mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, PxCookingParams(PxTolerancesScale()));
if (!mCooking)
LOG("PxCreateCooking failed!")
else
LOG("PxCooking created Succesfully");
#pragma endregion Cooking_Initialize
//Initialize Extensions
#pragma region Extensions_Initialize
if (!PxInitExtensions(*mPhysics, mPvd))
LOG("PxInitExtensions failed!")
else
LOG("PxInitextension Succesfull");
#pragma endregion Extensions_Initialize
//Initialize Scene
#pragma region Scene_Initialize
PxSceneDesc sceneDesc(mPhysics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
mDispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = mDispatcher;
sceneDesc.filterShader = PxDefaultSimulationFilterShader;
mScene = mPhysics->createScene(sceneDesc);
#pragma endregion Scene_Initialize
//Initialize SceneClient
#pragma region SceneClient_Initialize
PxPvdSceneClient* pvdClient = mScene->getScenePvdClient();
if (pvdClient)
{
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true);
}
#pragma endregion SceneClient_Initialize
//Initialize Material with default values staticFric 0.5 DynamicFric 0.5 restitution 0.1
mMaterial = CreateMaterial();
//PxRigidStatic* groundPlane = PxCreatePlane(*mPhysics, PxPlane(0, 1, 0, 0), *mMaterial);
//mScene->addActor(*groundPlane);
//Init vehicle after foundation and physics
PxInitVehicleSDK(*mPhysics);
return true;
}
update_status ModulePhysics::Update(float gameTimestep) {
if (App->timeManager->started)
SceneSimulation(gameTimestep);
//TODO: REMOVE OR REPLACE
mScene->setGravity(PxVec3(gravity.x, gravity.y, gravity.z));
RenderGeometry();
return update_status::UPDATE_CONTINUE;
}
void ModulePhysics::SceneSimulation(float gameTimestep, bool fetchResults) {
mScene->simulate(gameTimestep);
mScene->fetchResults(fetchResults);
}
bool ModulePhysics::CleanUp() {
if (App->vehicle->gVehicle4W != nullptr) {
App->vehicle->gVehicle4W->getRigidDynamicActor()->release();
App->vehicle->gVehicle4W->free();
}
PX_RELEASE(App->vehicle->gBatchQuery);
App->vehicle->gVehicleSceneQueryData->free(mAllocator);
PX_RELEASE(App->vehicle->gFrictionPairs);
PxCloseVehicleSDK(); //->Close vehicle sdk before close physics and foundation
PX_RELEASE(mScene);
PX_RELEASE(mMaterial);
PX_RELEASE(mPhysics);
if (mPvd)
{
PxPvdTransport* transport = mPvd->getTransport();
mPvd->release(); mPvd = NULL;
PX_RELEASE(transport);
}
PX_RELEASE(mCooking);
PxCloseExtensions(); // Needed to close extensions we inited before
PX_RELEASE(mDispatcher);
//Remember to release the last
PX_RELEASE(mFoundation);
return true;
}
void ModulePhysics::RenderGeometry() {
PxGetPhysics().getScenes(&mScene, 1);
PxU32 nbActors = mScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC);
if (nbActors)
{
std::vector<PxRigidActor*> actors(nbActors);
mScene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors);
renderActors(&actors[0], static_cast<PxU32>(actors.size()), false);
}
}
void ModulePhysics::renderActors(PxRigidActor** actors, const PxU32 numActors, bool shadows)
{
const PxVec3 color = PxVec3(0.0f, 0.75f, 0.0f);
PxShape* shapes[MAX_NUM_ACTOR_SHAPES];
for (PxU32 i = 0; i < numActors; i++)
{
const PxU32 nbShapes = actors[i]->getNbShapes();
PX_ASSERT(nbShapes <= MAX_NUM_ACTOR_SHAPES);
actors[i]->getShapes(shapes, nbShapes);
const bool sleeping = actors[i]->is<PxRigidDynamic>() ? actors[i]->is<PxRigidDynamic>()->isSleeping() : false;
for (PxU32 j = 0; j < nbShapes; j++)
{
const PxMat44 shapePose(PxShapeExt::getGlobalPose(*shapes[j], *actors[i]));
const PxGeometryHolder h = shapes[j]->getGeometry();
if (shapes[j]->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render object
glPushMatrix();
glMultMatrixf(&shapePose.column0.x);
if (sleeping)
{
const PxVec3 darkColor = color * 0.25f;
glColor4f(darkColor.x, darkColor.y, darkColor.z, 1.0f);
}
else
glColor4f(color.x, color.y, color.z, 1.0f);
renderGeometryHolder(h);
glPopMatrix();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
}
void ModulePhysics::renderGeometryHolder(const PxGeometryHolder& h) {
renderGeometry(h.any());
};
void ModulePhysics::renderGeometry(const PxGeometry& geom)
{
switch (geom.getType())
{
case PxGeometryType::eCONVEXMESH:
{
const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom);
//Compute triangles for each polygon.
const PxVec3& scale = convexGeom.scale.scale;
PxConvexMesh* mesh = convexGeom.convexMesh;
const PxU32 nbPolys = mesh->getNbPolygons();
const PxU8* polygons = mesh->getIndexBuffer();
const PxVec3* verts = mesh->getVertices();
PxU32 nbVerts = mesh->getNbVertices();
PX_UNUSED(nbVerts);
PxU32 numTotalTriangles = 0;
for (PxU32 i = 0; i < nbPolys; i++)
{
PxHullPolygon data;
mesh->getPolygonData(i, data);
const PxU32 nbTris = PxU32(data.mNbVerts - 2);
const PxU8 vref0 = polygons[data.mIndexBase + 0];
PX_ASSERT(vref0 < nbVerts);
for (PxU32 j = 0; j < nbTris; j++)
{
const PxU32 vref1 = polygons[data.mIndexBase + 0 + j + 1];
const PxU32 vref2 = polygons[data.mIndexBase + 0 + j + 2];
//generate face normal:
PxVec3 e0 = verts[vref1] - verts[vref0];
PxVec3 e1 = verts[vref2] - verts[vref0];
PX_ASSERT(vref1 < nbVerts);
PX_ASSERT(vref2 < nbVerts);
PxVec3 fnormal = e0.cross(e1);
fnormal.normalize();
if (numTotalTriangles * 6 < MAX_NUM_MESH_VEC3S)
{
gVertexBuffer[numTotalTriangles * 6 + 0] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 1] = verts[vref0];
gVertexBuffer[numTotalTriangles * 6 + 2] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 3] = verts[vref1];
gVertexBuffer[numTotalTriangles * 6 + 4] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 5] = verts[vref2];
numTotalTriangles++;
}
}
}
glPushMatrix();
glScalef(scale.x, scale.y, scale.z);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), gVertexBuffer);
glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), gVertexBuffer + 1);
glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3));
glPopMatrix();
}
break;
case PxGeometryType::eTRIANGLEMESH:
{
const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom);
const PxTriangleMesh& mesh = *triGeom.triangleMesh;
const PxVec3 scale = triGeom.scale.scale;
const PxU32 triangleCount = mesh.getNbTriangles();
const PxU32 has16BitIndices = mesh.getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES;
const void* indexBuffer = mesh.getTriangles();
const PxVec3* vertexBuffer = mesh.getVertices();
const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer);
const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer);
PxU32 numTotalTriangles = 0;
for (PxU32 i = 0; i < triangleCount; ++i)
{
PxVec3 triVert[3];
if (has16BitIndices)
{
triVert[0] = vertexBuffer[*shortIndices++];
triVert[1] = vertexBuffer[*shortIndices++];
triVert[2] = vertexBuffer[*shortIndices++];
}
else
{
triVert[0] = vertexBuffer[*intIndices++];
triVert[1] = vertexBuffer[*intIndices++];
triVert[2] = vertexBuffer[*intIndices++];
}
PxVec3 fnormal = (triVert[1] - triVert[0]).cross(triVert[2] - triVert[0]);
fnormal.normalize();
if (numTotalTriangles * 6 < MAX_NUM_MESH_VEC3S)
{
gVertexBuffer[numTotalTriangles * 6 + 0] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 1] = triVert[0];
gVertexBuffer[numTotalTriangles * 6 + 2] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 3] = triVert[1];
gVertexBuffer[numTotalTriangles * 6 + 4] = fnormal;
gVertexBuffer[numTotalTriangles * 6 + 5] = triVert[2];
numTotalTriangles++;
}
}
glPushMatrix();
glScalef(scale.x, scale.y, scale.z);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, 2 * 3 * sizeof(float), gVertexBuffer);
glVertexPointer(3, GL_FLOAT, 2 * 3 * sizeof(float), gVertexBuffer + 1);
glDrawArrays(GL_TRIANGLES, 0, int(numTotalTriangles * 3));
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glPopMatrix();
}
break;
case PxGeometryType::ePLANE:
break;
}
}
//--------------CREATE A NEW GEOMETRY--------------//
physx::PxRigidDynamic* ModulePhysics::CreateGeometry(GeometryType type, float3 pos, float mass, float radius, float3 size){
physx::PxRigidDynamic* geometry = nullptr;
PxTransform position = PxTransform(pos.x, pos.y, pos.z);
switch (type)
{
case GeometryType::BOX:
{
PxShape* shape = mPhysics->createShape(PxBoxGeometry(size.x, size.y, size.z), *mMaterial);
geometry = mPhysics->createRigidDynamic(position);
geometry->attachShape(*shape);
geometry->setAngularDamping(0.5f);
geometry->setLinearVelocity(PxVec3(0));
//LOG("CREATED BOX");
}
break;
case GeometryType::SPHERE:
{
PxShape* shape = mPhysics->createShape(PxSphereGeometry(radius), *mMaterial);
geometry = PxCreateDynamic(*mPhysics, position, PxSphereGeometry(radius), *mMaterial, mass);
geometry->attachShape(*shape);
geometry->setAngularDamping(0.05f);
//LOG("CREATED SPHERE");
}
break;
case GeometryType::CAPSULE:
{
PxReal halfHeight = size.y / 2;
geometry = mPhysics->createRigidDynamic(PxTransform(position));
PxShape* shape = PxRigidActorExt::createExclusiveShape(*geometry, PxCapsuleGeometry(radius, halfHeight), *mMaterial);
geometry->attachShape(*shape);
geometry->setAngularDamping(0.05f);
//LOG("CREATED CAPSULE");
}
break;
case GeometryType::NONE:
break;
}
geometry->setMass(mass);
mScene->addActor(*geometry);
return geometry;
}
//--------------DRAW THE GEOMETRY--------------//
void ModulePhysics::DrawGeometry(GeometryType type, float3 pos, float radius, float3 size){
switch (type)
{
case GeometryType::BOX:
{
glBegin(GL_QUADS);
glPushMatrix();
glNormal3f(-1.0f, 0.0f, 0.0f); //FRONT
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 0.0f);
glNormal3f(0.0f, 0.0f, -1.0f); //BOTTOM
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glNormal3f(1.0f, 0.0f, 0.0f); //BACK
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(0.0f, 1.0f, 1.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glNormal3f(0.0f, 0.0f, 1.0f); //TOP
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 1.0f, 1.0f);
glNormal3f(0.0f, 1.0f, 0.0f); //LEFT
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 1.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 1.0f);
glNormal3f(0.0f, -1.0f, 0.0f); //RIGHT
glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(1.0f, 0.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glScalef(size.x, size.y, size.z);
glTranslatef(pos.x, pos.y, pos.z);
glPopMatrix();
glEnd();
}
break;
case GeometryType::SPHERE:
{
GLfloat x, y, z, alpha, beta; // Storage for coordinates and angles
int gradation = 10;
for (alpha = 0.0; alpha < PI; alpha += PI / gradation)
{
glBegin(GL_TRIANGLE_STRIP);
glPushMatrix();
for (beta = 0.0; beta < 2.01 * PI; beta += PI / gradation)
{
x = cos(beta) * sin(alpha);
y = sin(beta) * sin(alpha);
z = cos(alpha);
glVertex3f(x, y, z);
x = cos(beta) * sin(alpha + PI / gradation);
y = sin(beta) * sin(alpha + PI / gradation);
z = cos(alpha + PI / gradation);
glVertex3f(x, y, z);
}
glTranslatef(pos.x, 0.0f, 0.0f);
glScalef(radius, radius, radius);
glPopMatrix();
glEnd();
}
}
break;
case GeometryType::CAPSULE:
{
glBegin(GL_QUAD_STRIP);
glPushMatrix();
glTranslatef(-pos.x, 0.0f, 0.0f);
//glScalef(2.0f * pos.x, radius, radius);
for (int i = 0; i < 480; i += (360 / 16)) {
float a = i * M_PI / 180; // degrees to radians
glVertex3f(2 * cos(a), 2 * sin(a), 0.0);
glVertex3f(2 * cos(a), 2 * sin(a), 4);
}
glEnd();
glPopMatrix();
glEnd();
}
break;
case GeometryType::NONE:
break;
}
}
physx::PxRigidStatic* ModulePhysics::CreateRigidStatic(float3 pos) {
PxTransform position(pos.x, pos.y, pos.z);
PxRigidStatic* staticBody = nullptr;
staticBody = mPhysics->createRigidStatic(position);
mScene->addActor(*staticBody);
return staticBody;
}
physx::PxRigidDynamic* ModulePhysics::CreateRigidDynamic(float3 pos) {
PxTransform position(pos.x, pos.y, pos.z);
PxRigidDynamic* dynamicBody = nullptr;
dynamicBody = mPhysics->createRigidDynamic(position);
mScene->addActor(*dynamicBody);
return dynamicBody;
}
physx::PxShape* ModulePhysics::CreateCollider(GeometryType colliderType, float3 size, PxMaterial* material) {
PxShape* colliderShape = nullptr;
if (material == nullptr)
material = mMaterial;
switch (colliderType) {
case GeometryType::BOX:
colliderShape = mPhysics->createShape(PxBoxGeometry(size.x, size.y, size.z), *material, true);
break;
case GeometryType::SPHERE:
colliderShape = mPhysics->createShape(PxSphereGeometry(size.MaxElement()), *material, true);
break;
case GeometryType::CAPSULE:
colliderShape = mPhysics->createShape(PxCapsuleGeometry(size.x, size.y), *material, true);
break;
}
return colliderShape;
}
physx::PxMaterial* ModulePhysics::CreateMaterial(float staticFriction, float dynamicFriction, float restitution) {
PxMaterial* material = nullptr;
material = mPhysics->createMaterial(staticFriction, dynamicFriction, restitution);
return material;
}
void ModulePhysics::ReleaseActor(PxRigidActor* actor) {
physx::PxShape* shapes[128];
actor->getShapes(shapes, actor->getNbShapes());
for (size_t i = 0; i < actor->getNbShapes(); i++)
actor->detachShape(*shapes[i]);
App->physX->mScene->removeActor(*actor);
actor->release();
actor = nullptr;
}
void ModulePhysics::DrawCollider(ComponentCollider* collider)
{
/*
PxTransform new_transform = collider->rigidbody->rigid_dynamic->getGlobalPose() * collider->colliderShape->getLocalPose();
float3 pos = { new_transform.p.x, new_transform.p.y, new_transform.p.z };
Quat rot = { new_transform.q.x, new_transform.q.y, new_transform.q.z, new_transform.q.w };
float4x4 transformation = float4x4(rot, pos);
*/
float4x4 transform = collider->transform->GetGlobalMatrix().Transposed() * PhysXTransformToF4F(collider->colliderShape->getLocalPose());
switch (collider->type)
{
case GeometryType::BOX:
{
PxBoxGeometry boxCollider;
collider->colliderShape->getBoxGeometry(boxCollider);
float3 size = { boxCollider.halfExtents.x, boxCollider.halfExtents.y, boxCollider.halfExtents.z };
App->renderer3D->DrawBoxCollider(transform, size);
}
break;
case GeometryType::SPHERE:
{
PxSphereGeometry sphereCollider;
collider->colliderShape->getSphereGeometry(sphereCollider);
App->renderer3D->DrawSphereCollider(transform, sphereCollider.radius);
}
break;
case GeometryType::CAPSULE:
{
PxCapsuleGeometry capsuleCollider;
collider->colliderShape->getCapsuleGeometry(capsuleCollider);
App->renderer3D->DrawCapsuleCollider(transform, capsuleCollider.halfHeight, capsuleCollider.radius);
}
break;
}
}
void ModulePhysics::WakeUpGeometry(GameObject* gameObject) {
gameObject->GetRigidbody()->rigid_dynamic->wakeUp();
}
float4x4 ModulePhysics::PhysXTransformToF4F(PxTransform transform) {
float3 pos = { transform.p.x, transform.p.y, transform.p.z };
Quat rot = { transform.q.x, transform.q.y, transform.q.z, transform.q.w};
float4x4 matrix = float4x4(rot, pos);
return matrix;
}
PxTransform ModulePhysics::TRStoPxTransform(float3 pos, float3 rot){
Quat rotation = Quat::FromEulerXYZ(rot.x * DEGTORAD, rot.y * DEGTORAD, rot.z * DEGTORAD);
PxVec3 Pxposition(pos.x, pos.y, pos.z);
PxQuat PxRotation(rotation.x, rotation.y, rotation.z, rotation.w);
return PxTransform(Pxposition, PxRotation);
} | 29.468468 | 137 | 0.710639 | [
"mesh",
"geometry",
"render",
"object",
"shape",
"vector",
"transform"
] |
dbc1d7a7d4038979b3f422feede81ae76ccd16e9 | 5,144 | cpp | C++ | tasks/day04/day_04.cpp | Majrusz/AdventOfCode2018 | 1ecd68185faa4b31a23f57f81d5e848766ad3014 | [
"MIT"
] | null | null | null | tasks/day04/day_04.cpp | Majrusz/AdventOfCode2018 | 1ecd68185faa4b31a23f57f81d5e848766ad3014 | [
"MIT"
] | null | null | null | tasks/day04/day_04.cpp | Majrusz/AdventOfCode2018 | 1ecd68185faa4b31a23f57f81d5e848766ad3014 | [
"MIT"
] | null | null | null | // Created by Majrusz on 25/07/2021. All rights reserved.
#include "day_04.h"
#include <algorithm>
#include <map>
#include <set>
#include <sstream>
#include "common/file_loader.h"
#include "common/zipper.h"
void aoc::day04::start() {
std::vector< Record > records{ loadFile< Record >( "day04/input.txt" ) };
std::sort( std::begin( records ), std::end( records ), []( const Record &a, const Record &b ){
return a.year < b.year || a.year == b.year && ( a.month < b.month || a.month == b.month && ( a.day < b.day || a.day == b.day && ( a.hour < b.hour || a.hour == b.hour && a.minute < b.minute ) ) );
} );
size_t currentGuardID;
std::for_each( std::begin( records ), std::end( records ), [¤tGuardID]( Record &record ){
if( record.state == Record::State::BEGINS_SHIFT )
currentGuardID = record.guardID;
else
record.guardID = currentGuardID;
} );
std::cout << "Task1 result: " << getTask1Result( records ) << std::endl;
std::cout << "Task2 result: " << getTask2Result( records ) << std::endl;
}
size_t aoc::day04::getTask1Result( const std::vector< Record > &records ) {
size_t guardID{ getGuardIDWithMostAsleepMinutes( records ) };
return getMostAsleepMinute( records, guardID ) * guardID;
}
size_t aoc::day04::getGuardIDWithMostAsleepMinutes( const std::vector< Record > &records ) {
std::map< size_t, size_t > minutes;
const Record *previousRecord{};
std::for_each( std::begin( records ), std::end( records ), [&previousRecord, &minutes]( const Record &record ){
if( record.state == Record::State::WAKES_UP )
minutes[ record.guardID ] += record.minute - previousRecord->minute + ( record.hour - previousRecord->hour )*60 + ( record.day - previousRecord->day )*60*24;
previousRecord = &record;
} );
return std::max_element( std::begin( minutes ), std::end( minutes ), []( const auto &a, const auto &b ){
return a.second < b.second;
} )->first;
}
std::map< int, size_t > aoc::day04::getMostAsleepMinutes( const std::vector< Record > &records, size_t guardID ) {
std::map< int, size_t > minuteOccurrences{};
auto increaseIndex = [&minuteOccurrences]( int index ){
if( minuteOccurrences.count( index ) > 0 )
++minuteOccurrences[ index ];
else
minuteOccurrences[ index ] = 1;
};
const Record *previousRecord{};
std::for_each( std::begin( records ), std::end( records ), [&]( const Record &record ){
if( record.guardID != guardID )
return;
if( record.state == Record::State::WAKES_UP ) {
if( record.minute > previousRecord->minute ) {
for( int minute{ previousRecord->minute }; minute < record.minute; ++minute )
increaseIndex( minute );
} else {
for( int minute{ 0 }; minute < record.minute; ++minute )
increaseIndex( minute );
for( int minute{ previousRecord->minute }; minute <= 60; ++minute )
increaseIndex( minute );
}
}
previousRecord = &record;
} );
return minuteOccurrences;
}
int aoc::day04::getMostAsleepMinute( const std::vector< Record > &records, size_t guardID ) {
auto minuteOccurrences{ getMostAsleepMinutes( records, guardID ) };
return std::max_element( std::begin( minuteOccurrences ), std::end( minuteOccurrences ), []( const auto &a, const auto &b ){
return a.second < b.second;
} )->first;
}
size_t aoc::day04::getTask2Result( const std::vector< Record > &records ) {
std::set< size_t > guardIDs;
std::for_each( std::begin( records ), std::end( records ), [&guardIDs]( const Record &record ){
guardIDs.insert( record.guardID );
} );
int mostAsleepMinute{}, mostOccurrences{};
size_t mostAsleepGuardID{};
std::for_each( std::begin( records ), std::end( records ), [&]( size_t guardID ){
auto minuteOccurrences{ getMostAsleepMinutes( records, guardID ) };
auto mostAsleepMinutePair{ std::max_element( std::begin( minuteOccurrences ), std::end( minuteOccurrences ), []( const auto &a, const auto &b ){
return a.second < b.second;
} ) };
if( mostAsleepMinutePair->second > mostOccurrences ) {
mostAsleepMinute = mostAsleepMinutePair->first;
mostOccurrences = mostAsleepMinutePair->second;
mostAsleepGuardID = guardID;
}
} );
return mostAsleepMinute * mostAsleepGuardID;
}
std::istream &std::operator>>( std::istream &stream, aoc::day04::Record &record ) {
std::string input;
std::getline( stream, input );
if( !input.empty() ) {
size_t dateEndIndex{ input.find_first_of( ']' ) };
std::string dateFormat{ input.substr( 1, dateEndIndex - 1 ) };
size_t index;
while( ( index = dateFormat.find_first_of( "-:" ) ) != std::string::npos )
dateFormat.replace( index, 1, " " );
std::stringstream{ dateFormat } >> record.year >> record.month >> record.day >> record.hour >> record.minute;
if( std::string information{ input.substr( dateEndIndex + 2 ) }; information == "falls asleep" ) {
record.state = aoc::day04::Record::State::FALLS_ASLEEP;
} else if( information == "wakes up" ) {
record.state = aoc::day04::Record::State::WAKES_UP;
} else {
record.state = aoc::day04::Record::State::BEGINS_SHIFT;
information[ information.find( '#' ) ] = ' ';
std::stringstream{ information } >> input >> record.guardID;
}
}
return stream;
}
| 35.972028 | 197 | 0.667379 | [
"vector"
] |
dbc218ed44a2bafa158c180d0e2c0364e5358d7f | 4,676 | cpp | C++ | Source/Core/Visualization/Mapper/HexahedralCell.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Source/Core/Visualization/Mapper/HexahedralCell.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Source/Core/Visualization/Mapper/HexahedralCell.cpp | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /****************************************************************************/
/**
* @file HexahedralCell.cpp
* @author Naohisa Sakamoto
*/
/****************************************************************************/
#include "HexahedralCell.h"
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new HexahedralCell class.
* @param volume [in] pointer to the unstructured volume object
*/
/*===========================================================================*/
HexahedralCell::HexahedralCell(
const kvs::UnstructuredVolumeObject* volume ):
kvs::CellBase( volume )
{
// Set the initial interpolation functions and differential functions.
this->updateInterpolationFunctions( BaseClass::localPoint() );
this->updateDifferentialFunctions( BaseClass::localPoint() );
}
/*==========================================================================*/
/**
* @brief Calculates the interpolation functions in the local coordinate.
* @return local [in] point in the local coordinate
*/
/*==========================================================================*/
void HexahedralCell::updateInterpolationFunctions( const kvs::Vec3& local ) const
{
KVS_ASSERT( BaseClass::containsLocalPoint( local ) );
const float p = local.x();
const float q = local.y();
const float r = local.z();
const float pq = p * q;
const float qr = q * r;
const float rp = r * p;
const float pqr = pq * r;
kvs::Real32* N = BaseClass::interpolationFunctions();
N[0] = r - rp - qr + pqr;
N[1] = rp - pqr;
N[2] = pqr;
N[3] = qr - pqr;
N[4] = 1.0f - p - q - r + pq + qr + rp - pqr;
N[5] = p - pq - rp + pqr;
N[6] = pq - pqr;
N[7] = q - pq - qr + pqr;
}
/*==========================================================================*/
/**
* @brief Calculates the differential functions in the local coordinate.
* @return local [in] point in the local coordinate
*/
/*==========================================================================*/
void HexahedralCell::updateDifferentialFunctions( const kvs::Vec3& local ) const
{
KVS_ASSERT( BaseClass::containsLocalPoint( local ) );
const float p = local.x();
const float q = local.y();
const float r = local.z();
const float pq = p * q;
const float qr = q * r;
const float rp = r * p;
const size_t nnodes = BaseClass::numberOfCellNodes();
kvs::Real32* dN = BaseClass::differentialFunctions();
kvs::Real32* dNdp = dN;
kvs::Real32* dNdq = dN + nnodes;
kvs::Real32* dNdr = dN + nnodes + nnodes;
dNdp[0] = - r + qr;
dNdp[1] = r - qr;
dNdp[2] = qr;
dNdp[3] = - qr;
dNdp[4] = - 1.0f + q +r - qr;
dNdp[5] = 1.0f - q - r + qr;
dNdp[6] = q - qr;
dNdp[7] = - q + qr;
dNdq[0] = - r + rp;
dNdq[1] = - rp;
dNdq[2] = rp;
dNdq[3] = r - rp;
dNdq[4] = - 1.0f + p + r - rp;
dNdq[5] = - p + rp;
dNdq[6] = p - rp;
dNdq[7] = 1.0f - p - r + rp;
dNdr[0] = 1.0f - q - p + pq;
dNdr[1] = p - pq;
dNdr[2] = pq;
dNdr[3] = q - pq;
dNdr[4] = - 1.0f + q + p - pq;
dNdr[5] = - p + pq;
dNdr[6] = - pq;
dNdr[7] = - q + pq;
}
/*===========================================================================*/
/**
* @brief Returns the volume of the cell.
* @return volume of the cell
*/
/*===========================================================================*/
kvs::Real32 HexahedralCell::volume() const
{
const size_t resolution = 3;
const float sampling_length = 1.0f / (float)resolution;
const float adjustment = sampling_length * 0.5f;
kvs::Vec3 sampling_position( -adjustment, -adjustment, -adjustment );
float sum_metric = 0;
for ( size_t k = 0 ; k < resolution ; k++ )
{
sampling_position[ 2 ] += sampling_length;
for( size_t j = 0 ; j < resolution ; j++ )
{
sampling_position[ 1 ] += sampling_length;
for( size_t i = 0 ; i < resolution ; i++ )
{
sampling_position[ 0 ] += sampling_length;
this->setLocalPoint( sampling_position );
const kvs::Mat3 J = BaseClass::JacobiMatrix();
const float metric_element = J.determinant();
sum_metric += kvs::Math::Abs<float>( metric_element );
}
sampling_position[ 0 ] = -adjustment;
}
sampling_position[ 1 ] = -adjustment;
}
const float resolution3 = resolution * resolution * resolution;
return sum_metric / resolution3;
}
} // end of namespace kvs
| 31.173333 | 81 | 0.473268 | [
"object"
] |
3a7aeeb21a0e88056a65c55e7b53a79f161b9dd7 | 1,744 | cpp | C++ | Practise/OOPS/main.cpp | Himanshu40/Learn-Cpp | f0854f7c88bf31857c0c6216af80245666ca9b54 | [
"CC-BY-4.0"
] | 2 | 2021-07-18T18:12:10.000Z | 2021-07-19T15:40:25.000Z | Practise/OOPS/main.cpp | Himanshu40/Learn-Cpp | f0854f7c88bf31857c0c6216af80245666ca9b54 | [
"CC-BY-4.0"
] | null | null | null | Practise/OOPS/main.cpp | Himanshu40/Learn-Cpp | f0854f7c88bf31857c0c6216af80245666ca9b54 | [
"CC-BY-4.0"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Base {
private:
static int objCount;
int size;
int *data;
public:
Base() : Base {0, 0} {
cout << "No-args constructor called for " << *data << endl;
}
Base(int size, int value) : size {size} {
data = new int;
*data = value;
++objCount;
cout << "Parameterized constructor called for " << *data << endl;
}
Base(const Base &obj) : Base {obj.size, *obj.data} {
cout << "Deep copy constructor called for " << *data << endl;
}
Base(Base &&obj) noexcept : size {obj.size}, data {obj.data} {
obj.data = nullptr;
cout << "Move constructor called for " << *data << endl;
}
~Base() {
if (data != nullptr) {
cout << "Destructor called for " << *data << endl;
--objCount;
}
else {
cout << "Destructor called for nullptr" << endl;
}
delete data;
}
void display() const {
cout << "Size = " << size << ", Data = " << *data << endl;
}
static int getObjCount() {
return objCount;
}
};
int Base::objCount {0};
void displayObjCount() {
cout << "Total object created = " << Base::getObjCount() << endl;
}
int main() {
Base b1;
b1.display();
Base b2 {5, 10};
b2.display();
Base b3 {b2};
b3.display();
vector<Base> vec;
vec.push_back(Base {6, 11});
vec.push_back(Base {7, 12});
const Base b4;
b4.display();
displayObjCount();
return 0;
}
| 20.517647 | 77 | 0.466743 | [
"object",
"vector"
] |
3a7c7e3d53a068481acce793231776f49d5ef54b | 30,144 | cc | C++ | chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/apps/app_service/publishers/extension_apps_chromeos.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "chrome/browser/apps/app_service/publishers/extension_apps_chromeos.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/app_list/app_list_metrics.h"
#include "ash/public/cpp/app_menu_constants.h"
#include "ash/public/cpp/multi_user_window_manager.h"
#include "ash/public/cpp/shelf_types.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "base/scoped_observation.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/app_icon_factory.h"
#include "chrome/browser/apps/app_service/app_service_metrics.h"
#include "chrome/browser/apps/app_service/launch_utils.h"
#include "chrome/browser/apps/app_service/menu_util.h"
#include "chrome/browser/ash/arc/arc_util.h"
#include "chrome/browser/ash/arc/arc_web_contents_data.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_time_limit_interface.h"
#include "chrome/browser/ash/crostini/crostini_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/extensions/gfx_utils.h"
#include "chrome/browser/chromeos/policy/handlers/system_features_disable_list_policy_handler.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/launch_util.h"
#include "chrome/browser/notifications/notification_display_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ui/app_list/extension_app_utils.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_util.h"
#include "chrome/browser/ui/ash/multi_user/multi_user_window_manager_helper.h"
#include "chrome/browser/ui/ash/session_controller_client_impl.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_metrics.h"
#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "components/arc/arc_service_manager.h"
#include "components/full_restore/app_launch_info.h"
#include "components/full_restore/full_restore_utils.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/services/app_service/public/cpp/instance.h"
#include "components/services/app_service/public/cpp/intent_filter_util.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
#include "content/public/browser/clear_site_data_utils.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/management_policy.h"
#include "extensions/browser/ui_util.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/manifest_handlers/options_page_info.h"
#include "ui/message_center/public/cpp/notification.h"
namespace {
// Get the LaunchId for a given |app_window|. Set launch_id default value to an
// empty string. If show_in_shelf parameter is true and the window key is not
// empty, its value is appended to the launch_id. Otherwise, if the window key
// is empty, the session_id is used.
std::string GetLaunchId(extensions::AppWindow* app_window) {
std::string launch_id;
if (app_window->show_in_shelf()) {
if (!app_window->window_key().empty()) {
launch_id = app_window->window_key();
} else {
launch_id = base::StringPrintf("%d", app_window->session_id().id());
}
}
return launch_id;
}
} // namespace
namespace apps {
ExtensionAppsChromeOs::ExtensionAppsChromeOs(
const mojo::Remote<apps::mojom::AppService>& app_service,
Profile* profile,
apps::InstanceRegistry* instance_registry)
: ExtensionAppsBase(app_service, profile),
instance_registry_(instance_registry) {
DCHECK(instance_registry_);
Initialize();
}
ExtensionAppsChromeOs::~ExtensionAppsChromeOs() {
app_window_registry_.Reset();
// In unit tests, AppServiceProxy might be ReInitializeForTesting, so
// ExtensionApps might be destroyed without calling Shutdown, so arc_prefs_
// needs to be removed from observer in the destructor function.
if (arc_prefs_) {
arc_prefs_->RemoveObserver(this);
arc_prefs_ = nullptr;
}
}
// static
void ExtensionAppsChromeOs::RecordUninstallCanceledAction(
Profile* profile,
const std::string& app_id) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(
app_id);
if (!extension) {
return;
}
if (extension->from_bookmark()) {
UMA_HISTOGRAM_ENUMERATION(
"Webapp.UninstallDialogAction",
extensions::ExtensionUninstallDialog::CLOSE_ACTION_CANCELED,
extensions::ExtensionUninstallDialog::CLOSE_ACTION_LAST);
} else {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.UninstallDialogAction",
extensions::ExtensionUninstallDialog::CLOSE_ACTION_CANCELED,
extensions::ExtensionUninstallDialog::CLOSE_ACTION_LAST);
}
}
void ExtensionAppsChromeOs::Shutdown() {
if (arc_prefs_) {
arc_prefs_->RemoveObserver(this);
arc_prefs_ = nullptr;
}
}
void ExtensionAppsChromeOs::ObserveArc() {
// Observe the ARC apps to set the badge on the equivalent Chrome app's icon.
if (arc_prefs_) {
arc_prefs_->RemoveObserver(this);
}
arc_prefs_ = ArcAppListPrefs::Get(profile());
if (arc_prefs_) {
arc_prefs_->AddObserver(this);
}
}
void ExtensionAppsChromeOs::Initialize() {
app_window_registry_.Observe(extensions::AppWindowRegistry::Get(profile()));
media_dispatcher_.Observe(MediaCaptureDevicesDispatcher::GetInstance());
notification_display_service_.Observe(
NotificationDisplayServiceFactory::GetForProfile(profile()));
profile_pref_change_registrar_.Init(profile()->GetPrefs());
profile_pref_change_registrar_.Add(
prefs::kHideWebStoreIcon,
base::BindRepeating(&ExtensionAppsBase::OnHideWebStoreIconPrefChanged,
GetWeakPtr()));
auto* local_state = g_browser_process->local_state();
if (local_state) {
local_state_pref_change_registrar_.Init(local_state);
local_state_pref_change_registrar_.Add(
policy::policy_prefs::kSystemFeaturesDisableList,
base::BindRepeating(&ExtensionAppsBase::OnSystemFeaturesPrefChanged,
GetWeakPtr()));
local_state_pref_change_registrar_.Add(
policy::policy_prefs::kSystemFeaturesDisableMode,
base::BindRepeating(&ExtensionAppsBase::OnSystemFeaturesPrefChanged,
GetWeakPtr()));
OnSystemFeaturesPrefChanged();
}
}
void ExtensionAppsChromeOs::LaunchAppWithIntent(
const std::string& app_id,
int32_t event_flags,
apps::mojom::IntentPtr intent,
apps::mojom::LaunchSource launch_source,
apps::mojom::WindowInfoPtr window_info) {
auto* tab = LaunchAppWithIntentImpl(app_id, event_flags, std::move(intent),
launch_source, std::move(window_info));
if (launch_source == apps::mojom::LaunchSource::kFromArc && tab) {
// Add a flag to remember this tab originated in the ARC context.
tab->SetUserData(&arc::ArcWebContentsData::kArcTransitionFlag,
std::make_unique<arc::ArcWebContentsData>());
}
}
void ExtensionAppsChromeOs::PauseApp(const std::string& app_id) {
if (paused_apps_.MaybeAddApp(app_id)) {
SetIconEffect(app_id);
}
constexpr bool kPaused = true;
Publish(paused_apps_.GetAppWithPauseStatus(apps::mojom::AppType::kExtension,
app_id, kPaused),
subscribers());
if (instance_registry_->GetWindows(app_id).empty()) {
return;
}
ash::app_time::AppTimeLimitInterface* app_limit =
ash::app_time::AppTimeLimitInterface::Get(profile());
DCHECK(app_limit);
app_limit->PauseWebActivity(app_id);
}
void ExtensionAppsChromeOs::UnpauseApp(const std::string& app_id) {
if (paused_apps_.MaybeRemoveApp(app_id)) {
SetIconEffect(app_id);
}
constexpr bool kPaused = false;
Publish(paused_apps_.GetAppWithPauseStatus(apps::mojom::AppType::kExtension,
app_id, kPaused),
subscribers());
ash::app_time::AppTimeLimitInterface* app_time =
ash::app_time::AppTimeLimitInterface::Get(profile());
DCHECK(app_time);
app_time->ResumeWebActivity(app_id);
}
void ExtensionAppsChromeOs::GetMenuModel(const std::string& app_id,
apps::mojom::MenuType menu_type,
int64_t display_id,
GetMenuModelCallback callback) {
apps::mojom::MenuItemsPtr menu_items = apps::mojom::MenuItems::New();
const auto* extension = MaybeGetExtension(app_id);
if (!extension) {
std::move(callback).Run(std::move(menu_items));
return;
}
if (app_id == extension_misc::kChromeAppId) {
std::move(callback).Run(CreateBrowserMenuItems(menu_type, profile()));
return;
}
bool is_platform_app = extension->is_platform_app();
if (!is_platform_app) {
CreateOpenNewSubmenu(
menu_type,
extensions::GetLaunchType(extensions::ExtensionPrefs::Get(profile()),
extension) ==
extensions::LaunchType::LAUNCH_TYPE_WINDOW
? IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW
: IDS_APP_LIST_CONTEXT_MENU_NEW_TAB,
&menu_items);
}
if (!is_platform_app && menu_type == apps::mojom::MenuType::kAppList &&
extensions::util::IsAppLaunchableWithoutEnabling(app_id, profile()) &&
extensions::OptionsPageInfo::HasOptionsPage(extension)) {
AddCommandItem(ash::OPTIONS, IDS_NEW_TAB_APP_OPTIONS, &menu_items);
}
if (menu_type == apps::mojom::MenuType::kShelf &&
!instance_registry_->GetWindows(app_id).empty()) {
AddCommandItem(ash::MENU_CLOSE, IDS_SHELF_CONTEXT_MENU_CLOSE, &menu_items);
}
const extensions::ManagementPolicy* policy =
extensions::ExtensionSystem::Get(profile())->management_policy();
DCHECK(policy);
if (policy->UserMayModifySettings(extension, nullptr) &&
!policy->MustRemainInstalled(extension, nullptr)) {
AddCommandItem(ash::UNINSTALL, IDS_APP_LIST_UNINSTALL_ITEM, &menu_items);
}
if (extension->ShouldDisplayInAppLauncher()) {
AddCommandItem(ash::SHOW_APP_INFO, IDS_APP_CONTEXT_MENU_SHOW_INFO,
&menu_items);
}
std::move(callback).Run(std::move(menu_items));
}
void ExtensionAppsChromeOs::OnAppWindowAdded(
extensions::AppWindow* app_window) {
if (!ShouldRecordAppWindowActivity(app_window)) {
return;
}
DCHECK(!instance_registry_->Exists(
apps::Instance::InstanceKey(app_window->GetNativeWindow())));
app_window_to_aura_window_[app_window] = app_window->GetNativeWindow();
// Attach window to multi-user manager now to let it manage visibility state
// of the window correctly.
if (SessionControllerClientImpl::IsMultiProfileAvailable()) {
auto* multi_user_window_manager =
MultiUserWindowManagerHelper::GetWindowManager();
if (multi_user_window_manager) {
multi_user_window_manager->SetWindowOwner(
app_window->GetNativeWindow(),
multi_user_util::GetAccountIdFromProfile(profile()));
}
}
RegisterInstance(app_window, InstanceState::kStarted);
}
void ExtensionAppsChromeOs::OnAppWindowShown(extensions::AppWindow* app_window,
bool was_hidden) {
if (!ShouldRecordAppWindowActivity(app_window)) {
return;
}
InstanceState state = instance_registry_->GetState(
apps::Instance::InstanceKey(app_window->GetNativeWindow()));
// If the window is shown, it should be started, running and not hidden.
state = static_cast<apps::InstanceState>(
state | apps::InstanceState::kStarted | apps::InstanceState::kRunning);
state =
static_cast<apps::InstanceState>(state & ~apps::InstanceState::kHidden);
RegisterInstance(app_window, state);
}
void ExtensionAppsChromeOs::OnAppWindowHidden(
extensions::AppWindow* app_window) {
if (!ShouldRecordAppWindowActivity(app_window)) {
return;
}
// For hidden |app_window|, the other state bit, started, running, active, and
// visible should be cleared.
RegisterInstance(app_window, InstanceState::kHidden);
}
void ExtensionAppsChromeOs::OnAppWindowRemoved(
extensions::AppWindow* app_window) {
if (!ShouldRecordAppWindowActivity(app_window)) {
return;
}
RegisterInstance(app_window, InstanceState::kDestroyed);
app_window_to_aura_window_.erase(app_window);
}
void ExtensionAppsChromeOs::OnExtensionUninstalled(
content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UninstallReason reason) {
if (!Accepts(extension)) {
return;
}
app_notifications_.RemoveNotificationsForApp(extension->id());
paused_apps_.MaybeRemoveApp(extension->id());
auto result = media_requests_.RemoveRequests(extension->id());
ModifyCapabilityAccess(subscribers(), extension->id(), result.camera,
result.microphone);
ExtensionAppsBase::OnExtensionUninstalled(browser_context, extension, reason);
}
void ExtensionAppsChromeOs::OnPackageInstalled(
const arc::mojom::ArcPackageInfo& package_info) {
ApplyChromeBadge(package_info.package_name);
}
void ExtensionAppsChromeOs::OnPackageRemoved(const std::string& package_name,
bool uninstalled) {
ApplyChromeBadge(package_name);
}
void ExtensionAppsChromeOs::OnPackageListInitialRefreshed() {
if (!arc_prefs_) {
return;
}
for (const auto& app_name : arc_prefs_->GetPackagesFromPrefs()) {
ApplyChromeBadge(app_name);
}
}
void ExtensionAppsChromeOs::OnArcAppListPrefsDestroyed() {
arc_prefs_ = nullptr;
}
void ExtensionAppsChromeOs::OnRequestUpdate(
int render_process_id,
int render_frame_id,
blink::mojom::MediaStreamType stream_type,
const content::MediaRequestState state) {
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(
content::RenderFrameHost::FromID(render_process_id, render_frame_id));
if (!web_contents) {
return;
}
Profile* web_profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
if (web_profile != profile()) {
return;
}
absl::optional<web_app::AppId> web_app_id =
web_app::FindInstalledAppWithUrlInScope(profile(), web_contents->GetURL(),
/*window_only=*/false);
if (web_app_id.has_value()) {
// WebAppsChromeOs is responsible for |app_id|.
return;
}
std::string app_id = extension_misc::kChromeAppId;
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile());
DCHECK(registry);
const extensions::ExtensionSet& extensions = registry->enabled_extensions();
const extensions::Extension* extension =
extensions.GetAppByURL(web_contents->GetURL());
if (extension && Accepts(extension)) {
app_id = extension->id();
}
if (media_requests_.IsNewRequest(app_id, web_contents, state)) {
content::WebContentsUserData<AppWebContentsData>::CreateForWebContents(
web_contents, this);
}
auto result =
media_requests_.UpdateRequests(app_id, web_contents, stream_type, state);
ModifyCapabilityAccess(subscribers(), app_id, result.camera,
result.microphone);
}
void ExtensionAppsChromeOs::OnWebContentsDestroyed(
content::WebContents* web_contents) {
DCHECK(web_contents);
std::string app_id = extension_misc::kChromeAppId;
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile());
DCHECK(registry);
const extensions::ExtensionSet& extensions = registry->enabled_extensions();
const extensions::Extension* extension =
extensions.GetAppByURL(web_contents->GetLastCommittedURL());
if (extension && Accepts(extension)) {
app_id = extension->id();
}
auto result = media_requests_.OnWebContentsDestroyed(app_id, web_contents);
ModifyCapabilityAccess(subscribers(), app_id, result.camera,
result.microphone);
}
void ExtensionAppsChromeOs::OnNotificationDisplayed(
const message_center::Notification& notification,
const NotificationCommon::Metadata* const metadata) {
switch (notification.notifier_id().type) {
case message_center::NotifierType::APPLICATION:
MaybeAddNotification(notification.notifier_id().id, notification.id());
return;
case message_center::NotifierType::WEB_PAGE:
MaybeAddWebPageNotifications(notification, metadata);
return;
default:
return;
}
}
void ExtensionAppsChromeOs::OnNotificationClosed(
const std::string& notification_id) {
const auto app_ids =
app_notifications_.GetAppIdsForNotification(notification_id);
if (app_ids.empty()) {
return;
}
app_notifications_.RemoveNotification(notification_id);
for (const auto& app_id : app_ids) {
Publish(app_notifications_.GetAppWithHasBadgeStatus(
apps::mojom::AppType::kExtension, app_id),
subscribers());
}
}
void ExtensionAppsChromeOs::OnNotificationDisplayServiceDestroyed(
NotificationDisplayService* service) {
DCHECK(notification_display_service_.IsObservingSource(service));
notification_display_service_.Reset();
}
bool ExtensionAppsChromeOs::MaybeAddNotification(
const std::string& app_id,
const std::string& notification_id) {
if (MaybeGetExtension(app_id) == nullptr) {
return false;
}
app_notifications_.AddNotification(app_id, notification_id);
Publish(app_notifications_.GetAppWithHasBadgeStatus(
apps::mojom::AppType::kExtension, app_id),
subscribers());
return true;
}
void ExtensionAppsChromeOs::MaybeAddWebPageNotifications(
const message_center::Notification& notification,
const NotificationCommon::Metadata* const metadata) {
const PersistentNotificationMetadata* persistent_metadata =
PersistentNotificationMetadata::From(metadata);
const NonPersistentNotificationMetadata* non_persistent_metadata =
NonPersistentNotificationMetadata::From(metadata);
GURL url = notification.origin_url();
if (persistent_metadata) {
url = persistent_metadata->service_worker_scope;
} else if (non_persistent_metadata &&
!non_persistent_metadata->document_url.is_empty()) {
url = non_persistent_metadata->document_url;
}
extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(profile());
DCHECK(registry);
const extensions::ExtensionSet& extensions = registry->enabled_extensions();
const extensions::Extension* extension = extensions.GetAppByURL(url);
if (extension) {
MaybeAddNotification(extension->id(), notification.id());
}
}
// static
bool ExtensionAppsChromeOs::IsBlocklisted(const std::string& app_id) {
// We blocklist (meaning we don't publish the app, in the App Service sense)
// some apps that are already published by other app publishers.
//
// This sense of "blocklist" is separate from the extension registry's
// kDisabledByBlocklist concept, which is when SafeBrowsing will send out a
// blocklist of malicious extensions to disable.
// The Play Store is conceptually provided by the ARC++ publisher, but
// because it (the Play Store icon) is also the UI for enabling Android apps,
// we also want to show the app icon even before ARC++ is enabled. Prior to
// the App Service, as a historical implementation quirk, the Play Store both
// has an "ARC++ app" component and an "Extension app" component, and both
// share the same App ID.
//
// In the App Service world, there should be a unique app publisher for any
// given app. In this case, the ArcApps publisher publishes the Play Store
// app, and the ExtensionApps publisher does not.
return app_id == arc::kPlayStoreAppId;
}
void ExtensionAppsChromeOs::UpdateShowInFields(const std::string& app_id) {
const auto* extension = MaybeGetExtension(app_id);
if (!extension) {
return;
}
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kExtension;
app->app_id = app_id;
SetShowInFields(app, extension);
Publish(std::move(app), subscribers());
}
void ExtensionAppsChromeOs::OnHideWebStoreIconPrefChanged() {
UpdateShowInFields(extensions::kWebStoreAppId);
UpdateShowInFields(extension_misc::kEnterpriseWebStoreAppId);
}
void ExtensionAppsChromeOs::OnSystemFeaturesPrefChanged() {
PrefService* const local_state = g_browser_process->local_state();
if (!local_state || !local_state->FindPreference(
policy::policy_prefs::kSystemFeaturesDisableList)) {
return;
}
const base::ListValue* disabled_system_features_pref =
local_state->GetList(policy::policy_prefs::kSystemFeaturesDisableList);
if (!disabled_system_features_pref) {
return;
}
const bool is_pref_disabled_mode_hidden =
local_state->GetString(
policy::policy_prefs::kSystemFeaturesDisableMode) ==
policy::kHiddenDisableMode;
const bool is_disabled_mode_changed =
(is_pref_disabled_mode_hidden != is_disabled_apps_mode_hidden_);
is_disabled_apps_mode_hidden_ = is_pref_disabled_mode_hidden;
UpdateAppDisabledState(
disabled_system_features_pref, policy::SystemFeature::kCamera,
extension_misc::kCameraAppId, is_disabled_mode_changed);
UpdateAppDisabledState(disabled_system_features_pref,
policy::SystemFeature::kWebStore,
extensions::kWebStoreAppId, is_disabled_mode_changed);
}
bool ExtensionAppsChromeOs::Accepts(const extensions::Extension* extension) {
if (!extension->is_app() || IsBlocklisted(extension->id())) {
return false;
}
return !extension->from_bookmark();
}
void ExtensionAppsChromeOs::SetShowInFields(
apps::mojom::AppPtr& app,
const extensions::Extension* extension) {
if (extension->id() == extension_misc::kWallpaperManagerId) {
// Explicitly show the Wallpaper Picker app in search only.
app->show_in_launcher = apps::mojom::OptionalBool::kFalse;
// Hide from shelf and search if new Personalization SWA is enabled.
auto should_show = ash::features::IsWallpaperWebUIEnabled()
? apps::mojom::OptionalBool::kFalse
: apps::mojom::OptionalBool::kTrue;
app->show_in_shelf = should_show;
app->show_in_search = should_show;
app->show_in_management = apps::mojom::OptionalBool::kFalse;
return;
}
ExtensionAppsBase::SetShowInFields(app, extension);
}
bool ExtensionAppsChromeOs::ShouldShownInLauncher(
const extensions::Extension* extension) {
return app_list::ShouldShowInLauncher(extension, profile());
}
apps::mojom::AppPtr ExtensionAppsChromeOs::Convert(
const extensions::Extension* extension,
apps::mojom::Readiness readiness) {
const bool is_app_disabled = base::Contains(disabled_apps_, extension->id());
apps::mojom::AppPtr app = ConvertImpl(
extension,
is_app_disabled ? apps::mojom::Readiness::kDisabledByPolicy : readiness);
bool paused = paused_apps_.IsPaused(extension->id());
app->icon_key =
icon_key_factory().MakeIconKey(GetIconEffects(extension, paused));
app->has_badge = app_notifications_.HasNotification(extension->id())
? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
app->paused = paused ? apps::mojom::OptionalBool::kTrue
: apps::mojom::OptionalBool::kFalse;
if (is_app_disabled && is_disabled_apps_mode_hidden_) {
app->show_in_launcher = apps::mojom::OptionalBool::kFalse;
app->show_in_search = apps::mojom::OptionalBool::kFalse;
app->show_in_shelf = apps::mojom::OptionalBool::kFalse;
}
return app;
}
IconEffects ExtensionAppsChromeOs::GetIconEffects(
const extensions::Extension* extension,
bool paused) {
IconEffects icon_effects = IconEffects::kNone;
if (base::FeatureList::IsEnabled(features::kAppServiceAdaptiveIcon)) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kCrOsStandardIcon);
} else {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kResizeAndPad);
}
if (extensions::util::ShouldApplyChromeBadge(profile(), extension->id())) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kChromeBadge);
}
icon_effects = static_cast<IconEffects>(
icon_effects | ExtensionAppsBase::GetIconEffects(extension));
if (paused) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kPaused);
}
if (base::Contains(disabled_apps_, extension->id())) {
icon_effects =
static_cast<IconEffects>(icon_effects | IconEffects::kBlocked);
}
return icon_effects;
}
void ExtensionAppsChromeOs::ApplyChromeBadge(const std::string& package_name) {
const std::vector<std::string> extension_ids =
extensions::util::GetEquivalentInstalledExtensions(profile(),
package_name);
for (auto& app_id : extension_ids) {
SetIconEffect(app_id);
}
}
void ExtensionAppsChromeOs::SetIconEffect(const std::string& app_id) {
const auto* extension = MaybeGetExtension(app_id);
if (!extension) {
return;
}
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_type = apps::mojom::AppType::kExtension;
app->app_id = app_id;
app->icon_key = icon_key_factory().MakeIconKey(
GetIconEffects(extension, paused_apps_.IsPaused(app_id)));
Publish(std::move(app), subscribers());
}
bool ExtensionAppsChromeOs::ShouldRecordAppWindowActivity(
extensions::AppWindow* app_window) {
DCHECK(app_window);
const extensions::Extension* extension = app_window->GetExtension();
if (!extension) {
return false;
}
// ARC Play Store is not published by this publisher, but the window for Play
// Store should be able to be added to InstanceRegistry.
if (extension->id() == arc::kPlayStoreAppId) {
return true;
}
if (!Accepts(extension)) {
return false;
}
return true;
}
void ExtensionAppsChromeOs::RegisterInstance(extensions::AppWindow* app_window,
InstanceState new_state) {
aura::Window* window = app_window->GetNativeWindow();
// If the current state has been marked as |new_state|, we don't need to
// update.
if (instance_registry_->GetState(apps::Instance::InstanceKey(window)) ==
new_state) {
return;
}
if (new_state == InstanceState::kDestroyed) {
DCHECK(base::Contains(app_window_to_aura_window_, app_window));
window = app_window_to_aura_window_[app_window];
}
std::vector<std::unique_ptr<apps::Instance>> deltas;
auto instance = std::make_unique<apps::Instance>(
app_window->extension_id(),
std::make_unique<apps::Instance::InstanceKey>(window));
instance->SetLaunchId(GetLaunchId(app_window));
instance->UpdateState(new_state, base::Time::Now());
instance->SetBrowserContext(app_window->browser_context());
deltas.push_back(std::move(instance));
instance_registry_->OnInstances(deltas);
}
content::WebContents* ExtensionAppsChromeOs::LaunchImpl(
AppLaunchParams&& params) {
AppLaunchParams params_for_restore(
params.app_id, params.container, params.disposition, params.source,
params.display_id, params.launch_files, params.intent);
auto* web_contents = ExtensionAppsBase::LaunchImpl(std::move(params));
std::unique_ptr<full_restore::AppLaunchInfo> launch_info;
int session_id = GetSessionIdForRestoreFromWebContents(web_contents);
if (!SessionID::IsValidValue(session_id)) {
// Save all launch information for platform apps, which can launch via
// event, e.g. file app.
launch_info = std::make_unique<full_restore::AppLaunchInfo>(
params_for_restore.app_id, params_for_restore.container,
params_for_restore.disposition, params_for_restore.display_id,
std::move(params_for_restore.launch_files),
std::move(params_for_restore.intent));
full_restore::SaveAppLaunchInfo(profile()->GetPath(),
std::move(launch_info));
}
return web_contents;
}
void ExtensionAppsChromeOs::UpdateAppDisabledState(
const base::ListValue* disabled_system_features_pref,
int feature,
const std::string& app_id,
bool is_disabled_mode_changed) {
const bool is_disabled = base::Contains(
disabled_system_features_pref->GetList(), base::Value(feature));
// Sometimes the policy is updated before the app is installed, so this way
// the disabled_apps_ is updated regardless the Publish should happen or not
// and the app will be published with the correct readiness upon its
// installation.
const bool should_publish =
(base::Contains(disabled_apps_, app_id) != is_disabled) ||
is_disabled_mode_changed;
if (is_disabled) {
disabled_apps_.insert(app_id);
} else {
disabled_apps_.erase(app_id);
}
if (!should_publish) {
return;
}
const auto* extension = MaybeGetExtension(app_id);
if (!extension) {
return;
}
Publish(
Convert(extension, is_disabled ? apps::mojom::Readiness::kDisabledByPolicy
: apps::mojom::Readiness::kReady),
subscribers());
}
} // namespace apps
| 36.014337 | 96 | 0.724323 | [
"vector"
] |
3a7c929d305a98807129fae299e70d66aaffcbea | 13,040 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "easingcontextpane.h"
#include "ui_easingcontextpane.h"
#include <qmljs/qmljspropertyreader.h>
#include <utils/utilsicons.h>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
namespace QmlEditorWidgets {
class PixmapItem : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
Q_PROPERTY(QPointF pos READ pos WRITE setPos)
public:
PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix) { }
};
class EasingSimulation : public QObject
{
Q_OBJECT
public:
QGraphicsView *m_g;
EasingSimulation(QObject *parent=0, QGraphicsView *v=0):QObject(parent) {
m_qtLogo = new PixmapItem(QPixmap(QLatin1String(":/qt_logo.png")));
m_scene.addItem(m_qtLogo);
m_scene.setSceneRect(0,0,v->viewport()->width(),m_qtLogo->boundingRect().height());
m_qtLogo->hide();
m_sequential = 0;
m_g = v;
m_g->setScene(&m_scene);
}
~EasingSimulation() { delete m_qtLogo; }
QGraphicsScene *scene() { return &m_scene; }
void show() { m_qtLogo->show(); }
void hide() { m_qtLogo->hide(); }
void reset() {
m_qtLogo->setPos(0,0);
m_scene.setSceneRect(0,0,m_g->viewport()->width(),m_qtLogo->boundingRect().height());
}
void stop() {
if (m_sequential) {
m_sequential->stop();
reset();
emit finished();
}
}
bool running() {
if (m_sequential)
return m_sequential->state()==QAbstractAnimation::Running;
else
return false;
}
void updateCurve(QEasingCurve newCurve, int newDuration) {
if (running()) {
m_sequential->pause();
static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setEasingCurve(newCurve);
static_cast<QPropertyAnimation *>(m_sequential->animationAt(1))->setDuration(newDuration);
m_sequential->resume();
}
}
void animate(int duration, const QEasingCurve &curve) {
reset();
m_sequential = new QSequentialAnimationGroup;
connect(m_sequential,&QAbstractAnimation::finished,this,&EasingSimulation::finished);
m_sequential->addPause(150);
QPropertyAnimation *m_anim = new QPropertyAnimation (m_qtLogo, "pos");
m_anim->setStartValue(QPointF(0, 0));
m_anim->setEndValue(QPointF(m_scene.sceneRect().width() - m_qtLogo->boundingRect().width(), 0));
m_anim->setDuration(duration);
m_anim->setEasingCurve(curve);
m_sequential->addAnimation(m_anim);
m_sequential->addPause(300);
m_sequential->start();
}
signals:
void finished();
private:
PixmapItem *m_qtLogo;
QGraphicsScene m_scene;
QSequentialAnimationGroup *m_sequential;
};
EasingContextPane::EasingContextPane(QWidget *parent) :
QWidget(parent),
ui(new Ui::EasingContextPane)
{
ui->setupUi(this);
m_simulation = new EasingSimulation(this,ui->graphicsView);
m_easingGraph = new EasingGraph(this);
m_easingGraph->raise();
setLinear();
ui->playButton->setIcon(Utils::Icons::RUN_SMALL.icon());
setGraphDisplayMode(GraphMode);
connect(m_simulation,&EasingSimulation::finished,this,&EasingContextPane::switchToGraph);
}
EasingContextPane::~EasingContextPane()
{
delete ui;
}
bool EasingContextPane::acceptsType(const QStringList &types)
{
return types.contains(QLatin1String("NumberAnimation")) ||
types.contains(QLatin1String("PropertyAnimation")) ||
types.contains(QLatin1String("ColorAnimation")) ||
types.contains(QLatin1String("RotationAnimation"));
}
void EasingContextPane::setProperties(QmlJS::PropertyReader *propertyReader)
{
m_easingGraph->setGeometry(ui->graphicsView->geometry().adjusted(2,2,-2,-2));
QString newEasingType = QLatin1String("Linear");
if (propertyReader->hasProperty(QLatin1String("easing.type"))) {
newEasingType = propertyReader->readProperty(QLatin1String("easing.type")).toString();
if (newEasingType.contains(QLatin1Char('.')))
newEasingType = newEasingType.right(newEasingType.length() - newEasingType.indexOf(QLatin1Char('.')) - 1);
}
m_easingGraph->setEasingName(newEasingType);
ui->easingShapeComboBox->setCurrentIndex(ui->easingShapeComboBox->findText(m_easingGraph->easingShape()));
ui->easingExtremesComboBox->setCurrentIndex(ui->easingExtremesComboBox->findText(m_easingGraph->easingExtremes()));
if (propertyReader->hasProperty(QLatin1String("easing.period"))) {
qreal period = propertyReader->readProperty(QLatin1String("easing.period")).toDouble();
if (period < ui->periodSpinBox->minimum() || period > ui->periodSpinBox->maximum())
ui->periodSpinBox->setValue(ui->periodSpinBox->minimum());
else
ui->periodSpinBox->setValue(period);
}
else
ui->periodSpinBox->setValue(0.3);
if (propertyReader->hasProperty(QLatin1String("easing.amplitude"))) {
qreal amplitude = propertyReader->readProperty(QLatin1String("easing.amplitude")).toDouble();
if (amplitude < ui->amplitudeSpinBox->minimum() || amplitude > ui->amplitudeSpinBox->maximum())
ui->amplitudeSpinBox->setValue(ui->amplitudeSpinBox->minimum());
else
ui->amplitudeSpinBox->setValue(amplitude);
}
else
ui->amplitudeSpinBox->setValue(1.0);
if (propertyReader->hasProperty(QLatin1String("easing.overshoot"))) {
qreal overshoot = propertyReader->readProperty(QLatin1String("easing.overshoot")).toDouble();
if (overshoot < ui->overshootSpinBox->minimum() || overshoot > ui->overshootSpinBox->maximum())
ui->overshootSpinBox->setValue(ui->overshootSpinBox->minimum());
else
ui->overshootSpinBox->setValue(overshoot);
}
else
ui->overshootSpinBox->setValue(1.70158);
if (propertyReader->hasProperty(QLatin1String("duration"))) {
qreal duration = propertyReader->readProperty(QLatin1String("duration")).toInt();
if (duration < ui->durationSpinBox->minimum() || duration > ui->durationSpinBox->maximum())
ui->durationSpinBox->setValue(ui->durationSpinBox->minimum());
else
ui->durationSpinBox->setValue(duration);
}
else
ui->durationSpinBox->setValue(250);
}
void EasingContextPane::setGraphDisplayMode(GraphDisplayMode newMode)
{
m_displayMode = newMode;
switch (newMode) {
case GraphMode: {
m_simulation->hide();
m_easingGraph->show();
break;
}
case SimulationMode: {
m_simulation->show();
m_easingGraph->hide();
break;
}
default: break;
}
}
void EasingContextPane::startAnimation()
{
if (m_simulation->running()) {
m_simulation->stop();
} else {
m_simulation->animate(ui->durationSpinBox->value(), m_easingGraph->easingCurve());
ui->playButton->setIcon(Utils::Icons::STOP_SMALL.icon());
}
}
void EasingContextPane::switchToGraph()
{
ui->playButton->setIcon(Utils::Icons::RUN_SMALL.icon());
setGraphDisplayMode(GraphMode);
}
void EasingContextPane::setOthers()
{
ui->easingExtremesComboBox->setEnabled(true);
ui->amplitudeSpinBox->setEnabled(false);
ui->overshootSpinBox->setEnabled(false);
ui->overshootSpinBox->setEnabled(false);
ui->periodSpinBox->setEnabled(false);
}
void EasingContextPane::setLinear()
{
ui->easingExtremesComboBox->setEnabled(false);
ui->amplitudeSpinBox->setEnabled(false);
ui->overshootSpinBox->setEnabled(false);
ui->periodSpinBox->setEnabled(false);
}
void EasingContextPane::setBack()
{
ui->easingExtremesComboBox->setEnabled(true);
ui->amplitudeSpinBox->setEnabled(false);
ui->overshootSpinBox->setEnabled(true);
ui->periodSpinBox->setEnabled(false);
}
void EasingContextPane::setElastic()
{
ui->easingExtremesComboBox->setEnabled(true);
ui->amplitudeSpinBox->setEnabled(true);
ui->overshootSpinBox->setEnabled(false);
ui->periodSpinBox->setEnabled(true);
}
void EasingContextPane::setBounce()
{
ui->easingExtremesComboBox->setEnabled(true);
ui->amplitudeSpinBox->setEnabled(true);
ui->overshootSpinBox->setEnabled(false);
ui->periodSpinBox->setEnabled(false);
}
} //QmlDesigner
void QmlEditorWidgets::EasingContextPane::on_durationSpinBox_valueChanged(int newValue)
{
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("duration"), newValue);
}
void QmlEditorWidgets::EasingContextPane::on_easingShapeComboBox_currentIndexChanged(const QString &newShape)
{
if (newShape==QLatin1String("Linear"))
setLinear();
else if (newShape==QLatin1String("Bounce"))
setBounce();
else if (newShape==QLatin1String("Elastic"))
setElastic();
else if (newShape==QLatin1String("Back"))
setBack();
else
setOthers();
if (m_easingGraph->easingShape() != newShape) {
m_easingGraph->setEasingShape(newShape);
// reload easing parameters
m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());
m_easingGraph->setPeriod(ui->periodSpinBox->value());
m_easingGraph->setOvershoot(ui->overshootSpinBox->value());
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.type"), QVariant(QLatin1String("Easing.")+m_easingGraph->easingName()));
}
}
void QmlEditorWidgets::EasingContextPane::on_easingExtremesComboBox_currentIndexChanged(const QString &newExtremes)
{
if (m_easingGraph->easingExtremes() != newExtremes) {
m_easingGraph->setEasingExtremes(newExtremes);
m_easingGraph->setAmplitude(ui->amplitudeSpinBox->value());
m_easingGraph->setPeriod(ui->periodSpinBox->value());
m_easingGraph->setOvershoot(ui->overshootSpinBox->value());
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.type"), QVariant(QLatin1String("Easing.")+m_easingGraph->easingName()));
}
}
void QmlEditorWidgets::EasingContextPane::on_amplitudeSpinBox_valueChanged(double newAmplitude)
{
if ((newAmplitude != m_easingGraph->amplitude()) &&
(m_easingGraph->easingShape()==QLatin1String("Bounce")
|| m_easingGraph->easingShape()==QLatin1String("Elastic"))) {
m_easingGraph->setAmplitude(newAmplitude);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.amplitude"), newAmplitude);
}
}
void QmlEditorWidgets::EasingContextPane::on_periodSpinBox_valueChanged(double newPeriod)
{
if ((newPeriod != m_easingGraph->period()) && (m_easingGraph->easingShape()==QLatin1String("Elastic"))) {
m_easingGraph->setPeriod(newPeriod);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.period"), newPeriod);
}
}
void QmlEditorWidgets::EasingContextPane::on_overshootSpinBox_valueChanged(double newOvershoot)
{
if ((newOvershoot != m_easingGraph->overshoot()) && (m_easingGraph->easingShape()==QLatin1String("Back"))) {
m_easingGraph->setOvershoot(newOvershoot);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.overshoot"), newOvershoot);
}
}
void QmlEditorWidgets::EasingContextPane::on_playButton_clicked()
{
setGraphDisplayMode(SimulationMode);
startAnimation();
}
#include "easingcontextpane.moc"
| 35.922865 | 123 | 0.68635 | [
"geometry"
] |
3a7ee6d1a2144e659da2bdb292b86af60d668104 | 13,852 | cpp | C++ | XV8/XV8.cpp | web-atoms/xamarin-v8 | 22e67bd7e100fbfdfe0fb2600e47f609baa2020a | [
"MIT"
] | 6 | 2020-04-26T04:55:33.000Z | 2021-12-03T05:53:21.000Z | XV8/XV8.cpp | web-atoms/xamarin-v8 | 22e67bd7e100fbfdfe0fb2600e47f609baa2020a | [
"MIT"
] | 5 | 2020-10-06T19:29:20.000Z | 2022-02-27T09:21:35.000Z | XV8/XV8.cpp | web-atoms/xamarin-v8 | 22e67bd7e100fbfdfe0fb2600e47f609baa2020a | [
"MIT"
] | 3 | 2020-09-23T15:31:33.000Z | 2022-02-13T20:11:12.000Z | #include "v8.h"
#include <stdlib.h>
#include "libplatform.h"
using namespace v8;
typedef char* XString;
/**
Everything is sent as a pointer to Persistent object, reason is, JavaScript engine should
not destroy it till it is explicitly destroyed by host application.
*/
typedef Persistent<Value, CopyablePersistentTraits<Value>>* V8Handle;
enum V8ResponseType : int16_t {
Error = 0,
Handle = 1,
String = 2
};
enum V8HandleType : int16_t {
None = 0,
Undefined = 1,
Null = 2,
Number = 3,
NotANumber = 4,
BigInt = 5,
Boolean = 6,
String = 0xFF,
Object = 0xF0,
Function = 0xF1,
Array = 0xF2,
Remote = 0xF3,
Date = 0xF4
};
typedef union {
bool boolValue;
int32_t intValue;
int64_t longValue;
double doubleValue;
XString stringValue;
} V8Value;
XString V8StringToXString(Local<Context> context, Local<v8::String> text);
/*
When a call is made from outside, response will indicate success/failure
and it will contain the value. In case of string, the response must be
disposed by the caller by calling V8Context_Release method.
*/
struct V8Response
{
public:
V8ResponseType type;
union {
struct {
V8Handle handle;
V8HandleType handleType;
V8Value value;
} handle;
struct {
XString message;
XString stack;
} error;
XString stringValue;
long longValue;
} result;
static V8Response From(Local<Context> context, Local<Value> handle);
static V8Response FromError(Local<Context> context, Local<Value> error);
static V8Response ToString(Local<Context> context, Local<Value> error);
};
static bool _V8Initialized = false;
typedef V8Response(*ExternalCall)(V8Response target, V8Response args);
class V8Context {
protected:
int32_t _engineID;
std::unique_ptr<Platform> _platform;
Isolate* _isolate;
Persistent<Context, CopyablePersistentTraits<Context>> _context;
// delete array allocator
ArrayBuffer::Allocator* _arrayBufferAllocator;
Local<Context> GetContext() {
return _context.Get(_isolate);
}
public:
V8Context();
void Dispose();
void Release(V8Handle handle);
V8Response CreateObject();
V8Response CreateNull();
V8Response CreateUndefined();
V8Response CreateBoolean(bool value);
V8Response CreateNumber(double value);
V8Response CreateString(XString value);
V8Response CreateDate(int64_t value);
V8Response CreateFunction(ExternalCall function, XString debugHelper);
V8Response Evaluate(XString script, XString location);
V8Response GetProperty(V8Handle target, XString name);
V8Response SetProperty(V8Handle target, XString name, V8Handle value);
V8Response GetPropertyAt(V8Handle target, int index);
V8Response SetPropertyAt(V8Handle target, int index, V8Handle value);
private:
};
V8Context* V8Context_Create() {
return new V8Context();
}
void V8Context_Dispose(V8Context* context) {
context->Dispose();
delete context;
}
V8Response V8Context_CreateString(V8Context* context, XString value) {
return context->CreateString(value);
}
V8Response V8Context_CreateDate(V8Context* context, int64_t value) {
return context->CreateDate(value);
}
V8Response V8Context_CreateBoolean(V8Context* context, bool value) {
return context->CreateBoolean(value);
}
V8Response V8Context_CreateNumber(V8Context* context, double value) {
return context->CreateNumber(value);
}
V8Response V8Context_CreateObject(V8Context* context) {
return context->CreateObject();
}
V8Response V8Context_CreateNull(V8Context* context) {
return context->CreateNull();
}
V8Response V8Context_CreateUndefined(V8Context* context) {
return context->CreateUndefined();
}
V8Response V8Context_GetProperty(
V8Context* context,
V8Handle target,
XString text) {
return context->GetProperty(target, text);
}
V8Response V8Context_GetPropertyAt(
V8Context* context,
V8Handle target,
int index) {
return context->GetPropertyAt(target, index);
}
V8Response V8Context_SetProperty(
V8Context* context,
V8Handle target,
XString text,
V8Handle value) {
return context->SetProperty(target, text, value);
}
V8Response V8Context_SetPropertyAt(
V8Context* context,
V8Handle target,
int index,
V8Handle value) {
return context->SetPropertyAt(target, index, value);
}
V8Response V8Context_Evaluate(V8Context* context, XString script, XString location) {
return context->Evaluate(script, location);
}
V8Response V8Response::From(Local<Context> context, Local<Value> handle)
{
V8Response v = V8Response();
v.type = V8ResponseType::Handle;
Isolate* isolate = context->GetIsolate();
if (handle.IsEmpty()) {
return FromError(context, v8::String::NewFromUtf8(isolate, "Unexpected empty value").ToLocalChecked());
}
// for handle, we need to set the type..
if (handle->IsUndefined()) {
v.result.handle.handleType = V8HandleType::Undefined;
}
else if (handle->IsNull()) {
v.result.handle.handleType = V8HandleType::Null;
}
else if (handle->IsString() || handle->IsStringObject()) {
v.result.handle.handleType = V8HandleType::String;
}
else if (handle->IsBoolean() || handle->IsBooleanObject()) {
v.result.handle.handleType = V8HandleType::Boolean;
v.result.handle.value.boolValue = handle->BooleanValue(isolate);
}
else if (handle->IsNumber() || handle->IsNumberObject()) {
double d;
if (handle->NumberValue(context).To(&d)) {
v.result.handle.handleType = V8HandleType::Number;
v.result.handle.value.doubleValue = d;
}
else {
v.result.handle.handleType = V8HandleType::NotANumber;
}
}
else if (handle->IsDate()) {
v.result.handle.handleType = V8HandleType::Date;
v.result.handle.value.doubleValue = handle->ToObject(context).ToLocalChecked().As<v8::Date>()->ValueOf();
}
else if (handle->IsArray()
|| handle->IsArgumentsObject()
|| handle->IsBigInt64Array()) {
v.result.handle.handleType = V8HandleType::Array;
}
else if (handle->IsObject()) {
v.result.handle.handleType = V8HandleType::Object;
}
v.result.handle.handle = new Persistent<Value, CopyablePersistentTraits<Value>>();
v.result.handle.handle->Reset(isolate, handle);
return v;
}
V8Response V8Response::FromError(Local<Context> context, Local<Value> error) {
V8Response v = V8Response();
v.type = V8ResponseType::Error;
Isolate* isolate = context->GetIsolate();
MaybeLocal<v8::Object> obj = error->ToObject(context);
Local<v8::Object> local = obj.ToLocalChecked();
Local<v8::Name> name = v8::String::NewFromUtf8(isolate, "stack").ToLocalChecked();
if (local->HasOwnProperty(context, name).ToChecked()) {
Local<v8::Value> stack = local->Get(context, name).ToLocalChecked();
v.result.error.stack = V8StringToXString(context, stack.As<v8::String>());
}
else {
v.result.error.stack = nullptr;
}
Local<v8::String> msg = local->ToString(context).ToLocalChecked();
v.result.error.message = V8StringToXString(context, msg);
return v;
}
XString V8StringToXString(Local<Context> context, Local<v8::String> text) {
if (text.IsEmpty())
return nullptr;
Isolate* isolate = context->GetIsolate();
int len = text->Utf8Length(isolate);
char* atext = (char*)malloc(len);
text->WriteUtf8(isolate, atext, len);
return atext;
}
V8Response V8Response::ToString(Local<Context> context, Local<Value> value) {
V8Response v = V8Response();
v.type = V8ResponseType::String;
Local<v8::String> s = value->ToString(context).ToLocalChecked();
v.result.stringValue = V8StringToXString(context, s);
return v;
}
int V8Context_Release(V8Response r) {
if (r.type == V8ResponseType::Error) {
if (r.result.error.message != nullptr) {
delete r.result.error.message;
}
if (r.result.error.stack != nullptr) {
delete r.result.error.stack;
}
} else {
if (r.type == V8ResponseType::String) {
delete r.result.stringValue;
}
}
return 0;
}
int V8Context_ReleaseHandle(V8Handle r) {
r->Reset();
delete r;
return 0;
}
V8Context::V8Context() {
if (!_V8Initialized) // (the API changed: https://groups.google.com/forum/#!topic/v8-users/wjMwflJkfso)
{
V8::InitializeICU();
//?v8::V8::InitializeExternalStartupData(PLATFORM_TARGET "\\");
// (Startup data is not included by default anymore)
_platform = platform::NewDefaultPlatform();
V8::InitializePlatform(_platform.get());
V8::Initialize();
_V8Initialized = true;
}
Isolate::CreateParams params;
_arrayBufferAllocator = ArrayBuffer::Allocator::NewDefaultAllocator();
params.array_buffer_allocator = _arrayBufferAllocator;
_isolate = Isolate::New(params);
Local<v8::ObjectTemplate> global = ObjectTemplate::New(_isolate);
Local<v8::Context> c = Context::New(_isolate, nullptr, global);
_context.Reset(_isolate, c);
}
void V8Context::Dispose() {
_context.Reset();
_isolate->Dispose();
// delete _Isolate;
delete _arrayBufferAllocator;
}
V8Response V8Context::CreateObject() {
return V8Response::From(GetContext(), Object::New(_isolate));
}
V8Response V8Context::CreateNumber(double value) {
return V8Response::From(GetContext(), Number::New(_isolate, value));
}
V8Response V8Context::CreateBoolean(bool value) {
return V8Response::From(GetContext(), v8::Boolean::New(_isolate, value));
}
V8Response V8Context::CreateUndefined() {
return V8Response::From(GetContext(), v8::Undefined(_isolate));
}
V8Response V8Context::CreateNull() {
return V8Response::From(GetContext(), v8::Null(_isolate));
}
V8Response V8Context::CreateString(XString value) {
return V8Response::From(GetContext(), v8::String::NewFromUtf8(_isolate, value).ToLocalChecked());
}
V8Response V8Context::CreateDate(int64_t value) {
return V8Response::From(GetContext(), v8::Date::New(GetContext(), (double)value).ToLocalChecked());
}
void X8Call(const FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context(isolate->GetCurrentContext());
ExternalCall function = (ExternalCall)(args.Data()->ToBigInt(context).ToLocalChecked()->Uint64Value());
HandleScope scope(isolate);
uint32_t n = args.Length();
Local<v8::Array> a = v8::Array::New(isolate, n);
for (uint32_t i = 0; i < n; i++) {
a->Set(context, i, args[i]).Check();
}
V8Response target = V8Response::From(context, args.This());
V8Response handleArgs = V8Response::From(context, a);
V8Response r = function(target, handleArgs);
if (r.type == V8ResponseType::Error) {
Local<v8::String> error = v8::String::NewFromUtf8(isolate, r.result.error.message).ToLocalChecked();
Local<Value> ex = Exception::Error(error);
isolate->ThrowException(ex);
delete r.result.error.message;
} else if (r.type == V8ResponseType::String) {
args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, r.result.stringValue).ToLocalChecked());
delete r.result.stringValue;
}
else {
Local<Value> rx = r.result.handle.handle->Get(isolate);
args.GetReturnValue().Set(rx);
delete r.result.handle.handle;
}
}
V8Response V8Context::CreateFunction(ExternalCall function, XString debugHelper) {
Local<Value> v = v8::BigInt::NewFromUnsigned(_isolate, (uint64_t)function);
Local<Context> context(_isolate->GetCurrentContext());
; Local<v8::Function> f = v8::Function::New(context, X8Call, v).ToLocalChecked();
Local<v8::String> n = v8::String::NewFromUtf8(_isolate, debugHelper).ToLocalChecked();
f->SetName(n);
return V8Response::From(GetContext(), f);
}
V8Response V8Context::Evaluate(XString script, XString location) {
HandleScope scoppe(_isolate);
TryCatch tryCatch(_isolate);
Local<Context> context(_isolate->GetCurrentContext());
ScriptOrigin origin(String::NewFromUtf8(_isolate, location).ToLocalChecked());
Local<v8::String> sc = String::NewFromUtf8(_isolate, script).ToLocalChecked();
Local<Script> s;
if (!Script::Compile(context, sc, &origin).ToLocal(&s)) {
return V8Response::FromError(context, tryCatch.Exception());
}
Local<Value> result;
if (!s->Run(context).ToLocal(&result)) {
return V8Response::FromError(context, tryCatch.Exception());
}
return V8Response::From(context, result);
}
void V8Context::Release(V8Handle handle) {
handle->Reset();
delete handle;
}
V8Response V8Context::GetProperty(V8Handle target, XString name) {
Local<Value> v = target->Get(_isolate);
Local<Context> context = GetContext();
if (!v->IsObject())
return V8Response::FromError(context, v8::String::NewFromUtf8(_isolate, "This is not an object").ToLocalChecked());
Local<v8::String> jsName = v8::String::NewFromUtf8(_isolate, name).ToLocalChecked();
Local<Value> item = v->ToObject(context).ToLocalChecked()->Get(context, jsName).ToLocalChecked();
return V8Response::From(context, item);
}
V8Response V8Context::GetPropertyAt(V8Handle target, int index) {
Local<Value> v = target->Get(_isolate);
Local<Context> context = GetContext();
if (!v->IsArray())
return V8Response::FromError(context, v8::String::NewFromUtf8(_isolate, "This is not an array").ToLocalChecked());
Local<Value> item = v->ToObject(context).ToLocalChecked()->Get(context, index).ToLocalChecked();
return V8Response::From(context, item);
}
V8Response V8Context::SetProperty(V8Handle target, XString name, V8Handle value) {
Local<Value> t = target->Get(_isolate);
Local<Value> v = value->Get(_isolate);
Local<Context> context = GetContext();
if (!t->IsObject())
return V8Response::FromError(context, v8::String::NewFromUtf8(_isolate, "This is not an object").ToLocalChecked());
Local<v8::String> jsName = v8::String::NewFromUtf8(_isolate, name).ToLocalChecked();
t->ToObject(context).ToLocalChecked()->Set(context, jsName, v).ToChecked();
return V8Response::From(context, v);
}
V8Response V8Context::SetPropertyAt(V8Handle target, int index, V8Handle value) {
Local<Value> t = target->Get(_isolate);
Local<Value> v = value->Get(_isolate);
Local<Context> context = GetContext();
if (!t->IsArray())
return V8Response::FromError(context, v8::String::NewFromUtf8(_isolate, "This is not an array").ToLocalChecked());
t->ToObject(context).ToLocalChecked()->Set(context, index, v).ToChecked();
return V8Response::From(context, v);
} | 29.285412 | 117 | 0.736572 | [
"object"
] |
3a8339d85d7342f65f1c09c0b4149443172f3f46 | 1,891 | cpp | C++ | Command/Editor/EditorTests/InsertImageCommandTests.cpp | chosti34/ood | 3d74b5253f667d3de1ee610fb7509cf3015ea79c | [
"MIT"
] | null | null | null | Command/Editor/EditorTests/InsertImageCommandTests.cpp | chosti34/ood | 3d74b5253f667d3de1ee610fb7509cf3015ea79c | [
"MIT"
] | 9 | 2018-02-09T06:12:29.000Z | 2018-06-06T06:26:40.000Z | Command/Editor/EditorTests/InsertImageCommandTests.cpp | chosti34/ood | 3d74b5253f667d3de1ee610fb7509cf3015ea79c | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "../InsertImageCommand.h"
#include "ImageFileStorageMock.h"
#include "../Image.h"
#include "../CommandManager.h"
#include <boost/test/tools/output_test_stream.hpp>
namespace
{
struct InsertImageCommandFixture
{
InsertImageCommandFixture()
: storage(std::make_shared<ImageFileStorageMock>(&strm))
, manager(10)
{
}
std::unique_ptr<InsertImageCommand> CreateAndExecuteCommand()
{
auto image = std::make_shared<Image>(storage->AddImage("%TEMP%/image.jpg"), 100, 500, manager);
auto command = std::make_unique<InsertImageCommand>(boost::none, image, items, storage);
command->Execute();
return command;
}
std::shared_ptr<ImageFileStorageMock> storage;
CommandManager manager;
std::vector<std::shared_ptr<DocumentItem>> items;
boost::test_tools::output_test_stream strm;
};
}
BOOST_FIXTURE_TEST_SUITE(CInsertImageCommand, InsertImageCommandFixture)
BOOST_AUTO_TEST_CASE(image_will_be_copied_by_storage_on_execute_once_when_command_destroyed)
{
{
auto command = CreateAndExecuteCommand();
}
storage->CopyTo("C:/Windows");
BOOST_CHECK(strm.is_equal("%TEMP%/image.jpg copied to C:/Windows"));
}
BOOST_AUTO_TEST_CASE(image_will_not_be_copied_and_will_be_deleted_from_storage_if_command_is_unexecuted)
{
{
auto command = CreateAndExecuteCommand();
command->Unexecute();
storage->CopyTo("C:/Windows");
}
BOOST_CHECK(strm.is_equal("Delete %TEMP%/image.jpg"));
}
BOOST_AUTO_TEST_CASE(image_will_be_copied_and_will_not_be_deleted_from_storage_if_command_is_executed_twice)
{
{
auto command = CreateAndExecuteCommand();
command->Unexecute();
storage->CopyTo("C:/Windows");
BOOST_CHECK(strm.is_empty());
command->Execute();
}
BOOST_CHECK(strm.is_empty());
storage->CopyTo("C:/Windows");
BOOST_CHECK(strm.is_equal("%TEMP%/image.jpg copied to C:/Windows"));
}
BOOST_AUTO_TEST_SUITE_END()
| 27.014286 | 109 | 0.756742 | [
"vector"
] |
3a8a7b42f90482da2113ce434849acacafa79c2e | 423 | cpp | C++ | devertexwahn/flatland/tests/third_party/eigen_test.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | 62 | 2021-09-21T18:58:02.000Z | 2022-03-07T02:17:43.000Z | devertexwahn/flatland/tests/third_party/eigen_test.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | null | null | null | devertexwahn/flatland/tests/third_party/eigen_test.cpp | Vertexwahn/FlatlandRT | 37d09fde38b25eff5f802200b43628efbd1e3198 | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-FileCopyrightText: 2022 Julian Amann <dev@vertexwahn.de>
* SPDX-License-Identifier: Apache-2.0
*/
#include "include/gmock/gmock.h"
#include "Eigen/Geometry"
TEST(Eigen, Eigen_Translate) {
Eigen::Affine3f transform(Eigen::Translation3f(1,2,3));
Eigen::Matrix4f matrix = transform.matrix();
EXPECT_THAT(matrix(0,3), testing::FloatEq(1.f));
EXPECT_THAT(matrix(1,3), testing::FloatEq(2.f));
} | 26.4375 | 65 | 0.699764 | [
"geometry",
"transform"
] |
3a8e8fdd54ff5239c9af9f0691f27ce0752f8476 | 20,625 | cpp | C++ | utils/ResourceLibrary.cpp | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | utils/ResourceLibrary.cpp | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | utils/ResourceLibrary.cpp | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | #include <log4cxx/logger.h>
#include <KrisLibrary/Logger.h>
#include "ResourceLibrary.h"
#include "AnyCollection.h"
#include "stringutils.h"
#include "fileutils.h"
#include "ioutils.h"
#include <set>
#include <fstream>
#include <sstream>
#if HAVE_TINYXML
#include <tinyxml.h>
#else
class TiXmlElement {};
#endif
using namespace std;
template <> const char* BasicResource<int>::className = "int";
template <> const char* BasicResource<double>::className = "double";
template <> const char* BasicResource<std::string>::className = "string";
template <> const char* BasicArrayResource<int>::className = "vector<int>";
template <> const char* BasicArrayResource<double>::className = "vector<double>";
template <> const char* BasicArrayResource<std::string>::className = "vector<string>";
template class BasicResource<int>;
template class BasicResource<double>;
template class BasicResource<std::string>;
template class BasicArrayResource<int>;
template class BasicArrayResource<double>;
//specialization to allow for whitespace in strings
template <>
bool BasicArrayResource<std::string>::Load(std::istream& in) {
size_t n;
in>>n;
if(in.bad()) return false;
data.resize(n);
for(size_t i=0;i<n;i++) {
if(!SafeInputString(in,data[i])) return false;
}
return true;
}
//specialization to allow for whitespace in strings
template <>
bool BasicArrayResource<std::string>::Save(std::ostream& out) {
out<<data.size()<<'\t';
for(size_t i=0;i<data.size();i++) {
SafeOutputString(out,data[i]);
if(i+1!=data.size()) out<<" ";
}
out<<std::endl;
return true;
}
template class BasicArrayResource<std::string>;
vector<ResourcePtr> ResourcesByType(std::vector<ResourcePtr>& resources,const std::string& type)
{
vector<ResourcePtr> res;
for(size_t i=0;i<resources.size();i++)
if(type == resources[i]->Type())
res.push_back(resources[i]);
return res;
}
vector<string> ResourceTypes(const vector<ResourcePtr>& resources)
{
set<string> types;
for(size_t i=0;i<resources.size();i++)
types.insert(resources[i]->Type());
return vector<string>(types.begin(),types.end());
}
ResourceBase::ResourceBase()
{}
ResourceBase::ResourceBase(const string& _name)
:name(_name)
{}
ResourceBase::ResourceBase(const string& _name,const string& fn)
:name(_name),fileName(fn)
{}
bool ResourceBase::Load(AnyCollection& c)
{
string data;
if(c["data"].as<string>(data)) {
stringstream ss(data);
return Load(ss);
}
return false;
}
bool ResourceBase::Save(AnyCollection& c)
{
stringstream ss;
if(!Save(ss)) return false;
c["data"] = ss.str();
return true;
}
bool ResourceBase::Load(TiXmlElement* in)
{
#if HAVE_TINYXML
if(in->GetText()) {
stringstream ss(in->GetText());
return Load(ss);
}
#endif
return false;
}
bool ResourceBase::Save(TiXmlElement* out)
{
#if HAVE_TINYXML
stringstream ss;
if(!Save(ss)) return false;
TiXmlText text(ss.str().c_str());
text.SetCDATA(true);
out->InsertEndChild(text);
return true;
#else
return false;
#endif //HAVE_TINYXML
}
bool ResourceBase::Load(const string& fn)
{
ifstream in(fn.c_str(),ios::in);
if(!in) return false;
if(!Load(in)) {
#if HAVE_TINYXML
TiXmlDocument doc;
if(doc.LoadFile(fn)) {
if(Load(doc.RootElement())) {
fileName = fn;
return true;
}
}
#endif
return false;
}
fileName = fn;
return true;
}
bool ResourceBase::Load()
{
return Load(fileName);
}
bool ResourceBase::Save(const string& fn)
{
//create the path if it does not exist
string path = GetFilePath(fn);
if(!path.empty()) {
if(!FileUtils::IsDirectory(path.c_str()))
FileUtils::MakeDirectory(path.c_str());
}
//save
ofstream out(fn.c_str(),ios::out);
if(!out) return false;
if(Save(out)) return true;
out.close();
#if HAVE_TINYXML
TiXmlDocument doc;
TiXmlElement* element = new TiXmlElement("ResourceBase");
doc.LinkEndChild(element);
if(Save(doc.RootElement())) {
if(doc.SaveFile(fn)) {
return true;
}
}
#endif
return false;
}
bool ResourceBase::Save()
{
return Save(fileName);
}
bool CompoundResourceBase::Extract(const char* subtype,std::vector<ResourcePtr>& subobjects)
{
std::vector<ResourcePtr> all;
if(Unpack(all)) {
subobjects = ResourcesByType(all,subtype);
if(subobjects.empty()) {
//no objects -- do we extract of this given type?
vector<string> extractTypes = ExtractTypes();
for(size_t i=0;i<extractTypes.size();i++)
if(subtype == extractTypes[i]) return true;
return false;
}
else
return true;
}
return false;
}
void ResourceLibrary::Clear()
{
itemsByName.clear();
itemsByType.clear();
}
bool ResourceLibrary::SaveXml(const std::string& fn)
{
#if HAVE_TINYXML
TiXmlDocument doc;
TiXmlElement* element = new TiXmlElement("resource_library");
doc.LinkEndChild(element);
if(!Save(element)) return false;
return doc.SaveFile(fn.c_str());
#else
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::SaveXml(): tinyxml not defined\n");
return false;
#endif
}
bool ResourceLibrary::Save(TiXmlElement* root)
{
#if HAVE_TINYXML
root->SetValue("resource_library");
Assert(root != NULL);
bool res=true;
for(Map::iterator i=itemsByType.begin();i!=itemsByType.end();i++) {
for(size_t j=0;j<i->second.size();j++) {
TiXmlElement* c = new TiXmlElement(i->first.c_str());
c->SetAttribute("name",i->second[j]->name.c_str());
if(!i->second[j]->fileName.empty())
c->SetAttribute("file",i->second[j]->fileName.c_str());
if(i->second[j]->Save(c)) {
//ok, saved directly to TiXmlElement
root->LinkEndChild(c);
}
else {
if(!i->second[j]->Save()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::SaveXml(): "<<i->second[j]->name<<" failed to save to "<<i->second[j]->fileName<<"\n");
res=false;
delete c;
}
else {
root->LinkEndChild(c);
}
}
}
}
return res;
#else
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Save(): tinyxml not defined\n");
return false;
#endif
}
bool ResourceLibrary::SaveJSON(std::ostream& s)
{
AnyCollection c;
if(!Save(c)) return false;
c.write(s);
return true;
}
bool ResourceLibrary::Save(AnyCollection& c)
{
c.clear();
c.resize(itemsByType.size());
int k=0;
for(Map::iterator i=itemsByType.begin();i!=itemsByType.end();i++,k++) {
for(size_t j=0;j<i->second.size();j++) {
if(i->second[j]->Save(c[k])) {
//ok, saved directly to AnyCollection
c[k]["type"] = string(i->second[j]->Type());
c[k]["name"] = i->second[j]->name;
}
else if(!i->second[j]->fileName.empty()) {
c[k]["type"] = string(i->second[j]->Type());
c[k]["name"] = i->second[j]->name;
c[k]["file"] = i->second[j]->fileName;
if(!i->second[j]->Save()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Save(): "<<i->second[j]->name<<" failed to save to "<<i->second[j]->fileName<<"\n");
return false;
}
}
else {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Save(): "<<i->second[j]->name<<" failed to save to AnyCollection or file"<<"\n");
return false;
}
}
}
return true;
}
bool ResourceLibrary::LoadXml(const std::string& fn)
{
#if HAVE_TINYXML
TiXmlDocument doc;
//whitespace needs to be preserved for some items to load properly
TiXmlBase::SetCondenseWhiteSpace(false);
if(!doc.LoadFile(fn.c_str()))
return false;
return Load(doc.RootElement());
#else
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): tinyxml not defined\n");
return false;
#endif
}
bool ResourceLibrary::Load(TiXmlElement* root)
{
#if HAVE_TINYXML
if(0 != strcmp(root->Value(),"resource_library")) return false;
TiXmlElement* element = root->FirstChildElement();
bool res=true;
while(element != NULL) {
if(knownTypes.count(element->Value()) == 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): do not know how to load objects of type "<<element->Value());
res = false;
}
else {
shared_ptr<ResourceBase> resource(knownTypes[element->Value()][0]->Make());
if(element->Attribute("name")!=NULL)
resource->name = element->Attribute("name");
if(element->Attribute("file")!=NULL) {
resource->fileName = element->Attribute("file");
if(!resource->Load()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): error loading element of type "<<element->Value());
res = false;
}
else {
Add(resource);
}
}
else if(!resource->Load(element)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): error loading element of type "<<element->Value());
res = false;
}
else {
Add(resource);
}
}
element = element->NextSiblingElement();
}
return res;
#else
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Load(): tinyxml not defined\n");
return false;
#endif
}
bool ResourceLibrary::LoadJSON(istream& s)
{
AnyCollection c;
if(!c.read(s)) return false;
return Load(c);
}
bool ResourceLibrary::Load(AnyCollection& c)
{
vector<shared_ptr<AnyCollection> > subitems;
c.enumerate(subitems);
for(size_t i=0;i<subitems.size();i++) {
AnyCollection& c=(*subitems[i]);
string type;
if(!c["type"].as<string>(type)) {
LOG4CXX_INFO(KrisLibrary::logger(),"ResourceLibrary::Load: Item "<<i);
return false;
}
if(knownTypes.count(type) == 0) {
LOG4CXX_INFO(KrisLibrary::logger(),"ResourceLibrary::Load: Item "<<i<<" type "<<type.c_str());
return false;
}
shared_ptr<ResourceBase> res(knownTypes[type][0]->Make());
c["name"].as<string>(res->name);
if(c["file"].as<string>(res->fileName)) {
if(!res->Load()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Load: Error reading item "<<i);
return false;
}
}
else if(!res->Load(c)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::Load: Error reading item "<<i);
return false;
}
Add(res);
}
return true;
}
bool ResourceLibrary::LazyLoadXml(const std::string& fn)
{
#if HAVE_TINYXML
TiXmlDocument doc;
if(!doc.LoadFile(fn.c_str()))
return false;
TiXmlElement* element = doc.RootElement()->FirstChildElement();
bool res=true;
while(element != NULL) {
if(knownTypes.count(element->Value()) == 0) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): do not know how to load objects of type "<<element->Value());
res = false;
}
else {
ResourceBase* resource=knownTypes[element->Value()][0]->Make();
if(element->Attribute("name") != NULL)
resource->name = element->Attribute("name");
if(element->Attribute("file") != NULL) {
resource->fileName = element->Attribute("file");
Add(ResourcePtr(resource));
}
else {
if(!resource->Load(element)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LoadXml(): error loading element of type "<<element->Value());
delete resource;
res = false;
}
else
Add(ResourcePtr(resource));
}
}
element = element->NextSiblingElement();
}
return res;
#else
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LazyLoadXml(): tinyxml not defined\n");
return false;
#endif
}
bool ResourceLibrary::LazyLoadJSON(std::istream& s)
{
AnyCollection c;
if(!c.read(s)) return false;
return LazyLoad(c);
}
bool ResourceLibrary::LazyLoad(AnyCollection& c)
{
vector<shared_ptr<AnyCollection> > subitems;
c.enumerate(subitems);
for(size_t i=0;i<subitems.size();i++) {
AnyCollection& c=*subitems[i];
string type;
if(!c["type"].as<string>(type)) {
LOG4CXX_INFO(KrisLibrary::logger(),"ResourceLibrary::LazyLoad: Item "<<i);
return false;
}
if(knownTypes.count(type) == 0) {
LOG4CXX_INFO(KrisLibrary::logger(),"ResourceLibrary::LazyLoad: Item "<<i<<" type "<<type.c_str());
return false;
}
shared_ptr<ResourceBase> res(knownTypes[type][0]->Make());
c["name"].as<string>(res->name);
if(c["file"].as<string>(res->fileName)) {
//lazy load
}
else if(!res->Load(c)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"ResourceLibrary::LazyLoad: Error reading item "<<i);
return false;
}
Add(res);
}
return true;
}
ResourcePtr ResourceLibrary::LoadItem(const string& fn)
{
string ext=FileExtension(fn);
Map::iterator i=loaders.find(ext);
if(i == loaders.end()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"No known loaders for type "<<ext.c_str());
return NULL;
}
for(size_t j=0;j<i->second.size();j++) {
ResourcePtr r(i->second[j]->Make());
if(r->Load(fn)) {
r->name = GetFileName(fn);
StripExtension(r->name);
Add(r);
return r;
}
}
LOG4CXX_ERROR(KrisLibrary::logger(),"Unable to load "<<fn.c_str());
for(size_t j=0;j<i->second.size();j++)
LOG4CXX_ERROR(KrisLibrary::logger()," "<<i->second[j]->Type());
LOG4CXX_ERROR(KrisLibrary::logger(),"\n");
return NULL;
}
bool ResourceLibrary::ReloadAll()
{
bool res=true;
for(Map::iterator i=itemsByName.begin();i!=itemsByName.end();i++) {
for(size_t j=0;j<i->second.size();j++)
if(!i->second[j]->Load()) res=false;
}
return res;
}
bool ResourceLibrary::SaveItem(const string& name)
{
Map::iterator i=itemsByName.find(name);
if(i==itemsByName.end()) return false;
bool res=true;
for(size_t j=0;j<i->second.size();j++)
if(!i->second[j]->Save()) res=false;
return res;
}
bool ResourceLibrary::SaveAll()
{
bool res=true;
for(Map::iterator i=itemsByName.begin();i!=itemsByName.end();i++) {
for(size_t j=0;j<i->second.size();j++)
if(!i->second[j]->Save()) res=false;
}
return res;
}
bool ResourceLibrary::LoadAll(const string& dir)
{
vector<string> files;
FileUtils::ListDirectory(dir.c_str(),files);
bool res=true;
vector<string> path(2);
path[0] = dir;
for(size_t i=0;i<files.size();i++) {
if(files[i] == ".") continue;
if(files[i] == "..") continue;
path[1] = files[i];
string filepath = JoinPath(path);
if(FileUtils::IsDirectory(filepath.c_str())) {
ResourceLibrary sublib;
swap(knownTypes,sublib.knownTypes);
swap(loaders,sublib.loaders);
if(!sublib.LoadAll(filepath)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"Unable to load sub-directory "<<filepath<<"\n");
res = false;
}
for(Map::iterator j=sublib.itemsByName.begin();j!=sublib.itemsByName.end();j++) {
for(size_t k=0;k<j->second.size();k++) {
j->second[k]->name = files[i] + "/" + j->second[k]->name;
Add(j->second[k]);
}
}
swap(knownTypes,sublib.knownTypes);
swap(loaders,sublib.loaders);
}
else {
if(LoadItem(filepath) == NULL) {
LOG4CXX_ERROR(KrisLibrary::logger(),"Unable to load file "<<filepath<<"\n");
res = false;
}
}
}
return res;
}
bool ResourceLibrary::LazyLoadAll(const string& dir)
{
vector<string> files;
FileUtils::ListDirectory(dir.c_str(),files);
bool res=true;
vector<string> path(2);
path[0] = dir;
for(size_t i=0;i<files.size();i++) {
if(files[i] == ".") continue;
if(files[i] == "..") continue;
path[1] = files[i];
string fn = JoinPath(path);
string ext=FileExtension(fn);
Map::iterator it=loaders.find(ext);
if(it == loaders.end()) {
LOG4CXX_ERROR(KrisLibrary::logger(),"Unable to load file "<<fn<<"\n");
res = false;
continue;
}
for(size_t j=0;j<it->second.size();j++) {
ResourcePtr r(it->second[j]->Make());
r->name = GetFileName(fn);
StripExtension(r->name);
Add(r);
return true;
}
}
return res;
}
void ResourceLibrary::AddBaseDirectory(const string& dir)
{
if(dir.empty()) return;
for(Map::iterator i=itemsByName.begin();i!=itemsByName.end();i++) {
for(size_t j=0;j<i->second.size();j++) {
i->second[j]->fileName=JoinPath(dir,i->second[j]->fileName);
}
}
}
void ResourceLibrary::ChangeBaseDirectory(const string& dir)
{
vector<string> oldpath,newpath;
for(Map::iterator i=itemsByName.begin();i!=itemsByName.end();i++) {
for(size_t j=0;j<i->second.size();j++) {
SplitPath(i->second[j]->fileName,oldpath);
if(dir.empty()) {
if(oldpath.size()==1) newpath=oldpath;
else {
newpath.resize(oldpath.size()-1);
copy(oldpath.begin()+1,oldpath.end(),newpath.begin());
}
}
else {
newpath.resize(oldpath.size()+1);
newpath[0] = dir;
copy(oldpath.begin(),oldpath.end(),newpath.begin()+1);
}
i->second[j]->fileName=JoinPath(newpath);
}
}
}
std::vector<ResourcePtr >& ResourceLibrary::Get(const string& name)
{
return itemsByName[name];
}
std::vector<ResourcePtr >& ResourceLibrary::GetByType(const std::string& type)
{
return itemsByType[type];
}
size_t ResourceLibrary::Count(const std::string& name) const
{
Map::const_iterator i=itemsByName.find(name);
if(i==itemsByName.end()) return 0;
return i->second.size();
}
size_t ResourceLibrary::CountByType(const std::string& name) const
{
Map::const_iterator i=itemsByType.find(name);
if(i==itemsByType.end()) return 0;
return i->second.size();
}
std::vector<ResourcePtr> ResourceLibrary::Enumerate() const
{
std::vector<ResourcePtr> res;
for(Map::const_iterator i=itemsByName.begin();i!=itemsByName.end();i++)
res.insert(res.end(),i->second.begin(),i->second.end());
return res;
}
void ResourceLibrary::Add(const ResourcePtr& r)
{
itemsByName[r->name].push_back(r);
itemsByType[r->Type()].push_back(r);
}
bool ResourceLibrary::Erase(const ResourcePtr& resource)
{
Map::iterator i=itemsByName.find(resource->name);
if(i==itemsByName.end()) return false;
Map::iterator it=itemsByType.find(resource->Type());
Assert(it != itemsByType.end());
for(size_t j=0;j<it->second.size();j++) {
if(it->second[j] == resource) {
it->second.erase(it->second.begin()+j);
break;
}
}
for(size_t j=0;j<i->second.size();j++) {
if(i->second[j] == resource) {
i->second.erase(i->second.begin()+j);
return true;
}
}
return false;
}
bool ResourceLibrary::Erase(const std::string& name,int index)
{
Map::iterator i=itemsByName.find(name);
if(i==itemsByName.end()) return false;
if(index < 0 || index >= (int)i->second.size()) return false;
ResourcePtr r=i->second[index];
Map::iterator it=itemsByType.find(r->Type());
Assert(it != itemsByType.end());
for(size_t j=0;j<it->second.size();j++) {
if(it->second[j] == r) {
it->second.erase(it->second.begin()+j);
break;
}
}
i->second.erase(i->second.begin()+index);
return true;
}
bool ResourceLibraryResource::Load(AnyCollection& c)
{
return library.Load(c["data"]);
}
bool ResourceLibraryResource::Save(AnyCollection& c)
{
return library.Save(c["data"]);
}
ResourceBase* ResourceLibraryResource::Copy()
{
ResourceLibraryResource* res = new ResourceLibraryResource;
res->library = library;
return res;
}
std::vector<std::string> ResourceLibraryResource::SubTypes() const
{
std::vector<std::string> res;
for(ResourceLibrary::Map::const_iterator i=library.itemsByType.begin();i!=library.itemsByName.end();i++)
res.push_back(i->first);
return res;
}
bool ResourceLibraryResource::Extract(const char* subtype,std::vector<ResourcePtr>& res)
{
if(library.itemsByType.count(subtype)==0) return false;
res = library.itemsByType.find(subtype)->second;
return true;
}
bool ResourceLibraryResource::Pack(std::vector<ResourcePtr>& subobjects,std::string* errorMessage)
{
library.Clear();
for(size_t i=0;i<subobjects.size();i++)
library.Add(subobjects[i]);
return true;
}
bool ResourceLibraryResource::Unpack(std::vector<ResourcePtr>& subobjects,bool* incomplete)
{
subobjects = library.Enumerate();
return true;
}
bool ResourceLibraryResource::Load(const std::string& fn)
{
//if fn is a directory, loads from a directory
if(FileUtils::IsDirectory(fn.c_str()))
return library.LoadAll(fn);
else
return library.LoadXml(fn);
}
bool ResourceLibraryResource::Save(const std::string& fn)
{
//if fn is a directory, saves to a directory
if(FileUtils::IsDirectory(fn.c_str()) || fn[fn.length()-1]=='/' || fn[fn.length()-1]=='\\') {
library.ChangeBaseDirectory(fn);
return library.SaveAll();
}
else {
return library.SaveXml(fn);
}
}
std::string ResourceLibrary::DefaultFileName(const ResourcePtr& r)
{
std::string ext = "txt";
for(Map::const_iterator i=loaders.begin();i!=loaders.end();i++) {
for(size_t j=0;j<i->second.size();j++) {
if(string(i->second[j]->Type())==string(r->Type())) {
ext = i->first;
break;
}
}
}
return r->name+"."+ext;
}
| 26.307398 | 144 | 0.652412 | [
"vector"
] |
3a904777f2befa290c8aa06c01787ba6ca8d7f2f | 21,180 | cpp | C++ | CombBLAS/DenseParVec.cpp | shoaibkamil/OLD-kdt-specializer | 85074ec1990df980d25096ea8c55dd81350e531e | [
"BSD-3-Clause"
] | 1 | 2021-11-15T02:11:33.000Z | 2021-11-15T02:11:33.000Z | CombBLAS/DenseParVec.cpp | shoaibkamil/OLD-kdt-specializer | 85074ec1990df980d25096ea8c55dd81350e531e | [
"BSD-3-Clause"
] | null | null | null | CombBLAS/DenseParVec.cpp | shoaibkamil/OLD-kdt-specializer | 85074ec1990df980d25096ea8c55dd81350e531e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.2 -------------------------------------------------*/
/* date: 10/06/2011 --------------------------------------------*/
/* authors: Aydin Buluc (abuluc@lbl.gov), Adam Lugowski --------*/
/****************************************************************/
/*
Copyright (c) 2011, Aydin Buluc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "DenseParVec.h"
#include "SpParVec.h"
#include "Operations.h"
template <class IT, class NT>
DenseParVec<IT, NT>::DenseParVec ()
{
zero = static_cast<NT>(0);
commGrid.reset(new CommGrid(MPI::COMM_WORLD, 0, 0));
if(commGrid->GetRankInProcRow() == commGrid->GetRankInProcCol())
diagonal = true;
else
diagonal = false;
}
// Create a new distributed dense array with all values initialized to zero
template<class IT, class NT>
DenseParVec<IT, NT>::DenseParVec (IT globallength)
{
zero = static_cast<NT>(0);
commGrid.reset(new CommGrid(MPI::COMM_WORLD, 0, 0));
if(commGrid->GetRankInProcRow() == commGrid->GetRankInProcCol())
diagonal = true;
else
diagonal = false;
if (diagonal)
{
int nprocs = commGrid->GetDiagWorld().Get_size();
int ndrank = commGrid->GetDiagWorld().Get_rank();
IT typical = globallength/nprocs;
if(ndrank == nprocs - 1)
arr.resize(globallength - ndrank*typical, zero);
else
arr.resize(typical, zero);
}
}
template <class IT, class NT>
DenseParVec<IT, NT>::DenseParVec (IT locallength, NT initval, NT id): zero(id)
{
commGrid.reset(new CommGrid(MPI::COMM_WORLD, 0, 0));
if(commGrid->GetRankInProcRow() == commGrid->GetRankInProcCol())
diagonal = true;
else
diagonal = false;
if (diagonal)
arr.resize(locallength, initval);
}
template <class IT, class NT>
DenseParVec<IT, NT>::DenseParVec ( shared_ptr<CommGrid> grid, NT id): zero(id)
{
commGrid.reset(new CommGrid(*grid));
if(commGrid->GetRankInProcRow() == commGrid->GetRankInProcCol())
diagonal = true;
else
diagonal = false;
};
template <class IT, class NT>
DenseParVec<IT, NT>::DenseParVec ( shared_ptr<CommGrid> grid, IT locallength, NT initval, NT id): commGrid(grid), zero(id)
{
if(commGrid->GetRankInProcRow() == commGrid->GetRankInProcCol())
diagonal = true;
else
diagonal = false;
if (diagonal)
arr.resize(locallength, initval);
};
template <class IT, class NT>
template <typename _BinaryOperation>
NT DenseParVec<IT,NT>::Reduce(_BinaryOperation __binary_op, NT identity)
{
// std::accumulate returns identity for empty sequences
NT localsum = std::accumulate( arr.begin(), arr.end(), identity, __binary_op);
NT totalsum = identity;
(commGrid->GetWorld()).Allreduce( &localsum, &totalsum, 1, MPIType<NT>(), MPIOp<_BinaryOperation, NT>::op());
return totalsum;
}
template <class IT, class NT>
DenseParVec< IT,NT > & DenseParVec<IT,NT>::operator=(const SpParVec< IT,NT > & rhs) // SpParVec->DenseParVec conversion operator
{
arr.resize(rhs.length);
std::fill(arr.begin(), arr.end(), zero);
IT spvecsize = rhs.ind.size();
for(IT i=0; i< spvecsize; ++i)
{
arr[rhs.ind[i]] = rhs.num[i];
}
return *this;
}
template <class IT, class NT>
DenseParVec< IT,NT > & DenseParVec<IT,NT>::operator=(const DenseParVec< IT,NT > & rhs)
{
if (this == &rhs) // Same object?
return *this; // Yes, so skip assignment, and just return *this.
commGrid.reset(new CommGrid(*(rhs.commGrid)));
arr = rhs.arr;
diagonal = rhs.diagonal;
zero = rhs.zero;
return *this;
}
template <class IT, class NT>
DenseParVec< IT,NT > & DenseParVec<IT,NT>::stealFrom(DenseParVec<IT,NT> & victim) // SpParVec->DenseParVec conversion operator
{
commGrid.reset(new CommGrid(*(victim.commGrid)));
arr.swap(victim.arr);
diagonal = victim.diagonal;
zero = victim.zero;
return *this;
}
template <class IT, class NT>
DenseParVec< IT,NT > & DenseParVec<IT,NT>::operator+=(const SpParVec< IT,NT > & rhs)
{
IT spvecsize = rhs.ind.size();
for(IT i=0; i< spvecsize; ++i)
{
if(arr[rhs.ind[i]] == zero) // not set before
arr[rhs.ind[i]] = rhs.num[i];
else
arr[rhs.ind[i]] += rhs.num[i];
}
return *this;
}
template <class IT, class NT>
DenseParVec< IT,NT > & DenseParVec<IT,NT>::operator-=(const SpParVec< IT,NT > & rhs)
{
IT spvecsize = rhs.ind.size();
for(IT i=0; i< spvecsize; ++i)
{
arr[rhs.ind[i]] -= rhs.num[i];
}
}
/**
* Perform __binary_op(*this, v2) for every element in rhs, *this,
* which are of the same size. and write the result back to *this
*/
template <class IT, class NT>
template <typename _BinaryOperation>
void DenseParVec<IT,NT>::EWise(const DenseParVec<IT,NT> & rhs, _BinaryOperation __binary_op)
{
if(zero == rhs.zero)
{
transform ( arr.begin(), arr.end(), rhs.arr.begin(), arr.begin(), __binary_op );
}
else
{
cout << "DenseParVec objects have different identity (zero) elements..." << endl;
cout << "Operation didn't happen !" << endl;
}
};
template <class IT, class NT>
DenseParVec<IT,NT> & DenseParVec<IT, NT>::operator+=(const DenseParVec<IT,NT> & rhs)
{
if(this != &rhs)
{
if(!(*commGrid == *rhs.commGrid))
{
cout << "Grids are not comparable elementwise addition" << endl;
MPI::COMM_WORLD.Abort(GRIDMISMATCH);
}
else if(diagonal) // Only the diagonal processors hold values
{
EWise(rhs, std::plus<NT>());
}
}
return *this;
};
template <class IT, class NT>
DenseParVec<IT,NT> & DenseParVec<IT, NT>::operator-=(const DenseParVec<IT,NT> & rhs)
{
if(this != &rhs)
{
if(!(*commGrid == *rhs.commGrid))
{
cout << "Grids are not comparable elementwise addition" << endl;
MPI::COMM_WORLD.Abort(GRIDMISMATCH);
}
else if(diagonal) // Only the diagonal processors hold values
{
EWise(rhs, std::minus<NT>());
}
}
return *this;
};
template <class IT, class NT>
bool DenseParVec<IT,NT>::operator==(const DenseParVec<IT,NT> & rhs) const
{
ErrorTolerantEqual<NT> epsilonequal;
int local = 1;
if(diagonal)
{
local = (int) std::equal(arr.begin(), arr.end(), rhs.arr.begin(), epsilonequal );
#ifdef DEBUG
vector<NT> diff(arr.size());
transform(arr.begin(), arr.end(), rhs.arr.begin(), diff.begin(), minus<NT>());
typename vector<NT>::iterator maxitr;
maxitr = max_element(diff.begin(), diff.end());
cout << maxitr-diff.begin() << ": " << *maxitr << " where lhs: " << *(arr.begin()+(maxitr-diff.begin()))
<< " and rhs: " << *(rhs.arr.begin()+(maxitr-diff.begin())) << endl;
#endif
}
int whole = 1;
commGrid->GetWorld().Allreduce( &local, &whole, 1, MPI::INT, MPI::BAND);
return static_cast<bool>(whole);
}
template <class IT, class NT>
template <typename _Predicate>
IT DenseParVec<IT,NT>::Count(_Predicate pred) const
{
IT local = 0;
if(diagonal)
{
local = count_if( arr.begin(), arr.end(), pred );
}
IT whole = 0;
commGrid->GetWorld().Allreduce( &local, &whole, 1, MPIType<IT>(), MPI::SUM);
return whole;
}
//! Returns a dense vector of global indices
//! for which the predicate is satisfied
template <class IT, class NT>
template <typename _Predicate>
DenseParVec<IT,IT> DenseParVec<IT,NT>::FindInds(_Predicate pred) const
{
DenseParVec<IT,IT> found(commGrid, (IT) 0);
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
IT old_n_perproc = getTypicalLocLength();
IT size = arr.size();
for(IT i=0; i<size; ++i)
{
if(pred(arr[i]))
{
found.arr.push_back(i+old_n_perproc*dgrank);
}
}
DiagWorld.Barrier();
// Since the found vector is not reshuffled yet, we can't use getTypicalLocLength() at this point
IT n_perproc = found.getTotalLength(DiagWorld) / nprocs;
if(n_perproc == 0) // it has less than sqrt(p) elements, all owned by the last processor
{
if(dgrank != nprocs-1)
{
int arrsize = found.arr.size();
DiagWorld.Gather(&arrsize, 1, MPI::INT, NULL, 1, MPI::INT, nprocs-1);
DiagWorld.Gatherv(&(found.arr[0]), arrsize, MPIType<IT>(), NULL, NULL, NULL, MPIType<IT>(), nprocs-1);
}
else
{
int * allnnzs = new int[nprocs];
allnnzs[dgrank] = found.arr.size();
DiagWorld.Gather(MPI::IN_PLACE, 1, MPI::INT, allnnzs, 1, MPI::INT, nprocs-1);
int * rdispls = new int[nprocs];
rdispls[0] = 0;
for(int i=0; i<nprocs-1; ++i)
rdispls[i+1] = rdispls[i] + allnnzs[i];
IT totrecv = accumulate(allnnzs, allnnzs+nprocs, 0);
vector<IT> recvbuf(totrecv);
DiagWorld.Gatherv(MPI::IN_PLACE, 1, MPI::INT, &(recvbuf[0]), allnnzs, rdispls, MPIType<IT>(), nprocs-1);
found.arr.swap(recvbuf);
DeleteAll(allnnzs, rdispls);
}
return found; // don't execute further
}
IT lengthuntil = dgrank * n_perproc;
// rebalance/redistribute
IT nsize = found.arr.size();
int * sendcnt = new int[nprocs];
fill(sendcnt, sendcnt+nprocs, 0);
for(IT i=0; i<nsize; ++i)
{
// owner id's are monotonically increasing and continuous
int owner = std::min(static_cast<int>( (i+lengthuntil) / n_perproc), nprocs-1);
sendcnt[owner]++;
}
int * recvcnt = new int[nprocs];
DiagWorld.Alltoall(sendcnt, 1, MPI::INT, recvcnt, 1, MPI::INT); // share the counts
int * sdispls = new int[nprocs];
int * rdispls = new int[nprocs];
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<nprocs-1; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
IT totrecv = accumulate(recvcnt,recvcnt+nprocs, (IT) 0);
vector<IT> recvbuf(totrecv);
// data is already in the right order in found.arr
DiagWorld.Alltoallv(&(found.arr[0]), sendcnt, sdispls, MPIType<IT>(), &(recvbuf[0]), recvcnt, rdispls, MPIType<IT>());
found.arr.swap(recvbuf);
DeleteAll(sendcnt, recvcnt, sdispls, rdispls);
}
return found;
}
//! Requires no communication because SpParVec (the return object)
//! is distributed based on length, not nonzero counts
template <class IT, class NT>
template <typename _Predicate>
SpParVec<IT,NT> DenseParVec<IT,NT>::Find(_Predicate pred) const
{
SpParVec<IT,NT> found(commGrid);
if(diagonal)
{
IT size = arr.size();
for(IT i=0; i<size; ++i)
{
if(pred(arr[i]))
{
found.ind.push_back(i);
found.num.push_back(arr[i]);
}
}
found.length = size;
}
return found;
}
template <class IT, class NT>
ifstream& DenseParVec<IT,NT>::ReadDistribute (ifstream& infile, int master)
{
SpParVec<IT,NT> tmpSpVec(commGrid);
tmpSpVec.ReadDistribute(infile, master);
*this = tmpSpVec;
return infile;
}
template <class IT, class NT>
void DenseParVec<IT,NT>::SetElement (IT indx, NT numx)
{
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
IT n_perproc = getTypicalLocLength();
IT offset = dgrank * n_perproc;
if (n_perproc == 0) {
cout << "DenseParVec::SetElement can't be called on an empty vector." << endl;
return;
}
IT owner = std::min(static_cast<int>(indx / n_perproc), nprocs-1);
if(owner == dgrank) // this process is the owner
{
IT locindx = indx-offset;
if (locindx > arr.size()-1)
{
cout << "DenseParVec::SetElement cannot expand array" << endl;
}
else if (locindx < 0)
{
cout << "DenseParVec::SetElement local index < 0" << endl;
}
else
{
arr[locindx] = numx;
}
}
}
}
template <class IT, class NT>
NT DenseParVec<IT,NT>::GetElement (IT indx) const
{
NT ret;
int owner = 0;
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
IT n_perproc = getTypicalLocLength();
IT offset = dgrank * n_perproc;
if (n_perproc == 0 && dgrank == 0) {
cout << "DenseParVec::GetElement can't be called on an empty vector." << endl;
return numeric_limits<NT>::min();
}
owner = std::min(static_cast<int>(indx / n_perproc), nprocs-1);
if(owner == dgrank) // this process is the owner
{
IT locindx = indx-offset;
if (locindx > arr.size()-1)
{
cout << "DenseParVec::GetElement cannot expand array" << endl;
}
else if (locindx < 0)
{
cout << "DenseParVec::GetElement local index < 0" << endl;
}
else
{
ret = arr[locindx];
}
}
}
int worldowner = commGrid->GetRank(owner); // 0 is always on the diagonal
(commGrid->GetWorld()).Bcast(&worldowner, 1, MPIType<int>(), 0);
(commGrid->GetWorld()).Bcast(&ret, 1, MPIType<NT>(), worldowner);
return ret;
}
template <class IT, class NT>
void DenseParVec<IT,NT>::DebugPrint()
{
// ABAB: Alternative
// ofstream out;
// commGrid->OpenDebugFile("DenseParVec", out);
// copy(recvbuf, recvbuf+totrecv, ostream_iterator<IT>(out, " "));
// out << " <end_of_vector>"<< endl;
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
int64_t* all_nnzs = new int64_t[nprocs];
all_nnzs[dgrank] = arr.size();
DiagWorld.Allgather(MPI::IN_PLACE, 1, MPIType<int64_t>(), all_nnzs, 1, MPIType<int64_t>());
int64_t offset = 0;
for (int i = 0; i < nprocs; i++)
{
if (i == dgrank)
{
cerr << arr.size() << " elements stored on proc " << dgrank << "," << dgrank << ":" ;
for (int j = 0; j < arr.size(); j++)
{
cerr << "\n[" << (j+offset) << "] = " << arr[j] ;
}
cerr << endl;
}
offset += all_nnzs[i];
DiagWorld.Barrier();
}
DiagWorld.Barrier();
if (dgrank == 0)
cerr << "total size: " << offset << endl;
DiagWorld.Barrier();
}
}
template <class IT, class NT>
template <typename _UnaryOperation>
void DenseParVec<IT,NT>::Apply(_UnaryOperation __unary_op, const SpParVec<IT,NT> & mask)
{
typename vector< IT >::const_iterator miter = mask.ind.begin();
while (miter < mask.ind.end())
{
IT index = *miter++;
arr[index] = __unary_op(arr[index]);
}
}
// Randomly permutes an already existing vector
template <class IT, class NT>
void DenseParVec<IT,NT>::RandPerm()
{
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
IT size = arr.size();
pair<double,IT> * vecpair = new pair<double,IT>[size];
int nproc = DiagWorld.Get_size();
int diagrank = DiagWorld.Get_rank();
long * dist = new long[nproc];
dist[diagrank] = size;
DiagWorld.Allgather(MPI::IN_PLACE, 1, MPIType<long>(), dist, 1, MPIType<long>());
IT lengthuntil = accumulate(dist, dist+diagrank, 0);
MTRand M; // generate random numbers with Mersenne Twister
for(int i=0; i<size; ++i)
{
vecpair[i].first = M.rand();
vecpair[i].second = arr[i];
}
// less< pair<T1,T2> > works correctly (sorts wrt first elements)
vpsort::parallel_sort (vecpair, vecpair + size, dist, DiagWorld);
vector< NT > nnum(size);
for(int i=0; i<size; ++i)
nnum[i] = vecpair[i].second;
delete [] vecpair;
delete [] dist;
arr.swap(nnum);
}
}
template <class IT, class NT>
void DenseParVec<IT,NT>::iota(IT size, NT first)
{
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
IT n_perproc = size / nprocs;
IT length = (dgrank != nprocs-1) ? n_perproc: (size - (n_perproc * (nprocs-1)));
arr.resize(length);
SpHelper::iota(arr.begin(), arr.end(), (dgrank * n_perproc) + first); // global across processors
}
}
template <class IT, class NT>
DenseParVec<IT,NT> DenseParVec<IT,NT>::operator() (const DenseParVec<IT,IT> & ri) const
{
if(!(*commGrid == *ri.commGrid))
{
cout << "Grids are not comparable for dense vector subsref" << endl;
return DenseParVec<IT,NT>();
}
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
DenseParVec<IT,NT> Indexed(commGrid, zero); // length(Indexed) = length(ri)
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
IT n_perproc = getTypicalLocLength();
vector< vector< IT > > data_req(nprocs);
vector< vector< IT > > revr_map(nprocs); // to put the incoming data to the correct location
for(IT i=0; i < ri.arr.size(); ++i)
{
int owner = ri.arr[i] / n_perproc; // numerical values in ri are 0-based
owner = std::min(owner, nprocs-1); // find its owner
data_req[owner].push_back(ri.arr[i] - (n_perproc * owner));
revr_map[owner].push_back(i);
}
IT * sendbuf = new IT[ri.arr.size()];
int * sendcnt = new int[nprocs];
int * sdispls = new int[nprocs];
for(int i=0; i<nprocs; ++i)
sendcnt[i] = data_req[i].size();
int * rdispls = new int[nprocs];
int * recvcnt = new int[nprocs];
DiagWorld.Alltoall(sendcnt, 1, MPI::INT, recvcnt, 1, MPI::INT); // share the request counts
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<nprocs-1; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
IT totrecv = accumulate(recvcnt,recvcnt+nprocs,zero);
IT * recvbuf = new IT[totrecv];
for(int i=0; i<nprocs; ++i)
{
copy(data_req[i].begin(), data_req[i].end(), sendbuf+sdispls[i]);
vector<IT>().swap(data_req[i]);
}
IT * reversemap = new IT[ri.arr.size()];
for(int i=0; i<nprocs; ++i)
{
copy(revr_map[i].begin(), revr_map[i].end(), reversemap+sdispls[i]);
vector<IT>().swap(revr_map[i]);
}
DiagWorld.Alltoallv(sendbuf, sendcnt, sdispls, MPIType<IT>(), recvbuf, recvcnt, rdispls, MPIType<IT>()); // request data
// We will return the requested data,
// our return will be as big as the request
// as we are indexing a dense vector, all elements exist
// so the displacement boundaries are the same as rdispls
NT * databack = new NT[totrecv];
for(int i=0; i<nprocs; ++i)
{
for(int j = rdispls[i]; j < rdispls[i] + recvcnt[i]; ++j) // fetch the numerical values
{
databack[j] = arr[recvbuf[j]];
}
}
delete [] recvbuf;
NT * databuf = new NT[ri.arr.size()];
// the response counts are the same as the request counts
DiagWorld.Alltoallv(databack, recvcnt, rdispls, MPIType<NT>(), databuf, sendcnt, sdispls, MPIType<NT>()); // send data
DeleteAll(rdispls, recvcnt, databack);
// Now create the output from databuf
Indexed.arr.resize(ri.arr.size());
for(int i=0; i<nprocs; ++i)
{
for(int j=sdispls[i]; j< sdispls[i]+sendcnt[i]; ++j)
{
Indexed.arr[reversemap[j]] = databuf[j];
}
}
DeleteAll(sdispls, sendcnt, databuf,reversemap);
}
return Indexed;
}
template <class IT, class NT>
IT DenseParVec<IT,NT>::getTotalLength(MPI::Intracomm & comm) const
{
IT totnnz = 0;
if (comm != MPI::COMM_NULL)
{
IT locnnz = arr.size();
comm.Allreduce( &locnnz, & totnnz, 1, MPIType<IT>(), MPI::SUM);
}
return totnnz;
}
template <class IT, class NT>
IT DenseParVec<IT,NT>::getTypicalLocLength() const
{
IT n_perproc = 0 ;
MPI::Intracomm DiagWorld = commGrid->GetDiagWorld();
if(DiagWorld != MPI::COMM_NULL) // Diagonal processors only
{
int dgrank = DiagWorld.Get_rank();
int nprocs = DiagWorld.Get_size();
n_perproc = arr.size();
if (dgrank == nprocs-1 && nprocs > 1)
{
// the local length on the last processor will be greater than the others if the vector length is not evenly divisible
// but for these calculations we need that length
DiagWorld.Recv(&n_perproc, 1, MPIType<IT>(), 0, 1);
}
else if (dgrank == 0 && nprocs > 1)
{
DiagWorld.Send(&n_perproc, 1, MPIType<IT>(), nprocs-1, 1);
}
}
return n_perproc;
}
template <class IT, class NT>
void DenseParVec<IT,NT>::PrintInfo(string vectorname) const
{
IT totl = getTotalLength(commGrid->GetDiagWorld());
if (commGrid->GetRank() == 0) // is always on the diagonal
cout << "As a whole, " << vectorname << " has length " << totl << endl;
}
| 29.173554 | 142 | 0.646034 | [
"object",
"vector",
"transform"
] |
3a91b76494660e6753f5e8b685cb43f718f25d1d | 1,240 | cpp | C++ | src/LinuxLibraryLoader.cpp | matt-komm/CPX | 48ec3b39c0a6b58c97a6acb6221619113e8a6406 | [
"MIT"
] | null | null | null | src/LinuxLibraryLoader.cpp | matt-komm/CPX | 48ec3b39c0a6b58c97a6acb6221619113e8a6406 | [
"MIT"
] | null | null | null | src/LinuxLibraryLoader.cpp | matt-komm/CPX | 48ec3b39c0a6b58c97a6acb6221619113e8a6406 | [
"MIT"
] | null | null | null | #include "cpx/LinuxLibraryLoader.hpp"
#include "cpx/PluginFactory.hpp"
#include <dlfcn.h>
namespace cpx
{
LinuxLibraryLoader::LinuxLibraryLoader(PluginFactory* pluginFactory):
_pluginFactory(pluginFactory)
{
}
void LinuxLibraryLoader::loadLibrary(std::string file)
{
typedef void (*InitFct)(cpx::PluginFactory*);
if (_loadedLibHandles.find(file)==_loadedLibHandles.end())
{
void* lib_handle;
char *error;
lib_handle = dlopen(file.c_str(), RTLD_LAZY);
if (!lib_handle)
{
cpx_throw("Error while opening file: '",file,"': ",dlerror());
}
_loadedLibHandles[file]=lib_handle;
//hides object-to-function cast from the compiler
SharedMemory<void*,InitFct> smemory(dlsym(lib_handle, "init"));
InitFct initFct = smemory.get();
if ((error = dlerror()) != NULL)
{
cpx_throw("Error while initializing file: '",file,"': ",dlerror());
}
(*initFct)(_pluginFactory);
}
else
{
cpx_throw("Plugin file '",file,"' already loaded");
}
}
LinuxLibraryLoader::~LinuxLibraryLoader()
{
for (auto handle: _loadedLibHandles)
{
dlclose(handle.second);
}
}
}
| 23.846154 | 79 | 0.614516 | [
"object"
] |
3a96962381b7a4988e195a2c939303ac94d1df75 | 7,070 | cpp | C++ | src/qt/marketdecisiontablemodel.cpp | truthcoin/truthcoin-cpp | a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529 | [
"MIT"
] | 34 | 2015-06-23T16:06:35.000Z | 2021-04-02T20:34:11.000Z | src/qt/marketdecisiontablemodel.cpp | truthcoin/truthcoin-cpp | a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529 | [
"MIT"
] | 2 | 2016-05-13T15:21:08.000Z | 2016-05-15T17:43:24.000Z | src/qt/marketdecisiontablemodel.cpp | truthcoin/truthcoin-cpp | a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529 | [
"MIT"
] | 6 | 2015-06-23T18:12:18.000Z | 2015-09-16T13:45:35.000Z | // Copyright (c) 2015 The Truthcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QList>
#include "guiutil.h"
#include "main.h"
#include "marketdecisiontablemodel.h"
#include "primitives/market.h"
#include "sync.h"
#include "txdb.h"
#include "uint256.h"
#include "util.h"
#include "wallet.h"
#include "walletmodel.h"
extern CMarketTreeDB *pmarkettree;
// Amount column is right-aligned it contains numbers
static int column_alignments[] = {
Qt::AlignLeft|Qt::AlignVCenter, /* Address */
Qt::AlignLeft|Qt::AlignVCenter, /* Prompt */
Qt::AlignRight|Qt::AlignVCenter, /* EventOverBy */
Qt::AlignRight|Qt::AlignVCenter, /* IsScaled */
Qt::AlignRight|Qt::AlignVCenter, /* Minimum */
Qt::AlignRight|Qt::AlignVCenter, /* Maximum */
Qt::AlignRight|Qt::AlignVCenter, /* AnswerOptional */
};
// Private implementation
class MarketDecisionTablePriv
{
public:
MarketDecisionTablePriv(CWallet *wallet, MarketDecisionTableModel *parent)
: wallet(wallet),
parent(parent)
{
}
CWallet *wallet;
MarketDecisionTableModel *parent;
/* Local cache of Decisions */
QList<const marketDecision *> cached;
int size()
{
return cached.size();
}
const marketDecision *index(int idx)
{
if(idx >= 0 && idx < cached.size())
return cached[idx];
return 0;
}
QString describe(const marketDecision *decision, int unit)
{
return QString();
}
};
MarketDecisionTableModel::MarketDecisionTableModel(CWallet *wallet, WalletModel *parent)
: QAbstractTableModel(parent),
wallet(wallet),
walletModel(parent),
priv(new MarketDecisionTablePriv(wallet, this))
{
columns
<< tr("Address")
<< tr("Prompt")
<< tr("Event Over By")
<< tr("IsScaled")
<< tr("Minimum")
<< tr("Maximum")
<< tr("AnswerOptional")
;
}
MarketDecisionTableModel::~MarketDecisionTableModel()
{
delete priv;
}
int MarketDecisionTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MarketDecisionTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MarketDecisionTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
const marketDecision *decision = (const marketDecision *) index.internalPointer();
switch(role)
{
case Qt::DisplayRole:
switch(index.column())
{
case Address:
return formatAddress(decision);
case Prompt:
return formatPrompt(decision);
case EventOverBy:
return QVariant((int)decision->eventOverBy);
case IsScaled:
return formatIsScaled(decision);
case Minimum:
return QVariant((double)decision->min*1e-8);
case Maximum:
return QVariant((double)decision->max*1e-8);
default:
;
}
break;
case AddressRole:
return formatAddress(decision);
case PromptRole:
return formatPrompt(decision);
case Qt::TextAlignmentRole:
return column_alignments[index.column()];
}
return QVariant();
}
QVariant MarketDecisionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
return columns[section];
else
if (role == Qt::TextAlignmentRole)
return column_alignments[section];
else
if (role == Qt::ToolTipRole)
{
switch(section)
{
case Address:
return tr("Address");
case Prompt:
return tr("Prompt");
case EventOverBy:
return tr("EventOverBy");
case IsScaled:
return tr("IsScaled");
case Minimum:
return tr("Minimum");
case Maximum:
return tr("Maximum");
}
}
}
return QVariant();
}
const marketDecision *MarketDecisionTableModel::index(int row) const
{
return priv->index(row);
}
QModelIndex MarketDecisionTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
const marketDecision *decision = priv->index(row);
if (decision)
return createIndex(row, column, (void *)decision);
return QModelIndex();
}
Qt::ItemFlags MarketDecisionTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
void
MarketDecisionTableModel::onBranchChange(const marketBranch *branch)
{
if (!priv)
return;
/* erase cache */
if (priv->cached.size()) {
beginRemoveRows(QModelIndex(), 0, priv->cached.size()-1);
for(ssize_t i=0; i < priv->cached.size(); i++)
delete priv->cached[i];
priv->cached.clear();
endRemoveRows();
}
if (!branch)
return;
/* insert into cache */
vector<marketDecision *> vec = pmarkettree->GetDecisions(branch->GetHash());
if (vec.size()) {
beginInsertRows(QModelIndex(), 0, vec.size()-1);
for(uint32_t i=0; i < vec.size(); i++)
priv->cached.append(vec[i]);
endInsertRows();
}
}
QString formatAddress(const marketDecision *decision)
{
CTruthcoinAddress addr;
if (addr.Set(decision->keyID))
return QString::fromStdString(addr.ToString());
return QString("Address");
}
QString formatPrompt(const marketDecision *decision)
{
return QString::fromStdString(decision->prompt);
}
QString formatEventOverBy(const marketDecision *decision)
{
char tmp[32];
snprintf(tmp, sizeof(tmp), "%u", decision->eventOverBy);
return QString(tmp);
}
QString formatIsScaled(const marketDecision *decision)
{
return QString(decision->isScaled? "Yes": "No");
}
QString formatMaximum(const marketDecision *decision)
{
if (decision->isScaled) {
char tmp[32];
snprintf(tmp, sizeof(tmp), "%.8f", decision->max*1e-8);
return QString(tmp);
}
return QString("");
}
QString formatMinimum(const marketDecision *decision)
{
if (decision->isScaled) {
char tmp[32];
snprintf(tmp, sizeof(tmp), "%.8f", decision->min*1e-8);
return QString(tmp);
}
return QString("");
}
QString formatAnswerOptional(const marketDecision *decision)
{
return QString(decision->answerOptionality? "Optional": "Not Optional");
}
QString formatBranchID(const marketDecision *decision)
{
return QString::fromStdString(decision->branchid.ToString());
}
QString formatHash(const marketDecision *decision)
{
return QString::fromStdString(decision->GetHash().ToString());
}
| 25.340502 | 103 | 0.628996 | [
"vector"
] |
3a99642d2d7be8c2d201e88508378258331ff67a | 10,754 | cpp | C++ | src/Grid/Grid.cpp | lhilbert/active-microemulsion | c0514f148d673501d1966e2d65a4568b26b8bacb | [
"BSD-2-Clause"
] | 2 | 2020-05-01T19:45:39.000Z | 2022-02-20T06:47:25.000Z | src/Grid/Grid.cpp | lhilbert/active-microemulsion | c0514f148d673501d1966e2d65a4568b26b8bacb | [
"BSD-2-Clause"
] | 33 | 2018-08-20T08:36:38.000Z | 2019-08-07T18:48:38.000Z | src/Grid/Grid.cpp | lhilbert/active-microemulsion | c0514f148d673501d1966e2d65a4568b26b8bacb | [
"BSD-2-Clause"
] | null | null | null | #include <utility>
//
// Created by tommaso on 03/08/18.
//
#include <cstdlib>
#include <functional>
#include "Grid.h"
#include "../Utils/RandomGenerator.h"
std::mt19937 Grid::randomNumberGenerator = RandomGenerator::getInstance().getGenerator();
// NOTE: nice alloc and dealloc come from https://stackoverflow.com/a/1403157
void Grid::allocateGrid()
{
int extendedRows = rows + 2;
int extendedColumns = columns + 2;
data = new CellData *[extendedRows];
data[0] = new CellData[extendedRows * extendedColumns](); // "()" at the end ensure initialization to 0
// #pragma omp parallel for schedule(static) //first touch on grid
for (int i = 1; i < extendedRows - 1; ++i)
{
data[i] = data[0] + i * extendedColumns;
// memset(data[i], 0, static_cast<size_t>(extendedColumns));
}
data[extendedRows - 1] = data[0] + (extendedRows - 1) * extendedColumns;
}
void Grid::deallocateGrid()
{
delete[] data[0];
delete[] data;
}
Grid::Grid(int columns, int rows, Logger &logger) : columns(columns),
rows(rows),
numElements(columns * rows),
rowDistribution(1, rows),
columnDistribution(1, columns),
elementDistribution(0, numElements-1),
rowColOffsetDistribution(0, 8),
logger(logger),
nextAvailableChainId(1)
{
#pragma omp parallel for schedule(static,1)
for (int i=0; i < omp_get_num_threads(); ++i)
{
randomNumberGenerator = RandomGenerator::getInstance().getGenerator();
}
allocateGrid();
}
Grid::~Grid()
{
deallocateGrid();
}
const CellData **Grid::getData()
{
return const_cast<const CellData **>(data);
}
inline int Grid::pickRow()
{
return rowDistribution(randomNumberGenerator);
}
inline int Grid::pickColumn()
{
return columnDistribution(randomNumberGenerator);
}
void Grid::pickRandomElement(int &i, int &j)
{
int elementId = elementDistribution(randomNumberGenerator);
i = 1 + (elementId % getColumns());
j = 1 + (elementId / getColumns());
}
inline int Grid::pickRowColOffset()
{
return rowColOffsetDistribution(randomNumberGenerator);
}
void Grid::pickNeighbourOffsets(int &rowOffset, int &colOffset)
{
int rowColOffset = pickRowColOffset();
rowOffset = (rowColOffset / 3) - 1;
colOffset = (rowColOffset % 3) - 1;
}
void Grid::pickRandomNeighbourOf(int i, int j, int &neighbourI, int &neighbourJ)
{
do
{
int rowOffset, colOffset;
pickNeighbourOffsets(rowOffset, colOffset);
neighbourI = i + colOffset;
neighbourJ = j + rowOffset;
} while (
(neighbourI == i && neighbourJ == j) // We want a neighbour, not the cell itself
|| neighbourI < 1 || neighbourI > columns // We want to be inside the grid
|| neighbourJ < 1 || neighbourJ > rows // We want to be inside the grid
);
}
void Grid::initializeCellProperties(int column, int row, ChemicalProperties chemicalProperties, Flags flags,
bool enforceChainIntegrity, ChainId chainId, unsigned int chainLength,
unsigned int position)
{
setChemicalProperties(column, row, chemicalProperties);
setFlags(column, row, flags);
if (enforceChainIntegrity)
{
setChainProperties(column, row, chainId, position, chainLength);
}
}
void Grid::setChemicalSpecies(int column, int row, ChemicalSpecies species)
{
getElement(column, row).setChemicalSpecies(species);
}
void Grid::setActivity(int column, int row, Activity activity)
{
getElement(column, row).setActivity(activity);
}
void Grid::setChemicalProperties(int column, int row, ChemicalSpecies species, Activity activity)
{
getElement(column, row).setChemicalProperties(species, activity);
}
void Grid::setChemicalProperties(int column, int row, ChemicalProperties chemicalProperties)
{
setChemicalProperties(column, row,
static_cast<ChemicalSpecies>(BitwiseOperations::getBit(chemicalProperties, SPECIES_BIT)),
static_cast<Activity>(BitwiseOperations::getBit(chemicalProperties, ACTIVE_BIT)));
}
void Grid::setFlags(int column, int row, Flags flags)
{
getElement(column, row).flags = flags;
}
void Grid::setTranscribability(int column, int row, Transcribability transcribability)
{
getElement(column, row).setTranscribability(transcribability);
}
void Grid::setTranscriptionInhibition(int column, int row, TranscriptionInhibition inhibition)
{
getElement(column, row).setTranscriptionInhibition(inhibition);
}
CellData &Grid::getElement(int elementId)
{
return data[0][elementId]; // data[0] is the pointer to the array storing the entire grid in 1D
}
CellData &Grid::getElement(int column, int row)
{
return data[row][column];
}
CellData &Grid::getElement(int column, int row) const
{
return data[row][column];
}
void Grid::setElement(int column, int row, CellData &value)
{
data[row][column] = value;
}
size_t Grid::setChainProperties(int column, int row, ChainId chainId, unsigned int position, unsigned int length)
{
CellData &element = getElement(column, row);
int k = 0;
while (element.chainProperties[k].chainLength != 0 && k < MAX_CROSSING_CHAINS)
{
++k;
}
if (k == MAX_CROSSING_CHAINS)
{
logger.logMsg(ERROR, "Trying to get too many chains to cross!");
logger.flush(); // Flushing before everything explodes...
throw std::out_of_range("Trying to get too many chains to cross");
}
element.chainProperties[k].chainId = chainId;
element.chainProperties[k].position = position;
element.chainProperties[k].chainLength = length;
return static_cast<size_t>(k);
}
unsigned char Grid::cellBelongsToChain(int column, int row, ChainId chainId)
{
unsigned char found = MAX_CROSSING_CHAINS;
for (unsigned char k = 0; k < MAX_CROSSING_CHAINS; ++k)
{
if (getElement(column, row).chainProperties[k].chainId == chainId)
{
found = k;
break;
}
}
return found;
}
bool Grid::isPositionInChainPropertiesArrayValid(unsigned char position)
{
return position < MAX_CROSSING_CHAINS;
}
bool Grid::isCellNeighbourInChain(int column, int row, const ChainProperties &chainProperties)
{
bool isNeighbourInChain = false;
// First check if the given cell belongs to the given chain
unsigned char pos = cellBelongsToChain(column, row, chainProperties.chainId);
if (isPositionInChainPropertiesArrayValid(pos))
{
// Then check if it is actually a neighbour within the given chain
unsigned int neighbourPositionInChain =
getElement(column, row).chainProperties[pos].position;
unsigned int currentCellPositionInChain = chainProperties.position;
int distance = neighbourPositionInChain - currentCellPositionInChain;
isNeighbourInChain = (distance == 1) || (distance == -1);
}
return isNeighbourInChain;
}
bool Grid::isCellNeighbourInAnyChain(int column, int row,
std::vector<std::reference_wrapper<ChainProperties>> &chainPropertiesVector)
{
bool isNeighbour = false;
for (auto chain : chainPropertiesVector)
{
if (isCellNeighbourInChain(column, row, chain))
{
isNeighbour = true;
break;
}
}
return isNeighbour;
}
std::vector<std::reference_wrapper<ChainProperties>> Grid::chainsCellBelongsTo(int column, int row)
{
auto chains = std::vector<std::reference_wrapper<ChainProperties>>();
for (unsigned char k = 0; k < MAX_CROSSING_CHAINS; ++k)
{
ChainProperties &chainProperties = getElement(column, row).chainProperties[k];
unsigned int chainLength = chainProperties.chainLength;
if (chainLength > 0)
{
chains.push_back(std::ref(chainProperties));
}
}
return chains;
}
ChainId Grid::getNewChainId()
{
logger.logMsg(PRODUCTION, "Initializing new chain with chainId=%d", nextAvailableChainId);
return nextAvailableChainId++; // Return and increment
}
int Grid::getSpeciesCount(ChemicalSpecies chemicalSpecies)
{
int counter = 0;
for (int j = getFirstRow(); j <= getLastRow(); ++j)
{
for (int i = getFirstColumn(); i <= getLastColumn(); ++i)
{
counter += (getChemicalSpecies(i, j) == chemicalSpecies);
}
}
return counter;
}
bool Grid::doesAnyNeighbourMatchCondition(int column, int row, bool (*condition)(CellData &))
{
return condition(getElement(column - 1, row - 1))
|| condition(getElement(column, row - 1))
|| condition(getElement(column + 1, row - 1))
|| condition(getElement(column - 1, row))
|| condition(getElement(column + 1, row))
|| condition(getElement(column - 1, row + 1))
|| condition(getElement(column, row + 1))
|| condition(getElement(column + 1, row + 1));
}
std::vector<std::reference_wrapper<CellData>>
Grid::getNeighboursMatchingConditions(int column, int row, bool (*condition)(CellData &))
{
auto neighboursMatchingCondition = std::vector<std::reference_wrapper<CellData>>();
for (int colOffset = -1; colOffset <= 1; ++colOffset)
{
for (int rowOffset = -1; rowOffset <= 1; ++rowOffset)
{
if (!(colOffset == 0 && rowOffset == 0))
{
CellData &neighbour = getElement(column + colOffset, row + rowOffset);
if (condition(neighbour))
{
neighboursMatchingCondition.push_back(neighbour);
}
}
}
}
return neighboursMatchingCondition;
}
bool Grid::isPositionNextToBoundary(int column, int row)
{
return column == getFirstColumn() || column == getLastColumn()
|| row == getFirstRow() || row == getLastRow();
}
void Grid::walkOnGrid(int &column, int &row, signed char colOffset, signed char rowOffset)
{
column += colOffset;
row += rowOffset;
}
bool Grid::isCellWithinInternalDomain(int column, int row)
{
return column >= getFirstColumn()
&& column <= getLastColumn()
&& row >= getFirstRow()
&& row <= getLastRow();
}
int Grid::getColumns() const
{
return columns;
}
int Grid::getRows() const
{
return rows;
}
| 30.902299 | 115 | 0.634741 | [
"vector"
] |
3a9a1a7245cba19eec82ffb0c680d1d072bfe834 | 13,931 | cpp | C++ | applications/plugins/SofaPython/PythonScriptController.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/SofaPython/PythonScriptController.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | applications/plugins/SofaPython/PythonScriptController.cpp | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include "PythonMacros.h"
#include "PythonScriptController.h"
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/AdvancedTimer.h>
using sofa::helper::AdvancedTimer;
using sofa::core::objectmodel::Base;
using sofa::simulation::Node;
#include "Binding_PythonScriptController.h"
using sofa::simulation::PythonEnvironment;
#include "PythonScriptEvent.h"
using sofa::core::objectmodel::PythonScriptEvent;
#include <sofa/helper/system/FileMonitor.h>
using sofa::helper::system::FileMonitor ;
using sofa::helper::system::FileEventListener ;
#include <sofa/core/objectmodel/IdleEvent.h>
using sofa::core::objectmodel::IdleEvent ;
#include "PythonFactory.h"
//TODO(dmarchal): This have to be merged with the ScopedAdvancedTimer
struct ActivableScopedAdvancedTimer {
const char* message;
bool m_active ;
Base* m_base;
ActivableScopedAdvancedTimer(bool active, const char* message, Base* base)
: message( message ), m_active(active), m_base(base)
{
if(m_active)
AdvancedTimer::stepBegin(message, m_base);
}
~ActivableScopedAdvancedTimer()
{
if(m_active)
AdvancedTimer::stepEnd(message, m_base);
}
};
namespace sofa
{
namespace component
{
namespace controller
{
class MyFileEventListener : public FileEventListener
{
PythonScriptController* m_controller ;
public:
MyFileEventListener(PythonScriptController* psc){
m_controller = psc ;
}
virtual ~MyFileEventListener(){}
virtual void fileHasChanged(const std::string& filepath){
/// This function is called when the file has changed. Two cases have
/// to be considered if the script was already loaded once or not.
if(!m_controller->scriptControllerInstance()){
m_controller->doLoadScript();
}else{
std::string file=filepath;
SP_CALL_FILEFUNC(const_cast<char*>("onReimpAFile"),
const_cast<char*>("s"),
const_cast<char*>(file.data()));
m_controller->refreshBinding();
}
}
};
int PythonScriptControllerClass = core::RegisterObject("A Sofa controller scripted in python")
.add< PythonScriptController >()
;
SOFA_DECL_CLASS(PythonScriptController)
PythonScriptController::PythonScriptController()
: ScriptController()
, m_filename(initData(&m_filename, "filename",
"Python script filename"))
, m_classname(initData(&m_classname, "classname",
"Python class implemented in the script to instanciate for the controller"))
, m_variables(initData(&m_variables, "variables",
"Array of string variables (equivalent to a c-like argv)" ) )
, m_timingEnabled(initData(&m_timingEnabled, true, "timingEnabled",
"Set this attribute to true or false to activate/deactivate the gathering"
" of timing statistics on the python execution time. Default value is set"
"to true." ))
, m_doAutoReload( initData( &m_doAutoReload, false, "autoreload",
"Automatically reload the file when the source code is changed. "
"Default value is set to false" ) )
, m_ScriptControllerClass(0)
, m_ScriptControllerInstance(0)
{
m_filelistener = new MyFileEventListener(this) ;
}
PythonScriptController::~PythonScriptController()
{
if(m_filelistener)
{
FileMonitor::removeListener(m_filelistener) ;
delete m_filelistener ;
}
}
void PythonScriptController::refreshBinding()
{
BIND_OBJECT_METHOD(onLoaded)
BIND_OBJECT_METHOD(createGraph)
BIND_OBJECT_METHOD(initGraph)
BIND_OBJECT_METHOD(bwdInitGraph)
BIND_OBJECT_METHOD(onKeyPressed)
BIND_OBJECT_METHOD(onKeyReleased)
BIND_OBJECT_METHOD(onMouseButtonLeft)
BIND_OBJECT_METHOD(onMouseButtonRight)
BIND_OBJECT_METHOD(onMouseButtonMiddle)
BIND_OBJECT_METHOD(onMouseWheel)
BIND_OBJECT_METHOD(onBeginAnimationStep)
BIND_OBJECT_METHOD(onEndAnimationStep)
BIND_OBJECT_METHOD(storeResetState)
BIND_OBJECT_METHOD(reset)
BIND_OBJECT_METHOD(cleanup)
BIND_OBJECT_METHOD(onGUIEvent)
BIND_OBJECT_METHOD(onScriptEvent)
BIND_OBJECT_METHOD(draw)
BIND_OBJECT_METHOD(onIdle)
}
bool PythonScriptController::isDerivedFrom(const std::string& name, const std::string& module)
{
PyObject* moduleDict = PyModule_GetDict(PyImport_AddModule(module.c_str()));
PyObject* controllerClass = PyDict_GetItemString(moduleDict, name.c_str());
return 1 == PyObject_IsInstance(m_ScriptControllerInstance, controllerClass);
}
void PythonScriptController::loadScript()
{
if(m_doAutoReload.getValue())
{
FileMonitor::addFile(m_filename.getFullPath(), m_filelistener) ;
}
// if the filename is empty, the controller is supposed to be in an already loaded file
// otherwise load the controller's file
if( m_filename.isSet() && !m_filename.getRelativePath().empty() && !PythonEnvironment::runFile(m_filename.getFullPath().c_str()) )
{
SP_MESSAGE_ERROR( getName() << " object - "<<m_filename.getFullPath().c_str()<<" script load error." )
return;
}
// classe
PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__"));
m_ScriptControllerClass = PyDict_GetItemString(pDict,m_classname.getValueString().c_str());
if (!m_ScriptControllerClass)
{
SP_MESSAGE_ERROR( getName() << " load error (class \""<<m_classname.getValueString()<<"\" not found)." )
return;
}
// verify that the class is a subclass of PythonScriptController
if (1!=PyObject_IsSubclass(m_ScriptControllerClass,(PyObject*)&SP_SOFAPYTYPEOBJECT(PythonScriptController)))
{
// LOAD ERROR
SP_MESSAGE_ERROR( getName() << " load error (class \""<<m_classname.getValueString()<<"\" does not inherit from \"Sofa.PythonScriptController\")." )
return;
}
// créer l'instance de la classe
m_ScriptControllerInstance = BuildPySPtr<Base>(this,(PyTypeObject*)m_ScriptControllerClass);
if (!m_ScriptControllerInstance)
{
SP_MESSAGE_ERROR( getName() << " load error (class \""<<m_classname.getValueString()<<"\" instanciation error)." )
return;
}
BIND_OBJECT_METHOD(onLoaded)
BIND_OBJECT_METHOD(createGraph)
BIND_OBJECT_METHOD(initGraph)
BIND_OBJECT_METHOD(bwdInitGraph)
BIND_OBJECT_METHOD(onKeyPressed)
BIND_OBJECT_METHOD(onKeyReleased)
BIND_OBJECT_METHOD(onMouseButtonLeft)
BIND_OBJECT_METHOD(onMouseButtonRight)
BIND_OBJECT_METHOD(onMouseButtonMiddle)
BIND_OBJECT_METHOD(onMouseWheel)
BIND_OBJECT_METHOD(onBeginAnimationStep)
BIND_OBJECT_METHOD(onEndAnimationStep)
BIND_OBJECT_METHOD(storeResetState)
BIND_OBJECT_METHOD(reset)
BIND_OBJECT_METHOD(cleanup)
BIND_OBJECT_METHOD(onGUIEvent)
BIND_OBJECT_METHOD(onScriptEvent)
BIND_OBJECT_METHOD(draw)
BIND_OBJECT_METHOD(onIdle)
}
void PythonScriptController::doLoadScript()
{
loadScript() ;
}
void PythonScriptController::script_onIdleEvent(const IdleEvent* /*event*/)
{
FileMonitor::updates(0);
SP_CALL_MODULEFUNC_NOPARAM(m_Func_onIdle) ;
// Flush the console to avoid the sys.stdout.flush() in each script function.
std::cout.flush() ;
std::cerr.flush() ;
}
void PythonScriptController::script_onLoaded(Node *node)
{
SP_CALL_MODULEFUNC(m_Func_onLoaded, "(O)", sofa::PythonFactory::toPython(node))
}
void PythonScriptController::script_createGraph(Node *node)
{
SP_CALL_MODULEFUNC(m_Func_createGraph, "(O)", sofa::PythonFactory::toPython(node))
}
void PythonScriptController::script_initGraph(Node *node)
{
SP_CALL_MODULEFUNC(m_Func_initGraph, "(O)", sofa::PythonFactory::toPython(node))
}
void PythonScriptController::script_bwdInitGraph(Node *node)
{
SP_CALL_MODULEFUNC(m_Func_bwdInitGraph, "(O)", sofa::PythonFactory::toPython(node))
}
bool PythonScriptController::script_onKeyPressed(const char c)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onKeyPressed", this);
bool b = false;
SP_CALL_MODULEBOOLFUNC(m_Func_onKeyPressed,"(c)", c)
return b;
}
bool PythonScriptController::script_onKeyReleased(const char c)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onKeyReleased", this);
bool b = false;
SP_CALL_MODULEBOOLFUNC(m_Func_onKeyReleased,"(c)", c)
return b;
}
void PythonScriptController::script_onMouseButtonLeft(const int posX,const int posY,const bool pressed)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onMouseButtonLeft",this);
PyObject *pyPressed = pressed? Py_True : Py_False;
SP_CALL_MODULEFUNC(m_Func_onMouseButtonLeft, "(iiO)", posX,posY,pyPressed)
}
void PythonScriptController::script_onMouseButtonRight(const int posX,const int posY,const bool pressed)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onMouseButtonRight", this);
PyObject *pyPressed = pressed? Py_True : Py_False;
SP_CALL_MODULEFUNC(m_Func_onMouseButtonRight, "(iiO)", posX,posY,pyPressed)
}
void PythonScriptController::script_onMouseButtonMiddle(const int posX,const int posY,const bool pressed)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onMouseButtonMiddle", this);
PyObject *pyPressed = pressed? Py_True : Py_False;
SP_CALL_MODULEFUNC(m_Func_onMouseButtonMiddle, "(iiO)", posX,posY,pyPressed)
}
void PythonScriptController::script_onMouseWheel(const int posX,const int posY,const int delta)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onMouseWheel", this);
SP_CALL_MODULEFUNC(m_Func_onMouseWheel, "(iii)", posX,posY,delta)
}
void PythonScriptController::script_onBeginAnimationStep(const double dt)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onBeginAnimationStep", this);
SP_CALL_MODULEFUNC(m_Func_onBeginAnimationStep, "(d)", dt)
}
void PythonScriptController::script_onEndAnimationStep(const double dt)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onEndAnimationStep", this);
SP_CALL_MODULEFUNC(m_Func_onEndAnimationStep, "(d)", dt)
}
void PythonScriptController::script_storeResetState()
{
SP_CALL_MODULEFUNC_NOPARAM(m_Func_storeResetState)
}
void PythonScriptController::script_reset()
{
SP_CALL_MODULEFUNC_NOPARAM(m_Func_reset)
}
void PythonScriptController::script_cleanup()
{
SP_CALL_MODULEFUNC_NOPARAM(m_Func_cleanup)
}
void PythonScriptController::script_onGUIEvent(const char* controlID, const char* valueName, const char* value)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onGUIEvent", this);
SP_CALL_MODULEFUNC(m_Func_onGUIEvent,"(sss)",controlID,valueName,value);
}
void PythonScriptController::script_onScriptEvent(core::objectmodel::ScriptEvent* event)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_onScriptEvent", this);
PythonScriptEvent *pyEvent = static_cast<PythonScriptEvent*>(event);
SP_CALL_MODULEFUNC(m_Func_onScriptEvent,"(OsO)",sofa::PythonFactory::toPython(pyEvent->getSender().get()),pyEvent->getEventName().c_str(),pyEvent->getUserData())
}
void PythonScriptController::script_draw(const core::visual::VisualParams*)
{
ActivableScopedAdvancedTimer advancedTimer(m_timingEnabled.getValue(), "PythonScriptController_draw", this);
SP_CALL_MODULEFUNC_NOPARAM(m_Func_draw)
}
void PythonScriptController::handleEvent(core::objectmodel::Event *event)
{
if (PythonScriptEvent::checkEventType(event))
{
script_onScriptEvent(static_cast<PythonScriptEvent *> (event));
}
else ScriptController::handleEvent(event);
}
} // namespace controller
} // namespace component
} // namespace sofa
| 36.952255 | 165 | 0.695427 | [
"object"
] |
3a9d611d48a58ced136d0040c7a1f7460c7a537a | 18,154 | cpp | C++ | src/ngraph/runtime/plaidml/plaidml_ops_general.cpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/plaidml/plaidml_ops_general.cpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/plaidml/plaidml_ops_general.cpp | tzerrell/ngraph | b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/log.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/op/pad.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/op/result.hpp"
#include "ngraph/op/select.hpp"
#include "ngraph/op/stop_gradient.hpp"
#include "ngraph/runtime/plaidml/plaidml_impl.hpp"
#include "ngraph/runtime/plaidml/plaidml_translate.hpp"
namespace vp = vertexai::plaidml;
namespace ngraph
{
namespace runtime
{
namespace plaidml
{
NGRAPH_PLAIDML_OP_CLASS(ImplBroadcast, OpImpl<op::Broadcast>);
NGRAPH_PLAIDML_OP_CLASS(ImplConstant, OpImpl<op::Constant>);
NGRAPH_PLAIDML_OP_CLASS(ImplGetOutputElement, OpImpl<op::GetOutputElement>);
NGRAPH_PLAIDML_OP_CLASS(ImplPad, OpImpl<op::Pad>);
NGRAPH_PLAIDML_OP_CLASS(ImplReshape, OpImpl<op::Reshape>);
NGRAPH_PLAIDML_OP_CLASS(ImplSelect, OpImpl<op::Select>);
NGRAPH_PLAIDML_OP_CLASS(ImplStopGradient, OpImpl<op::StopGradient>);
}
}
}
// Broadcast broadcasts a tensor to a wider shape.
void ngraph::runtime::plaidml::ImplBroadcast::Apply()
{
check_inputs(1);
check_outputs(1);
auto in_dim_limit = op().get_inputs()[0].get_shape().size();
auto out_dim_limit = op().get_broadcast_shape().size();
NGRAPH_DEBUG << "Broadcast in_dim_limit: " << in_dim_limit
<< " out_dim_limit:" << out_dim_limit;
NGRAPH_DEBUG << "Broadcast axes: " << op().get_broadcast_axes();
NGRAPH_DEBUG << "Broadcast input shape: " << op().get_input_shape(0);
NGRAPH_DEBUG << "Broadcast output shape: " << op().get_broadcast_shape();
auto input_didx = in_dim_limit;
std::vector<std::size_t> out_didxs;
for (std::size_t idx = 0; idx < out_dim_limit; ++idx)
{
if (!op().get_broadcast_axes().count(idx))
{
out_didxs.push_back(out_dim_limit - idx - 1);
}
}
set_output(
start_tile_function()
.add(builder::Input{op_input(0), "I"}.add_rdims("D", in_dim_limit, 0))
.add(builder::Output{"O"})
.add(builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"O"}
.add_rindices("o", out_dim_limit, 0)
.add_dims([&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < out_dim_limit; ++idx)
{
if (op().get_broadcast_axes().count(idx))
{
out = std::to_string(op().get_broadcast_shape()[idx]);
}
else
{
out = "D" + std::to_string(--input_didx);
}
}
}))
.set(builder::ContractionInput{"I"}.add_indices(
[&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < in_dim_limit; ++idx)
{
out = "o" + std::to_string(out_didxs[idx]);
}
})))
.finalize());
}
// Constant fills in a tensor constant.
void ngraph::runtime::plaidml::ImplConstant::Apply()
{
check_inputs(0);
check_outputs(1);
bool output_to_result = false;
for (const std::shared_ptr<Node>& node : op().get_users())
{
if (dynamic_cast<op::Result*>(node.get()))
{
output_to_result = true;
break;
}
}
if (!op().get_shape().size() && !output_to_result)
{
switch (to_plaidml(op().get_element_type()))
{
case PLAIDML_DATA_BOOLEAN:
set_output(static_cast<std::int64_t>(*static_cast<const char*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_INT8:
set_output(
static_cast<std::int64_t>(*static_cast<const std::int8_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_INT16:
set_output(
static_cast<std::int64_t>(*static_cast<const std::int16_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_INT32:
set_output(
static_cast<std::int64_t>(*static_cast<const std::int32_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_INT64:
set_output(*static_cast<const std::int64_t*>(op().get_data_ptr()));
return;
case PLAIDML_DATA_UINT8:
set_output(
static_cast<std::int64_t>(*static_cast<const std::uint8_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_UINT16:
set_output(
static_cast<std::int64_t>(*static_cast<const std::uint16_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_UINT32:
set_output(
static_cast<std::int64_t>(*static_cast<const std::uint32_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_UINT64:
set_output(
static_cast<std::int64_t>(*static_cast<const std::uint64_t*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_FLOAT16:
set_output(static_cast<double>(
static_cast<float>(*static_cast<const half*>(op().get_data_ptr()))));
return;
case PLAIDML_DATA_FLOAT32:
set_output(static_cast<double>(*static_cast<const float*>(op().get_data_ptr())));
return;
case PLAIDML_DATA_FLOAT64:
set_output(static_cast<double>(*static_cast<const double*>(op().get_data_ptr())));
return;
default: break;
}
}
auto tensor = build()->config->dev->allocate(
to_plaidml(build()->config->ctx, op().get_element_type(), op().get_shape()));
{
vp::mapping<char> mp = tensor.map(vp::map_for_write);
const char* src = static_cast<const char*>(op().get_data_ptr());
char* dest = mp.raw();
std::copy(src, src + tensor.get_shape().buffer_size(), dest);
}
set_output(tensor);
}
// GetOutputElement pipes one of its N inputs to its output.
void ngraph::runtime::plaidml::ImplGetOutputElement::Apply()
{
check_inputs_ge(op().get_n() + 1);
check_outputs(1);
set_output(op_input(op().get_n()));
}
// Pad adds interior and exterior padding to a tensor.
void ngraph::runtime::plaidml::ImplPad::Apply()
{
check_inputs(2);
check_outputs(1);
auto tensor = op_input(0);
auto value = op_input(1);
// For padding, we construct two intermediate tensors: the first is the input tensor expanded by
// the requisite padding (with zeros in all padded locations), and the second is a boolean
// tensor expanded the same way, but with true at the source locations and false at the padded
// locations. We then combine these elementwise using a trinary condition, with the pad value
// being used everywhere the boolean intermediate is false.
// It's a little wasteful, but it expresses the logic correctly, and doesn't take long to run;
// the runtime is also free to optimize it through combining the intermediate contractions.
NGRAPH_DEBUG << "Pad below: " << op().get_padding_below();
NGRAPH_DEBUG << "Pad above: " << op().get_padding_above();
NGRAPH_DEBUG << "Pad input dims: " << op().get_input_shape(0);
NGRAPH_DEBUG << "Pad output dims: " << op().get_shape();
// FIXME: Compatibility hack inserted by amprocte, now that nGraph's Pad op no longer supports
// interior padding.
Shape padding_interior(op().get_padding_below().size(), 0);
auto dim_limit = op().get_shape().size();
bool any_zero_dims = false;
for (auto sz : op().get_input_shape(0))
{
if (!sz)
{
any_zero_dims = true;
break;
}
}
auto out_dsize = [&](std::size_t idx) {
std::ostringstream s;
std::size_t total_pad = op().get_padding_below().at(idx) + op().get_padding_above().at(idx);
std::size_t in_dsize = op().get_input_shape(0).at(idx);
if (in_dsize)
{
total_pad += padding_interior.at(idx) * (in_dsize - 1);
}
if (!any_zero_dims)
{
s << "DI" << idx + 1;
if (total_pad)
{
s << " + " << total_pad;
}
}
else
{
s << total_pad + in_dsize;
}
return s.str();
};
auto out_didx = [&](std::size_t idx) {
std::ostringstream s;
auto below = op().get_padding_below().at(idx);
if (below)
{
s << below << " + ";
}
auto interior = padding_interior.at(idx) + 1;
if (interior != 1)
{
s << "(d" << idx + 1 << " * " << interior << ")";
}
else
{
s << "d" << idx + 1;
}
return s.str();
};
auto flag_constraints = [&](std::size_t idx) {
std::ostringstream s;
s << "d" << idx + 1 << " < DI" << idx + 1;
return s.str();
};
auto f = start_tile_function();
f.add(builder::Input{op_input(1), "V"}).add(builder::Output{"O"});
if (!any_zero_dims)
{
f.add(builder::Input{op_input(0), "I"}.add_dims("DI", 1, dim_limit + 1))
.add(builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"P"}
.add_indices(
[&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = out_didx(idx);
}
})
.add_dims([&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = out_dsize(idx);
}
}))
.set(builder::ContractionInput{"I"}.add_indices("d", 1, dim_limit + 1)))
.add(builder::Elementwise{"T", "1"})
.add(builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"F"}
.add_indices(
[&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = out_didx(idx);
}
})
.add_dims([&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = out_dsize(idx);
}
}))
.set(builder::ContractionInput{"T"})
.add_constraints([&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = flag_constraints(idx);
}
}))
.add(builder::Elementwise{"O", "F ? P : V"});
}
else
{
f.add(builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"O"}
.add_indices("d", 0, dim_limit)
.add_dims([&](std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = out_dsize(idx);
}
}))
.set(builder::ContractionInput{"V"}));
}
set_output(f.finalize());
}
// Reshape reshapes an input tensor.
void ngraph::runtime::plaidml::ImplReshape::Apply()
{
check_inputs(1);
check_outputs(1);
// The reshape operation doesn't just describe a new way of looking at an input tensor; it can
// optionally rearrange the elements of the input tensor.
auto src = op_input(0);
auto dim_limit = op().get_inputs()[0].get_shape().size();
if (!dim_limit)
{
// This reshape is being used to create a tensor from a scalar. PlaidML's reshape()
// operation requires a tensor input (as of this writing), so instead of a reshape(), we'll
// just use a contraction to build the tensor.
auto& out_shape = op().get_shape();
set_output(
start_tile_function()
.add(builder::Input{src, "I"})
.add(builder::Output{"O"})
.add(builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"O"}
.add_indices("d", 0, out_shape.size())
.add_dims(
[&](std::back_insert_iterator<std::list<std::string>> out) {
std::transform(
out_shape.begin(),
out_shape.end(),
out,
[](std::size_t sz) { return std::to_string(sz); });
}))
.set(builder::ContractionInput{"I"}))
.finalize());
return;
}
std::size_t dim_idx = 0;
auto input_order = op().get_input_order();
for (std::size_t src_idx : op().get_input_order())
{
if (src_idx != dim_idx++)
{
// This reshape operation doesn't just describe a new way of looking at an input tensor;
// it's also rearranging the elements of the input tensor. This is pretty easy to
// handle with a contraction.
src =
start_tile_function()
.add(builder::Input{src, "I"}.add_dims("D", 1, dim_limit + 1))
.add(builder::Output{"O"})
.add(
builder::UnaryContraction{"="}
.set(builder::ContractionOutput{"O"}
.add_indices([&](
std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = "d" + std::to_string(input_order[idx] + 1);
}
})
.add_dims([&](
std::back_insert_iterator<std::list<std::string>> out) {
for (std::size_t idx = 0; idx < dim_limit; ++idx)
{
out = "D" + std::to_string(input_order[idx] + 1);
}
}))
.set(builder::ContractionInput{"I"}.add_indices("d", 1, dim_limit + 1)))
.finalize();
break;
}
}
std::ostringstream reshape_expr;
reshape_expr << "reshape(I";
for (std::size_t dsize : op().get_output_shape())
{
reshape_expr << ", " << dsize;
}
reshape_expr << ")";
set_output(start_tile_function()
.add(builder::Input{src, "I"})
.add(builder::Output{"O"})
.add(builder::Elementwise("O", reshape_expr.str()))
.finalize());
}
// Select conditionally selects elements from input tensors.
void ngraph::runtime::plaidml::ImplSelect::Apply()
{
check_inputs(3);
check_outputs(1);
set_output(start_tile_function()
.add(builder::Input{op_input(0), "C"})
.add(builder::Input{op_input(1), "T"})
.add(builder::Input{op_input(2), "F"})
.add(builder::Output{"O"})
.add(builder::Elementwise{"O", "C ? T : F"})
.finalize());
}
// Used by nGraph for bprop graph generation, no-op as a kernel
void ngraph::runtime::plaidml::ImplStopGradient::Apply()
{
set_output(start_tile_function()
.add(builder::Output{"O"})
.add(builder::Elementwise{"O", "0"})
.finalize());
}
| 39.724289 | 100 | 0.488873 | [
"shape",
"vector",
"transform"
] |
3aa6cbb33fc3689709e72f6be6a59110356ddf2e | 2,314 | cpp | C++ | src/ErrorReporting/Error.cpp | little-blue/Surelog | 1c2459f841f6e6d923b336feacd22ccfb9aea845 | [
"Apache-2.0"
] | null | null | null | src/ErrorReporting/Error.cpp | little-blue/Surelog | 1c2459f841f6e6d923b336feacd22ccfb9aea845 | [
"Apache-2.0"
] | null | null | null | src/ErrorReporting/Error.cpp | little-blue/Surelog | 1c2459f841f6e6d923b336feacd22ccfb9aea845 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2019 Alain Dargelas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* File: Error.cpp
* Author: alain
*
* Created on March 5, 2017, 11:30 PM
*/
#include <Surelog/ErrorReporting/Error.h>
namespace SURELOG {
Error::Error(ErrorDefinition::ErrorType errorId, const Location& loc,
const std::vector<Location>* extraLocs)
: m_errorId(errorId), m_reported(false), m_waived(false) {
m_locations.push_back(loc);
if (extraLocs) {
for (const auto& location : *extraLocs) m_locations.push_back(location);
}
}
Error::Error(ErrorDefinition::ErrorType errorId, const Location& loc,
const Location& extra)
: m_errorId(errorId), m_reported(false), m_waived(false) {
m_locations.push_back(loc);
m_locations.push_back(extra);
}
Error::Error(ErrorDefinition::ErrorType errorId,
const std::vector<Location>& locations)
: m_errorId(errorId), m_reported(false), m_waived(false) {
for (const auto& location : locations) m_locations.push_back(location);
}
bool Error::operator==(const Error& rhs) const {
if (m_errorId != rhs.m_errorId) return false;
if (m_locations.size() < rhs.m_locations.size())
return std::equal(m_locations.begin(), m_locations.end(),
rhs.m_locations.begin());
else
return std::equal(rhs.m_locations.begin(), rhs.m_locations.end(),
m_locations.begin());
}
bool Error::operator<(const Error& rhs) const {
if (m_errorId < rhs.m_errorId) return true;
if (m_locations.size() < rhs.m_locations.size()) return true;
if (m_reported != rhs.m_reported) return false;
if (m_waived != rhs.m_waived) return false;
for (unsigned int i = 0; i < m_locations.size(); i++) {
if (m_locations[i] < rhs.m_locations[i]) return true;
}
return false;
}
} // namespace SURELOG
| 32.138889 | 76 | 0.700086 | [
"vector"
] |
3aab9217d2eb186631f3cbfee7ecd6ef4c0c5ea4 | 15,567 | cpp | C++ | plugins/community/repos/dBiz/src/TROSC.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/dBiz/src/TROSC.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/dBiz/src/TROSC.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z |
#include "dBiz.hpp"
#include "dsp/decimator.hpp"
#include "dsp/filter.hpp"
namespace rack_plugin_dBiz {
extern float sawTable[2048];
extern float triTable[2048];
template <int OVERSAMPLE, int QUALITY>
struct VoltageControlledOscillator
{
bool analog = false;
bool soft = false;
float lastSyncValue = 0.0f;
float phase = 0.0f;
float freq;
float pw = 0.5f;
float pitch;
bool syncEnabled = false;
bool syncDirection = false;
Decimator<OVERSAMPLE, QUALITY> sinDecimator;
Decimator<OVERSAMPLE, QUALITY> triDecimator;
Decimator<OVERSAMPLE, QUALITY> sawDecimator;
Decimator<OVERSAMPLE, QUALITY> sqrDecimator;
RCFilter sqrFilter;
// For analog detuning effect
float pitchSlew = 0.0f;
int pitchSlewIndex = 0;
float sinBuffer[OVERSAMPLE] = {};
float triBuffer[OVERSAMPLE] = {};
float sawBuffer[OVERSAMPLE] = {};
float sqrBuffer[OVERSAMPLE] = {};
void setPitch(float pitchKnob, float pitchCv)
{
// Compute frequency
pitch = pitchKnob;
if (analog)
{
// Apply pitch slew
const float pitchSlewAmount = 3.0f;
pitch += pitchSlew * pitchSlewAmount;
}
else
{
// Quantize coarse knob if digital mode
pitch = roundf(pitch);
}
pitch += pitchCv;
// Note C4
freq = 261.626f * powf(2.0f, pitch / 12.0f);
}
void setPulseWidth(float pulseWidth)
{
const float pwMin = 0.01f;
pw = clamp(pulseWidth, pwMin, 1.0f - pwMin);
}
void process(float deltaTime, float syncValue)
{
if (analog)
{
// Adjust pitch slew
if (++pitchSlewIndex > 32)
{
const float pitchSlewTau = 100.0f; // Time constant for leaky integrator in seconds
pitchSlew += (randomNormal() - pitchSlew / pitchSlewTau) * engineGetSampleTime();
pitchSlewIndex = 0;
}
}
// Advance phase
float deltaPhase = clamp(freq * deltaTime, 1e-6, 0.5f);
// Detect sync
int syncIndex = -1; // Index in the oversample loop where sync occurs [0, OVERSAMPLE)
float syncCrossing = 0.0f; // Offset that sync occurs [0.0f, 1.0f)
if (syncEnabled)
{
syncValue -= 0.01f;
if (syncValue > 0.0f && lastSyncValue <= 0.0f)
{
float deltaSync = syncValue - lastSyncValue;
syncCrossing = 1.0f - syncValue / deltaSync;
syncCrossing *= OVERSAMPLE;
syncIndex = (int)syncCrossing;
syncCrossing -= syncIndex;
}
lastSyncValue = syncValue;
}
if (syncDirection)
deltaPhase *= -1.0f;
sqrFilter.setCutoff(40.0f * deltaTime);
for (int i = 0; i < OVERSAMPLE; i++)
{
if (syncIndex == i)
{
if (soft)
{
syncDirection = !syncDirection;
deltaPhase *= -1.0f;
}
else
{
// phase = syncCrossing * deltaPhase / OVERSAMPLE;
phase = 0.0f;
}
}
if (analog)
{
// Quadratic approximation of sine, slightly richer harmonics
if (phase < 0.5f)
sinBuffer[i] = 1.f - 16.f * powf(phase - 0.25f, 2);
else
sinBuffer[i] = -1.f + 16.f * powf(phase - 0.75f, 2);
sinBuffer[i] *= 1.08f;
}
else
{
sinBuffer[i] = sinf(2.f * M_PI * phase);
}
if (analog)
{
triBuffer[i] = 1.25f * interpolateLinear(triTable, phase * 2047.f);
}
else
{
if (phase < 0.25f)
triBuffer[i] = 4.f * phase;
else if (phase < 0.75f)
triBuffer[i] = 2.f - 4.f * phase;
else
triBuffer[i] = -4.f + 4.f * phase;
}
if (analog)
{
sawBuffer[i] = 1.66f * interpolateLinear(sawTable, phase * 2047.f);
}
else
{
if (phase < 0.5f)
sawBuffer[i] = 2.f * phase;
else
sawBuffer[i] = -2.f + 2.f * phase;
}
sqrBuffer[i] = (phase < pw) ? 1.f : -1.f;
if (analog)
{
// Simply filter here
sqrFilter.process(sqrBuffer[i]);
sqrBuffer[i] = 0.71f * sqrFilter.highpass();
}
// Advance phase
phase += deltaPhase / OVERSAMPLE;
phase = eucmod(phase, 1.0f);
}
}
float sin()
{
return sinDecimator.process(sinBuffer);
}
float tri()
{
return triDecimator.process(triBuffer);
}
float saw()
{
return sawDecimator.process(sawBuffer);
}
float sqr()
{
return sqrDecimator.process(sqrBuffer);
}
float light()
{
return sinf(2 * M_PI * phase);
}
};
struct TROSC : Module
{
enum ParamIds
{
LINK_A_PARAM,
LINK_B_PARAM,
MODE_A_PARAM,
SYNC_A_PARAM,
MODE_B_PARAM,
SYNC_B_PARAM,
MODE_C_PARAM,
SYNC_C_PARAM,
WAVE_A_SEL_PARAM,
WAVE_B_SEL_PARAM,
WAVE_C_SEL_PARAM,
FREQ_A_PARAM,
FINE_A_PARAM,
FREQ_B_PARAM,
FINE_B_PARAM,
FREQ_C_PARAM,
FINE_C_PARAM,
FM_A_PARAM,
FM_B_PARAM,
FM_C_PARAM,
LEVEL_A_PARAM,
LEVEL_B_PARAM,
LEVEL_C_PARAM,
WAVE_A_MIX,
WAVE2_A_MIX,
WAVE_B_MIX,
WAVE2_B_MIX,
WAVE_C_MIX,
C_WIDTH_PARAM,
NUM_PARAMS
};
enum InputIds
{
PITCH_A_INPUT,
PITCH_B_INPUT,
PITCH_C_INPUT,
SYNC_A_INPUT,
SYNC_B_INPUT,
SYNC_C_INPUT,
FM_A_INPUT,
FM_B_INPUT,
FM_C_INPUT,
A_WAVE_MIX_INPUT,
B_WAVE_MIX_INPUT,
C_WAVE_MIX_INPUT,
A_VOL_IN,
B_VOL_IN,
C_VOL_IN,
C_WIDTH_INPUT,
NUM_INPUTS
};
enum OutputIds
{
A_OUTPUT,
B_OUTPUT,
C_OUTPUT,
MIX_OUTPUT,
NUM_OUTPUTS
};
enum LightIds
{
NUM_LIGHTS
};
VoltageControlledOscillator<8, 8> a_osc;
VoltageControlledOscillator<8, 8> b_osc;
VoltageControlledOscillator<8, 8> c_osc;
TROSC() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
void step() override;
// For more advanced Module features, read Rack's engine.hpp header file
// - toJson, fromJson: serialization of internal data
// - onSampleRateChange: event triggered by a change of sample rate
// - onReset, onRandomize, onCreate, onDelete: implements special behavior when user clicks these from the context menu
};
void TROSC::step() {
float a_pitchCv = 0.0;
float b_pitchCv = 0.0;
float c_pitchCv = 0.0;
a_osc.analog = params[MODE_A_PARAM].value > 0.0f;
a_osc.soft = params[SYNC_A_PARAM].value <= 0.0f;
b_osc.analog = params[MODE_B_PARAM].value > 0.0f;
b_osc.soft = params[SYNC_B_PARAM].value <= 0.0f;
c_osc.analog = params[MODE_C_PARAM].value > 0.0f;
c_osc.soft = params[SYNC_C_PARAM].value <= 0.0f;
float a_pitchFine = 3.0f * quadraticBipolar(params[FINE_A_PARAM].value);
a_pitchCv = 12.0f * inputs[PITCH_A_INPUT].value;
float b_pitchFine = 3.0f * quadraticBipolar(params[FINE_B_PARAM].value);
if(params[LINK_A_PARAM].value==1)
b_pitchCv = 12.0f * inputs[PITCH_B_INPUT].value;
else
b_pitchCv = a_pitchCv ;
float c_pitchFine = 3.0f * quadraticBipolar(params[FINE_C_PARAM].value);
if (params[LINK_B_PARAM].value == 1)
c_pitchCv = 12.0f * inputs[PITCH_C_INPUT].value;
else
c_pitchCv = b_pitchCv;
if (inputs[FM_A_INPUT].active)
{
a_pitchCv += quadraticBipolar(params[FM_A_PARAM].value) * 12.0f * inputs[FM_A_INPUT].value;
}
a_osc.setPitch(params[FREQ_A_PARAM].value, a_pitchFine + a_pitchCv);
a_osc.syncEnabled = inputs[SYNC_A_INPUT].active;
if (inputs[FM_B_INPUT].active)
{
b_pitchCv += quadraticBipolar(params[FM_B_PARAM].value) * 12.0f * inputs[FM_B_INPUT].value;
}
b_osc.setPitch(params[FREQ_B_PARAM].value, b_pitchFine + b_pitchCv);
b_osc.syncEnabled = inputs[SYNC_B_INPUT].active;
if (inputs[FM_C_INPUT].active)
{
c_pitchCv += quadraticBipolar(params[FM_C_PARAM].value) * 12.0f * inputs[FM_C_INPUT].value;
}
c_osc.setPitch(params[FREQ_C_PARAM].value, c_pitchFine + c_pitchCv);
c_osc.setPulseWidth(0.5+params[C_WIDTH_PARAM].value * inputs[C_WIDTH_INPUT].value / 10.0f);
c_osc.syncEnabled = inputs[SYNC_C_INPUT].active;
a_osc.process(engineGetSampleTime(), inputs[SYNC_A_INPUT].value);
b_osc.process(engineGetSampleTime(), inputs[SYNC_A_INPUT].value);
c_osc.process(engineGetSampleTime(), inputs[SYNC_A_INPUT].value);
// Set output
float wave_a = clamp(params[WAVE_A_MIX].value, 0.0f, 1.0f);
float wave2_a = clamp(params[WAVE2_A_MIX].value, 0.0f, 1.0f);
float mix_a = clamp(params[WAVE_A_SEL_PARAM].value, 0.0f, 1.0f)*clamp(inputs[A_WAVE_MIX_INPUT].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
float wave_b = clamp(params[WAVE_B_MIX].value, 0.0f, 1.0f);
float wave2_b = clamp(params[WAVE2_B_MIX].value, 0.0f, 1.0f);
float mix_b = clamp(params[WAVE_B_SEL_PARAM].value, 0.0f, 1.0f)*clamp(inputs[B_WAVE_MIX_INPUT].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
float wave_c = clamp(params[WAVE_C_MIX].value, 0.0f, 1.0f);
float mix_c = clamp(params[WAVE_C_SEL_PARAM].value, 0.0f, 1.0f)*clamp(inputs[C_WAVE_MIX_INPUT].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
float out_a;
float out2_a;
float a_out;
float out_b;
float out2_b;
float b_out;
float out_c;
float out2_c;
float c_out;
float mixa,mixb,mixc;
out_a = crossfade(a_osc.sin(), a_osc.tri(), wave_a);
out2_a = crossfade(a_osc.saw(), a_osc.sqr(), wave2_a);
a_out = crossfade(out_a, out2_a, mix_a);
out_b = crossfade(b_osc.sin(), b_osc.tri(), wave_b);
out2_b = crossfade(b_osc.saw(), b_osc.sqr(), wave2_b);
b_out = crossfade(out_b, out2_b, mix_b);
out_c = crossfade(c_osc.sin(), c_osc.tri(), wave_c);
out2_c =c_osc.sqr();
c_out = crossfade(out_c, out2_c, mix_c);
mixa = 2.0f * (a_out)*params[LEVEL_A_PARAM].value*clamp(inputs[A_VOL_IN].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
outputs[A_OUTPUT].value= mixa;
mixb = 2.0f * (b_out)*params[LEVEL_B_PARAM].value*clamp(inputs[B_VOL_IN].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
outputs[B_OUTPUT].value = mixb;
mixc = 2.0f * (c_out)*params[LEVEL_C_PARAM].value*clamp(inputs[C_VOL_IN].normalize(10.0f) / 10.0f, 0.0f, 1.0f);
outputs[C_OUTPUT].value = mixc;
outputs[MIX_OUTPUT].value = mixa+mixb+mixc;
}
struct TROSCWidget : ModuleWidget {
TROSCWidget(TROSC *module) : ModuleWidget(module) {
setPanel(SVG::load(assetPlugin(plugin, "res/TROSC.svg")));
addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0)));
addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0)));
addChild(Widget::create<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH)));
int space = 170;
int vspace = 50;
addParam(ParamWidget::create<VerboDL>(Vec(30,20), module, TROSC::FREQ_A_PARAM,-54.0f, 54.0f, 0.0f));
addParam(ParamWidget::create<VerboDL>(Vec(30, 150), module, TROSC::FREQ_B_PARAM, -54.0f, 54.0f, 0.0f));
addParam(ParamWidget::create<VerboDL>(Vec(30, 280), module, TROSC::FREQ_C_PARAM, -54.0f, 54.0f, 0.0f));
addParam(ParamWidget::create<CKSS>(Vec(5, 5 + 20), module, TROSC::MODE_A_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<CKSS>(Vec(5, 5 + 150), module, TROSC::MODE_B_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<CKSS>(Vec(5, 5 + 280), module, TROSC::MODE_C_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<CKSS>(Vec(143, 75 + 20), module, TROSC::SYNC_A_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<CKSS>(Vec(143, 75 + 150), module, TROSC::SYNC_B_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<CKSS>(Vec(143, 75 + 280), module, TROSC::SYNC_C_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(110, 20), module, TROSC::FINE_A_PARAM, -1.0f, 1.0f, 0.0f));
addParam(ParamWidget::create<VerboDS>(Vec(110, 150), module, TROSC::FINE_B_PARAM, -1.0f, 1.0f, 0.0f));
addParam(ParamWidget::create<VerboDS>(Vec(110, 280), module, TROSC::FINE_C_PARAM, -1.0f, 1.0f, 0.0f));
addParam(ParamWidget::create<VerboDS>(Vec(150, 20 -10), module, TROSC::FM_A_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(150, 150-10), module, TROSC::FM_B_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(150, 280-10), module, TROSC::FM_C_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(250, vspace+20), module, TROSC::LEVEL_A_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(250, vspace+150), module, TROSC::LEVEL_B_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(250, vspace+280), module, TROSC::LEVEL_C_PARAM , 0.0, 1.0, 0.0));
addParam(ParamWidget::create<LEDSliderGreen>(Vec(20+space, 20), module, TROSC::WAVE_A_MIX, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<LEDSliderGreen>(Vec(50 + space, 20), module, TROSC::WAVE2_A_MIX, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<LEDSliderGreen>(Vec(20 + space, 150), module, TROSC::WAVE_B_MIX, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<LEDSliderGreen>(Vec(50 + space, 150), module, TROSC::WAVE2_B_MIX, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<LEDSliderGreen>(Vec(20 + space, 280), module, TROSC::WAVE_C_MIX, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<VerboDS>(Vec(40 + space, 290), module, TROSC::C_WIDTH_PARAM, 0.0, 1.0, 0.0));
addParam(ParamWidget::create<Trimpot>(Vec(73 + space, 20 -10), module, TROSC::WAVE_A_SEL_PARAM, 0.0, 1.0, 0.5));
addParam(ParamWidget::create<Trimpot>(Vec(73 + space, 150-10), module, TROSC::WAVE_B_SEL_PARAM, 0.0, 1.0, 0.5));
addParam(ParamWidget::create<Trimpot>(Vec(73 + space, 280-10), module, TROSC::WAVE_C_SEL_PARAM, 0.0, 1.0, 0.5));
addInput(Port::create<PJ301MCPort>(Vec(100 + space,20-13), Port::INPUT, module, TROSC::A_WAVE_MIX_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(100 + space,150-13), Port::INPUT, module, TROSC::B_WAVE_MIX_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(100 + space,280-13), Port::INPUT, module, TROSC::C_WAVE_MIX_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(2, 30 + 20), Port::INPUT, module, TROSC::PITCH_A_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(2, 30 + 150), Port::INPUT, module, TROSC::PITCH_B_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(2, 30 + 280), Port::INPUT, module, TROSC::PITCH_C_INPUT));
addParam(ParamWidget::create<SilverSwitch>(Vec(60, 90 + 20), module, TROSC::LINK_A_PARAM,0.0,1.0,0.0));
addParam(ParamWidget::create<SilverSwitch>(Vec(60, 90 + 150),module, TROSC::LINK_B_PARAM,0.0,1.0,0.0));
addInput(Port::create<PJ301MOrPort>(Vec(115, 55 + 20), Port::INPUT, module, TROSC::SYNC_A_INPUT));
addInput(Port::create<PJ301MOrPort>(Vec(115, 55 + 150), Port::INPUT, module, TROSC::SYNC_B_INPUT));
addInput(Port::create<PJ301MOrPort>(Vec(115, 55 + 280), Port::INPUT, module, TROSC::SYNC_C_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(155, 45 + 20), Port::INPUT, module, TROSC::FM_A_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(155, 45 + 150), Port::INPUT, module, TROSC::FM_B_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(155, 45 + 280), Port::INPUT, module, TROSC::FM_C_INPUT));
addInput(Port::create<PJ301MCPort>(Vec(290,vspace+10+20), Port::INPUT, module, TROSC::A_VOL_IN));
addInput(Port::create<PJ301MCPort>(Vec(290,vspace+10+150), Port::INPUT, module, TROSC::B_VOL_IN));
addInput(Port::create<PJ301MCPort>(Vec(290,vspace+10+280), Port::INPUT, module, TROSC::C_VOL_IN));
addInput(Port::create<PJ301MCPort>(Vec(215, 50 + 280), Port::INPUT, module, TROSC::C_WIDTH_INPUT));
addOutput(Port::create<PJ301MOPort>(Vec(290, 30), Port::OUTPUT, module, TROSC::MIX_OUTPUT));
addOutput(Port::create<PJ301MOPort>(Vec(255, 20 + 20), Port::OUTPUT, module, TROSC::A_OUTPUT));
addOutput(Port::create<PJ301MOPort>(Vec(255, 20 + 150), Port::OUTPUT, module, TROSC::B_OUTPUT));
addOutput(Port::create<PJ301MOPort>(Vec(255, 20 + 280), Port::OUTPUT, module, TROSC::C_OUTPUT));
}
};
} // namespace rack_plugin_dBiz
using namespace rack_plugin_dBiz;
RACK_PLUGIN_MODEL_INIT(dBiz, TROSC) {
// Specify the Module and ModuleWidget subclass, human-readable
// author name for categorization per plugin, module slug (should never
// change), human-readable module name, and any number of tags
// (found in `include/tags.hpp`) separated by commas.
Model *modelTROSC = Model::create<TROSC, TROSCWidget>("dBiz", "TROSC", "Triple Oscillator", OSCILLATOR_TAG);
return modelTROSC;
}
| 31.196393 | 134 | 0.69082 | [
"model"
] |
3aaee48d08bf4aa77c43761deede619628ad3870 | 32,951 | cc | C++ | astrobee/behaviors/inspection/src/inspection_node.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | 1 | 2021-12-07T22:59:34.000Z | 2021-12-07T22:59:34.000Z | astrobee/behaviors/inspection/src/inspection_node.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | null | null | null | astrobee/behaviors/inspection/src/inspection_node.cc | oleg-alexandrov/isaac | 94996bc1a20fa090336e67b3db5c10a9bb30f0f7 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The "ISAAC - Integrated System for Autonomous and Adaptive Caretaking
* platform" software is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
// Standard ROS includes
#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include <ros/ros.h>
#include <ros/package.h>
// Include inspection library header
#include <inspection/inspection.h>
// TF2 support
#include <tf2_ros/transform_listener.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
// Shared project includes
#include <ff_util/ff_nodelet.h>
#include <ff_util/ff_action.h>
#include <ff_util/ff_service.h>
#include <ff_util/ff_fsm.h>
#include <ff_util/config_server.h>
#include <ff_util/config_client.h>
#include <isaac_util/isaac_names.h>
// Software messages
#include <sensor_msgs/CompressedImage.h>
#include <ff_msgs/CommandConstants.h>
#include <ff_msgs/CommandStamped.h>
#include <isaac_msgs/InspectionState.h>
// Services
#include <ff_msgs/SetState.h>
// Actions
#include <ff_msgs/MotionAction.h>
#include <ff_msgs/DockAction.h>
#include <isaac_msgs/InspectionAction.h>
#include <isaac_msgs/ImageInspectionAction.h>
// Eigen for math
#include <Eigen/Dense>
typedef actionlib::SimpleActionServer<isaac_msgs::InspectionAction> Server;
/**
* \ingroup beh
*/
namespace inspection {
// Match the internal states and responses with the message definition
using FSM = ff_util::FSM;
using STATE = isaac_msgs::InspectionState;
using RESPONSE = isaac_msgs::InspectionResult;
/*
This class provides the high-level logic that allows the freeflyer to
perform inspection, detecting any anomaly. Please see the accompanying
state diagram for a high level overview of this logic.
Here are the rules of inspection:
* Vent blocked: the freeflyer will approach the possibly obstructed
vent and run image analysis to detect if the vent is obstructed.
* Other: todo
*/
class InspectionNode : public ff_util::FreeFlyerNodelet {
public:
// All possible events that can occur
enum : FSM::Event {
READY = (1<<0), // System is initialized
GOAL_INSPECT = (1<<1), // Goal to start inspection
GOAL_CANCEL = (1<<2), // Cancel an existing goal
GOAL_PREEMPT = (1<<3), // Preempt an existing goal
GOAL_PAUSE = (1<<4), // Pause an existing goal
GOAL_UNPAUSE = (1<<5), // Resume an existing goal
MOTION_SUCCESS = (1<<6), // Mobility motion action success
MOTION_FAILED = (1<<7), // Mobility motion action problem
MOTION_UPDATE = (1<<8), // Mobility motion update
DOCK_SUCCESS = (1<<9), // Dock motion action success
DOCK_FAILED = (1<<10), // Dock motion action problem
DOCK_UPDATE = (1<<11), // Dock motion update
NEXT_INSPECT = (1<<12), // Visual Inspection action success
INSPECT_FAILED = (1<<13), // Visual inspection action problem
INSPECT_UPDATE = (1<<14), // Visual inspection update
MANUAL_STATE_SET = (1<<15) // Setting the state manually with service
};
InspectionNode() : ff_util::FreeFlyerNodelet(NODE_INSPECTION, false),
fsm_(STATE::INITIALIZING, std::bind(&InspectionNode::UpdateCallback,
this, std::placeholders::_1, std::placeholders::_2)) {
// Add the state transition lambda functions - refer to the FSM diagram
// [0]
fsm_.Add(STATE::INITIALIZING,
READY, [this](FSM::Event const& event) -> FSM::State {
return STATE::WAITING;
});
// [1]
fsm_.Add(STATE::WAITING,
GOAL_INSPECT | GOAL_UNPAUSE, [this](FSM::Event const& event) -> FSM::State {
Dock("UNDOCK");
return STATE::INIT_INSPECTION;
});
// [2]
fsm_.Add(STATE::INIT_INSPECTION,
DOCK_SUCCESS, [this](FSM::Event const& event) -> FSM::State {
switch (goal_.command) {
// Vent command
case isaac_msgs::InspectionGoal::ANOMALY:
if (inspection_->GenSegment(goal_.inspect_poses.poses[goal_counter_])) {
MoveInspect(ff_msgs::MotionGoal::NOMINAL, inspection_->GetInspectionPose());
return STATE::MOVING_TO_APPROACH_POSE;
} else {
Result(RESPONSE::MOTION_APPROACH_FAILED);
return STATE::WAITING;
}
// Geometry or Panorama command
case isaac_msgs::InspectionGoal::GEOMETRY:
case isaac_msgs::InspectionGoal::PANORAMA:
MoveInspect(ff_msgs::MotionGoal::NOMINAL, goal_.inspect_poses.poses[goal_counter_]);
return STATE::MOVING_TO_APPROACH_POSE;
// Volumetric command
case isaac_msgs::InspectionGoal::VOLUMETRIC:
MoveInspect(ff_msgs::MotionGoal::NOMINAL, goal_.inspect_poses.poses[goal_counter_]);
return STATE::VOL_INSPECTION;
}
return STATE::WAITING;
});
fsm_.Add(STATE::INIT_INSPECTION,
DOCK_FAILED, [this](FSM::Event const& event) -> FSM::State {
Result(RESPONSE::DOCK_FAILED);
return STATE::WAITING;
});
// [3]
fsm_.Add(STATE::MOVING_TO_APPROACH_POSE,
MOTION_SUCCESS, [this](FSM::Event const& event) -> FSM::State {
ImageInspect();
return STATE::VISUAL_INSPECTION;
});
// [4]
fsm_.Add(STATE::VISUAL_INSPECTION,
NEXT_INSPECT, [this](FSM::Event const& event) -> FSM::State {
// After successful inspection, can increment the counter
goal_counter_++;
// There is more to inspect
if (goal_counter_ < goal_.inspect_poses.poses.size()) {
switch (goal_.command) {
// Vent command
case isaac_msgs::InspectionGoal::ANOMALY:
if (inspection_->GenSegment(goal_.inspect_poses.poses[goal_counter_])) {
MoveInspect(ff_msgs::MotionGoal::NOMINAL, inspection_->GetInspectionPose());
return STATE::MOVING_TO_APPROACH_POSE;
} else {
Result(RESPONSE::MOTION_APPROACH_FAILED);
return STATE::WAITING;
}
case isaac_msgs::InspectionGoal::GEOMETRY:
case isaac_msgs::InspectionGoal::PANORAMA:
MoveInspect(ff_msgs::MotionGoal::NOMINAL, goal_.inspect_poses.poses[goal_counter_]);
return STATE::MOVING_TO_APPROACH_POSE;
}
}
// Inspection is over, return
Result(RESPONSE::SUCCESS);
return STATE::WAITING;
});
// [5]
fsm_.Add(STATE::VOL_INSPECTION,
MOTION_SUCCESS, [this](FSM::Event const& event) -> FSM::State {
// After successful inspection, can increment the counter
goal_counter_++;
// There is more to inspect
if (goal_counter_ < goal_.inspect_poses.poses.size()) {
MoveInspect(ff_msgs::MotionGoal::NOMINAL, goal_.inspect_poses.poses[goal_counter_]);
return STATE::VOL_INSPECTION;
}
// Inspection is over, return
Result(RESPONSE::SUCCESS);
Dock("DOCK");
return STATE::RETURN_INSPECTION;
});
// [6]
fsm_.Add(STATE::RETURN_INSPECTION,
DOCK_SUCCESS | DOCK_FAILED | MOTION_SUCCESS, [this](FSM::Event const& event) -> FSM::State {
return STATE::WAITING;
});
// [7]
fsm_.Add(MOTION_FAILED | INSPECT_FAILED,
[this](FSM::State const& state, FSM::Event const& event) -> FSM::State {
switch (event) {
case MOTION_FAILED:
Result(RESPONSE::MOTION_APPROACH_FAILED);
break;
case INSPECT_FAILED:
Result(RESPONSE::VISUAL_INSPECTION_FAILED);
break;
}
return STATE::WAITING;
});
//////////////////////////////////////////////////////
// CATCH-ALL FOR CANCELLATIONS / PREEMPTION / PAUSE //
//////////////////////////////////////////////////////
fsm_.Add(GOAL_CANCEL | GOAL_PREEMPT | GOAL_PAUSE,
[this](FSM::State const& state, FSM::Event const& event) -> FSM::State {
switch (state) {
// Dock/Undock in progress
case STATE::INIT_INSPECTION:
client_d_.CancelGoal();
break;
// Motion in progress
case STATE::MOVING_TO_APPROACH_POSE:
client_m_.CancelGoal();
break;
case STATE::RETURN_INSPECTION:
client_m_.CancelGoal();
client_d_.CancelGoal();
break;
// Visual Inspection in progress
case STATE::VISUAL_INSPECTION:
break;
}
// After cancellations, wait
return STATE::WAITING;
});
}
~InspectionNode() {}
protected:
void Initialize(ros::NodeHandle* nh) {
nh_ = nh;
// Set the config path to ISAAC
char *path = getenv("ISAAC_CONFIG_DIR");
if (path != NULL)
cfg_.SetPath(path);
// Grab some configuration parameters for this node from the LUA config reader
cfg_.Initialize(GetPrivateHandle(), "behaviors/inspection.config");
if (!cfg_.Listen(boost::bind(
&InspectionNode::ReconfigureCallback, this, _1)))
return AssertFault(ff_util::INITIALIZATION_FAILED,
"Could not load config");
// Publish the inspection state as a latched topic
pub_state_ = nh->advertise<isaac_msgs::InspectionState>(
TOPIC_BEHAVIORS_INSPECTION_STATE, 1, true);
// Publish the guest science command fr the sci cam
pub_guest_sci_ = nh->advertise<ff_msgs::CommandStamped>(
TOPIC_COMMAND, 1, true);
// Subscribe to the sci camera topic to make sure a picture was taken
sub_sci_cam_ = nh->subscribe(TOPIC_HARDWARE_SCI_CAM + std::string("/compressed"), 1,
&InspectionNode::SciCamCallback, this);
// Allow the state to be manually set
server_set_state_ = nh->advertiseService(SERVICE_BEHAVIORS_INSPECTION_SET_STATE,
&InspectionNode::SetStateCallback, this);
// Setup move client action
client_m_.SetConnectedTimeout(cfg_.Get<double>("timeout_motion_connected"));
client_m_.SetActiveTimeout(cfg_.Get<double>("timeout_motion_active"));
client_m_.SetResponseTimeout(cfg_.Get<double>("timeout_motion_response"));
client_m_.SetFeedbackCallback(std::bind(&InspectionNode::MFeedbackCallback,
this, std::placeholders::_1));
client_m_.SetResultCallback(std::bind(&InspectionNode::MResultCallback,
this, std::placeholders::_1, std::placeholders::_2));
client_m_.SetConnectedCallback(std::bind(
&InspectionNode::ConnectedCallback, this));
client_m_.Create(nh, ACTION_MOBILITY_MOTION);
// Setup dock client action
client_d_.SetConnectedTimeout(cfg_.Get<double>("timeout_dock_connected"));
client_d_.SetActiveTimeout(cfg_.Get<double>("timeout_dock_active"));
client_d_.SetResponseTimeout(cfg_.Get<double>("timeout_dock_response"));
client_d_.SetFeedbackCallback(std::bind(&InspectionNode::DFeedbackCallback,
this, std::placeholders::_1));
client_d_.SetResultCallback(std::bind(&InspectionNode::DResultCallback,
this, std::placeholders::_1, std::placeholders::_2));
client_d_.SetConnectedCallback(std::bind(
&InspectionNode::ConnectedCallback, this));
client_d_.Create(nh, ACTION_BEHAVIORS_DOCK);
// Get parameter whether we running this in simulation or the robot
ros::param::get("sim_mode", sim_mode_);
// Setup image analysis client action
client_i_.SetConnectedTimeout(cfg_.Get<double>("timeout_image_analysis_connected"));
client_i_.SetActiveTimeout(cfg_.Get<double>("timeout_image_analysis_active"));
client_i_.SetResponseTimeout(cfg_.Get<double>("timeout_image_analysis_response"));
client_i_.SetFeedbackCallback(std::bind(&InspectionNode::IFeedbackCallback,
this, std::placeholders::_1));
client_i_.SetResultCallback(std::bind(&InspectionNode::IResultCallback,
this, std::placeholders::_1, std::placeholders::_2));
client_i_.SetConnectedCallback(std::bind(
&InspectionNode::GroundConnectedCallback, this));
client_i_.Create(nh, ACTION_ANOMALY_IMG_ANALYSIS);
// Setup the execute action
server_.SetGoalCallback(std::bind(
&InspectionNode::GoalCallback, this, std::placeholders::_1));
server_.SetPreemptCallback(std::bind(
&InspectionNode::PreemptCallback, this));
server_.SetCancelCallback(std::bind(
&InspectionNode::CancelCallback, this));
server_.Create(nh, ACTION_BEHAVIORS_INSPECTION);
// Read maximum number of retryals for a motion action
max_motion_retry_number_= cfg_.Get<int>("max_motion_retry_number");
// Initiate inspection library
inspection_ = new Inspection(nh, cfg_);
}
// Ensure all clients are connected
void ConnectedCallback() {
NODELET_DEBUG_STREAM("ConnectedCallback()");
if (!client_m_.IsConnected()) return; // Move action
if (!client_d_.IsConnected()) return; // Dock action
fsm_.Update(READY); // Ready!
}
void GroundConnectedCallback() {
ROS_DEBUG_STREAM("GroundConnectedCallback()");
if (!client_i_.IsConnected()) return; // Move action
ground_active_ = true;
}
// Service callback to manually change the state
bool SetStateCallback(ff_msgs::SetState::Request& req,
ff_msgs::SetState::Response& res) {
fsm_.SetState(req.state);
res.success = true;
UpdateCallback(fsm_.GetState(), MANUAL_STATE_SET);
return true;
}
// Send a move command
bool MoveInspect(std::string const& mode, geometry_msgs::Pose pose) {
// Create a new motion goal
ff_msgs::MotionGoal goal;
goal.command = ff_msgs::MotionGoal::MOVE;
goal.flight_mode = mode;
// Package up the desired end pose
geometry_msgs::PoseStamped inspection_pose;
inspection_pose.pose = pose;
inspection_pose.header.stamp = ros::Time::now();
goal.states.push_back(inspection_pose);
// Load parameters from config file
std::string planner = cfg_.Get<std::string>("planner");
bool coll_check = cfg_.Get<bool>("enable_collision_checking");
bool replanning = cfg_.Get<bool>("enable_replanning");
int replanning_attempts = cfg_.Get<int>("max_replanning_attempts");
bool validation = cfg_.Get<bool>("enable_validation");
bool boostrapping = cfg_.Get<bool>("enable_bootstrapping");
bool immediate = cfg_.Get<bool>("enable_immediate");
bool timesync = cfg_.Get<bool>("enable_timesync");
double desired_vel = cfg_.Get<double>("desired_vel");
double desired_accel = cfg_.Get<double>("desired_accel");
double desired_omega = cfg_.Get<double>("desired_omega");
double desired_alpha = cfg_.Get<double>("desired_alpha");
// Reconfigure the choreographer
ff_util::ConfigClient choreographer_cfg(GetPlatformHandle(), NODE_CHOREOGRAPHER);
choreographer_cfg.Set<std::string>("planner", planner);
choreographer_cfg.Set<bool>("enable_collision_checking", coll_check);
switch (goal_.command) {
// Vent command
case isaac_msgs::InspectionGoal::ANOMALY:
choreographer_cfg.Set<bool>("enable_faceforward",
cfg_.Get<bool>("enable_faceforward_anomaly")); break;
case isaac_msgs::InspectionGoal::GEOMETRY:
choreographer_cfg.Set<bool>("enable_faceforward",
cfg_.Get<bool>("enable_faceforward_geometry")); break;
}
choreographer_cfg.Set<bool>("enable_replanning", replanning);
choreographer_cfg.Set<int>("max_replanning_attempts", replanning_attempts);
choreographer_cfg.Set<bool>("enable_validation", validation);
choreographer_cfg.Set<bool>("enable_bootstrapping", boostrapping);
choreographer_cfg.Set<bool>("enable_immediate", immediate);
choreographer_cfg.Set<bool>("enable_timesync", timesync);
choreographer_cfg.Set<double>("desired_vel", desired_vel);
choreographer_cfg.Set<double>("desired_accel", desired_accel);
choreographer_cfg.Set<double>("desired_omega", desired_omega);
choreographer_cfg.Set<double>("desired_alpha", desired_alpha);
if (!choreographer_cfg.Reconfigure()) {
NODELET_ERROR_STREAM("Failed to reconfigure choreographer");
return false;
}
// Send the goal to the mobility subsystem
return client_m_.SendGoal(goal);
}
// Ignore the move feedback, for now
void MFeedbackCallback(ff_msgs::MotionFeedbackConstPtr const& feedback) {
m_fsm_subevent_ = feedback->state.fsm_event;
m_fsm_substate_ = feedback->state.fsm_state;
UpdateCallback(fsm_.GetState(), MOTION_UPDATE);
}
// Result of a move action
void MResultCallback(ff_util::FreeFlyerActionState::Enum result_code,
ff_msgs::MotionResultConstPtr const& result) {
switch (result_code) {
case ff_util::FreeFlyerActionState::SUCCESS:
motion_retry_number_ = 0;
return fsm_.Update(MOTION_SUCCESS);
}
if (result != nullptr) {
switch (result->response) {
case ff_msgs::MotionResult::PLAN_FAILED:
case ff_msgs::MotionResult::VALIDATE_FAILED:
case ff_msgs::MotionResult::OBSTACLE_DETECTED:
case ff_msgs::MotionResult::REPLAN_NOT_ENOUGH_TIME:
case ff_msgs::MotionResult::REPLAN_FAILED:
case ff_msgs::MotionResult::REVALIDATE_FAILED:
case ff_msgs::MotionResult::VIOLATES_KEEP_OUT:
case ff_msgs::MotionResult::VIOLATES_KEEP_IN:
{
// Try to find an alternate inspection position
if (inspection_->RemoveInspectionPose()) {
MoveInspect(ff_msgs::MotionGoal::NOMINAL, inspection_->GetInspectionPose());
return;
} else {
ROS_ERROR_STREAM("No inspection pose possible for selected target");
}
break;
}
case ff_msgs::MotionResult::TOLERANCE_VIOLATION_POSITION:
case ff_msgs::MotionResult::TOLERANCE_VIOLATION_ATTITUDE:
case ff_msgs::MotionResult::TOLERANCE_VIOLATION_VELOCITY:
case ff_msgs::MotionResult::TOLERANCE_VIOLATION_OMEGA:
{ // If it fails because of a motion error, retry
if (motion_retry_number_ < max_motion_retry_number_) {
motion_retry_number_++;
switch (goal_.command) {
// Vent command
case isaac_msgs::InspectionGoal::ANOMALY:
MoveInspect(ff_msgs::MotionGoal::NOMINAL, inspection_->GetInspectionPose());
break;
case isaac_msgs::InspectionGoal::GEOMETRY:
case isaac_msgs::InspectionGoal::VOLUMETRIC:
MoveInspect(ff_msgs::MotionGoal::NOMINAL, goal_.inspect_poses.poses[goal_counter_]);
break;
}
}
}
}
ROS_ERROR_STREAM("Motion failed result error: " << result->response);
} else {
ROS_ERROR_STREAM("Invalid result received Motion");
}
return fsm_.Update(MOTION_FAILED);
}
// Dock ACTION CLIENT
// Send a dock or undock command
bool Dock(std::string const& mode) {
// Create a new motion goal
ff_msgs::DockGoal goal;
if (mode == "DOCK") {
goal.command = ff_msgs::DockGoal::DOCK;
goal.berth = ff_msgs::DockGoal::BERTH_1;
} else if (mode == "UNDOCK") {
goal.command = ff_msgs::DockGoal::UNDOCK;
}
// Send the goal to the dock behavior
return client_d_.SendGoal(goal);
}
// Ignore the move feedback, for now
void DFeedbackCallback(ff_msgs::DockFeedbackConstPtr const& feedback) {
d_fsm_subevent_ = feedback->state.fsm_event;
d_fsm_substate_ = feedback->state.fsm_state;
UpdateCallback(fsm_.GetState(), DOCK_UPDATE);
dock_state_ = feedback->state;
}
// Result of a move action
void DResultCallback(ff_util::FreeFlyerActionState::Enum result_code,
ff_msgs::DockResultConstPtr const& result) {
switch (result_code) {
case ff_util::FreeFlyerActionState::SUCCESS:
return fsm_.Update(DOCK_SUCCESS);
default:
return fsm_.Update(DOCK_FAILED);
}
}
// IMG ANALYSIS
// Send a move command
bool ImageInspect() {
// Activate image anomaly detector if there are gound communications
if (goal_.command == isaac_msgs::InspectionGoal::ANOMALY && ground_active_) {
// Send goal
isaac_msgs::ImageInspectionGoal goal;
goal.type = isaac_msgs::ImageInspectionGoal::VENT;
client_i_.SendGoal(goal);
ROS_ERROR_STREAM("sent image inspection goal");
}
// Allow image to stabilize
ros::Duration(2.0).sleep();
// Signal an imminent sci cam image
sci_cam_req_ = true;
// If using the simulation
if (sim_mode_) {
// Take picture
ff_msgs::CommandArg arg;
std::vector<ff_msgs::CommandArg> cmd_args;
// The command sends two strings. The first has the app name,
// and the second the command value, encoded as json.
arg.data_type = ff_msgs::CommandArg::DATA_TYPE_STRING;
arg.s = "gov.nasa.arc.irg.astrobee.sci_cam_image";
cmd_args.push_back(arg);
arg.data_type = ff_msgs::CommandArg::DATA_TYPE_STRING;
arg.s = "{\"name\": \"takeSinglePicture\"}";
cmd_args.push_back(arg);
ff_msgs::CommandStamped cmd;
cmd.header.stamp = ros::Time::now();
cmd.cmd_name = ff_msgs::CommandConstants::CMD_NAME_CUSTOM_GUEST_SCIENCE;
cmd.cmd_id = "inspection" + std::to_string(ros::Time::now().toSec());
cmd.cmd_src = "guest science";
cmd.cmd_origin = "guest science";
cmd.args = cmd_args;
pub_guest_sci_.publish(cmd);
} else {
// If using the real robot
FILE *f = popen("ssh -t -t llp /opt/astrobee/ops/sci_cam_img_control.bash single pub_ros", "r");
}
// Timer for the sci cam camera
ros::Timer sci_cam_timeout_ = nh_->createTimer(ros::Duration(5), &InspectionNode::SciCamTimeout, this, true, false);
return 0;
}
void SciCamCallback(const sensor_msgs::CompressedImage::ConstPtr& msg) {
// The sci cam image was received
if (sci_cam_req_) {
sci_cam_req_ = false;
result_.geometry_result.push_back(isaac_msgs::InspectionResult::PIC_ACQUIRED);
result_.picture_time.push_back(msg->header.stamp);
if (goal_.command == isaac_msgs::InspectionGoal::ANOMALY && ground_active_) {
ROS_ERROR_STREAM("wait for result()");
return;
}
ROS_DEBUG_STREAM("Scicam picture acquired " << ros::Time::now());
return fsm_.Update(NEXT_INSPECT);
}
return;
}
void SciCamTimeout(const ros::TimerEvent& event) {
// The sci cam image was not received
return fsm_.Update(INSPECT_FAILED);
}
// Feedback of an action
void IFeedbackCallback(isaac_msgs::ImageInspectionFeedbackConstPtr const& feedback) {
ROS_DEBUG_STREAM("IFeedbackCallback()");
}
// Result of an action
void IResultCallback(ff_util::FreeFlyerActionState::Enum result_code,
isaac_msgs::ImageInspectionResultConstPtr const& result) {
ROS_DEBUG_STREAM("IResultCallback()");
// Fill in the result message with the result
if (result != nullptr)
result_.vent_result.push_back(result->response);
else
ROS_ERROR_STREAM("Invalid result received Image Analysis");
return fsm_.Update(NEXT_INSPECT);
}
// INSPECTION ACTION SERVER
// A new arm action has been called
void GoalCallback(isaac_msgs::InspectionGoalConstPtr const& goal) {
if (!goal_.inspect_poses.poses.empty()) {
switch (goal->command) {
// Pause command
case isaac_msgs::InspectionGoal::PAUSE:
return fsm_.Update(GOAL_PAUSE);
// Resume command
case isaac_msgs::InspectionGoal::RESUME:
return fsm_.Update(GOAL_INSPECT);
// Skip command
case isaac_msgs::InspectionGoal::SKIP:
{
isaac_msgs::InspectionResult result;
if (!goal_.inspect_poses.poses.empty() && goal_counter_ < goal_.inspect_poses.poses.size()) {
// Skip the current pose
goal_counter_++;
result.fsm_result = "Skipped pose";
result.response = RESPONSE::SUCCESS;
server_.SendResult(ff_util::FreeFlyerActionState::SUCCESS, result);
} else {
result.fsm_result = "Nothing to skip";
result.response = RESPONSE::INVALID_COMMAND;
server_.SendResult(ff_util::FreeFlyerActionState::ABORTED, result);
}
return;
}
// Repeat last executed step command
case isaac_msgs::InspectionGoal::REPEAT:
{
isaac_msgs::InspectionResult result;
if (!goal_.inspect_poses.poses.empty() && goal_counter_ > 0) {
// Go back to the last pose
goal_counter_--;
result.fsm_result = "Will repeat last pose";
result.response = RESPONSE::SUCCESS;
server_.SendResult(ff_util::FreeFlyerActionState::SUCCESS, result);
} else {
result.fsm_result = "Nothing to repeat";
result.response = RESPONSE::INVALID_COMMAND;
server_.SendResult(ff_util::FreeFlyerActionState::ABORTED, result);
}
return;
}
// Save command
case isaac_msgs::InspectionGoal::SAVE:
std::ofstream myfile;
std::string path = ros::package::getPath("inspection") + "/resources/current.txt";
myfile.open(path);
for (int i = 0; i < goal_.inspect_poses.poses.size(); i++) {
myfile << goal_.inspect_poses.poses[i].position.x << " "
<< goal_.inspect_poses.poses[i].position.y << " "
<< goal_.inspect_poses.poses[i].position.z << " "
<< goal_.inspect_poses.poses[i].orientation.x << " "
<< goal_.inspect_poses.poses[i].orientation.y << " "
<< goal_.inspect_poses.poses[i].orientation.z << " "
<< goal_.inspect_poses.poses[i].orientation.w<< "\n";
}
myfile.close();
return;
}
}
// Save new goal
goal_ = *goal;
result_.vent_result.clear();
result_.geometry_result.clear();
result_.picture_time.clear();
goal_counter_ = 0;
ROS_DEBUG_STREAM("RESET COUNTER");
// Check if there is at least one valid inspection pose
if (goal_.inspect_poses.poses.empty()) {
isaac_msgs::InspectionResult result;
result.fsm_result = "No inspection pose added / nothing to pause or resume";
result.response = RESPONSE::INVALID_COMMAND;
server_.SendResult(ff_util::FreeFlyerActionState::ABORTED, result);
return;
}
// Identify command
switch (goal_.command) {
// Vent command
case isaac_msgs::InspectionGoal::ANOMALY:
NODELET_DEBUG("Received Goal Vent");
return fsm_.Update(GOAL_INSPECT);
break;
// Geometry command
case isaac_msgs::InspectionGoal::GEOMETRY:
NODELET_DEBUG("Received Goal Geometry");
return fsm_.Update(GOAL_INSPECT);
break;
// Panorama command
case isaac_msgs::InspectionGoal::PANORAMA:
ROS_ERROR("Received Goal Panorama");
inspection_->GeneratePanoramaSurvey(goal_.inspect_poses);
return fsm_.Update(GOAL_INSPECT);
break;
// Volumetric command
case isaac_msgs::InspectionGoal::VOLUMETRIC:
NODELET_DEBUG("Received Goal Volumetric");
return fsm_.Update(GOAL_INSPECT);
break;
// Invalid command
default:
{
isaac_msgs::InspectionResult result;
result.fsm_result = "Invalid command in request";
result.response = RESPONSE::INVALID_COMMAND;
server_.SendResult(ff_util::FreeFlyerActionState::ABORTED, result);
break;
}
}
}
// Complete the current inspection action
void Result(int32_t response, std::string const& msg = "") {
// Package up the feedback
result_.fsm_result = msg;
result_.response = response;
if (response > 0)
server_.SendResult(ff_util::FreeFlyerActionState::SUCCESS, result_);
else if (response < 0)
server_.SendResult(ff_util::FreeFlyerActionState::ABORTED, result_);
else
server_.SendResult(ff_util::FreeFlyerActionState::PREEMPTED, result_);
}
// Callback to handle reconfiguration requests
bool ReconfigureCallback(dynamic_reconfigure::Config & config) {
if ( fsm_.GetState() == STATE::WAITING)
return cfg_.Reconfigure(config);
return false;
}
// When the FSM state changes we get a callback here, so that we
// can choose to do various things.
void UpdateCallback(FSM::State const& state, FSM::Event const& event) {
// Debug events
isaac_msgs::InspectionState msg;
msg.header.frame_id = GetPlatform();
msg.header.stamp = ros::Time::now();
msg.state = state;
// Debug events
switch (event) {
case READY: msg.fsm_event = "READY"; break;
case GOAL_INSPECT: msg.fsm_event = "GOAL_INSPECT"; break;
case GOAL_CANCEL: msg.fsm_event = "GOAL_CANCEL"; break;
case GOAL_PREEMPT: msg.fsm_event = "GOAL_PREEMPT"; break;
case GOAL_PAUSE: msg.fsm_event = "GOAL_PAUSE"; break;
case GOAL_UNPAUSE: msg.fsm_event = "GOAL_UNPAUSE"; break;
case MOTION_SUCCESS: msg.fsm_event = "MOTION_SUCCESS"; break;
case MOTION_FAILED: msg.fsm_event = "MOTION_FAILED"; break;
case MOTION_UPDATE:
msg.fsm_event = "MOTION_UPDATE";
msg.fsm_subevent = m_fsm_subevent_;
msg.fsm_substate = m_fsm_substate_;
break;
case DOCK_SUCCESS: msg.fsm_event = "DOCK_SUCCESS"; break;
case DOCK_FAILED: msg.fsm_event = "DOCK_FAILED"; break;
case DOCK_UPDATE:
msg.fsm_event = "DOCK_UPDATE";
msg.fsm_subevent = d_fsm_subevent_;
msg.fsm_substate = d_fsm_substate_;
break;
case NEXT_INSPECT: msg.fsm_event = "NEXT_INSPECT"; break;
case INSPECT_FAILED: msg.fsm_event = "INSPECT_FAILED"; break;
case INSPECT_UPDATE:
msg.fsm_event = "INSPECT_UPDATE";
msg.fsm_subevent = "";
msg.fsm_substate = i_fsm_substate_;
break;
case MANUAL_STATE_SET: msg.fsm_event = "MANUAL_STATE_SET"; break;
}
ROS_DEBUG_STREAM("Received event " << msg.fsm_event);
// Debug state changes
switch (state) {
case STATE::INITIALIZING:
msg.fsm_state = "INITIALIZING"; break;
case STATE::WAITING:
msg.fsm_state = "WAITING"; break;
case STATE::INIT_INSPECTION:
msg.fsm_state = "INIT_INSPECTION"; break;
case STATE::MOVING_TO_APPROACH_POSE:
msg.fsm_state = "MOVING_TO_APPROACH_POSE"; break;
case STATE::VISUAL_INSPECTION:
msg.fsm_state = "VISUAL_INSPECTION"; break;
case STATE::RETURN_INSPECTION:
msg.fsm_state = "RETURN_INSPECTION"; break;
}
ROS_DEBUG_STREAM("State changed to " << msg.fsm_state);
// Broadcast the docking state
pub_state_.publish(msg);
// Send the feedback if needed
switch (state) {
case STATE::INITIALIZING:
case STATE::WAITING:
break;
default:
{
ROS_DEBUG_STREAM("InspectionFeedback ");
isaac_msgs::InspectionFeedback feedback;
feedback.state = msg;
server_.SendFeedback(feedback);
}
}
}
// Preempt the current action with a new action
void PreemptCallback() {
NODELET_DEBUG_STREAM("PreemptCallback");
return fsm_.Update(GOAL_PREEMPT);
}
// A Cancellation request arrives
void CancelCallback() {
NODELET_DEBUG_STREAM("CancelCallback");
return fsm_.Update(GOAL_CANCEL);
}
private:
ros::NodeHandle* nh_;
ff_util::FSM fsm_;
ff_util::FreeFlyerActionClient<ff_msgs::MotionAction> client_m_;
ff_util::FreeFlyerActionClient<ff_msgs::DockAction> client_d_;
ff_util::FreeFlyerActionClient<isaac_msgs::ImageInspectionAction> client_i_;
ff_msgs::DockState dock_state_;
ff_util::FreeFlyerActionServer<isaac_msgs::InspectionAction> server_;
ff_util::ConfigServer cfg_;
ros::Publisher pub_state_;
ros::Publisher pub_guest_sci_;
ros::Subscriber sub_sci_cam_;
ros::ServiceServer server_set_state_;
isaac_msgs::InspectionGoal goal_;
int goal_counter_= 0;
std::string m_fsm_subevent_, m_fsm_substate_;
std::string d_fsm_subevent_, d_fsm_substate_;
std::string i_fsm_substate_;
isaac_msgs::InspectionResult result_;
int motion_retry_number_= 0;
int max_motion_retry_number_ = 0;
// Flag to wait for sci camera
bool sci_cam_req_ = false;
bool ground_active_ = false;
bool sim_mode_ = false;
// Inspection library
Inspection* inspection_;
};
PLUGINLIB_EXPORT_CLASS(inspection::InspectionNode, nodelet::Nodelet);
} // namespace inspection
| 38.137731 | 120 | 0.669873 | [
"geometry",
"vector"
] |
3aaffabcd7d19a3aa219f5b21f8e9e01675bdb47 | 4,011 | cpp | C++ | vpc/src/v2/model/CreateVpcRouteOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | vpc/src/v2/model/CreateVpcRouteOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | vpc/src/v2/model/CreateVpcRouteOption.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/vpc/v2/model/CreateVpcRouteOption.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Vpc {
namespace V2 {
namespace Model {
CreateVpcRouteOption::CreateVpcRouteOption()
{
destination_ = "";
destinationIsSet_ = false;
nexthop_ = "";
nexthopIsSet_ = false;
type_ = "";
typeIsSet_ = false;
vpcId_ = "";
vpcIdIsSet_ = false;
}
CreateVpcRouteOption::~CreateVpcRouteOption() = default;
void CreateVpcRouteOption::validate()
{
}
web::json::value CreateVpcRouteOption::toJson() const
{
web::json::value val = web::json::value::object();
if(destinationIsSet_) {
val[utility::conversions::to_string_t("destination")] = ModelBase::toJson(destination_);
}
if(nexthopIsSet_) {
val[utility::conversions::to_string_t("nexthop")] = ModelBase::toJson(nexthop_);
}
if(typeIsSet_) {
val[utility::conversions::to_string_t("type")] = ModelBase::toJson(type_);
}
if(vpcIdIsSet_) {
val[utility::conversions::to_string_t("vpc_id")] = ModelBase::toJson(vpcId_);
}
return val;
}
bool CreateVpcRouteOption::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("destination"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("destination"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setDestination(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("nexthop"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("nexthop"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setNexthop(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("type"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("type"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setType(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("vpc_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("vpc_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVpcId(refVal);
}
}
return ok;
}
std::string CreateVpcRouteOption::getDestination() const
{
return destination_;
}
void CreateVpcRouteOption::setDestination(const std::string& value)
{
destination_ = value;
destinationIsSet_ = true;
}
bool CreateVpcRouteOption::destinationIsSet() const
{
return destinationIsSet_;
}
void CreateVpcRouteOption::unsetdestination()
{
destinationIsSet_ = false;
}
std::string CreateVpcRouteOption::getNexthop() const
{
return nexthop_;
}
void CreateVpcRouteOption::setNexthop(const std::string& value)
{
nexthop_ = value;
nexthopIsSet_ = true;
}
bool CreateVpcRouteOption::nexthopIsSet() const
{
return nexthopIsSet_;
}
void CreateVpcRouteOption::unsetnexthop()
{
nexthopIsSet_ = false;
}
std::string CreateVpcRouteOption::getType() const
{
return type_;
}
void CreateVpcRouteOption::setType(const std::string& value)
{
type_ = value;
typeIsSet_ = true;
}
bool CreateVpcRouteOption::typeIsSet() const
{
return typeIsSet_;
}
void CreateVpcRouteOption::unsettype()
{
typeIsSet_ = false;
}
std::string CreateVpcRouteOption::getVpcId() const
{
return vpcId_;
}
void CreateVpcRouteOption::setVpcId(const std::string& value)
{
vpcId_ = value;
vpcIdIsSet_ = true;
}
bool CreateVpcRouteOption::vpcIdIsSet() const
{
return vpcIdIsSet_;
}
void CreateVpcRouteOption::unsetvpcId()
{
vpcIdIsSet_ = false;
}
}
}
}
}
}
| 21.449198 | 102 | 0.653702 | [
"object",
"model"
] |
3ab735633cd447b05c2475e465669687afd9befa | 8,874 | cpp | C++ | inetcore/connectionwizard/icwutil/registry.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/connectionwizard/icwutil/registry.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/connectionwizard/icwutil/registry.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /****************************************************************************
*
* REGISTRY.cpp
*
* Microsoft Confidential
* Copyright (c) Microsoft Corporation 1992-1997
* All rights reserved
*
* This module provides functionality for self-registering/unregistering via
* the regsvr32.exe
*
* The code comes almost verbatim from Chapter 7 of Dale Rogerson's
* "Inside COM", and thus is minimally commented.
*
* 05/14/98 donaldm copied from INETCFG
*
***************************************************************************/
#include "pre.h"
#include "registry.h"
////////////////////////////////////////////////////////
//
// Internal helper functions prototypes
//
BOOL setKeyAndValue(const LPTSTR pszPath,
const LPTSTR szSubkey,
const LPTSTR szValue,
const LPTSTR szName = NULL) ;
// Convert a CLSID into a tchar string.
void CLSIDtochar(const CLSID& clsid,
LPTSTR szCLSID,
int length) ;
// Delete szKeyChild and all of its descendents.
LONG recursiveDeleteKey(HKEY hKeyParent, const LPTSTR szKeyChild) ;
////////////////////////////////////////////////////////
//
// Constants
//
// Size of a CLSID as a string
const int CLSID_STRING_SIZE = 39 ;
/////////////////////////////////////////////////////////
//
// Public function implementation
//
//
// Register the component in the registry.
//
BOOL WINAPI RegisterServer(HMODULE hModule, // DLL module handle
const CLSID& clsid, // Class ID
const LPTSTR szFriendlyName, // Friendly Name
const LPTSTR szVerIndProgID, // Programmatic
const LPTSTR szProgID) // IDs
{
BOOL bRet = FALSE;
// Get server location.
TCHAR szModule[512] ;
DWORD dwResult =
::GetModuleFileName(hModule,
szModule,
sizeof(szModule)/sizeof(TCHAR)) ;
if (0 != dwResult )
{
while (1)
{
// Convert the CLSID into a TCHAR.
TCHAR szCLSID[CLSID_STRING_SIZE] ;
CLSIDtochar(clsid, szCLSID, sizeof(szCLSID)) ;
// Build the key CLSID\\{...}
TCHAR szKey[CLSID_STRING_SIZE + 10] ;
lstrcpy(szKey, TEXT("CLSID\\")) ;
lstrcat(szKey, szCLSID) ;
// Add the CLSID to the registry.
bRet = setKeyAndValue(szKey, NULL, szFriendlyName) ;
if (!bRet)
break;
// Add the server filename subkey under the CLSID key.
bRet = setKeyAndValue(szKey, TEXT("InprocServer32"), szModule) ;
if (!bRet)
break;
// 7/2/97 jmazner IE bug #41852
// Add Threading Model
bRet = setKeyAndValue(szKey,
TEXT("InprocServer32"),
TEXT("Apartment"),
TEXT("ThreadingModel")) ;
if (!bRet)
break;
// Add the ProgID subkey under the CLSID key.
bRet = setKeyAndValue(szKey, TEXT("ProgID"), szProgID) ;
if (!bRet)
break;
// Add the version-independent ProgID subkey under CLSID key.
bRet = setKeyAndValue(szKey, TEXT("VersionIndependentProgID"),
szVerIndProgID) ;
if (!bRet)
break;
// Add the version-independent ProgID subkey under HKEY_CLASSES_ROOT.
bRet = setKeyAndValue(szVerIndProgID, NULL, szFriendlyName) ;
if (!bRet)
break;
bRet = setKeyAndValue(szVerIndProgID, TEXT("CLSID"), szCLSID) ;
if (!bRet)
break;
bRet = setKeyAndValue(szVerIndProgID, TEXT("CurVer"), szProgID) ;
if (!bRet)
break;
// Add the versioned ProgID subkey under HKEY_CLASSES_ROOT.
bRet = setKeyAndValue(szProgID, NULL, szFriendlyName) ;
if (!bRet)
break;
bRet = setKeyAndValue(szProgID, TEXT("CLSID"), szCLSID) ;
break;
}
}
return bRet ;
}
//
// Remove the component from the registry.
//
BOOL WINAPI UnregisterServer(const CLSID& clsid, // Class ID
const LPTSTR szVerIndProgID, // Programmatic
const LPTSTR szProgID) // IDs
{
// Convert the CLSID into a TCHAR.
TCHAR szCLSID[CLSID_STRING_SIZE] ;
CLSIDtochar(clsid, szCLSID, sizeof(szCLSID)) ;
// Build the key CLSID\\{...}
TCHAR szKey[64] ;
lstrcpy(szKey, TEXT("CLSID\\")) ;
lstrcat(szKey, szCLSID) ;
// Delete the CLSID Key - CLSID\{...}
LONG lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, szKey) ;
ASSERT((lResult == ERROR_SUCCESS) ||
(lResult == ERROR_FILE_NOT_FOUND)) ; // Subkey may not exist.
// Delete the version-independent ProgID Key.
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, szVerIndProgID) ;
ASSERT((lResult == ERROR_SUCCESS) ||
(lResult == ERROR_FILE_NOT_FOUND)) ; // Subkey may not exist.
// Delete the ProgID key.
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, szProgID) ;
ASSERT((lResult == ERROR_SUCCESS) ||
(lResult == ERROR_FILE_NOT_FOUND)) ; // Subkey may not exist.
return TRUE;
}
///////////////////////////////////////////////////////////
//
// Internal helper functions
//
// Convert a CLSID to a TCHAR string.
void CLSIDtochar(const CLSID& clsid,
LPTSTR szCLSID,
int length)
{
ASSERT(length >= CLSID_STRING_SIZE) ;
// Get CLSID
LPOLESTR wszCLSID = NULL ;
HRESULT hr = StringFromCLSID(clsid, &wszCLSID) ;
ASSERT(SUCCEEDED(hr)) ;
if (SUCCEEDED(hr))
{
// Covert from wide characters to non-wide.
#ifdef UNICODE
lstrcpyn(szCLSID, wszCLSID, length / sizeof(WCHAR)) ;
#else
wcstombs(szCLSID, wszCLSID, length) ;
#endif
// Free memory.
CoTaskMemFree(wszCLSID) ;
}
else
{
szCLSID[0] = TEXT('\0');
}
}
//
// Delete a key and all of its descendents.
//
LONG recursiveDeleteKey(HKEY hKeyParent, // Parent of key to delete
const LPTSTR lpszKeyChild) // Key to delete
{
// Open the child.
HKEY hKeyChild ;
LONG lRes = RegOpenKeyEx(hKeyParent, lpszKeyChild, 0,
KEY_ALL_ACCESS, &hKeyChild) ;
if (lRes != ERROR_SUCCESS)
{
return lRes ;
}
// Enumerate all of the decendents of this child.
FILETIME time ;
TCHAR szBuffer[256] ;
DWORD dwSize = 256 ;
while (RegEnumKeyEx(hKeyChild, 0, szBuffer, &dwSize, NULL,
NULL, NULL, &time) == S_OK)
{
// Delete the decendents of this child.
lRes = recursiveDeleteKey(hKeyChild, szBuffer) ;
if (lRes != ERROR_SUCCESS)
{
// Cleanup before exiting.
RegCloseKey(hKeyChild) ;
return lRes;
}
dwSize = 256 ;
}
// Close the child.
RegCloseKey(hKeyChild) ;
// Delete this child.
return RegDeleteKey(hKeyParent, lpszKeyChild) ;
}
//
// Create a key and set its value.
// - This helper function was borrowed and modifed from
// Kraig Brockschmidt's book Inside OLE.
//
BOOL setKeyAndValue(const LPTSTR szKey,
const LPTSTR szSubkey,
const LPTSTR szValue,
const LPTSTR szName)
{
HKEY hKey;
TCHAR szKeyBuf[1024] ;
// Copy keyname into buffer.
lstrcpy(szKeyBuf, szKey) ;
// Add subkey name to buffer.
if (szSubkey != NULL)
{
lstrcat(szKeyBuf, TEXT("\\")) ;
lstrcat(szKeyBuf, szSubkey ) ;
}
// Create and open key and subkey.
long lResult = RegCreateKeyEx(HKEY_CLASSES_ROOT ,
szKeyBuf,
0, NULL, REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL,
&hKey, NULL) ;
if (lResult != ERROR_SUCCESS)
{
return FALSE ;
}
// Set the Value.
if (szValue != NULL)
{
RegSetValueEx(hKey, szName, 0, REG_SZ,
(BYTE *)szValue,
sizeof(TCHAR)*(lstrlen(szValue)+1)) ;
}
RegCloseKey(hKey) ;
return TRUE ;
}
| 30.286689 | 82 | 0.506423 | [
"model"
] |
3abeee13f180a984a952e5c00580ad8a215aba43 | 15,874 | cpp | C++ | Src/Basler/Samples/PCL/MergePointClouds/SynchronousGrabber.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | 1 | 2019-03-17T14:03:14.000Z | 2019-03-17T14:03:14.000Z | Src/Basler/Samples/PCL/MergePointClouds/SynchronousGrabber.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | null | null | null | Src/Basler/Samples/PCL/MergePointClouds/SynchronousGrabber.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "SynchronousGrabber.h"
// Utility class for time measurements.
#include "StopWatch.h"
#ifdef CIH_LINUX_BUILD // Make sure proper headers are used when compiling under Linux ...
#include <unistd.h>
#endif
#ifdef CIH_WIN_BUILD // ... or under Windows.
#include <windows.h>
#endif
#include <iostream>
using namespace std;
using namespace GenTLConsumerImplHelper;
using namespace GenApi;
namespace
{
// Sleep function for Windows and Linux
void mSleep(int sleepMs)
{
#ifdef CIH_LINUX_BUILD
usleep(sleepMs * 1000); // usleep takes sleep time in us
#endif
#ifdef CIH_WIN_BUILD
Sleep(sleepMs); // Sleep expects time in ms
#endif
}
}
SynchronousGrabber::SynchronousGrabber(size_t nCameras, unsigned int DepthMin, unsigned int DepthMax)
: m_nCams(nCameras)
, m_DepthMin(DepthMin)
, m_DepthMax(DepthMax)
, m_IsMaster(nCameras)
{
}
void SynchronousGrabber::setupCameras()
{
cout << "Searching for cameras ... ";
CameraList cameras = CToFCamera::EnumerateCameras();
cout << "found " << cameras.size() << " ToF cameras " << endl << endl;
if (m_nCams != cameras.size())
{
std::stringstream errmsg;
errmsg << "The number of cameras found (" << cameras.size() << ") is not equal to the number of expected cameras (" << m_nCams << ").";
throw std::runtime_error(errmsg.str());
}
int64_t camIdx = 0;
// Initialize array with master/slave info.
for (size_t i = 0; i < m_nCams; i++)
{
m_IsMaster[i] = false;
}
// Iterate over list of cameras.
for (auto &cInfo : cameras)
{
cout << "Configuring Camera " << camIdx << " : " << cInfo.strDisplayName << "." << endl;
// Create shared pointer to ToF camera.
shared_ptr<CToFCamera> cam(new CToFCamera());
// Store shared pointer for later use.
m_Cameras.push_back(cam);
// Open camera with camera info.
cam->Open(cInfo);
//
// Configure camera for synchronous free run.
// Do not yet configure trigger delays.
//
// Enable IEEE1588.
CBooleanPtr ptrIEEE1588Enable = cam->GetParameter("GevIEEE1588");
ptrIEEE1588Enable->SetValue(true);
// Enable trigger.
GenApi::CEnumerationPtr ptrTriggerMode = cam->GetParameter("TriggerMode");
// Set trigger mode to "on".
ptrTriggerMode->FromString("On");
// Configure the sync timer as trigger source.
GenApi::CEnumerationPtr ptrTriggerSource = cam->GetParameter("TriggerSource");
ptrTriggerSource->FromString("SyncTimer");
// Configure the cameras to send 3D coordinates and intensity values. We will use
// the intensity values as colors for the points in the point cloud.
CEnumerationPtr ptrComponentSelector = cam->GetParameter("ComponentSelector");
CBooleanPtr ptrComponentEnable = cam->GetParameter("ComponentEnable");
CEnumerationPtr ptrPixelFormat = cam->GetParameter("PixelFormat");
ptrComponentSelector->FromString("Range");
ptrComponentEnable->SetValue(true);
ptrPixelFormat->FromString("Coord3D_ABC32f");
ptrComponentSelector->FromString("Intensity");
ptrComponentEnable->SetValue(true);
ptrPixelFormat->FromString("Mono16");
// Set the desired depth range.
CIntegerPtr ptrDepthMin = cam->GetParameter("DepthMin");
ptrDepthMin->SetValue(m_DepthMin);
CIntegerPtr ptrDepthMax = cam->GetParameter("DepthMax");
ptrDepthMax->SetValue(m_DepthMax);
// Allocate the memory buffers and prepare image acquisition.
cam->PrepareAcquisition(c_nBuffers);
// Enqueue all buffers to be filled with image data.
for (size_t i = 0; i < c_nBuffers; ++i)
{
cam->QueueBuffer(i);
}
// Start acquisition engine.
cam->StartAcquisition();
// Proceed to next camera.
camIdx++;
}
}
void SynchronousGrabber::findMaster()
{
unsigned int nMaster;
cout << endl << "Waiting for cameras to negotiate master role ..." << endl << endl;
do
{
// Number of devices that currently claim to be a master clock.
nMaster = 0;
//
// Wait until a master camera (if any) and the slave cameras have been chosen.
// Note that if a PTP master clock is present in the subnet, all ToF cameras
// ultimately assume the slave role.
//
for (size_t i = 0; i < m_nCams; i++)
{
// Latch IEEE1588 status.
CCommandPtr ptrGevIEEE1588DataSetLatch = m_Cameras.at(i)->GetParameter("GevIEEE1588DataSetLatch");
ptrGevIEEE1588DataSetLatch->Execute();
// Read out latched status.
GenApi::CEnumerationPtr ptrGevIEEE1588StatusLatched = m_Cameras.at(i)->GetParameter("GevIEEE1588StatusLatched");
// The smart pointer holds the node, not the value.
// The node value is always up to date.
// Therefore, there is no need to repeatedly retrieve the pointer here.
while (ptrGevIEEE1588StatusLatched->ToString() == "Listening")
{
// Latch GevIEEE1588 status.
ptrGevIEEE1588DataSetLatch->Execute();
cout << "." << std::flush;
mSleep(1000);
}
//
// Store the information whether the camera is master or slave.
//
if (ptrGevIEEE1588StatusLatched->ToString() == "Master")
{
m_IsMaster[i] = true;
nMaster++;
}
else
{
m_IsMaster[i] = false;
}
}
} while (nMaster > 1); // Repeat until there is at most one master left.
// Use this variable to check whether there is an external master clock.
bool externalMasterClock = true;
for (size_t camIdx = 0; camIdx < m_nCams; camIdx++)
{
if (true == m_IsMaster[camIdx])
{
cout << " camera " << camIdx << " is master" << endl << endl;
externalMasterClock = false;
}
}
if (true == externalMasterClock)
{
cout << "External master clock present in subnet: All cameras are slaves." << endl << endl;
}
}
void SynchronousGrabber::syncCameras()
{
// Maximum allowed offset from master clock.
const uint64_t tsOffsetMax = 10000;
cout << "Wait until offsets from master clock have settled below " << tsOffsetMax << " ns " << endl << endl;
for (size_t camIdx = 0; camIdx < m_nCams; camIdx++)
{
// Check all slaves for deviations from master clock.
if (false == m_IsMaster[camIdx])
{
uint64_t tsOffset;
do
{
tsOffset = GetMaxAbsGevIEEE1588OffsetFromMasterInTimeWindow(camIdx, 1.0, 0.1);
cout << "max offset of cam " << camIdx << " = " << tsOffset << " ns" << endl;
} while (tsOffset >= tsOffsetMax);
}
}
}
/*
\param camIndex Index in smart pointer array of camera which is in Slave state.
\param timeToMeasureSec Amount of time in seconds for computing the maximum absolute offset from master.
\param timeDeltaSec Amount of time in seconds between latching the offset from master.
\return Maximum absolute offset from master in nanoseconds.
*/
int64_t SynchronousGrabber::GetMaxAbsGevIEEE1588OffsetFromMasterInTimeWindow(int camIdx, double timeToMeasureSec, double timeDeltaSec)
{
CCommandPtr ptrGevIEEE1588DataSetLatch = m_Cameras.at(camIdx)->GetParameter("GevIEEE1588DataSetLatch");
ptrGevIEEE1588DataSetLatch->Execute();
CIntegerPtr ptrGevIEEE1588OffsetFromMaster = m_Cameras.at(camIdx)->GetParameter("GevIEEE1588OffsetFromMaster");
StopWatch m_StopWatch;
m_StopWatch.reset();
// Maximum of offsets from master
int64_t maxOffset = 0;
// Number of samples
uint32_t n(0);
// Current time
double currTime(0);
do
{
// Update the current time
currTime = m_StopWatch.get(false);
if (currTime >= n * timeDeltaSec)
{
// Time for next sample has elapsed.
// Latch IEEE1588 data set to get offset from master.
ptrGevIEEE1588DataSetLatch->Execute();
// Maximum of offsets from master.
maxOffset = max(maxOffset, std::abs(ptrGevIEEE1588OffsetFromMaster->GetValue()));
// Increase number of samples.
n++;
}
mSleep(1);
} while (currTime <= timeToMeasureSec);
// Return maximum of offsets from master for given time interval.
return maxOffset;
}
void SynchronousGrabber::setTriggerDelays()
{
// Current timestamp
uint64_t timestamp, syncStartTimestamp;
// The low and high part of the timestamp
uint64_t tsLow, tsHigh;
// Initialize trigger delay.
m_TriggerDelay = 0;
cout << endl << "configuring start time and trigger delays ..." << endl << endl;
//
// Cycle through cameras and set trigger delay.
//
for (size_t camIdx = 0; camIdx < m_Cameras.size(); camIdx++)
{
cout << "Camera " << camIdx << " : " << endl;
//
// Read timestamp and exposure time.
// Calculation of synchronous free run timestamps will all be based
// on timestamp and exposure time(s) of first camera.
//
if (camIdx == 0)
{
// Latch timestamp registers.
CCommandPtr ptrTimestampLatch = m_Cameras.at(camIdx)->GetParameter("TimestampLatch");
ptrTimestampLatch->Execute();
// Read the two 32-bit halves of the 64-bit timestamp.
CIntegerPtr ptrTimeStampLow(m_Cameras.at(camIdx)->GetParameter("TimestampLow"));
CIntegerPtr ptrTimeStampHigh(m_Cameras.at(camIdx)->GetParameter("TimestampHigh"));
tsLow = ptrTimeStampLow->GetValue();
tsHigh = ptrTimeStampHigh->GetValue();
// Assemble 64-bit timestamp and keep it.
timestamp = tsLow + (tsHigh << 32);
cout << "Reading time stamp from first camera. \ntimestamp = " << timestamp << endl << endl;
cout << "Reading exposure times from first camera:" << endl;
// Get exposure time count (in case of HDR there will be 2, otherwise 1).
CIntegerPtr ptrExposureTimeSelector = m_Cameras.at(camIdx)->GetParameter("ExposureTimeSelector");
size_t n_expTimes = 1 + (size_t)ptrExposureTimeSelector->GetMax();
// Sum up exposure times.
CFloatPtr ptrExposureTime = m_Cameras.at(camIdx)->GetParameter("ExposureTime");
for (size_t l = 0; l < n_expTimes; l++)
{
ptrExposureTimeSelector->SetValue(l);
cout << "exposure time " << l << " = " << ptrExposureTime->GetValue() << endl << endl;
m_TriggerDelay += (int64_t)(1000 * ptrExposureTime->GetValue()); // Convert from us -> ns
}
cout << "Calculating trigger delay." << endl;
// Add readout time.
m_TriggerDelay += (n_expTimes - 1) * c_ReadoutTime;
// Add safety margin for clock jitter.
m_TriggerDelay += 1000000;
// Calculate synchronous trigger rate.
cout << "Calculating maximum synchronous trigger rate ... " << endl;
m_SyncTriggerRate = 1000000000 / (m_nCams * m_TriggerDelay);
// If the calculated value is greater than the maximum supported rate,
// adjust it.
CFloatPtr ptrSyncRate(m_Cameras.at(camIdx)->GetParameter("SyncRate"));
if (m_SyncTriggerRate > ptrSyncRate->GetMax())
{
m_SyncTriggerRate = (uint64_t)ptrSyncRate->GetMax();
}
// Print trigger delay and synchronous trigger rate.
cout << "Trigger delay = " << m_TriggerDelay / 1000000 << " ms" << endl;
cout << "Setting synchronous trigger rate to " << m_SyncTriggerRate << " fps" << endl << endl;
}
// Set synchronization rate.
CFloatPtr ptrSyncRate(m_Cameras.at(camIdx)->GetParameter("SyncRate"));
ptrSyncRate->SetValue((double)m_SyncTriggerRate);
// Calculate new timestamp by adding trigger delay.
// First camera starts after triggerBaseDelay, nth camera is triggered
// after a delay of triggerBaseDelay + n * triggerDelay.
syncStartTimestamp = timestamp + m_TriggerBaseDelay + camIdx * m_TriggerDelay;
// Disassemble 64-bit timestamp.
tsHigh = syncStartTimestamp >> 32;
tsLow = syncStartTimestamp - (tsHigh << 32);
// Get pointers to the two 32-bit registers, which together hold the 64-bit
// synchronous free run start time.
CIntegerPtr ptrSyncStartLow(m_Cameras.at(camIdx)->GetParameter("SyncStartLow"));
CIntegerPtr ptrSyncStartHigh(m_Cameras.at(camIdx)->GetParameter("SyncStartHigh"));
ptrSyncStartLow->SetValue(tsLow);
ptrSyncStartHigh->SetValue(tsHigh);
// Latch synchronization start time & synchronization rate registers.
// Until the values have been latched, they won't have any effect.
CCommandPtr ptrSyncUpdate = m_Cameras.at(camIdx)->GetParameter("SyncUpdate");
ptrSyncUpdate->Execute();
// Show new synchronous free run start time.
cout << "Setting Sync Start time stamp" << endl;
cout << "SyncStartLow = " << ptrSyncStartLow->GetValue() << endl;
cout << "SyncStartHigh = " << ptrSyncStartHigh->GetValue() << endl << endl;
}
}
/*
Grab the next image from every camera and store the buffer parts in the output vector.
*/
int SynchronousGrabber::getNextImages(vector<shared_ptr<BufferParts> >& parts)
{
// Clear the output vector and reserve the required memory.
parts.clear();
parts.resize(m_nCams);
// Grab one image from every camera.
for (int i = 0; i < m_nCams; i++)
{
GrabResult grabResult;
shared_ptr<BufferParts> ptrParts(new BufferParts);
m_Cameras.at(i)->GetGrabResult(grabResult, 100);
if (grabResult.status == GrabResult::Ok) {
// Read the buffer parts and store them in the output vector.
m_Cameras.at(i)->GetBufferParts(grabResult, *ptrParts);
parts.at(i) = ptrParts;
}
else {
cout << "There was an invalid grab result." << endl;
return EXIT_FAILURE;
}
// We finished processing the data and put the buffer back into the acquisition
// engine's input queue to be filled with new image data.
m_Cameras.at(i)->QueueBuffer(grabResult.hBuffer);
}
return EXIT_SUCCESS;
}
/*
Set up the ToF cameras and synchronize them.
*/
int SynchronousGrabber::setupAndStart()
{
try
{
// Find all ToF cameras, open and parameterize them.
setupCameras();
// Let cameras negotiate which one should be the master.
findMaster();
// Wait until all camera clocks have been synchronized.
syncCameras();
// Set trigger delay for each camera.
setTriggerDelays();
// Start continuous image acquisition.
for (int i = 0; i < m_nCams; i++) {
// The camera continuously sends data now.
m_Cameras.at(i)->IssueAcquisitionStartCommand();
}
}
catch (const std::exception& e)
{
cerr << "Exception occurred: " << e.what() << endl;
return EXIT_FAILURE;
}
catch (const GenICam::GenericException& e)
{
cerr << "Exception occurred: " << e.GetDescription() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 35.275556 | 143 | 0.616669 | [
"vector",
"3d"
] |
3ac0c4a8f284d4ca98e5961242abc2b226208cb5 | 1,710 | cpp | C++ | idlcpp/src/Platform.cpp | ericyao2013/idlcpp | 01745707b3ec2e89acfec2eb4af0656a82d5337d | [
"MIT"
] | 31 | 2016-04-12T05:38:50.000Z | 2021-07-25T13:33:01.000Z | idlcpp/src/Platform.cpp | fdyjfd/idlcpp | d0bd13d96d546b06074062fb3984b42569e71fae | [
"MIT"
] | null | null | null | idlcpp/src/Platform.cpp | fdyjfd/idlcpp | d0bd13d96d546b06074062fb3984b42569e71fae | [
"MIT"
] | 6 | 2016-03-16T02:30:41.000Z | 2021-09-26T03:10:52.000Z | #include "Platform.h"
#include <Windows.h>
#include <shlwapi.h>
#include <algorithm>
#pragma comment(lib, "shlwapi.lib")
bool fileExisting(const char* fileName)
{
DWORD attr = GetFileAttributes(fileName);
return ((attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0));
}
bool isAbsolutePath(const char* fileName)
{
size_t len = strlen(fileName);
if(len > 2 && fileName[1] == ':')
{
return true;
}
return false;
}
void normalizeFileName(std::string& str, const char* fileName)
{
char buf[MAX_PATH];
*buf = 0;
char* fp;
if(0 != GetFullPathName(fileName, MAX_PATH, buf, &fp))
{
str = buf;
}
else
{
str = fileName;
}
std::replace(str.begin(), str.end(), '/', '\\');
//std::transform(str.begin(), str.end(), str.begin(), ::tolower);
}
const char* getExtNameBegin(const char* normalizedFileName)
{
const char* lastDot = strrchr(normalizedFileName, '.');
const char* lastBackSlash = strrchr(normalizedFileName, '\\');
if(lastDot < lastBackSlash)
{
return 0;
}
return lastDot;
}
const char* getDirNameEnd(const char* normalizedFileName)
{
const char* lastBackSlash = strrchr(normalizedFileName, '\\');
return lastBackSlash;
}
void GetRelativePath(std::string& str, const char* fileFrom, const char* fileTo)
{
char buf[MAX_PATH];
if(PathRelativePathTo(buf, fileFrom, 0, fileTo, 0))
{
str = buf;
}
else
{
str = fileTo;
}
}
void FormatPathForInclude(std::string& str)
{
std::replace(str.begin(), str.end(), '\\', '/');
}
void FormatPathForLine(std::string& str)
{
std::replace(str.begin(), str.end(), '\\', '/');
}
bool compareFileName(const std::string& str1, const std::string& str2)
{
return stricmp(str1.c_str(), str2.c_str()) < 0;
}
| 19.883721 | 88 | 0.67076 | [
"transform"
] |
3ac60e224aa8837cb353a34516b16e2df03b0a91 | 4,183 | cpp | C++ | code/cone.cpp | annaliseko/HW6 | 67e9ea212994c8ec9786719fa3646c5bcc2eee7a | [
"MIT"
] | null | null | null | code/cone.cpp | annaliseko/HW6 | 67e9ea212994c8ec9786719fa3646c5bcc2eee7a | [
"MIT"
] | null | null | null | code/cone.cpp | annaliseko/HW6 | 67e9ea212994c8ec9786719fa3646c5bcc2eee7a | [
"MIT"
] | null | null | null | #include "cone.h"
#include "parse.h"
#include "material.h"
#include "roots.h"
#include "main.h"
// single glu quadric object to draw all the cones with
static GLUquadricObj* coneQuadric = gluNewQuadric();
Cone::Cone ()
: Shape ()
{
closed = false;
}
Cone::~Cone ()
{
}
double Cone::intersect (Intersection& info)
{
/*
* z-axis aligned cone is of the form
* (x - x_0)^2 + (y - y_0)^2 = radius^2 / height^2 ((z - z_0) - height)^2
* with 0 <= z <= height
*
* ray is of the form ray.pos + alpha * ray.dir
*
* plug ray equation into that for the cone, solve for alpha, and find
* the corresponding z-values
*/
/* set up quadratic: a * alpha^2 + b * alpha * c = 0 */
return -1;
}
bool Cone::inside (const Point3d& pos, bool surfaceOpen)
{
return true;
}
// CLARIFICATION QUESTION:
// What is the purpose of the inInfCone function?
bool Cone::inInfCone (const Point3d& pos)
{
return true;
}
TexCoord2d Cone::getTexCoordinates (Point3d i)
{
Vector3d n(center, i);
TexCoord2d tCoord(0.0,0.0);
// This function calculates the texture coordinates for the cone
// intersection. It uses the normal at the point of intersection
// to calculate the polar coordinates of the intersection on that
// circle of the cone. Then we linearly map these coordinates as:
// Theta: [0, 2*PI] -> [0, 1]
// This remapped theta gives us tCoord[0]. For tCoord[1], we take
// the distance along the height of the cone, using the top as the
// zero point.
return tCoord;
}
void Cone::glDraw ()
{
material->glLoad();
glPushMatrix();
// move to the cone's origin
glTranslatef(center[0], center[1], center[2]);
// set glu quadric options - smooth filled polys with normals
gluQuadricDrawStyle(coneQuadric, GLU_FILL);
gluQuadricOrientation(coneQuadric, GLU_OUTSIDE);
gluQuadricNormals(coneQuadric, GLU_SMOOTH);
// only calc tex coords if textures are turned on
if (options->textures && textured && material->textured())
{
gluQuadricTexture(coneQuadric, GLU_TRUE);
glEnable(GL_TEXTURE_2D);
}
// draw the cone
gluCylinder(coneQuadric, radius, 0.0, height, 20, 5);
// if it's closed, cap it off with a disk
if (closed)
{
gluQuadricOrientation(coneQuadric, GLU_INSIDE);
gluDisk(coneQuadric, 0, radius, 20, 1);
}
glPopMatrix();
material->glUnload();
glDisable(GL_TEXTURE_2D);
}
inline istream& operator>> (istream& in, Cone& s)
{
return s.read(in);
}
istream& Cone::read (istream& in)
{
int numFlags = 5;
Flag flags[5] = { { (char*)"-n", STRING, false, MAX_NAME, name },
{ (char*)"-m", STRING, true, MAX_NAME, matname },
{ (char*)"-t", BOOL, false, sizeof(bool), &textured },
{ (char*)"-c", BOOL, false, sizeof(bool), &closed },
{ (char*)"-u", DOUBLE, false, sizeof(double), &bumpScale }
};
if (parseFlags(in, flags, numFlags) == -1)
{
cerr << "ERROR: Cone: flag parsing failed!" << endl;
return in;
}
if (bumpScale != 0)
bumpMapped = true;
in >> center;
radius = nextDouble(in);
height = nextDouble(in);
if (in.fail())
{
cerr << "ERROR: Cone: unknown stream error" << endl;
return in;
}
return in;
}
inline ostream& operator<< (ostream& out, Cone& s)
{
return s.write(out);
}
ostream& Cone::write (ostream& out)
{
out << "#cone -m " << matname << flush;
if (name[0] != '\0')
out << " -n " << name << flush;
if (textured)
out << " -t" << flush;
if (bumpMapped)
out << " -u" << flush;
if (closed)
out << " -c" << flush;
out << " --" << endl;
out << " " << center << endl;
out << " " << radius << endl;
out << " " << height << endl;
return out;
}
| 22.610811 | 81 | 0.545781 | [
"object",
"shape"
] |
3aca479ccf5e8c5c8d67c6d8b048e2fd6960bbc3 | 7,698 | cc | C++ | mindspore/lite/src/pack_weight_manager.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/pack_weight_manager.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/pack_weight_manager.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* 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.
*/
#ifdef SERVER_INFERENCE
#include "src/pack_weight_manager.h"
namespace mindspore::lite {
namespace {
constexpr size_t kMemAliginSize = 64;
size_t RoundMemSize(size_t size) { return (size + kMemAliginSize - 1) & (~(kMemAliginSize - 1)); }
} // namespace
PackWeightManager *PackWeightManager::GetInstance() {
static PackWeightManager instance;
return &instance;
}
STATUS PackWeightManager::InitWeightManagerByBuf(const char *model_buf) {
MS_CHECK_TRUE_RET(model_buf != nullptr, RET_ERROR);
if (buf_model_weight_.find(model_buf) == buf_model_weight_.end()) {
auto *model_const_weight = new (std::nothrow) ModelConstWeight();
if (model_const_weight == nullptr) {
MS_LOG(ERROR) << "model_const_weight is nullptr.";
return RET_ERROR;
}
buf_model_weight_[model_buf] = model_const_weight;
}
return RET_OK;
}
void PackWeightManager::InitWeightManagerByPath(const std::string &model_path, const char *model_buf) {
MS_CHECK_TRUE_RET_VOID(model_buf != nullptr);
if (path_model_buf_.find(model_path) == path_model_buf_.end()) {
auto *model_const_weight = new (std::nothrow) ModelConstWeight();
if (model_const_weight == nullptr) {
return;
}
path_model_weight_[model_path] = model_const_weight;
}
path_model_buf_[model_path].push_back(model_buf);
}
STATUS PackWeightManager::StoreLiteModel(const char *model_buf, const Model *model) {
MS_CHECK_TRUE_RET(model_buf != nullptr, RET_ERROR);
MS_CHECK_TRUE_RET(model != nullptr, RET_ERROR);
for (auto &item : path_model_buf_) {
auto &model_bufs = item.second;
auto path = item.first;
if (find(model_bufs.begin(), model_bufs.end(), model_buf) != model_bufs.end()) {
path_model_weight_[path]->lite_models.push_back(model);
return RET_OK;
}
}
{
if (buf_model_weight_.find(model_buf) == buf_model_weight_.end()) {
MS_LOG(ERROR) << "set model failed.";
return RET_ERROR;
}
buf_model_weight_[model_buf]->lite_models.push_back(model);
}
return RET_OK;
}
void *PackWeightManager::GetTensorData(const LiteModel *model, const SchemaTensorWrapper *origin_tensor,
size_t tensor_index) {
MS_CHECK_TRUE_RET(model != nullptr, nullptr);
for (auto &item : path_model_weight_) {
auto &path = item.first;
auto &model_weight = item.second;
auto &models = model_weight->lite_models;
if (find(models.begin(), models.end(), model) != models.end()) {
if (model_weight->packed_weight.find(tensor_index) != model_weight->packed_weight.end()) {
return model_weight->packed_weight[tensor_index];
}
path_model_weight_[path]->origin_weight[tensor_index] = origin_tensor->data();
path_model_weight_[path]->origin_data_index[origin_tensor->data()] = tensor_index;
return nullptr;
}
}
for (auto &item : buf_model_weight_) {
auto &model_buf = item.first;
auto &model_weight = item.second;
auto &models = model_weight->lite_models;
if (find(models.begin(), models.end(), model) != models.end()) {
if (model_weight->packed_weight.find(tensor_index) != model_weight->packed_weight.end()) {
return model_weight->packed_weight[tensor_index];
}
buf_model_weight_[model_buf]->origin_weight[tensor_index] = origin_tensor->data();
buf_model_weight_[model_buf]->origin_data_index[origin_tensor->data()] = tensor_index;
return nullptr;
}
}
MS_LOG(DEBUG) << "tensor data not packed.";
return nullptr;
}
std::pair<PackStatus, void *> PackWeightManager::FindPackedTensor(ModelConstWeight *weight, const Tensor *tensor,
const size_t size) {
std::unique_lock<std::mutex> weight_lock(mtx_weight_);
MS_CHECK_TRUE_RET(tensor != nullptr, std::make_pair(MALLOC, nullptr));
auto &packed_weights = weight->packed_weight;
if (size > MAX_MALLOC_SIZE) {
MS_LOG(ERROR) << "malloc size more than MAX_MALLOC_SIZE";
return std::make_pair(MALLOC, nullptr);
}
if (weight->packed_data.find(tensor->data()) != weight->packed_data.end()) {
return std::make_pair(PACKED, tensor->data());
} else if (weight->origin_data_index.find(tensor->data()) != weight->origin_data_index.end()) {
auto origin_index = weight->origin_data_index[tensor->data()];
void *data = nullptr;
#ifdef _WIN32
data = _aligned_malloc(allocate_size, kMemAlginSize);
#else
auto ret = posix_memalign(&data, kMemAliginSize, size);
if (ret != 0) {
MS_LOG(ERROR) << "posix_memalign failed.";
return std::make_pair(MALLOC, nullptr);
}
#endif
weight->packed_data.insert(data);
packed_weights.insert(std::make_pair(origin_index, data));
return std::make_pair(NOTPACK, packed_weights.at(origin_index));
}
return std::make_pair(MALLOC, nullptr);
}
std::pair<PackStatus, void *> PackWeightManager::GetPackedTensor(const Tensor *tensor, const size_t size) {
MS_CHECK_TRUE_RET(tensor != nullptr, std::make_pair(MALLOC, nullptr));
auto round_size = RoundMemSize(size);
for (auto &item : path_model_weight_) {
auto &model_weight = item.second;
auto packed_tensor_pair = FindPackedTensor(model_weight, tensor, round_size);
if (packed_tensor_pair.second != nullptr) {
return packed_tensor_pair;
}
}
for (auto &item : buf_model_weight_) {
auto &model_weight = item.second;
auto packed_tensor_pair = FindPackedTensor(model_weight, tensor, round_size);
if (packed_tensor_pair.second != nullptr) {
return packed_tensor_pair;
}
}
MS_LOG(DEBUG) << "not const tensor, need pack in kernel.";
return std::make_pair(MALLOC, nullptr);
}
void PackWeightManager::DeleteSavedModelPtr(LiteModel *delete_model) {
std::unique_lock<std::mutex> weight_lock(mtx_weight_);
MS_CHECK_TRUE_RET_VOID(delete_model != nullptr);
for (auto &item : path_model_weight_) {
auto &weight = item.second;
auto it = find(weight->lite_models.begin(), weight->lite_models.end(), delete_model);
if (it != weight->lite_models.end()) {
weight->lite_models.erase(it);
}
}
for (auto &item : buf_model_weight_) {
auto &weight = item.second;
auto it = find(weight->lite_models.begin(), weight->lite_models.end(), delete_model);
if (it != weight->lite_models.end()) {
weight->lite_models.erase(it);
}
}
}
void PackWeightManager::FreePackedWeight(ModelConstWeight *weight) {
for (auto &&packed_data : weight->packed_data) {
auto data = const_cast<void *>(packed_data);
if (data != nullptr) {
#ifdef _WIN32
_aligned_free(data);
#else
free(data);
#endif
data = nullptr;
}
}
weight->packed_weight.clear();
weight->packed_data.clear();
if (weight != nullptr) {
delete weight;
weight = nullptr;
}
}
PackWeightManager::~PackWeightManager() {
for (auto &item : path_model_weight_) {
FreePackedWeight(item.second);
}
path_model_weight_.clear();
for (auto &item : buf_model_weight_) {
FreePackedWeight(item.second);
}
buf_model_weight_.clear();
}
} // namespace mindspore::lite
#endif
| 36.657143 | 113 | 0.697844 | [
"model"
] |
3acdba37664a7946620f91af450a4e9a6e394db7 | 1,870 | cpp | C++ | example/main.cpp | particle-iot/model_gauge | 2cbca46597f7087a815aa2a2cec5280d86d20171 | [
"Apache-2.0"
] | null | null | null | example/main.cpp | particle-iot/model_gauge | 2cbca46597f7087a815aa2a2cec5280d86d20171 | [
"Apache-2.0"
] | null | null | null | example/main.cpp | particle-iot/model_gauge | 2cbca46597f7087a815aa2a2cec5280d86d20171 | [
"Apache-2.0"
] | null | null | null |
#include "Particle.h"
#include "model_gauge.h"
SerialLogHandler logHandler(115200, LOG_LEVEL_INFO);
SYSTEM_MODE(MANUAL);
// define your new battery model config first, or use the default config in model_gauge.h
// example: LG INR21700 battery model get from the .ini file
const model_config_t model_config_example = {
.EmptyAdjustment=0,
.FullAdjustment=100,
.RCOMP0 = 92,
.TempCoUp = -0.453125,
.TempCoDown = -0.8125,
.OCVTest = 58560,
.SOCCheckA = 203,
.SOCCheckB = 205,
.bits = 19,
.model_data = {
0x88, 0x70, 0xAA, 0x10, 0xAD, 0x90, 0xB0, 0x60, 0xB3, 0xF0, 0xB7, 0x00, 0xB8, 0xF0, 0xBC, 0x50,
0xBF, 0xE0, 0xC2, 0x00, 0xC4, 0x60, 0xC7, 0x40, 0xCA, 0xD0, 0xCC, 0x40, 0xCD, 0x00, 0xDA, 0xC0,
0x00, 0x40, 0x07, 0x00, 0x0C, 0x00, 0x10, 0x40, 0x13, 0x00, 0x1D, 0x60, 0x19, 0x20, 0x1A, 0xE0,
0x13, 0xC0, 0x15, 0x80, 0x11, 0xC0, 0x13, 0x20, 0x3D, 0x00, 0x5E, 0x60, 0x01, 0x20, 0x01, 0x20,
}
};
// create the ModelGauge object with the model config
ModelGauge model_gauge(model_config_example);
void setup()
{
Serial.begin();
waitFor(Serial.isConnected, 5000);
delay(50);
// load model config when power on
model_gauge.load_config();
}
void loop()
{
static uint32_t last_10s = 0;
static uint32_t last_1h = 0;
// print soc every 10 seconds
if(System.uptime() - last_10s >= 10)
{
last_10s = System.uptime();
// read battery voltage and soc from ModelGauge
float volt = model_gauge.get_volt();
float soc = model_gauge.get_soc();
Log.info(">>> volt:%.2f, soc:%.2f%%", volt, soc);
}
// verify model every 1 hour
if(System.uptime() - last_1h >= 3600)
{
last_1h = System.uptime();
// verify model, reload model if verify failed
model_gauge.verify_model();
}
}
| 28.333333 | 104 | 0.631016 | [
"object",
"model"
] |
3aceb3ab8a6acbe466efb20fc82cb218767ce796 | 1,249 | hpp | C++ | src/renderer.hpp | daniel-junior-dube/comfywm-cpp | ea1d19a11c8bfbbc49359af5d020956c0da6d281 | [
"MIT"
] | null | null | null | src/renderer.hpp | daniel-junior-dube/comfywm-cpp | ea1d19a11c8bfbbc49359af5d020956c0da6d281 | [
"MIT"
] | null | null | null | src/renderer.hpp | daniel-junior-dube/comfywm-cpp | ea1d19a11c8bfbbc49359af5d020956c0da6d281 | [
"MIT"
] | null | null | null | #pragma once
extern "C" {
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_xdg_shell.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_output_layout.h>
#define static
#include <wlr/types/wlr_matrix.h>
#include <wlr/render/wlr_renderer.h>
#undef static
}
#include <functional>
#include "output.hpp"
class CMFYView;
using RGBAColor = float[4];
class RenderOutputTransaction {
public:
CMFYOutput output;
timespec start_time;
RenderOutputTransaction(CMFYOutput output);
~RenderOutputTransaction();
void commit();
};
class CMFYRenderer {
bool should_clear = true;
RGBAColor clear_color = { 0.0, 0.0, 0.0, 1.0 };
public:
wlr_renderer* wlroots_renderer;
CMFYRenderer(wlr_renderer* wlroots_renderer);
~CMFYRenderer();
void render(int width, int height, std::function<void()> callback);
void render_output(CMFYOutput& output, std::function<void(RenderOutputTransaction transaction)> callback);
void with_output_attached(CMFYOutput& output, std::function<void(RenderOutputTransaction transaction)> callback);
static void draw_surface(wlr_surface *surface, int sx, int sy, void *data);
private:
};
struct RenderData {
CMFYOutput* output;
CMFYView* view;
CMFYRenderer* renderer;
timespec* when;
};
| 24.98 | 115 | 0.755805 | [
"render"
] |
3ad19cba91eba5ea5e7148d98e39f8341a0034c7 | 33,563 | hpp | C++ | luaWrapper/luaWrapper.hpp | HeeroYui-deprecated/luaWrapper | df103aa144b3adfc611de58b20760eb832385654 | [
"MIT"
] | 1 | 2018-02-26T18:22:59.000Z | 2018-02-26T18:22:59.000Z | luaWrapper/luaWrapper.hpp | HeeroYui-deprecated/luaWrapper | df103aa144b3adfc611de58b20760eb832385654 | [
"MIT"
] | null | null | null | luaWrapper/luaWrapper.hpp | HeeroYui-deprecated/luaWrapper | df103aa144b3adfc611de58b20760eb832385654 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2010-2013 Alexander Ames
* Alexander.Ames@gmail.com
* See Copyright Notice at the end of this file
*/
/** API Summary:
*
* LuaWrapper is a library designed to help bridge the gab between Lua and
* C++. It is designed to be small (a single header file), simple, fast,
* and typesafe. It has no external dependencies, and does not need to be
* precompiled; the header can simply be dropped into a project and used
* immediately. It even supports class inheritance to a certain degree. Objects
* can be created in either Lua or C++, and passed back and forth.
*
* The main functions of interest are the following:
* luaWrapper::is<LUAW_TYPE>
* luaWrapper::to<LUAW_TYPE>
* luaWrapper::check<LUAW_TYPE>
* luaWrapper::push<LUAW_TYPE>
* luaWrapper::registerElement<LUAW_TYPE>
* luaWrapper::setfuncs<LUAW_TYPE>
* luaWrapper::extend<LUAW_TYPE, LUAW_TYPE2>
* luaWrapper::hold<LUAW_TYPE>
* luaWrapper::release<LUAW_TYPE>
*
* These functions allow you to manipulate arbitrary classes just like you
* would the primitive types (e.g. numbers or strings). If you are familiar
* with the normal Lua API the behavior of these functions should be very
* intuative.
*
* For more information see the README and the comments below
*/
#pragma once
// If you are linking against Lua compiled in C++, define LUAW_NO_EXTERN_C
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
#include <ememory/memory.hpp>
#include <etk/typeInfo.hpp>
#include <etk/Allocator.hpp>
#include <etk/os/FSNode.hpp>
#include <etk/Exception.hpp>
#include <luaWrapper/debug.hpp>
#define LUAW_POSTCTOR_KEY "__postctor"
#define LUAW_EXTENDS_KEY "__extends"
#define LUAW_STORAGE_KEY "storage"
#define LUAW_CACHE_KEY "cache"
#define LUAW_CACHE_METATABLE_KEY "cachemetatable"
#define LUAW_HOLDS_KEY "holds"
#define LUAW_WRAPPER_KEY "LuaWrapper"
namespace luaWrapper {
namespace utils {
template<typename LUAW_TYPE> LUAW_TYPE check(lua_State* _luaState, int _index);
template<typename LUAW_TYPE> LUAW_TYPE to(lua_State* _luaState, int _index);
template<typename LUAW_TYPE> void push(lua_State* _luaState, const LUAW_TYPE& _value);
}
// end the recursive template...
inline void setCallParameters(lua_State* _luaState) {
// nothing to do...
}
template<class ... LUAW_ARGS>
void setCallParameters(lua_State* _luaState, const char* _value, LUAW_ARGS&&... _args) {
luaWrapper::utils::push<const char*>(_luaState, _value);
setCallParameters(_luaState, etk::forward<LUAW_ARGS>(_args)...);
}
template<class LUAW_ARG, class ... LUAW_ARGS>
void setCallParameters(lua_State* _luaState, LUAW_ARG&& _value, LUAW_ARGS&&... _args) {
luaWrapper::utils::push<LUAW_ARG>(_luaState, _value);
setCallParameters(_luaState, etk::forward<LUAW_ARGS>(_args)...);
}
/**
* @brief main interface of Lua engine.
*/
class Lua {
private:
lua_State* m_luaState = null;
public:
Lua() {
m_luaState = luaL_newstate();
if (m_luaState != null) {
luaL_openlibs(m_luaState);
}
}
~Lua() {
if (m_luaState != null) {
lua_close(m_luaState);
m_luaState = null;
}
}
void executeFile(const etk::String& _fileName) {
etk::String data = etk::FSNodeReadAllData(_fileName);
if (luaL_dostring(m_luaState, &data[0])) {
LUAW_PRINT(lua_tostring(m_luaState, -1));
}
}
void executeString(const etk::String& _rawData) {
if (luaL_dostring(m_luaState, &_rawData[0])) {
LUAW_PRINT(lua_tostring(m_luaState, -1));
}
}
lua_State* getState() {
return m_luaState;
}
private:
template<class ... LUAW_ARGS>
void callGeneric(int32_t _numberReturn, const char* _functionName, LUAW_ARGS&&... _args) {
/* push functions and arguments */
lua_getglobal(m_luaState, _functionName); /* function to be called */
setCallParameters(m_luaState, etk::forward<LUAW_ARGS>(_args)...);
/* do the call (n arguments, 1 result) */
if (lua_pcall(m_luaState, int32_t(sizeof...(LUAW_ARGS)), _numberReturn, 0) != 0) {
ETK_THROW_EXCEPTION(etk::exception::RuntimeError(etk::String("error running function `") + _functionName +": " + lua_tostring(m_luaState, -1)));
}
}
public:
/**
* Call a lua function with some generic parameters (with return value).
* @param[in] _functionName Funtion to call.
* @param[in] _args... Multiple argument (what you want).
* @return The specified type.
*/
template<class LUAW_RETURN_TYPE, class ... LUAW_ARGS>
LUAW_RETURN_TYPE call(const char* _functionName, LUAW_ARGS&&... _args) {
callGeneric(1, _functionName, etk::forward<LUAW_ARGS>(_args)...);
// retrieve result
LUAW_RETURN_TYPE returnValue = luaWrapper::utils::check<LUAW_RETURN_TYPE>(m_luaState, -1);
// pop returned value
lua_pop(m_luaState, 1);
return returnValue;
}
/**
* Call a lua function with some generic parameters (WITHOUT return value).
* @param[in] _functionName Funtion to call.
* @param[in] _args... Multiple argument (what you want).
*/
template<class ... LUAW_ARGS>
void callVoid(const char* _functionName, LUAW_ARGS&&... _args) {
callGeneric(0, _functionName, etk::forward<LUAW_ARGS>(_args)...);
}
};
/**
* A simple utility function to adjust a given index
* Useful for when a parameter index needs to be adjusted
* after pushing or popping things off the stack
*/
inline int correctindex(lua_State* _luaState, int _index, int _correction) {
return _index < 0 ? _index - _correction : _index;
}
/**
* These are the default allocator and deallocator. If you would prefer an
* alternative option, you may select a different function when registering
* your class.
*/
template <typename LUAW_TYPE>
ememory::SharedPtr<LUAW_TYPE> defaultallocator(lua_State* _luaState) {
return ememory::makeShared<LUAW_TYPE>();
}
/**
* The identifier function is responsible for pushing a value unique to each
* object on to the stack. Most of the time, this can simply be the address
* of the pointer, but sometimes that is not adaquate. For example, if you
* are using shared_ptr you would need to push the address of the object the
* shared_ptr represents, rather than the address of the shared_ptr itself.
*/
template <typename LUAW_TYPE>
void defaultidentifier(lua_State* _luaState, ememory::SharedPtr<LUAW_TYPE> _obj) {
lua_pushlightuserdata(_luaState, _obj.get());
}
/**
* This class is what is used by LuaWrapper to contain the userdata. data
* stores a pointer to the object itself, and cast is used to cast toward the
* base class if there is one and it is necessary. Rather than use RTTI and
* typid to compare types, I use the clever trick of using the cast to compare
* types. Because there is at most one cast per type, I can use it to identify
* when and object is the type I want. This is only used internally.
*/
struct Userdata {
Userdata(ememory::SharedPtr<void> _vptr = null, size_t _typeId = 0):
m_data(etk::move(_vptr)),
m_typeId(_typeId) {
// nothing to do ...
}
Userdata(Userdata&& _obj) {
etk::swap(m_data, _obj.m_data);
etk::swap(m_typeId, _obj.m_typeId);
}
Userdata(const Userdata& _obj) {
m_data = _obj.m_data;
m_typeId = _obj.m_typeId;
}
Userdata& operator= (Userdata&& _obj) {
etk::swap(m_data, _obj.m_data);
etk::swap(m_typeId, _obj.m_typeId);
return *this;
}
Userdata& operator= (const Userdata& _obj) {
m_data = _obj.m_data;
m_typeId = _obj.m_typeId;
return *this;
}
ememory::SharedPtr<void> m_data;
size_t m_typeId;
};
/**
* This class cannot actually to be instantiated. It is used only hold the
* table name and other information.
*/
template <typename LUAW_TYPE>
class LuaWrapper {
public:
static const char* classname;
static void (*identifier)(lua_State*, ememory::SharedPtr<LUAW_TYPE>);
static ememory::SharedPtr<LUAW_TYPE> (*allocator)(lua_State*);
static void (*postconstructorrecurse)(lua_State* _luaState, int numargs);
private:
LuaWrapper();
};
template <typename LUAW_TYPE> const char* LuaWrapper<LUAW_TYPE>::classname;
template <typename LUAW_TYPE> void (*LuaWrapper<LUAW_TYPE>::identifier)(lua_State*, ememory::SharedPtr<LUAW_TYPE>);
template <typename LUAW_TYPE> ememory::SharedPtr<LUAW_TYPE> (*LuaWrapper<LUAW_TYPE>::allocator)(lua_State*);
template <typename LUAW_TYPE> void (*LuaWrapper<LUAW_TYPE>::postconstructorrecurse)(lua_State* _luaState, int _numargs);
template <typename LUAW_TYPE, typename LUAW_TYPE2>
void identify(lua_State* _luaState, LUAW_TYPE* _obj) {
LuaWrapper<LUAW_TYPE2>::identifier(_luaState, static_cast<LUAW_TYPE2*>(_obj));
}
template <typename LUAW_TYPE>
inline void wrapperField(lua_State* _luaState, const char* _field) {
lua_getfield(_luaState, LUA_REGISTRYINDEX, LUAW_WRAPPER_KEY); // ... LuaWrapper
lua_getfield(_luaState, -1, _field); // ... LuaWrapper LuaWrapper.field
lua_getfield(_luaState, -1, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.field LuaWrapper.field.class
lua_replace(_luaState, -3); // ... LuaWrapper.field.class LuaWrapper.field
lua_pop(_luaState, 1); // ... LuaWrapper.field.class
}
/**
* Analogous to lua_is(boolean|string|*)
*
* Returns 1 if the value at the given acceptable index is of type T (or if
* strict is false, convertable to type T) and 0 otherwise.
*/
template <typename LUAW_TYPE>
bool is(lua_State *_luaState, int _index, bool _strict = false) {
bool equal = false;// lua_isnil(_luaState, index);
if ( equal == false
&& lua_isuserdata(_luaState, _index)
&& lua_getmetatable(_luaState, _index)) {
// ... ud ... udmt
luaL_getmetatable(_luaState, LuaWrapper<LUAW_TYPE>::classname); // ... ud ... udmt Tmt
equal = lua_rawequal(_luaState, -1, -2) != 0;
if (!equal && !_strict) {
lua_getfield(_luaState, -2, LUAW_EXTENDS_KEY); // ... ud ... udmt Tmt udmt.extends
for (lua_pushnil(_luaState); lua_next(_luaState, -2); lua_pop(_luaState, 1)) {
// ... ud ... udmt Tmt udmt.extends k v
equal = lua_rawequal(_luaState, -1, -4) != 0;
if (equal) {
lua_pop(_luaState, 2); // ... ud ... udmt Tmt udmt.extends
break;
}
}
lua_pop(_luaState, 1); // ... ud ... udmt Tmt
}
lua_pop(_luaState, 2); // ... ud ...
}
return equal;
}
/**
* Analogous to lua_to(boolean|string|*)
*
* Converts the given acceptable index to a T*. That value must be of (or
* convertable to) type T; otherwise, returns NULL.
*/
template <typename LUAW_TYPE>
ememory::SharedPtr<LUAW_TYPE> to(lua_State* _luaState, int _index, bool _strict = false) {
if (is<LUAW_TYPE>(_luaState, _index, _strict)) {
Userdata* pud = static_cast<Userdata*>(lua_touserdata(_luaState, _index));
return ememory::staticPointerCast<LUAW_TYPE>(pud->m_data);
}
return null;
}
/**
* Analogous to luaL_check(boolean|string|*)
*
* Converts the given acceptable index to a LUAW_TYPE*. That value must be of (or
* convertable to) type T; otherwise, an error is raised.
*/
template <typename LUAW_TYPE>
ememory::SharedPtr<LUAW_TYPE> check(lua_State* _luaState,
int _index,
bool _strict = false) {
ememory::SharedPtr<LUAW_TYPE> obj;
if (is<LUAW_TYPE>(_luaState, _index, _strict)) {
Userdata* pud = static_cast<Userdata*>(lua_touserdata(_luaState, _index));
obj = ememory::staticPointerCast<LUAW_TYPE>(pud->m_data);
} else {
const char *msg = lua_pushfstring(_luaState, "%s expected, got %s", LuaWrapper<LUAW_TYPE>::classname, luaL_typename(_luaState, _index));
luaL_argerror(_luaState, _index, msg);
}
return obj;
}
template <typename LUAW_TYPE>
ememory::SharedPtr<LUAW_TYPE> opt(lua_State* _luaState,
int _index,
ememory::SharedPtr<LUAW_TYPE> _fallback = null,
bool _strict = false) {
if (lua_isnil(_luaState, _index) == true) {
return _fallback;
} else {
return check<LUAW_TYPE>(_luaState, _index, _strict);
}
}
/**
* Analogous to lua_push(boolean|string|*)
*
* Pushes a userdata of type T onto the stack. If this object already exists in
* the Lua environment, it will assign the existing storage table to it.
* Otherwise, a new storage table will be created for it.
*/
template <typename LUAW_TYPE>
void push(lua_State* _luaState,
ememory::SharedPtr<LUAW_TYPE> _obj) {
if (_obj != null) {
LuaWrapper<LUAW_TYPE>::identifier(_luaState, _obj); // ... id
wrapperField<LUAW_TYPE>(_luaState, LUAW_CACHE_KEY); // ... id cache
lua_pushvalue(_luaState, -2); // ... id cache id
lua_gettable(_luaState, -2); // ... id cache obj
if (lua_isnil(_luaState, -1)) {
// Create the new userdata and place it in the cache
lua_pop(_luaState, 1); // ... id cache
lua_insert(_luaState, -2); // ... cache id
// placement new creation (need to initilaize the sructure:
Userdata* ud = new ((char*)lua_newuserdata(_luaState, sizeof(Userdata))) Userdata(_obj, ETK_GET_TYPE_ID(LUAW_TYPE)); // ... cache id obj
lua_pushvalue(_luaState, -1); // ... cache id obj obj
lua_insert(_luaState, -4); // ... obj cache id obj
lua_settable(_luaState, -3); // ... obj cache
luaL_getmetatable(_luaState, LuaWrapper<LUAW_TYPE>::classname); // ... obj cache mt
lua_setmetatable(_luaState, -3); // ... obj cache
lua_pop(_luaState, 1); // ... obj
} else {
lua_replace(_luaState, -3); // ... obj cache
lua_pop(_luaState, 1); // ... obj
}
} else {
lua_pushnil(_luaState);
}
}
/**
* Instructs LuaWrapper that it owns the userdata, and can manage its memory.
* When all references to the object are removed, Lua is free to garbage
* collect it and delete the object.
*
* Returns true if hold took hold of the object, and false if it was
* already held
*/
template <typename LUAW_TYPE>
bool hold(lua_State* _luaState,
ememory::SharedPtr<LUAW_TYPE> _obj) {
wrapperField<LUAW_TYPE>(_luaState, LUAW_HOLDS_KEY); // ... holds
LuaWrapper<LUAW_TYPE>::identifier(_luaState, _obj); // ... holds id
lua_pushvalue(_luaState, -1); // ... holds id id
lua_gettable(_luaState, -3); // ... holds id hold
// If it's not held, hold it
if (!lua_toboolean(_luaState, -1)) {
// Apply hold boolean
lua_pop(_luaState, 1); // ... holds id
lua_pushboolean(_luaState, true); // ... holds id true
lua_settable(_luaState, -3); // ... holds
lua_pop(_luaState, 1); // ...
return true;
}
lua_pop(_luaState, 3); // ...
return false;
}
/**
* Releases LuaWrapper's hold on an object. This allows the user to remove
* all references to an object in Lua and ensure that Lua will not attempt to
* garbage collect it.
*
* This function takes the index of the identifier for an object rather than
* the object itself. This is because needs to be able to run after the object
* has already been deallocated. A wrapper is provided for when it is more
* convenient to pass in the object directly.
*/
template <typename LUAW_TYPE>
void release(lua_State* _luaState,
int _index) {
wrapperField<LUAW_TYPE>(_luaState, LUAW_HOLDS_KEY); // ... id ... holds
lua_pushvalue(_luaState, correctindex(_luaState, _index, 1)); // ... id ... holds id
lua_pushnil(_luaState); // ... id ... holds id nil
lua_settable(_luaState, -3); // ... id ... holds
lua_pop(_luaState, 1); // ... id ...
}
template <typename LUAW_TYPE>
void release(lua_State* _luaState,
LUAW_TYPE* _obj) {
LuaWrapper<LUAW_TYPE>::identifier(_luaState, _obj); // ... id
release<LUAW_TYPE>(_luaState, -1); // ... id
lua_pop(_luaState, 1); // ...
}
template <typename LUAW_TYPE>
void postconstructorinternal(lua_State* _luaState,
int _numargs) {
// ... ud args...
if (LuaWrapper<LUAW_TYPE>::postconstructorrecurse) {
LuaWrapper<LUAW_TYPE>::postconstructorrecurse(_luaState, _numargs);
}
luaL_getmetatable(_luaState, LuaWrapper<LUAW_TYPE>::classname); // ... ud args... mt
lua_getfield(_luaState, -1, LUAW_POSTCTOR_KEY); // ... ud args... mt postctor
if (lua_type(_luaState, -1) == LUA_TFUNCTION) {
for (int i = 0; i < _numargs + 1; i++) {
lua_pushvalue(_luaState, -3 - _numargs); // ... ud args... mt postctor ud args...
}
lua_call(_luaState, _numargs + 1, 0); // ... ud args... mt
lua_pop(_luaState, 1); // ... ud args...
} else {
lua_pop(_luaState, 2); // ... ud args...
}
}
/**
* This function is called from Lua, not C++
*
* Calls the lua post-constructor (LUAW_POSTCTOR_KEY or "__postctor") on a
* userdata. Assumes the userdata is on the stack and numargs arguments follow
* it. This runs the LUAW_POSTCTOR_KEY function on T's metatable, using the
* object as the first argument and whatever else is below it as the rest of the
* arguments This exists to allow types to adjust values in thier storage table,
* which can not be created until after the constructor is called.
*/
template <typename LUAW_TYPE>
void postconstructor(lua_State* _luaState,
int _numargs) {
// ... ud args...
postconstructorinternal<LUAW_TYPE>(_luaState, _numargs); // ... ud args...
lua_pop(_luaState, _numargs); // ... ud
}
/**
* This function is generally called from Lua, not C++
*
* Creates an object of type T using the constructor and subsequently calls the
* post-constructor on it.
*/
template <typename LUAW_TYPE>
inline int create(lua_State* _luaState, int _numargs) {
// ... args...
ememory::SharedPtr<LUAW_TYPE> obj = LuaWrapper<LUAW_TYPE>::allocator(_luaState);
push<LUAW_TYPE>(_luaState, obj); // ... args... ud
hold<LUAW_TYPE>(_luaState, obj);
lua_insert(_luaState, -1 - _numargs); // ... ud args...
postconstructor<LUAW_TYPE>(_luaState, _numargs); // ... ud
return 1;
}
template <typename LUAW_TYPE>
int create(lua_State* _luaState) {
return create<LUAW_TYPE>(_luaState, lua_gettop(_luaState));
}
/**
* This function is called from Lua, not C++
*
* The default metamethod to call when indexing into lua userdata representing
* an object of type T. This will first check the userdata's environment table
* and if it's not found there it will check the metatable. This is done so
* individual userdata can be treated as a table, and can hold thier own
* values.
*/
template <typename LUAW_TYPE>
int index(lua_State* _luaState) {
// obj key
ememory::SharedPtr<LUAW_TYPE> obj = to<LUAW_TYPE>(_luaState, 1);
wrapperField<LUAW_TYPE>(_luaState, LUAW_STORAGE_KEY); // obj key storage
LuaWrapper<LUAW_TYPE>::identifier(_luaState, obj); // obj key storage id
lua_gettable(_luaState, -2); // obj key storage store
// Check if storage table exists
if (!lua_isnil(_luaState, -1)) {
lua_pushvalue(_luaState, -3); // obj key storage store key
lua_gettable(_luaState, -2); // obj key storage store store[k]
}
// If either there is no storage table or the key wasn't found
// then fall back to the metatable
if (lua_isnil(_luaState, -1)) {
lua_settop(_luaState, 2); // obj key
lua_getmetatable(_luaState, -2); // obj key mt
lua_pushvalue(_luaState, -2); // obj key mt k
lua_gettable(_luaState, -2); // obj key mt mt[k]
}
return 1;
}
/**
* This function is called from Lua, not C++
*
* The default metamethod to call when creating a new index on lua userdata
* representing an object of type T. This will index into the the userdata's
* environment table that it keeps for personal storage. This is done so
* individual userdata can be treated as a table, and can hold thier own
* values.
*/
template <typename LUAW_TYPE>
int newindex(lua_State* _luaState) {
// obj key value
ememory::SharedPtr<LUAW_TYPE> obj = check<LUAW_TYPE>(_luaState, 1);
wrapperField<LUAW_TYPE>(_luaState, LUAW_STORAGE_KEY); // obj key value storage
LuaWrapper<LUAW_TYPE>::identifier(_luaState, obj); // obj key value storage id
lua_pushvalue(_luaState, -1); // obj key value storage id id
lua_gettable(_luaState, -3); // obj key value storage id store
// Add the storage table if there isn't one already
if (lua_isnil(_luaState, -1)) {
lua_pop(_luaState, 1); // obj key value storage id
lua_newtable(_luaState); // obj key value storage id store
lua_pushvalue(_luaState, -1); // obj key value storage id store store
lua_insert(_luaState, -3); // obj key value storage store id store
lua_settable(_luaState, -4); // obj key value storage store
}
lua_pushvalue(_luaState, 2); // obj key value ... store key
lua_pushvalue(_luaState, 3); // obj key value ... store key value
lua_settable(_luaState, -3); // obj key value ... store
return 0;
}
/**
* This function is called from Lua, not C++
*
* The __gc metamethod handles cleaning up userdata. The userdata's reference
* count is decremented and if this is the final reference to the userdata its
* environment table is nil'd and pointer deleted with the destructor callback.
*/
template <typename LUAW_TYPE>
int gc(lua_State* _luaState) {
// obj
/*
ememory::SharedPtr<LUAW_TYPE> obj = to<LUAW_TYPE>(_luaState, 1);
LuaWrapper<LUAW_TYPE>::identifier(_luaState, obj); // obj key value storage id
wrapperField<LUAW_TYPE>(_luaState, LUAW_HOLDS_KEY); // obj id counts count holds
lua_pushvalue(_luaState, 2); // obj id counts count holds id
lua_gettable(_luaState, -2); // obj id counts count holds hold
if (lua_toboolean(_luaState, -1)) {
obj.reset();
}
wrapperField<LUAW_TYPE>(_luaState, LUAW_STORAGE_KEY); // obj id counts count holds hold storage
lua_pushvalue(_luaState, 2); // obj id counts count holds hold storage id
lua_pushnil(_luaState); // obj id counts count holds hold storage id nil
lua_settable(_luaState, -3); // obj id counts count holds hold storage
release<LUAW_TYPE>(_luaState, 2);
*/
Userdata *object = static_cast<Userdata*>( lua_touserdata( _luaState, 1 ) );
object->~Userdata();
lua_pop( _luaState, 1 );
return 0;
}
/**
* Thakes two tables and registers them with Lua to the table on the top of the
* stack.
*
* This function is only called from LuaWrapper internally.
*/
inline void registerfuncs(lua_State* _luaState, const luaL_Reg _defaulttable[], const luaL_Reg _table[]) {
// ... T
if (_defaulttable) {
luaL_setfuncs(_luaState, _defaulttable, 0); // ... T
}
if (_table) {
luaL_setfuncs(_luaState, _table, 0); // ... T
}
}
/**
* Initializes the LuaWrapper tables used to track internal state.
*
* This function is only called from LuaWrapper internally.
*/
inline void initialize(lua_State* _luaState) {
// Ensure that the LuaWrapper table is set up
lua_getfield(_luaState, LUA_REGISTRYINDEX, LUAW_WRAPPER_KEY); // ... LuaWrapper
if (lua_isnil(_luaState, -1)) {
lua_newtable(_luaState); // ... nil {}
lua_pushvalue(_luaState, -1); // ... nil {} {}
lua_setfield(_luaState, LUA_REGISTRYINDEX, LUAW_WRAPPER_KEY); // ... nil LuaWrapper
// Create a storage table
lua_newtable(_luaState); // ... LuaWrapper nil {}
lua_setfield(_luaState, -2, LUAW_STORAGE_KEY); // ... nil LuaWrapper
// Create a holds table
lua_newtable(_luaState); // ... LuaWrapper {}
lua_setfield(_luaState, -2, LUAW_HOLDS_KEY); // ... nil LuaWrapper
// Create a cache table, with weak values so that the userdata will not
// be ref counted
lua_newtable(_luaState); // ... nil LuaWrapper {}
lua_setfield(_luaState, -2, LUAW_CACHE_KEY); // ... nil LuaWrapper
lua_newtable(_luaState); // ... nil LuaWrapper {}
lua_pushstring(_luaState, "v"); // ... nil LuaWrapper {} "v"
lua_setfield(_luaState, -2, "__mode"); // ... nil LuaWrapper {}
lua_setfield(_luaState, -2, LUAW_CACHE_METATABLE_KEY); // ... nil LuaWrapper
lua_pop(_luaState, 1); // ... nil
}
lua_pop(_luaState, 1); // ...
}
/**
* Run register or setfuncs to create a table and metatable for your
* class. These functions create a table with filled with the function from
* the table argument in addition to the functions new and build (This is
* generally for things you think of as static methods in C++). The given
* metatable argument becomes a metatable for each object of your class. These
* can be thought of as member functions or methods.
*
* You may also supply constructors and destructors for classes that do not
* have a default constructor or that require special set up or tear down. You
* may specify NULL as the constructor, which means that you will not be able
* to call the new function on your class table. You will need to manually push
* objects from C++. By default, the default constructor is used to create
* objects and a simple call to delete is used to destroy them.
*
* By default LuaWrapper uses the address of C++ object to identify unique
* objects. In some cases this is not desired, such as in the case of
* shared_ptrs. Two shared_ptrs may themselves have unique locations in memory
* but still represent the same object. For cases like that, you may specify an
* identifier function which is responsible for pushing a key representing your
* object on to the stack.
*
* register will set table as the new value of the global of the given
* name. setfuncs is identical to register, but it does not set the
* table globally. As with luaL_register and luaL_setfuncs, both funcstions
* leave the new table on the top of the stack.
*/
template <typename LUAW_TYPE>
void setfuncs(lua_State* _luaState,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable,
ememory::SharedPtr<LUAW_TYPE> (*_allocator)(lua_State*),
void (*_identifier)(lua_State*, ememory::SharedPtr<LUAW_TYPE>)) {
initialize(_luaState);
LuaWrapper<LUAW_TYPE>::classname = _classname;
LuaWrapper<LUAW_TYPE>::identifier = _identifier;
LuaWrapper<LUAW_TYPE>::allocator = _allocator;
const luaL_Reg defaulttable[] = {
{ "new", create<LUAW_TYPE> },
{ NULL, NULL }
};
const luaL_Reg defaultmetatable[] = {
{ "__index", index<LUAW_TYPE> },
{ "__newindex", newindex<LUAW_TYPE> },
{ "__gc", gc<LUAW_TYPE> },
{ NULL, NULL }
};
// Set up per-type tables
lua_getfield(_luaState, LUA_REGISTRYINDEX, LUAW_WRAPPER_KEY); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_STORAGE_KEY); // ... LuaWrapper LuaWrapper.storage
lua_newtable(_luaState); // ... LuaWrapper LuaWrapper.storage {}
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.storage
lua_pop(_luaState, 1); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_HOLDS_KEY); // ... LuaWrapper LuaWrapper.holds
lua_newtable(_luaState); // ... LuaWrapper LuaWrapper.holds {}
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.holds
lua_pop(_luaState, 1); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_CACHE_KEY); // ... LuaWrapper LuaWrapper.cache
lua_newtable(_luaState); // ... LuaWrapper LuaWrapper.cache {}
wrapperField<LUAW_TYPE>(_luaState, LUAW_CACHE_METATABLE_KEY); // ... LuaWrapper LuaWrapper.cache {} cmt
lua_setmetatable(_luaState, -2); // ... LuaWrapper LuaWrapper.cache {}
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.cache
lua_pop(_luaState, 2); // ...
// Open table
lua_newtable(_luaState); // ... T
registerfuncs(_luaState, _allocator ? defaulttable : NULL, _table); // ... T
// Open metatable, set up extends table
luaL_newmetatable(_luaState, _classname); // ... T mt
lua_newtable(_luaState); // ... T mt {}
lua_setfield(_luaState, -2, LUAW_EXTENDS_KEY); // ... T mt
registerfuncs(_luaState, defaultmetatable, _metatable); // ... T mt
lua_setfield(_luaState, -2, "metatable"); // ... T
}
template <typename LUAW_TYPE>
void setfuncs(lua_State* _luaState,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable,
ememory::SharedPtr<LUAW_TYPE> (*_allocator)(lua_State*)) {
setfuncs(_luaState, _classname, _table, _metatable, _allocator, defaultidentifier<LUAW_TYPE>);
}
template <typename LUAW_TYPE>
void setfuncs(lua_State* _luaState,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable) {
setfuncs(_luaState, _classname, _table, _metatable, defaultallocator<LUAW_TYPE>, defaultidentifier<LUAW_TYPE>);
}
template <typename LUAW_TYPE>
void registerElement(Lua& _lua,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable,
ememory::SharedPtr<LUAW_TYPE> (*_allocator)(lua_State*),
void (*_identifier)(lua_State*, ememory::SharedPtr<LUAW_TYPE>)) {
setfuncs(_lua.getState(), _classname, _table, _metatable, _allocator, _identifier); // ... T
lua_pushvalue(_lua.getState(), -1); // ... LUAW_TYPE LUAW_TYPE
lua_setglobal(_lua.getState(), _classname); // ... LUAW_TYPE
}
template <typename LUAW_TYPE>
void registerElement(Lua& _lua,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable,
ememory::SharedPtr<LUAW_TYPE> (*_allocator)(lua_State*)) {
setfuncs(_lua.getState(), _classname, _table, _metatable, _allocator, defaultidentifier<LUAW_TYPE>);
lua_pushvalue(_lua.getState(), -1); // ... LUAW_TYPE LUAW_TYPE
lua_setglobal(_lua.getState(), _classname); // ... LUAW_TYPE
}
template <typename LUAW_TYPE>
void registerElement(Lua& _lua,
const char* _classname,
const luaL_Reg* _table,
const luaL_Reg* _metatable) {
setfuncs(_lua.getState(), _classname, _table, _metatable, defaultallocator<LUAW_TYPE>, defaultidentifier<LUAW_TYPE>); // ... T
lua_pushvalue(_lua.getState(), -1); // ... T T
lua_setglobal(_lua.getState(), _classname); // ... T
}
/**
* extend is used to declare that class T inherits from class U. All
* functions in the base class will be available to the derived class (except
* when they share a function name, in which case the derived class's function
* wins). This also allows to<LUAW_TYPE> to cast your object apropriately, as
* casts straight through a void pointer do not work.
*/
template <typename LUAW_TYPE, typename LUAW_TYPE2>
void extend(lua_State* _luaState) {
if(!LuaWrapper<LUAW_TYPE>::classname) {
luaL_error(_luaState, "attempting to call extend on a type that has not been registered");
}
if(!LuaWrapper<LUAW_TYPE2>::classname) {
luaL_error(_luaState, "attempting to extend %s by a type that has not been registered", LuaWrapper<LUAW_TYPE>::classname);
}
//LuaWrapper<LUAW_TYPE>::cast = cast<LUAW_TYPE, LUAW_TYPE2>;
LuaWrapper<LUAW_TYPE>::identifier = identify<LUAW_TYPE, LUAW_TYPE2>;
LuaWrapper<LUAW_TYPE>::postconstructorrecurse = postconstructorinternal<LUAW_TYPE2>;
luaL_getmetatable(_luaState, LuaWrapper<LUAW_TYPE>::classname); // mt
luaL_getmetatable(_luaState, LuaWrapper<LUAW_TYPE2>::classname); // mt emt
// Point T's metatable __index at U's metatable for inheritance
lua_newtable(_luaState); // mt emt {}
lua_pushvalue(_luaState, -2); // mt emt {} emt
lua_setfield(_luaState, -2, "__index"); // mt emt {}
lua_setmetatable(_luaState, -3); // mt emt
// Set up per-type tables to point at parent type
lua_getfield(_luaState, LUA_REGISTRYINDEX, LUAW_WRAPPER_KEY); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_STORAGE_KEY); // ... LuaWrapper LuaWrapper.storage
lua_getfield(_luaState, -1, LuaWrapper<LUAW_TYPE2>::classname); // ... LuaWrapper LuaWrapper.storage U
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.storage
lua_pop(_luaState, 1); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_HOLDS_KEY); // ... LuaWrapper LuaWrapper.holds
lua_getfield(_luaState, -1, LuaWrapper<LUAW_TYPE2>::classname); // ... LuaWrapper LuaWrapper.holds U
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.holds
lua_pop(_luaState, 1); // ... LuaWrapper
lua_getfield(_luaState, -1, LUAW_CACHE_KEY); // ... LuaWrapper LuaWrapper.cache
lua_getfield(_luaState, -1, LuaWrapper<LUAW_TYPE2>::classname); // ... LuaWrapper LuaWrapper.cache U
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE>::classname); // ... LuaWrapper LuaWrapper.cache
lua_pop(_luaState, 2); // ...
// Make a list of all types that inherit from U, for type checking
lua_getfield(_luaState, -2, LUAW_EXTENDS_KEY); // mt emt mt.extends
lua_pushvalue(_luaState, -2); // mt emt mt.extends emt
lua_setfield(_luaState, -2, LuaWrapper<LUAW_TYPE2>::classname); // mt emt mt.extends
lua_getfield(_luaState, -2, LUAW_EXTENDS_KEY); // mt emt mt.extends emt.extends
for (lua_pushnil(_luaState); lua_next(_luaState, -2); lua_pop(_luaState, 1)) {
// mt emt mt.extends emt.extends k v
lua_pushvalue(_luaState, -2); // mt emt mt.extends emt.extends k v k
lua_pushvalue(_luaState, -2); // mt emt mt.extends emt.extends k v k
lua_rawset(_luaState, -6); // mt emt mt.extends emt.extends k v
}
lua_pop(_luaState, 4); // mt emt
}
}
#include <luaWrapper/luaWrapperUtil.hpp>
| 41.95375 | 149 | 0.688854 | [
"object"
] |
3ad2a65de74d1081db492b000d0622bbb86f1f17 | 1,670 | hpp | C++ | GameCode/Generator.hpp | malysonb/Ludkerno | 8717710370d70583af2f05492dc5f38403137f11 | [
"MIT"
] | 1 | 2021-03-16T20:48:38.000Z | 2021-03-16T20:48:38.000Z | GameCode/Generator.hpp | malysonb/Ludkerno | 8717710370d70583af2f05492dc5f38403137f11 | [
"MIT"
] | null | null | null | GameCode/Generator.hpp | malysonb/Ludkerno | 8717710370d70583af2f05492dc5f38403137f11 | [
"MIT"
] | null | null | null | #pragma once
#include "../Ludkerno.hpp"
#include "Cactus.hpp"
class Generator : public Component
{
private:
Uint32 m_currenttime = 0;
Uint32 m_lasttime = 0;
Uint32 WaitTime = 60000;
public:
void Init()
{
m_lasttime = SDL_GetTicks();
Active = true;
}
void Update()
{
m_currenttime = SDL_GetTicks();
if (m_currenttime > m_lasttime + (WaitTime * 1/Game::FrameRate))
{
Entity *cactus = Game::EntityManager.Add();
cactus->transform->SetScreenPosition(Game::screen.DynamicHPosition(101), Game::screen.DynamicVPosition(50));
cactus->AddComponent<Cactus>(cactus);
cactus->getComponent<Cactus>()->Init();
cactus->AddComponent<Collider>(cactus);
cactus->getComponent<Collider>()->Init();
int range = Utils::Rand(8,10);
float res = (range*100)*static_cast<float>(Game::FrameRate);
WaitTime = static_cast<int>(res);
m_lasttime = SDL_GetTicks();
for (int i = 0; i < static_cast<int>(Game::EntityManager.SceneEntities.size()); i++)
{
Entity *temp = Game::EntityManager.SceneEntities[i]->object;
if (temp != nullptr && temp->getComponent<Cactus>() != nullptr)
{
if (temp->transform->GetScreenPosition().X < -16)
{
Game::EntityManager.RemoveID(temp->ID);
}
}
}
}
}
void Render()
{
}
const char *GetName() { return "Generator"; }
}; | 33.4 | 121 | 0.521557 | [
"render",
"object",
"transform"
] |
3ad30c34b7ba3ef4c537f7355b07d81ee19da7d6 | 6,724 | cpp | C++ | gui/ctrl/look/drop_down.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null | gui/ctrl/look/drop_down.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null | gui/ctrl/look/drop_down.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null | /**
* @copyright (c) 2016-2021 Ing. Buero Rothfuss
* Riedlinger Str. 8
* 70327 Stuttgart
* Germany
* http://www.rothfuss-web.de
*
* @author <a href="mailto:armin@rothfuss-web.de">Armin Rothfuss</a>
*
* Project gui++ lib
*
* @brief drop down list look
*
* @license MIT license. See accompanying file LICENSE.
*/
// --------------------------------------------------------------------------
//
// Library includes
//
#include <gui/core/color.h>
#include <gui/draw/graphics.h>
#include <gui/draw/drawers.h>
#include <gui/draw/frames.h>
#include <gui/draw/brush.h>
#include <gui/draw/pen.h>
#include <gui/draw/font.h>
#include <gui/ctrl/look/control.h>
#include <gui/ctrl/look/button.h>
#include <gui/ctrl/look/drop_down.h>
#include <gui/io/pnm.h>
namespace gui {
namespace image_data {
# include <gui/ctrl/look/res/osx_dropdown_button.h>
# include <gui/ctrl/look/res/osx_dropdown_disabled_button.h>
} // namespace image_data
namespace detail {
template<typename T, size_t N>
inline std::string make_string (T(&t)[N]) {
return std::string((const char*)t, N);
}
draw::rgbmap build_rgb_image (const std::string& data);
draw::graymap build_gray_image (const std::string& data);
template<typename T>
T upscale (const T& img);
const draw::rgbmap& get_osx_dropdown_button (bool enabled) {
static draw::rgbmap img = upscale(build_rgb_image(make_string(image_data::osx_dropdown_button)));
static draw::rgbmap dis = upscale(build_gray_image(make_string(image_data::osx_dropdown_disabled_button)).convert<pixel_format_t::RGB>());
return enabled ? img : dis;
}
}
namespace look {
void drop_down_item (draw::graphics& g,
const core::rectangle& r,
const draw::brush& b,
const std::string& t,
const ctrl::item_state& s) {
text_item(g, r, b, t, s, text_origin_t::vcenter_left);
}
std::vector<core::point> get_up_down_polygon (const core::rectangle& area, bool up) {
core::rectangle r = area.shrinked(area.size() / 3);
if (!r.empty()) {
if (up) {
return {r.x2y2(), {r.center_x(), r.y()}, r.x1y2()};
} else {
return {r.top_left(), {r.center_x(), r.y2()}, r.x2y1()};
}
}
return {};
}
template<>
void drop_down_button_t<look_and_feel_t::metal> (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state,
bool is_open) {
graph.fill(draw::polygon(get_up_down_polygon(area, is_open)), state.enabled() ? color::black : color::light_gray);
}
template<>
void drop_down_button_t<look_and_feel_t::w95> (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state,
bool is_open) {
look::button_frame_t<look_and_feel_t::w95>(graph, area, state);
graph.fill(draw::polygon(get_up_down_polygon(area, is_open)), state.enabled() ? color::black : color::light_gray);
}
template<>
void drop_down_button_t<look_and_feel_t::w10> (draw::graphics& graph,
const core::rectangle& r,
const core::button_state::is& state,
bool is_open) {
graph.frame(draw::polyline(get_up_down_polygon(r, is_open)), state.enabled() ? color::black : color::light_gray);
}
template<>
void drop_down_button_t<look_and_feel_t::osx> (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state,
bool) {
const auto& img = detail::get_osx_dropdown_button(state.enabled());
graph.fill(draw::image<decltype(img)>(img, area, text_origin_t::vcenter_right), color::buttonColor());
}
void drop_down_button (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state,
bool is_open) {
drop_down_button_t<>(graph, area, state, is_open);
}
template<>
void drop_down_t<look_and_feel_t::metal> (draw::graphics& graph,
const core::rectangle& r,
const core::button_state::is& state) {
button_frame_t<look_and_feel_t::metal>(graph, r, state);
}
template<>
void drop_down_t<look_and_feel_t::w95> (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state) {
draw::frame::sunken_deep_relief(graph, area);
if (state.focused()) {
draw::frame::dots(graph, area);
}
}
template<>
void drop_down_t<look_and_feel_t::w10> (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state) {
button_frame_t<look_and_feel_t::w10>(graph, area, state);
}
void drop_down_frame (draw::graphics& graph,
const core::rectangle& r,
bool pushed, bool hilite, bool focused) {
if (pushed && hilite) {
graph.copy(draw::frame_image(r, osx::get_pressed_frame(), 4), r.top_left());
} else if (focused) {
graph.copy(draw::frame_image(r, osx::get_focused_frame(), 4), r.top_left());
} else {
graph.copy(draw::frame_image(r, osx::get_frame(), 4), r.top_left());
}
}
template<>
void drop_down_t<look_and_feel_t::osx> (draw::graphics& graph,
const core::rectangle& r,
const core::button_state::is& state) {
drop_down_frame(graph, r, state.pushed(), state.hilited(), state.focused());
}
void drop_down (draw::graphics& graph,
const core::rectangle& area,
const core::button_state::is& state) {
drop_down_t<>(graph, area, state);
}
} // look
} // gui
| 37.775281 | 144 | 0.524836 | [
"vector"
] |
3ad8bf99c3e5b4a8132b1b041c9e90f196c3fbde | 5,686 | cpp | C++ | Chapter16/sd/sd.cpp | fengjixuchui/Win10SysProgBookSamples | 360aff30a19da2ea4c9be6f41c481aa8bf39a2b0 | [
"MIT"
] | 249 | 2019-07-09T17:14:43.000Z | 2022-03-28T01:54:26.000Z | Chapter16/sd/sd.cpp | fengjixuchui/Win10SysProgBookSamples | 360aff30a19da2ea4c9be6f41c481aa8bf39a2b0 | [
"MIT"
] | 8 | 2019-07-12T21:08:29.000Z | 2022-01-04T12:32:00.000Z | Chapter16/sd/sd.cpp | isabella232/Win10SysProgBookSamples | 97e479a9a4923ecf94866bae516a76bde02ef71e | [
"MIT"
] | 70 | 2019-07-10T02:14:55.000Z | 2022-03-08T00:53:07.000Z | // sd.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <stdio.h>
#include <sddl.h>
#include <string>
#include <AclAPI.h>
std::wstring SidToString(const PSID sid) {
PWSTR ssid;
std::wstring result;
if (::ConvertSidToStringSid(sid, &ssid)) {
result = ssid;
::LocalFree(ssid);
}
return result;
}
std::wstring GetUserNameFromSid(const PSID sid, SID_NAME_USE* puse = nullptr) {
WCHAR name[64], domain[64];
DWORD lname = _countof(name), ldomain = _countof(domain);
SID_NAME_USE use;
if (::LookupAccountSid(nullptr, sid, name, &lname, domain, &ldomain, &use)) {
if (puse)
*puse = use;
return std::wstring(domain) + L"\\" + name;
}
return L"";
}
std::string SDControlToString(SECURITY_DESCRIPTOR_CONTROL control) {
std::string result;
static const struct {
DWORD flag;
PCSTR text;
} attributes[] = {
{ SE_OWNER_DEFAULTED, "Owner Defaulted" },
{ SE_GROUP_DEFAULTED, "Group Defaulted" },
{ SE_DACL_PRESENT, "DACL Present" },
{ SE_DACL_DEFAULTED, "DACL Defaulted" },
{ SE_SACL_PRESENT, "SACL Present" },
{ SE_SACL_DEFAULTED, "SACL Defaulted" },
{ SE_DACL_AUTO_INHERIT_REQ, "DACL Auto Inherit Required" },
{ SE_SACL_AUTO_INHERIT_REQ, "SACL Auto Inherit Required" },
{ SE_DACL_AUTO_INHERITED, "DACL Auto Inherited" },
{ SE_SACL_AUTO_INHERITED, "SACL Auto Inherited" },
{ SE_DACL_PROTECTED, "DACL Protected" },
{ SE_SACL_PROTECTED, "SACL Protected" },
{ SE_RM_CONTROL_VALID, "RM Control Valid" },
{ SE_SELF_RELATIVE, "Self Relative" },
};
for (const auto& attr : attributes)
if ((attr.flag & control) == attr.flag)
(result += attr.text) += ", ";
if (!result.empty())
result = result.substr(0, result.size() - 2);
else
result = "(none)";
return result;
}
const char* AceTypeToString(BYTE type) {
switch (type) {
case ACCESS_ALLOWED_ACE_TYPE: return "ALLOW";
case ACCESS_DENIED_ACE_TYPE: return "DENY";
case ACCESS_ALLOWED_CALLBACK_ACE_TYPE: return "ALLOW CALLBACK";
case ACCESS_DENIED_CALLBACK_ACE_TYPE: return "DENY CALLBACK";
case ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: return "ALLOW CALLBACK OBJECT";
case ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: return "DENY CALLBACK OBJECT";
}
return "<unknown>";
}
void DisplayAce(PACE_HEADER header, int index) {
printf("ACE %2d: Size: %2d bytes, Flags: 0x%02X Type: %s\n",
index, header->AceSize, header->AceFlags, AceTypeToString(header->AceType));
switch (header->AceType) {
case ACCESS_ALLOWED_ACE_TYPE:
case ACCESS_DENIED_ACE_TYPE: // have the same binary layout
{
auto data = (ACCESS_ALLOWED_ACE*)header;
printf("\tAccess: 0x%08X %ws (%ws)\n", data->Mask,
GetUserNameFromSid((PSID)&data->SidStart).c_str(), SidToString((PSID)&data->SidStart).c_str());
}
break;
}
}
void DisplaySD(const PSECURITY_DESCRIPTOR sd) {
auto len = ::GetSecurityDescriptorLength(sd);
printf("SD Length: %u bytes\n", len);
PWSTR sddl;
if (::ConvertSecurityDescriptorToStringSecurityDescriptor(sd, SDDL_REVISION_1,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&sddl, nullptr) && sddl) {
printf("SD: %ws\n", sddl);
::LocalFree(sddl);
}
SECURITY_DESCRIPTOR_CONTROL control;
DWORD revision;
if (::GetSecurityDescriptorControl(sd, &control, &revision)) {
printf("Control: %s\n", SDControlToString(control).c_str());
}
PSID sid;
BOOL defaulted;
if (::GetSecurityDescriptorOwner(sd, &sid, &defaulted)) {
if (sid)
printf("Owner: %ws (%ws)\n", GetUserNameFromSid(sid).c_str(), SidToString(sid).c_str());
else
printf("No owner\n");
}
BOOL present;
PACL dacl;
if (::GetSecurityDescriptorDacl(sd, &present, &dacl, &defaulted)) {
if (!present)
printf("NULL DACL - object is unprotected\n");
else {
printf("DACL: ACE count: %d\n", (int)dacl->AceCount);
PACE_HEADER header;
for (int i = 0; i < dacl->AceCount; i++) {
::GetAce(dacl, i, (PVOID*)&header);
DisplayAce(header, i);
}
}
}
}
int wmain(int argc, const wchar_t* argv[]) {
if (argc < 2) {
printf("Usage: sd [[-p <pid>] | [-t <tid>] | [-f <filename>] | [-k <regkey>] | [objectname]]\n");
printf("If no arguments specified, shows the current process security descriptor\n");
}
bool thisProcess = argc == 1;
HANDLE hObject = argc == 1 ? ::GetCurrentProcess() : nullptr;
SE_OBJECT_TYPE type = SE_UNKNOWN_OBJECT_TYPE;
PCWSTR name = nullptr;
if(argc > 2) {
name = argv[2];
if (::_wcsicmp(argv[1], L"-p") == 0)
hObject = ::OpenProcess(READ_CONTROL, FALSE, _wtoi(argv[2]));
else if (::_wcsicmp(argv[1], L"-t") == 0)
hObject = ::OpenThread(READ_CONTROL, FALSE, _wtoi(argv[2]));
else if (::_wcsicmp(argv[1], L"-f") == 0)
type = SE_FILE_OBJECT;
else if (::_wcsicmp(argv[1], L"-k") == 0)
type = SE_REGISTRY_KEY;
}
else if (argc == 2) {
name = argv[1];
type = SE_KERNEL_OBJECT;
}
if (!hObject && type == SE_UNKNOWN_OBJECT_TYPE) {
printf("Error: %u\n", ::GetLastError());
return 1;
}
PSECURITY_DESCRIPTOR sd = nullptr;
BYTE buffer[1 << 12];
DWORD error = 0;
if (!hObject) {
error = ::GetNamedSecurityInfo(name, type, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
nullptr, nullptr, nullptr, nullptr, &sd);
if(error == ERROR_SUCCESS) {
DisplaySD(sd);
::LocalFree(sd);
}
}
else {
DWORD len;
auto success = ::GetKernelObjectSecurity(hObject,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSECURITY_DESCRIPTOR)buffer, sizeof(buffer), &len);
if (success)
DisplaySD((PSECURITY_DESCRIPTOR)buffer);
else
error = ::GetLastError();
}
if(error)
printf("Error getting Security Descriptor (%u)\n", error);
if (hObject && !thisProcess)
::CloseHandle(hObject);
return 0;
}
| 29.158974 | 100 | 0.682378 | [
"object"
] |
3adaabd3f425129c4d247c66398f963c0933aa59 | 10,746 | cpp | C++ | be/src/exec/vectorized/hdfs_scanner.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | 1 | 2022-03-08T09:13:32.000Z | 2022-03-08T09:13:32.000Z | be/src/exec/vectorized/hdfs_scanner.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | be/src/exec/vectorized/hdfs_scanner.cpp | stephen-shelby/starrocks | 67932670efddbc8c56e2aaf5d3758724dcb44b0a | [
"Zlib",
"PSF-2.0",
"BSD-2-Clause",
"Apache-2.0",
"ECL-2.0",
"BSD-3-Clause-Clear"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "exec/vectorized/hdfs_scanner.h"
#include "column/column_helper.h"
#include "exec/exec_node.h"
namespace starrocks::vectorized {
Status HdfsScanner::init(RuntimeState* runtime_state, const HdfsScannerParams& scanner_params) {
_runtime_state = runtime_state;
_scanner_params = scanner_params;
// which columsn do we need to scan.
for (const auto& slot : _scanner_params.materialize_slots) {
_scanner_columns.emplace_back(slot->col_name());
}
// general conjuncts.
RETURN_IF_ERROR(Expr::clone_if_not_exists(_scanner_params.conjunct_ctxs, runtime_state, &_conjunct_ctxs));
// slot id conjuncts.
const auto& conjunct_ctxs_by_slot = _scanner_params.conjunct_ctxs_by_slot;
if (!conjunct_ctxs_by_slot.empty()) {
for (auto iter = conjunct_ctxs_by_slot.begin(); iter != conjunct_ctxs_by_slot.end(); ++iter) {
SlotId slot_id = iter->first;
_conjunct_ctxs_by_slot.insert({slot_id, std::vector<ExprContext*>()});
RETURN_IF_ERROR(Expr::clone_if_not_exists(iter->second, runtime_state, &_conjunct_ctxs_by_slot[slot_id]));
}
}
// min/max conjuncts.
RETURN_IF_ERROR(
Expr::clone_if_not_exists(_scanner_params.min_max_conjunct_ctxs, runtime_state, &_min_max_conjunct_ctxs));
Status status = do_init(runtime_state, scanner_params);
return status;
}
Status HdfsScanner::_build_scanner_context() {
HdfsScannerContext& ctx = _scanner_ctx;
std::vector<ColumnPtr>& partition_values = ctx.partition_values;
// evaluate partition values.
for (size_t i = 0; i < _scanner_params.partition_slots.size(); i++) {
int part_col_idx = _scanner_params._partition_index_in_hdfs_partition_columns[i];
ASSIGN_OR_RETURN(auto partition_value_column,
_scanner_params.partition_values[part_col_idx]->evaluate(nullptr));
DCHECK(partition_value_column->is_constant());
partition_values.emplace_back(std::move(partition_value_column));
}
// build columns of materialized and partition.
for (size_t i = 0; i < _scanner_params.materialize_slots.size(); i++) {
auto* slot = _scanner_params.materialize_slots[i];
HdfsScannerContext::ColumnInfo column;
column.slot_desc = slot;
column.col_idx = _scanner_params.materialize_index_in_chunk[i];
column.col_type = slot->type();
column.slot_id = slot->id();
column.col_name = slot->col_name();
ctx.materialized_columns.emplace_back(std::move(column));
}
for (size_t i = 0; i < _scanner_params.partition_slots.size(); i++) {
auto* slot = _scanner_params.partition_slots[i];
HdfsScannerContext::ColumnInfo column;
column.slot_desc = slot;
column.col_idx = _scanner_params.partition_index_in_chunk[i];
column.col_type = slot->type();
column.slot_id = slot->id();
column.col_name = slot->col_name();
ctx.partition_columns.emplace_back(std::move(column));
}
ctx.tuple_desc = _scanner_params.tuple_desc;
ctx.conjunct_ctxs_by_slot = _conjunct_ctxs_by_slot;
ctx.scan_ranges = _scanner_params.scan_ranges;
ctx.min_max_conjunct_ctxs = _min_max_conjunct_ctxs;
ctx.min_max_tuple_desc = _scanner_params.min_max_tuple_desc;
ctx.timezone = _runtime_state->timezone();
ctx.stats = &_stats;
return Status::OK();
}
Status HdfsScanner::get_next(RuntimeState* runtime_state, ChunkPtr* chunk) {
RETURN_IF_CANCELLED(_runtime_state);
SCOPED_RAW_TIMER(&_stats.scan_ns);
Status status = do_get_next(runtime_state, chunk);
if (status.ok()) {
if (!_conjunct_ctxs.empty()) {
SCOPED_RAW_TIMER(&_stats.expr_filter_ns);
RETURN_IF_ERROR(ExecNode::eval_conjuncts(_conjunct_ctxs, (*chunk).get()));
}
} else if (status.is_end_of_file()) {
// do nothing.
} else {
LOG(ERROR) << "failed to read file: " << _scanner_params.path;
}
_stats.num_rows_read += (*chunk)->num_rows();
return status;
}
Status HdfsScanner::open(RuntimeState* runtime_state) {
if (_is_open) {
return Status::OK();
}
CHECK(_file == nullptr) << "File has already been opened";
ASSIGN_OR_RETURN(_file, _scanner_params.fs->new_random_access_file(_scanner_params.path));
_build_scanner_context();
auto status = do_open(runtime_state);
if (status.ok()) {
_is_open = true;
if (_scanner_params.open_limit != nullptr) {
_scanner_params.open_limit->fetch_add(1, std::memory_order_relaxed);
}
LOG(INFO) << "open file success: " << _scanner_params.path;
}
return status;
}
void HdfsScanner::close(RuntimeState* runtime_state) noexcept {
DCHECK(!has_pending_token());
if (_is_closed) {
return;
}
update_counter();
Expr::close(_conjunct_ctxs, runtime_state);
Expr::close(_min_max_conjunct_ctxs, runtime_state);
for (auto& it : _conjunct_ctxs_by_slot) {
Expr::close(it.second, runtime_state);
}
do_close(runtime_state);
_file.reset(nullptr);
_is_closed = true;
if (_is_open && _scanner_params.open_limit != nullptr) {
_scanner_params.open_limit->fetch_sub(1, std::memory_order_relaxed);
}
}
void HdfsScanner::cleanup() {
if (_runtime_state != nullptr) {
close(_runtime_state);
}
}
void HdfsScanner::enter_pending_queue() {
_pending_queue_sw.start();
}
uint64_t HdfsScanner::exit_pending_queue() {
return _pending_queue_sw.reset();
}
void HdfsScanner::update_hdfs_counter(HdfsScanProfile* profile) {
static const char* const kHdfsIOProfileSectionPrefix = "HdfsIO";
if (_file == nullptr) return;
auto res = _file->get_numeric_statistics();
if (!res.ok()) return;
std::unique_ptr<io::NumericStatistics> statistics = std::move(res).value();
if (statistics == nullptr || statistics->size() == 0) return;
RuntimeProfile* runtime_profile = profile->runtime_profile;
ADD_TIMER(runtime_profile, kHdfsIOProfileSectionPrefix);
for (int64_t i = 0, sz = statistics->size(); i < sz; i++) {
auto&& name = statistics->name(i);
auto&& counter = ADD_CHILD_COUNTER(runtime_profile, name, TUnit::UNIT, kHdfsIOProfileSectionPrefix);
COUNTER_UPDATE(counter, statistics->value(i));
}
}
void HdfsScanner::do_update_counter(HdfsScanProfile* profile) {}
void HdfsScanner::update_counter() {
HdfsScanProfile* profile = _scanner_params.profile;
if (profile == nullptr) return;
update_hdfs_counter(profile);
COUNTER_UPDATE(profile->scan_timer, _stats.scan_ns);
COUNTER_UPDATE(profile->reader_init_timer, _stats.reader_init_ns);
COUNTER_UPDATE(profile->rows_read_counter, _stats.raw_rows_read);
COUNTER_UPDATE(profile->bytes_read_counter, _stats.bytes_read);
COUNTER_UPDATE(profile->expr_filter_timer, _stats.expr_filter_ns);
COUNTER_UPDATE(profile->io_timer, _stats.io_ns);
COUNTER_UPDATE(profile->io_counter, _stats.io_count);
COUNTER_UPDATE(profile->column_read_timer, _stats.column_read_ns);
COUNTER_UPDATE(profile->column_convert_timer, _stats.column_convert_ns);
// update scanner private profile.
do_update_counter(profile);
}
void HdfsScannerContext::set_columns_from_file(const std::unordered_set<std::string>& names) {
for (auto& column : materialized_columns) {
if (names.find(column.col_name) == names.end()) {
not_existed_slots.push_back(column.slot_desc);
SlotId slot_id = column.slot_id;
if (conjunct_ctxs_by_slot.find(slot_id) != conjunct_ctxs_by_slot.end()) {
for (ExprContext* ctx : conjunct_ctxs_by_slot[slot_id]) {
conjunct_ctxs_of_non_existed_slots.emplace_back(ctx);
}
conjunct_ctxs_by_slot.erase(slot_id);
}
}
}
}
void HdfsScannerContext::append_not_exised_columns_to_chunk(vectorized::ChunkPtr* chunk, size_t row_count) {
if (not_existed_slots.size() == 0) return;
ChunkPtr& ck = (*chunk);
ck->set_num_rows(row_count);
for (auto* slot_desc : not_existed_slots) {
auto col = ColumnHelper::create_column(slot_desc->type(), slot_desc->is_nullable());
if (row_count > 0) {
col->append_default(row_count);
}
ck->append_column(std::move(col), slot_desc->id());
}
}
StatusOr<bool> HdfsScannerContext::should_skip_by_evaluating_not_existed_slots() {
if (not_existed_slots.size() == 0) return false;
// build chunk for evaluation.
ChunkPtr chunk = std::make_shared<Chunk>();
append_not_exised_columns_to_chunk(&chunk, 1);
// do evaluation.
{
SCOPED_RAW_TIMER(&stats->expr_filter_ns);
RETURN_IF_ERROR(ExecNode::eval_conjuncts(conjunct_ctxs_of_non_existed_slots, chunk.get()));
}
return !(chunk->has_rows());
}
void HdfsScannerContext::append_partition_column_to_chunk(vectorized::ChunkPtr* chunk, size_t row_count) {
if (partition_columns.size() == 0) return;
ChunkPtr& ck = (*chunk);
ck->set_num_rows(row_count);
for (size_t i = 0; i < partition_columns.size(); i++) {
SlotDescriptor* slot_desc = partition_columns[i].slot_desc;
DCHECK(partition_values[i]->is_constant());
auto* const_column = vectorized::ColumnHelper::as_raw_column<vectorized::ConstColumn>(partition_values[i]);
ColumnPtr data_column = const_column->data_column();
auto chunk_part_column = ColumnHelper::create_column(slot_desc->type(), slot_desc->is_nullable());
if (row_count > 0) {
if (data_column->is_nullable()) {
chunk_part_column->append_nulls(1);
} else {
chunk_part_column->append(*data_column, 0, 1);
}
chunk_part_column->assign(row_count, 0);
}
ck->append_column(std::move(chunk_part_column), slot_desc->id());
}
}
bool HdfsScannerContext::can_use_dict_filter_on_slot(SlotDescriptor* slot) const {
if (!slot->type().is_string_type()) {
return false;
}
SlotId slot_id = slot->id();
if (conjunct_ctxs_by_slot.find(slot_id) == conjunct_ctxs_by_slot.end()) {
return false;
}
for (ExprContext* ctx : conjunct_ctxs_by_slot.at(slot_id)) {
const Expr* root_expr = ctx->root();
if (root_expr->node_type() == TExprNodeType::FUNCTION_CALL) {
std::string is_null_str;
if (root_expr->is_null_scalar_function(is_null_str)) {
return false;
}
}
}
return true;
}
} // namespace starrocks::vectorized
| 37.055172 | 118 | 0.682207 | [
"vector"
] |
3ae79ce8ce3459d383fd0223c98ca4689fbbba72 | 13,570 | cc | C++ | src/components/application_manager/test/mobile_message_handler_test.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | 249 | 2015-01-15T16:50:53.000Z | 2022-03-24T13:23:34.000Z | src/components/application_manager/test/mobile_message_handler_test.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | 2,917 | 2015-01-12T16:17:49.000Z | 2022-03-31T11:57:47.000Z | src/components/application_manager/test/mobile_message_handler_test.cc | russjohnson09/sdl_core | 9de7f1456f1807ae97348f774f7eead0ee92fd6d | [
"BSD-3-Clause"
] | 306 | 2015-01-12T09:23:20.000Z | 2022-01-28T18:06:30.000Z | /*
* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/mobile_message_handler.h"
#include <algorithm>
#include <ctime>
#include <iterator>
#include <string>
#include <vector>
#include "application_manager/message.h"
#include "gmock/gmock.h"
#include "protocol/raw_message.h"
namespace test {
namespace components {
namespace application_manager_test {
using ::application_manager::Message;
using ::application_manager::MobileMessage;
using application_manager::MobileMessageHandler;
using protocol_handler::MajorProtocolVersion;
using protocol_handler::MessagePriority;
using protocol_handler::PROTOCOL_HEADER_V2_SIZE;
using protocol_handler::RawMessage;
using protocol_handler::RawMessagePtr;
using protocol_handler::ServiceType;
using ::testing::_;
using testing::Return;
namespace {
const unsigned char kJjson_size = 0x5e;
const unsigned char kCorrelation_id = 0x5c;
unsigned char binary_header[PROTOCOL_HEADER_V2_SIZE] = {0x20,
0x00,
0x00,
0xf7,
0x00,
0x00,
0x00,
kCorrelation_id,
0x00,
0x00,
0x00,
kJjson_size};
std::string data(
"{\n \"audioStreamingState\" : \"AUDIBLE\",\n \"hmiLevel\" : "
"\"FULL\",\n \"systemContext\" : \"MAIN\"\n}\n");
} // namespace
template <class T, class T2, class T3>
T joiner(T2 begin, T2 end, const T3& data) {
T cont(begin, end);
std::copy(data.begin(), data.end(), std::back_inserter(cont));
return cont;
}
class MobileMessageHandlerTest : public testing::Test {
public:
MobileMessageHandlerTest() : connection_key_(1) {}
protected:
RawMessagePtr message_ptr_;
const uint32_t connection_key_;
Message* HandleIncomingMessage(const uint32_t protocol_version,
const std::string data,
const uint32_t payload_size) {
std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
size_t full_size = sizeof(uint8_t) * full_data.size();
message_ptr_ = std::make_shared<RawMessage>(connection_key_,
protocol_version,
&full_data[0],
full_size,
false,
ServiceType::kRpc,
payload_size);
return MobileMessageHandler::HandleIncomingMessageProtocol(message_ptr_);
}
void TestHandlingIncomingMessageWithBinaryDataProtocol(
int32_t protocol_version) {
// Arrange
// Add binary data to json message
std::string binary_data("\a\a\a\a");
std::string json_plus_binary_data =
joiner<std::string>(data.begin(), data.end(), binary_data);
size_t full_data_size = json_plus_binary_data.size() * sizeof(uint8_t) +
PROTOCOL_HEADER_V2_SIZE;
// Act
size_t payload_size = data.size();
Message* message = HandleIncomingMessage(
protocol_version, json_plus_binary_data, payload_size);
// Checks
EXPECT_EQ(data, message->json_message());
EXPECT_EQ(1, message->connection_key());
EXPECT_EQ(247, message->function_id());
EXPECT_EQ(protocol_version, message->protocol_version());
EXPECT_EQ(0x5c, message->correlation_id());
EXPECT_EQ(full_data_size, message->data_size());
EXPECT_EQ(payload_size, message->payload_size());
EXPECT_TRUE(message->has_binary_data());
EXPECT_EQ(application_manager::MessageType::kNotification, message->type());
}
void TestHandlingIncomingMessageWithoutBinaryDataProtocol(
uint32_t protocol_version) {
// Arrange
size_t payload_size = data.size();
size_t full_data_size = data.size() + PROTOCOL_HEADER_V2_SIZE;
Message* message =
HandleIncomingMessage(protocol_version, data, payload_size);
// Checks
EXPECT_EQ(data, message->json_message());
EXPECT_EQ(1, message->connection_key());
EXPECT_EQ(247, message->function_id());
EXPECT_EQ(protocol_version, (uint32_t)message->protocol_version());
EXPECT_EQ(0x5c, message->correlation_id());
EXPECT_EQ(full_data_size, message->data_size());
EXPECT_EQ(payload_size, message->payload_size());
EXPECT_FALSE(message->has_binary_data());
EXPECT_EQ(application_manager::MessageType::kNotification, message->type());
}
MobileMessage CreateMessageForSending(
uint32_t protocol_version,
uint32_t function_id,
uint32_t correlation_id,
uint32_t connection_key,
const std::string& json_msg,
const application_manager::BinaryData* data = NULL) {
MobileMessage message = std::make_shared<Message>(
MessagePriority::FromServiceType(ServiceType::kRpc));
message->set_function_id(function_id);
message->set_correlation_id(correlation_id);
message->set_connection_key(connection_key);
message->set_protocol_version(
static_cast<protocol_handler::MajorProtocolVersion>(protocol_version));
message->set_message_type(application_manager::MessageType::kNotification);
if (data) {
message->set_binary_data(data);
}
if (!json_msg.empty()) {
message->set_json_message(json_msg);
}
return message;
}
void TestHandlingOutgoingMessageProtocolWithoutBinaryData(
const uint32_t protocol_version) {
// Arrange
const uint32_t function_id = 247u;
const uint32_t correlation_id = 92u;
const uint32_t connection_key = 1u;
MobileMessage message_to_send = CreateMessageForSending(
protocol_version, function_id, correlation_id, connection_key, data);
// Act
RawMessage* result_message =
MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
size_t full_size = sizeof(uint8_t) * full_data.size();
// Checks
EXPECT_EQ(protocol_version, result_message->protocol_version());
EXPECT_EQ(connection_key, result_message->connection_key());
EXPECT_EQ(full_size, result_message->data_size());
for (uint8_t i = 0; i < full_data.size(); ++i) {
EXPECT_EQ(full_data[i], result_message->data()[i]);
}
EXPECT_EQ(ServiceType::kRpc, result_message->service_type());
}
void TestHandlingOutgoingMessageProtocolWithBinaryData(
const uint32_t protocol_version) {
// Arrange
application_manager::BinaryData* bin_dat =
new application_manager::BinaryData;
bin_dat->push_back('\a');
const uint32_t function_id = 247u;
const uint32_t correlation_id = 92u;
const uint32_t connection_key = 1u;
MobileMessage message_to_send = CreateMessageForSending(protocol_version,
function_id,
correlation_id,
connection_key,
data,
bin_dat);
// Act
RawMessage* result_message =
MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
size_t full_size =
sizeof(uint8_t) * full_data.size() + bin_dat->size() * sizeof(uint8_t);
// Checks
EXPECT_EQ(protocol_version, result_message->protocol_version());
EXPECT_EQ(connection_key, result_message->connection_key());
EXPECT_EQ(full_size, result_message->data_size());
for (uint8_t i = 0; i < full_data.size(); ++i) {
EXPECT_EQ(full_data[i], result_message->data()[i]);
}
EXPECT_EQ(0x0F, result_message->service_type());
}
};
TEST(mobile_message_test, basic_test) {
// Example message
MobileMessage message =
std::make_shared<Message>(protocol_handler::MessagePriority::kDefault);
EXPECT_FALSE(message->has_binary_data());
application_manager::BinaryData binary_data;
binary_data.push_back('X');
message->set_binary_data(
(const application_manager::BinaryData*)&binary_data);
EXPECT_TRUE(message->has_binary_data());
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleIncomingMessageProtocol_MessageWithUnknownProtocolVersion_ExpectNull) {
// Arrange
size_t payload_size = data.size();
std::srand(time(0));
// Generate unknown random protocol version except 1-3
uint32_t protocol_version = 5 + rand() % UINT32_MAX;
Message* message =
HandleIncomingMessage(protocol_version, data, payload_size);
// Checks
EXPECT_EQ(NULL, message);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleOutgoingMessageProtocol_MessageWithUnknownProtocolVersion_ExpectNull) {
// Arrange
std::srand(time(0));
const uint32_t function_id = 247u;
const uint32_t correlation_id = 92u;
const uint32_t connection_key = 1u;
// Generate unknown random protocol version except 1-3
uint32_t protocol_version = 5 + rand() % UINT32_MAX;
MobileMessage message_to_send = CreateMessageForSending(
protocol_version, function_id, correlation_id, connection_key, data);
// Act
RawMessage* result_message =
MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
// Check
EXPECT_EQ(NULL, result_message);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleIncomingMessageProtocol_MessageWithProtocolV2_WithoutBinaryData) {
const uint32_t protocol_version = 2u;
TestHandlingIncomingMessageWithoutBinaryDataProtocol(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleIncomingMessageProtocol_MessageWithProtocolV3_WithoutBinaryData) {
const uint32_t protocol_version = 3u;
TestHandlingIncomingMessageWithoutBinaryDataProtocol(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleIncomingMessageProtocol_MessageWithProtocolV2_WithBinaryData) {
const uint32_t protocol_version = 2u;
TestHandlingIncomingMessageWithBinaryDataProtocol(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleIncomingMessageProtocol_MessageWithProtocolV3_WithBinaryData) {
const uint32_t protocol_version = 3u;
TestHandlingIncomingMessageWithBinaryDataProtocol(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleOutgoingMessageProtocol_MessageWithProtocolV2_WithoutBinaryData) {
const uint32_t protocol_version = 2u;
TestHandlingOutgoingMessageProtocolWithoutBinaryData(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleOutgoingMessageProtocol_MessageWithProtocolV3_WithoutBinaryData) {
const uint32_t protocol_version = 3u;
TestHandlingOutgoingMessageProtocolWithoutBinaryData(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleOutgoingMessageProtocol_MessageWithProtocolV2_WithBinaryData) {
const uint32_t protocol_version = 2u;
TestHandlingOutgoingMessageProtocolWithBinaryData(protocol_version);
}
TEST_F(
MobileMessageHandlerTest,
Test_HandleOutgoingMessageProtocol_MessageWithProtocolV3_WithBinaryData) {
const uint32_t protocol_version = 3u;
TestHandlingOutgoingMessageProtocolWithBinaryData(protocol_version);
}
} // namespace application_manager_test
} // namespace components
} // namespace test
| 37.486188 | 86 | 0.687325 | [
"vector"
] |
3aee887abd0de589319ee03abde24e829d82286a | 46,185 | cpp | C++ | storagehandler.cpp | medadyoung/phosphor-host-ipmid | 8e83f5cfd827ee439217bc72787a7431a6207210 | [
"Apache-2.0"
] | null | null | null | storagehandler.cpp | medadyoung/phosphor-host-ipmid | 8e83f5cfd827ee439217bc72787a7431a6207210 | [
"Apache-2.0"
] | null | null | null | storagehandler.cpp | medadyoung/phosphor-host-ipmid | 8e83f5cfd827ee439217bc72787a7431a6207210 | [
"Apache-2.0"
] | null | null | null | #include "storagehandler.hpp"
#include "fruread.hpp"
#include "read_fru_data.hpp"
#include "selutility.hpp"
#include "sensorhandler.hpp"
#include "storageaddsel.hpp"
#include <arpa/inet.h>
#include <mapper.h>
#include <systemd/sd-bus.h>
#include <algorithm>
#include <boost/beast/core/span.hpp>
#include <boost/process.hpp>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <ipmid/api.hpp>
#include <ipmid/utils.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/server.hpp>
#include <sdrutils.hpp>
#include <string>
#include <string_view>
#include <variant>
#include <xyz/openbmc_project/Common/error.hpp>
void register_netfn_storage_functions() __attribute__((constructor));
unsigned int g_sel_time = 0xFFFFFFFF;
namespace ipmi
{
namespace sensor
{
extern const IdInfoMap sensors;
} // namespace sensor
} // namespace ipmi
extern const FruMap frus;
constexpr uint8_t eventDataSize = 3;
namespace
{
constexpr auto TIME_INTERFACE = "xyz.openbmc_project.Time.EpochTime";
constexpr auto BMC_TIME_PATH = "/xyz/openbmc_project/time/bmc";
constexpr auto DBUS_PROPERTIES = "org.freedesktop.DBus.Properties";
constexpr auto PROPERTY_ELAPSED = "Elapsed";
} // namespace
#ifndef JOURNAL_SEL
namespace cache
{
/*
* This cache contains the object paths of the logging entries sorted in the
* order of the filename(numeric order). The cache is initialized by
* invoking readLoggingObjectPaths with the cache as the parameter. The
* cache is invoked in the execution of the Get SEL info and Delete SEL
* entry command. The Get SEL Info command is typically invoked before the
* Get SEL entry command, so the cache is utilized for responding to Get SEL
* entry command. The cache is invalidated by clearing after Delete SEL
* entry and Clear SEL command.
*/
ipmi::sel::ObjectPaths paths;
} // namespace cache
#endif
using InternalFailure =
sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
using namespace phosphor::logging;
using namespace ipmi::fru;
/**
* @enum Device access mode
*/
enum class AccessMode
{
bytes, ///< Device is accessed by bytes
words ///< Device is accessed by words
};
#ifdef JOURNAL_SEL
namespace ipmi::sel::erase_time
{
static constexpr const char* selEraseTimestamp = "/var/lib/ipmi/sel_erase_time";
void save()
{
// open the file, creating it if necessary
int fd = open(selEraseTimestamp, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
if (fd < 0)
{
std::cerr << "Failed to open file\n";
return;
}
// update the file timestamp to the current time
if (futimens(fd, NULL) < 0)
{
std::cerr << "Failed to update timestamp: "
<< std::string(strerror(errno));
}
close(fd);
}
int get()
{
struct stat st;
// default to an invalid timestamp
int timestamp = ::ipmi::sel::invalidTimeStamp;
int fd = open(selEraseTimestamp, O_RDWR | O_CLOEXEC, 0644);
if (fd < 0)
{
return timestamp;
}
if (fstat(fd, &st) >= 0)
{
timestamp = st.st_mtime;
}
return timestamp;
}
} // namespace ipmi::sel::erase_time
static int fromHexStr(const std::string hexStr, std::vector<uint8_t>& data)
{
for (unsigned int i = 0; i < hexStr.size(); i += 2)
{
try
{
data.push_back(static_cast<uint8_t>(
std::stoul(hexStr.substr(i, 2), nullptr, 16)));
}
catch (std::invalid_argument& e)
{
phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
return -1;
}
catch (std::out_of_range& e)
{
phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
return -1;
}
}
return 0;
}
static const std::filesystem::path selLogDir = "/var/log";
static const std::string selLogFilename = "ipmi_sel";
static bool getSELLogFiles(std::vector<std::filesystem::path>& selLogFiles)
{
// Loop through the directory looking for ipmi_sel log files
for (const std::filesystem::directory_entry& dirEnt :
std::filesystem::directory_iterator(selLogDir))
{
std::string filename = dirEnt.path().filename();
if (boost::starts_with(filename, selLogFilename))
{
// If we find an ipmi_sel log file, save the path
selLogFiles.emplace_back(selLogDir /
filename);
}
}
// As the log files rotate, they are appended with a ".#" that is higher for
// the older logs. Since we don't expect more than 10 log files, we
// can just sort the list to get them in order from newest to oldest
std::sort(selLogFiles.begin(), selLogFiles.end());
return !selLogFiles.empty();
}
static int countSELEntries()
{
// Get the list of ipmi_sel log files
std::vector<std::filesystem::path> selLogFiles;
if (!getSELLogFiles(selLogFiles))
{
return 0;
}
int numSELEntries = 0;
// Loop through each log file and count the number of logs
for (const std::filesystem::path& file : selLogFiles)
{
std::ifstream logStream(file);
if (!logStream.is_open())
{
continue;
}
std::string line;
while (std::getline(logStream, line))
{
numSELEntries++;
}
}
return numSELEntries;
}
static bool findSELEntry(const int recordID,
const std::vector<std::filesystem::path>& selLogFiles,
std::string& entry)
{
// Record ID is the first entry field following the timestamp. It is
// preceded by a space and followed by a comma
std::string search = " " + std::to_string(recordID) + ",";
// Loop through the ipmi_sel log entries
for (const std::filesystem::path& file : selLogFiles)
{
std::ifstream logStream(file);
if (!logStream.is_open())
{
continue;
}
while (std::getline(logStream, entry))
{
// Check if the record ID matches
if (entry.find(search) != std::string::npos)
{
return true;
}
}
}
return false;
}
static uint16_t
getNextRecordID(const uint16_t recordID,
const std::vector<std::filesystem::path>& selLogFiles)
{
uint16_t nextRecordID = recordID + 1;
std::string entry;
if (findSELEntry(nextRecordID, selLogFiles, entry))
{
return nextRecordID;
}
else
{
return ipmi::sel::lastEntry;
}
}
static int getFileTimestamp(const std::filesystem::path& file)
{
struct stat st;
if (stat(file.c_str(), &st) >= 0)
{
return st.st_mtime;
}
return ::ipmi::sel::invalidTimeStamp;
}
using systemEventType = std::tuple<
uint32_t, // Timestamp
uint16_t, // Generator ID
uint8_t, // EvM Rev
uint8_t, // Sensor Type
uint8_t, // Sensor Number
uint7_t, // Event Type
bool, // Event Direction
std::array<uint8_t, ipmi::sel::systemEventSize>>; // Event Data
using oemTsEventType = std::tuple<
uint32_t, // Timestamp
std::array<uint8_t, ipmi::sel::oemTsEventSize>>; // Event Data
using oemEventType =
std::array<uint8_t, ipmi::sel::oemEventSize>; // Event Data
ipmi::RspType<uint16_t, // Next Record ID
uint16_t, // Record ID
uint8_t, // Record Type
std::variant<systemEventType, oemTsEventType,
oemEventType>> // Record Content
ipmiStorageGetSELEntry(uint16_t reservationID, uint16_t targetID,
uint8_t offset, uint8_t size)
{
// Only support getting the entire SEL record. If a partial size or non-zero
// offset is requested, return an error
if (offset != 0 || size != ipmi::sel::entireRecord)
{
return ipmi::responseRetBytesUnavailable();
}
// Check the reservation ID if one is provided or required (only if the
// offset is non-zero)
if (reservationID != 0 || offset != 0)
{
if (!checkSELReservation(reservationID))
{
return ipmi::responseInvalidReservationId();
}
}
// Get the ipmi_sel log files
std::vector<std::filesystem::path> selLogFiles;
if (!getSELLogFiles(selLogFiles))
{
return ipmi::responseSensorInvalid();
}
std::string targetEntry;
if (targetID == ipmi::sel::firstEntry)
{
// The first entry will be at the top of the oldest log file
std::ifstream logStream(selLogFiles.back());
if (!logStream.is_open())
{
return ipmi::responseUnspecifiedError();
}
if (!std::getline(logStream, targetEntry))
{
return ipmi::responseUnspecifiedError();
}
}
else if (targetID == ipmi::sel::lastEntry)
{
// The last entry will be at the bottom of the newest log file
std::ifstream logStream(selLogFiles.front());
if (!logStream.is_open())
{
return ipmi::responseUnspecifiedError();
}
std::string line;
while (std::getline(logStream, line))
{
targetEntry = line;
}
}
else
{
if (!findSELEntry(targetID, selLogFiles, targetEntry))
{
return ipmi::responseSensorInvalid();
}
}
// The format of the ipmi_sel message is "<Timestamp>
// <ID>,<Type>,<EventData>,[<Generator ID>,<Path>,<Direction>]".
// First get the Timestamp
size_t space = targetEntry.find_first_of(" ");
if (space == std::string::npos)
{
return ipmi::responseUnspecifiedError();
}
std::string entryTimestamp = targetEntry.substr(0, space);
// Then get the log contents
size_t entryStart = targetEntry.find_first_not_of(" ", space);
if (entryStart == std::string::npos)
{
return ipmi::responseUnspecifiedError();
}
std::string_view entry(targetEntry);
entry.remove_prefix(entryStart);
// Use split to separate the entry into its fields
std::vector<std::string> targetEntryFields;
boost::split(targetEntryFields, entry, boost::is_any_of(","),
boost::token_compress_on);
if (targetEntryFields.size() < 3)
{
return ipmi::responseUnspecifiedError();
}
std::string& recordIDStr = targetEntryFields[0];
std::string& recordTypeStr = targetEntryFields[1];
std::string& eventDataStr = targetEntryFields[2];
uint16_t recordID;
uint8_t recordType;
try
{
recordID = std::stoul(recordIDStr);
recordType = std::stoul(recordTypeStr, nullptr, 16);
}
catch (const std::invalid_argument&)
{
return ipmi::responseUnspecifiedError();
}
uint16_t nextRecordID = getNextRecordID(recordID, selLogFiles);
std::vector<uint8_t> eventDataBytes;
if (fromHexStr(eventDataStr, eventDataBytes) < 0)
{
return ipmi::responseUnspecifiedError();
}
if (recordType == ipmi::sel::systemEvent)
{
// Get the timestamp
std::tm timeStruct = {};
std::istringstream entryStream(entryTimestamp);
uint32_t timestamp = ipmi::sel::invalidTimeStamp;
if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
{
timestamp = std::mktime(&timeStruct);
}
// Set the event message revision
uint8_t evmRev = ipmi::sel::eventMsgRev;
uint16_t generatorID = 0;
uint8_t sensorType = 0;
uint16_t sensorAndLun = 0;
uint8_t sensorNum = 0xFF;
uint7_t eventType = 0;
bool eventDir = 0;
// System type events should have six fields
if (targetEntryFields.size() >= 6)
{
std::string& generatorIDStr = targetEntryFields[3];
std::string& sensorPath = targetEntryFields[4];
std::string& eventDirStr = targetEntryFields[5];
// Get the generator ID
try
{
generatorID = std::stoul(generatorIDStr, nullptr, 16);
}
catch (const std::invalid_argument&)
{
std::cerr << "Invalid Generator ID\n";
}
// Get the sensor type, sensor number, and event type for the sensor
sensorType = getSensorTypeFromPath(sensorPath);
sensorAndLun = getSensorNumberFromPath(sensorPath);
sensorNum = static_cast<uint8_t>(sensorAndLun);
generatorID |= sensorAndLun >> 8;
eventType = getSensorEventTypeFromPath(sensorPath);
// Get the event direction
try
{
eventDir = std::stoul(eventDirStr) ? 0 : 1;
}
catch (const std::invalid_argument&)
{
std::cerr << "Invalid Event Direction\n";
}
}
// Only keep the eventData bytes that fit in the record
std::array<uint8_t, ipmi::sel::systemEventSize> eventData{};
std::copy_n(eventDataBytes.begin(),
std::min(eventDataBytes.size(), eventData.size()),
eventData.begin());
return ipmi::responseSuccess(
nextRecordID, recordID, recordType,
systemEventType{timestamp, generatorID, evmRev, sensorType,
sensorNum, eventType, eventDir, eventData});
}
else if (recordType >= ipmi::sel::oemTsEventFirst &&
recordType <= ipmi::sel::oemTsEventLast)
{
// Get the timestamp
std::tm timeStruct = {};
std::istringstream entryStream(entryTimestamp);
uint32_t timestamp = ipmi::sel::invalidTimeStamp;
if (entryStream >> std::get_time(&timeStruct, "%Y-%m-%dT%H:%M:%S"))
{
timestamp = std::mktime(&timeStruct);
}
// Only keep the bytes that fit in the record
std::array<uint8_t, ipmi::sel::oemTsEventSize> eventData{};
std::copy_n(eventDataBytes.begin(),
std::min(eventDataBytes.size(), eventData.size()),
eventData.begin());
return ipmi::responseSuccess(nextRecordID, recordID, recordType,
oemTsEventType{timestamp, eventData});
}
else if (recordType >= ipmi::sel::oemEventFirst)
{
// Only keep the bytes that fit in the record
std::array<uint8_t, ipmi::sel::oemEventSize> eventData{};
std::copy_n(eventDataBytes.begin(),
std::min(eventDataBytes.size(), eventData.size()),
eventData.begin());
return ipmi::responseSuccess(nextRecordID, recordID, recordType,
eventData);
}
return ipmi::responseUnspecifiedError();
}
ipmi::RspType<uint8_t> ipmiStorageClearSEL(ipmi::Context::ptr ctx,
uint16_t reservationID,
const std::array<uint8_t, 3>& clr,
uint8_t eraseOperation)
{
if (!checkSELReservation(reservationID))
{
return ipmi::responseInvalidReservationId();
}
static constexpr std::array<uint8_t, 3> clrExpected = {'C', 'L', 'R'};
if (clr != clrExpected)
{
return ipmi::responseInvalidFieldRequest();
}
// Erasure status cannot be fetched, so always return erasure status as
// `erase completed`.
if (eraseOperation == ipmi::sel::getEraseStatus)
{
return ipmi::responseSuccess(ipmi::sel::eraseComplete);
}
// Check that initiate erase is correct
if (eraseOperation != ipmi::sel::initiateErase)
{
return ipmi::responseInvalidFieldRequest();
}
// Per the IPMI spec, need to cancel any reservation when the SEL is
// cleared
cancelSELReservation();
// Save the erase time
ipmi::sel::erase_time::save();
// Clear the SEL by deleting the log files
std::vector<std::filesystem::path> selLogFiles;
if (getSELLogFiles(selLogFiles))
{
for (const std::filesystem::path& file : selLogFiles)
{
std::error_code ec;
std::filesystem::remove(file, ec);
}
}
// Reload rsyslog so it knows to start new log files
std::shared_ptr<sdbusplus::asio::connection> dbus = getSdBus();
sdbusplus::message::message rsyslogReload = dbus->new_method_call(
"org.freedesktop.systemd1", "/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager", "ReloadUnit");
rsyslogReload.append("rsyslog.service", "replace");
try
{
sdbusplus::message::message reloadResponse = dbus->call(rsyslogReload);
}
catch (sdbusplus::exception_t& e)
{
phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
}
return ipmi::responseSuccess(ipmi::sel::eraseComplete);
}
ipmi::RspType<uint8_t, // SEL version
uint16_t, // SEL entry count
uint16_t, // free space
uint32_t, // last add timestamp
uint32_t, // last erase timestamp
uint8_t> // operation support
ipmiStorageGetSelInfo()
{
constexpr uint8_t selVersion = ipmi::sel::selVersion;
uint16_t entries = countSELEntries();
uint32_t addTimeStamp = getFileTimestamp(
selLogDir / selLogFilename);
uint32_t eraseTimeStamp = ipmi::sel::erase_time::get();
constexpr uint8_t operationSupport =
ipmi::sel::selOperationSupport;
constexpr uint16_t freeSpace =
0xffff; // Spec indicates that more than 64kB is free
return ipmi::responseSuccess(selVersion, entries, freeSpace, addTimeStamp,
eraseTimeStamp, operationSupport);
}
#else // JOURNAL_SEL not used
/** @brief implements the get SEL Info command
* @returns IPMI completion code plus response data
* - selVersion - SEL revision
* - entries - Number of log entries in SEL.
* - freeSpace - Free Space in bytes.
* - addTimeStamp - Most recent addition timestamp
* - eraseTimeStamp - Most recent erase timestamp
* - operationSupport - Reserve & Delete SEL operations supported
*/
ipmi::RspType<uint8_t, // SEL revision.
uint16_t, // number of log entries in SEL.
uint16_t, // free Space in bytes.
uint32_t, // most recent addition timestamp
uint32_t, // most recent erase timestamp.
bool, // SEL allocation info supported
bool, // reserve SEL supported
bool, // partial Add SEL Entry supported
bool, // delete SEL supported
uint3_t, // reserved
bool // overflow flag
>
ipmiStorageGetSelInfo()
{
uint16_t entries = 0;
// Most recent addition timestamp.
uint32_t addTimeStamp = ipmi::sel::invalidTimeStamp;
try
{
ipmi::sel::readLoggingObjectPaths(cache::paths);
}
catch (const sdbusplus::exception::SdBusError& e)
{
// No action if reading log objects have failed for this command.
// readLoggingObjectPaths will throw exception if there are no log
// entries. The command will be responded with number of SEL entries
// as 0.
}
if (!cache::paths.empty())
{
entries = static_cast<uint16_t>(cache::paths.size());
try
{
addTimeStamp = static_cast<uint32_t>(
(ipmi::sel::getEntryTimeStamp(cache::paths.back()).count()));
}
catch (InternalFailure& e)
{
}
catch (const std::runtime_error& e)
{
log<level::ERR>(e.what());
}
}
constexpr uint8_t selVersion = ipmi::sel::selVersion;
constexpr uint16_t freeSpace = 0xFFFF;
constexpr uint32_t eraseTimeStamp = ipmi::sel::invalidTimeStamp;
constexpr uint3_t reserved{0};
return ipmi::responseSuccess(
selVersion, entries, freeSpace, addTimeStamp, eraseTimeStamp,
ipmi::sel::operationSupport::getSelAllocationInfo,
ipmi::sel::operationSupport::reserveSel,
ipmi::sel::operationSupport::partialAddSelEntry,
ipmi::sel::operationSupport::deleteSel, reserved,
ipmi::sel::operationSupport::overflow);
}
ipmi_ret_t getSELEntry(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
if (*data_len != sizeof(ipmi::sel::GetSELEntryRequest))
{
*data_len = 0;
return IPMI_CC_REQ_DATA_LEN_INVALID;
}
auto requestData =
reinterpret_cast<const ipmi::sel::GetSELEntryRequest*>(request);
if (requestData->reservationID != 0)
{
if (!checkSELReservation(requestData->reservationID))
{
*data_len = 0;
return IPMI_CC_INVALID_RESERVATION_ID;
}
}
if (cache::paths.empty())
{
*data_len = 0;
return IPMI_CC_SENSOR_INVALID;
}
ipmi::sel::ObjectPaths::const_iterator iter;
// Check for the requested SEL Entry.
if (requestData->selRecordID == ipmi::sel::firstEntry)
{
iter = cache::paths.begin();
}
else if (requestData->selRecordID == ipmi::sel::lastEntry)
{
iter = cache::paths.end();
}
else
{
std::string objPath = std::string(ipmi::sel::logBasePath) + "/" +
std::to_string(requestData->selRecordID);
iter = std::find(cache::paths.begin(), cache::paths.end(), objPath);
if (iter == cache::paths.end())
{
*data_len = 0;
return IPMI_CC_SENSOR_INVALID;
}
}
ipmi::sel::GetSELEntryResponse record{};
// Convert the log entry into SEL record.
try
{
record = ipmi::sel::convertLogEntrytoSEL(*iter);
}
catch (InternalFailure& e)
{
*data_len = 0;
return IPMI_CC_UNSPECIFIED_ERROR;
}
catch (const std::runtime_error& e)
{
log<level::ERR>(e.what());
*data_len = 0;
return IPMI_CC_UNSPECIFIED_ERROR;
}
// Identify the next SEL record ID
if (iter != cache::paths.end())
{
++iter;
if (iter == cache::paths.end())
{
record.nextRecordID = ipmi::sel::lastEntry;
}
else
{
namespace fs = std::filesystem;
fs::path path(*iter);
record.nextRecordID = static_cast<uint16_t>(
std::stoul(std::string(path.filename().c_str())));
}
}
else
{
record.nextRecordID = ipmi::sel::lastEntry;
}
if (requestData->readLength == ipmi::sel::entireRecord)
{
std::memcpy(response, &record, sizeof(record));
*data_len = sizeof(record);
}
else
{
if (requestData->offset >= ipmi::sel::selRecordSize ||
requestData->readLength > ipmi::sel::selRecordSize)
{
*data_len = 0;
return IPMI_CC_INVALID_FIELD_REQUEST;
}
auto diff = ipmi::sel::selRecordSize - requestData->offset;
auto readLength =
std::min(diff, static_cast<int>(requestData->readLength));
std::memcpy(response, &record.nextRecordID,
sizeof(record.nextRecordID));
std::memcpy(static_cast<uint8_t*>(response) +
sizeof(record.nextRecordID),
&record.event.eventRecord.recordID + requestData->offset,
readLength);
*data_len = sizeof(record.nextRecordID) + readLength;
}
return IPMI_CC_OK;
}
/** @brief implements the delete SEL entry command
* @request
* - reservationID; // reservation ID.
* - selRecordID; // SEL record ID.
*
* @returns ipmi completion code plus response data
* - Record ID of the deleted record
*/
ipmi::RspType<uint16_t // deleted record ID
>
deleteSELEntry(uint16_t reservationID, uint16_t selRecordID)
{
namespace fs = std::filesystem;
if (!checkSELReservation(reservationID))
{
return ipmi::responseInvalidReservationId();
}
// Per the IPMI spec, need to cancel the reservation when a SEL entry is
// deleted
cancelSELReservation();
try
{
ipmi::sel::readLoggingObjectPaths(cache::paths);
}
catch (const sdbusplus::exception::SdBusError& e)
{
// readLoggingObjectPaths will throw exception if there are no error
// log entries.
return ipmi::responseSensorInvalid();
}
if (cache::paths.empty())
{
return ipmi::responseSensorInvalid();
}
ipmi::sel::ObjectPaths::const_iterator iter;
uint16_t delRecordID = 0;
if (selRecordID == ipmi::sel::firstEntry)
{
iter = cache::paths.begin();
fs::path path(*iter);
delRecordID = static_cast<uint16_t>(
std::stoul(std::string(path.filename().c_str())));
}
else if (selRecordID == ipmi::sel::lastEntry)
{
iter = cache::paths.end();
fs::path path(*iter);
delRecordID = static_cast<uint16_t>(
std::stoul(std::string(path.filename().c_str())));
}
else
{
std::string objPath = std::string(ipmi::sel::logBasePath) + "/" +
std::to_string(selRecordID);
iter = std::find(cache::paths.begin(), cache::paths.end(), objPath);
if (iter == cache::paths.end())
{
return ipmi::responseSensorInvalid();
}
delRecordID = selRecordID;
}
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
std::string service;
try
{
service = ipmi::getService(bus, ipmi::sel::logDeleteIntf, *iter);
}
catch (const std::runtime_error& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
auto methodCall = bus.new_method_call(service.c_str(), (*iter).c_str(),
ipmi::sel::logDeleteIntf, "Delete");
auto reply = bus.call(methodCall);
if (reply.is_method_error())
{
return ipmi::responseUnspecifiedError();
}
// Invalidate the cache of dbus entry objects.
cache::paths.clear();
return ipmi::responseSuccess(delRecordID);
}
/** @brief implements the Clear SEL command
* @request
* - reservationID // Reservation ID.
* - clr // char array { 'C'(0x43h), 'L'(0x4Ch), 'R'(0x52h) }
* - eraseOperation; // requested operation.
*
* @returns ipmi completion code plus response data
* - erase status
*/
ipmi::RspType<uint8_t // erase status
>
clearSEL(uint16_t reservationID, const std::array<char, 3>& clr,
uint8_t eraseOperation)
{
static constexpr std::array<char, 3> clrOk = {'C', 'L', 'R'};
if (clr != clrOk)
{
return ipmi::responseInvalidFieldRequest();
}
if (!checkSELReservation(reservationID))
{
return ipmi::responseInvalidReservationId();
}
/*
* Erasure status cannot be fetched from DBUS, so always return erasure
* status as `erase completed`.
*/
if (eraseOperation == ipmi::sel::getEraseStatus)
{
return ipmi::responseSuccess(
static_cast<uint8_t>(ipmi::sel::eraseComplete));
}
// Per the IPMI spec, need to cancel any reservation when the SEL is cleared
cancelSELReservation();
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
ipmi::sel::ObjectPaths objectPaths;
auto depth = 0;
auto mapperCall =
bus.new_method_call(ipmi::sel::mapperBusName, ipmi::sel::mapperObjPath,
ipmi::sel::mapperIntf, "GetSubTreePaths");
mapperCall.append(ipmi::sel::logBasePath);
mapperCall.append(depth);
mapperCall.append(ipmi::sel::ObjectPaths({ipmi::sel::logEntryIntf}));
try
{
auto reply = bus.call(mapperCall);
if (reply.is_method_error())
{
return ipmi::responseSuccess(
static_cast<uint8_t>(ipmi::sel::eraseComplete));
}
reply.read(objectPaths);
if (objectPaths.empty())
{
return ipmi::responseSuccess(
static_cast<uint8_t>(ipmi::sel::eraseComplete));
}
}
catch (const sdbusplus::exception::SdBusError& e)
{
return ipmi::responseSuccess(
static_cast<uint8_t>(ipmi::sel::eraseComplete));
}
std::string service;
try
{
service = ipmi::getService(bus, ipmi::sel::logDeleteIntf,
objectPaths.front());
}
catch (const std::runtime_error& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
for (const auto& iter : objectPaths)
{
auto methodCall = bus.new_method_call(
service.c_str(), iter.c_str(), ipmi::sel::logDeleteIntf, "Delete");
auto reply = bus.call(methodCall);
if (reply.is_method_error())
{
return ipmi::responseUnspecifiedError();
}
}
// Invalidate the cache of dbus entry objects.
cache::paths.clear();
return ipmi::responseSuccess(
static_cast<uint8_t>(ipmi::sel::eraseComplete));
}
#endif
/** @brief implements the get SEL time command
* @returns IPMI completion code plus response data
* -current time
*/
ipmi::RspType<uint32_t> // current time
ipmiStorageGetSelTime()
{
using namespace std::chrono;
uint64_t bmc_time_usec = 0;
std::stringstream bmcTime;
try
{
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
std::variant<uint64_t> value;
// Get bmc time
auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,
DBUS_PROPERTIES, "Get");
method.append(TIME_INTERFACE, PROPERTY_ELAPSED);
auto reply = bus.call(method);
if (reply.is_method_error())
{
log<level::ERR>("Error getting time",
entry("SERVICE=%s", service.c_str()),
entry("PATH=%s", BMC_TIME_PATH));
return ipmi::responseUnspecifiedError();
}
reply.read(value);
bmc_time_usec = std::get<uint64_t>(value);
}
catch (InternalFailure& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
catch (const std::exception& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
bmcTime << "BMC time:"
<< duration_cast<seconds>(microseconds(bmc_time_usec)).count();
log<level::DEBUG>(bmcTime.str().c_str());
// Time is really long int but IPMI wants just uint32. This works okay until
// the number of seconds since 1970 overflows uint32 size.. Still a whole
// lot of time here to even think about that.
return ipmi::responseSuccess(
duration_cast<seconds>(microseconds(bmc_time_usec)).count());
}
/** @brief implements the set SEL time command
* @param selDeviceTime - epoch time
* -local time as the number of seconds from 00:00:00, January 1, 1970
* @returns IPMI completion code
*/
ipmi::RspType<> ipmiStorageSetSelTime(uint32_t selDeviceTime)
{
using namespace std::chrono;
microseconds usec{seconds(selDeviceTime)};
try
{
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
auto service = ipmi::getService(bus, TIME_INTERFACE, BMC_TIME_PATH);
std::variant<uint64_t> value{(uint64_t)usec.count()};
// Set bmc time
auto method = bus.new_method_call(service.c_str(), BMC_TIME_PATH,
DBUS_PROPERTIES, "Set");
method.append(TIME_INTERFACE, PROPERTY_ELAPSED, value);
auto reply = bus.call(method);
if (reply.is_method_error())
{
log<level::ERR>("Error setting time",
entry("SERVICE=%s", service.c_str()),
entry("PATH=%s", BMC_TIME_PATH));
return ipmi::responseUnspecifiedError();
}
}
catch (InternalFailure& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
catch (const std::exception& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
return ipmi::responseSuccess();
}
/** @brief implements the reserve SEL command
* @returns IPMI completion code plus response data
* - SEL reservation ID.
*/
ipmi::RspType<uint16_t> ipmiStorageReserveSel()
{
return ipmi::responseSuccess(reserveSel());
}
#ifdef JOURNAL_SEL
#if 0
static void toHexStr(const boost::beast::span<uint8_t> bytes,
std::string& hexStr)
{
std::stringstream stream;
stream << std::hex << std::uppercase << std::setfill('0');
for (const uint8_t& byte : bytes)
{
stream << std::setw(2) << static_cast<int>(byte);
}
hexStr = stream.str();
}
static inline bool defaultMessageHook(uint16_t recordID, uint8_t recordType,
uint32_t timestamp, uint16_t generatorID, uint8_t evmRev,
uint8_t sensorType, uint8_t sensorNum, uint8_t eventType,
std::array<uint8_t, eventDataSize> eventData)
{
// Log the record as a default Redfish message instead of a SEL record
// Save the raw IPMI string of the request
std::string ipmiRaw;
std::array selBytes = {static_cast<uint8_t>(recordID),
static_cast<uint8_t>(recordID >> 8),
recordType,
static_cast<uint8_t>(timestamp),
static_cast<uint8_t>(timestamp >> 8),
static_cast<uint8_t>(timestamp >> 16),
static_cast<uint8_t>(timestamp >> 24),
static_cast<uint8_t>(generatorID),
static_cast<uint8_t>(generatorID >> 8),
evmRev,
sensorType,
sensorNum,
eventType,
eventData[0],
eventData[1],
eventData[2]};
toHexStr(boost::beast::span<uint8_t>(selBytes), ipmiRaw);
static const std::string openBMCMessageRegistryVersion("0.1");
std::string messageID =
"OpenBMC." + openBMCMessageRegistryVersion + ".SELEntryAdded";
std::vector<std::string> messageArgs;
messageArgs.push_back(ipmiRaw);
// Log the Redfish message to the journal with the appropriate metadata
std::string journalMsg = "SEL Entry Added: " + ipmiRaw;
std::string messageArgsString = boost::algorithm::join(messageArgs, ",");
phosphor::logging::log<phosphor::logging::level::INFO>(
journalMsg.c_str(),
phosphor::logging::entry("REDFISH_MESSAGE_ID=%s", messageID.c_str()),
phosphor::logging::entry("REDFISH_MESSAGE_ARGS=%s",
messageArgsString.c_str()));
return true;
}
#endif
ipmi::RspType<uint16_t> ipmiStorageAddSEL(
uint16_t recordID, uint8_t recordType, uint32_t timestamp,
uint16_t generatorID, uint8_t evmRev, uint8_t sensorType, uint8_t sensorNum,
uint8_t eventType, std::array<uint8_t, eventDataSize> eventData)
{
// Per the IPMI spec, need to cancel any reservation when a SEL entry is
// added
cancelSELReservation();
#if 0
// Send this request to the Redfish hooks to log it as a Redfish message
// instead. There is no need to add it to the SEL, so just return success.
defaultMessageHook(
recordID, recordType, timestamp, generatorID, evmRev, sensorType,
sensorNum, eventType, eventData);
#endif
static constexpr char const* ipmiSELObject =
"xyz.openbmc_project.Logging.IPMI";
static constexpr char const* ipmiSELPath =
"/xyz/openbmc_project/Logging/IPMI";
static constexpr char const* ipmiSELAddInterface =
"xyz.openbmc_project.Logging.IPMI";
static const std::string ipmiSELAddMessage =
"IPMI SEL entry logged using IPMI Add SEL Entry command.";
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
if (recordType == ipmi::sel::systemEvent)
{
std::string sensorPath = getPathFromSensorNumber(sensorNum);
if(sensorPath.length() == 0){
return ipmi::responseSensorInvalid();
}
bool assert =
(eventType & ipmi::sel::deassertionEvent) ? false : true;
uint16_t genId = generatorID;
sdbusplus::message::message writeSEL = bus.new_method_call(
ipmiSELObject, ipmiSELPath, ipmiSELAddInterface, "IpmiSelAdd");
writeSEL.append(ipmiSELAddMessage, sensorPath, eventData, assert,
genId);
try
{
sdbusplus::message::message writeSELResp = bus.call(writeSEL);
writeSELResp.read(recordID);
}
catch (sdbusplus::exception_t& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
}
else if (recordType >= ipmi::sel::oemTsEventFirst &&
recordType <= ipmi::sel::oemEventLast)
{
sdbusplus::message::message writeSEL = bus.new_method_call(
ipmiSELObject, ipmiSELPath, ipmiSELAddInterface, "IpmiSelAddOem");
writeSEL.append(ipmiSELAddMessage, eventData, recordType);
try
{
sdbusplus::message::message writeSELResp = bus.call(writeSEL);
writeSELResp.read(recordID);
}
catch (sdbusplus::exception_t& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
}
else
{
return ipmi::responseUnspecifiedError();
}
// uint16_t responseID = 0xFFFF;
return ipmi::responseSuccess(recordID);
}
#else // JOURNAL_SEL not used
/** @brief implements the Add SEL entry command
* @request
*
* - recordID ID used for SEL Record access
* - recordType Record Type
* - timeStamp Time when event was logged. LS byte first
* - generatorID software ID if event was generated from
* system software
* - evmRev event message format version
* - sensorType sensor type code for service that generated
* the event
* - sensorNumber number of sensors that generated the event
* - eventDir event dir
* - eventData event data field contents
*
* @returns ipmi completion code plus response data
* - RecordID of the Added SEL entry
*/
ipmi::RspType<uint16_t // recordID of the Added SEL entry
>
ipmiStorageAddSEL(uint16_t recordID, uint8_t recordType, uint32_t timeStamp,
uint16_t generatorID, uint8_t evmRev, uint8_t sensorType,
uint8_t sensorNumber, uint8_t eventDir,
std::array<uint8_t, eventDataSize> eventData)
{
// Per the IPMI spec, need to cancel the reservation when a SEL entry is
// added
cancelSELReservation();
// Hostboot sends SEL with OEM record type 0xDE to indicate that there is
// a maintenance procedure associated with eSEL record.
static constexpr auto procedureType = 0xDE;
if (recordType == procedureType)
{
// In the OEM record type 0xDE, byte 11 in the SEL record indicate the
// procedure number.
createProcedureLogEntry(sensorType);
}
return ipmi::responseSuccess(recordID);
}
#endif // JOURNAL_SEL
/** @brief implements the get FRU Inventory Area Info command
*
* @returns IPMI completion code plus response data
* - FRU Inventory area size in bytes,
* - access bit
**/
ipmi::RspType<uint16_t, // FRU Inventory area size in bytes,
uint8_t // access size (bytes / words)
>
ipmiStorageGetFruInvAreaInfo(uint8_t fruID)
{
auto iter = frus.find(fruID);
if (iter == frus.end())
{
return ipmi::responseSensorInvalid();
}
try
{
return ipmi::responseSuccess(
static_cast<uint16_t>(getFruAreaData(fruID).size()),
static_cast<uint8_t>(AccessMode::bytes));
}
catch (const InternalFailure& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
}
/**@brief implements the Read FRU Data command
* @param fruDeviceId - FRU device ID. FFh = reserved
* @param offset - FRU inventory offset to read
* @param readCount - count to read
*
* @return IPMI completion code plus response data
* - returnCount - response data count.
* - data - response data
*/
ipmi::RspType<uint8_t, // count returned
std::vector<uint8_t>> // FRU data
ipmiStorageReadFruData(uint8_t fruDeviceId, uint16_t offset,
uint8_t readCount)
{
if (fruDeviceId == 0xFF)
{
return ipmi::responseInvalidFieldRequest();
}
auto iter = frus.find(fruDeviceId);
if (iter == frus.end())
{
return ipmi::responseSensorInvalid();
}
try
{
const auto& fruArea = getFruAreaData(fruDeviceId);
auto size = fruArea.size();
if (offset >= size)
{
return ipmi::responseParmOutOfRange();
}
// Write the count of response data.
uint8_t returnCount;
if ((offset + readCount) <= size)
{
returnCount = readCount;
}
else
{
returnCount = size - offset;
}
std::vector<uint8_t> fruData((fruArea.begin() + offset),
(fruArea.begin() + offset + returnCount));
return ipmi::responseSuccess(returnCount, fruData);
}
catch (const InternalFailure& e)
{
log<level::ERR>(e.what());
return ipmi::responseUnspecifiedError();
}
}
ipmi::RspType<uint8_t, // SDR version
uint16_t, // record count LS first
uint16_t, // free space in bytes, LS first
uint32_t, // addition timestamp LS first
uint32_t, // deletion timestamp LS first
uint8_t> // operation Support
ipmiGetRepositoryInfo()
{
constexpr uint8_t sdrVersion = 0x51;
constexpr uint16_t freeSpace = 0xFFFF;
constexpr uint32_t additionTimestamp = 0x0;
constexpr uint32_t deletionTimestamp = 0x0;
constexpr uint8_t operationSupport = 0;
uint16_t records = frus.size() + ipmi::sensor::sensors.size();
return ipmi::responseSuccess(sdrVersion, records, freeSpace,
additionTimestamp, deletionTimestamp,
operationSupport);
}
void register_netfn_storage_functions()
{
// <Get SEL Info>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdGetSelInfo, ipmi::Privilege::User,
ipmiStorageGetSelInfo);
// <Get SEL Time>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdGetSelTime, ipmi::Privilege::User,
ipmiStorageGetSelTime);
// <Set SEL Time>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdSetSelTime,
ipmi::Privilege::Operator, ipmiStorageSetSelTime);
// <Reserve SEL>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdReserveSel, ipmi::Privilege::User,
ipmiStorageReserveSel);
// <Get SEL Entry>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdGetSelEntry, ipmi::Privilege::User,
ipmiStorageGetSELEntry);
#ifndef JOURNAL_SEL
// <Delete SEL Entry>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdDeleteSelEntry,
ipmi::Privilege::Operator, deleteSELEntry);
#endif
// <Add SEL Entry>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdAddSelEntry,
ipmi::Privilege::Operator, ipmiStorageAddSEL);
// <Clear SEL>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdClearSel, ipmi::Privilege::Operator,
ipmiStorageClearSEL);
// <Get FRU Inventory Area Info>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdGetFruInventoryAreaInfo,
ipmi::Privilege::User, ipmiStorageGetFruInvAreaInfo);
// <READ FRU Data>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdReadFruData,
ipmi::Privilege::Operator, ipmiStorageReadFruData);
// <Get Repository Info>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdGetSdrRepositoryInfo,
ipmi::Privilege::User, ipmiGetRepositoryInfo);
// <Reserve SDR Repository>
ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnStorage,
ipmi::storage::cmdReserveSdrRepository,
ipmi::Privilege::User, ipmiSensorReserveSdr);
// <Get SDR>
ipmi_register_callback(NETFUN_STORAGE, IPMI_CMD_GET_SDR, nullptr,
ipmi_sen_get_sdr, PRIVILEGE_USER);
ipmi::fru::registerCallbackHandler();
return;
}
| 31.764099 | 80 | 0.601667 | [
"object",
"vector"
] |
3af0d87199767d8764ba6d251929ca9875745f32 | 22,650 | cpp | C++ | src/plugins/robots/e-puck/simulator/epuck_entity.cpp | wtrep/argos3 | 8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b | [
"MIT"
] | null | null | null | src/plugins/robots/e-puck/simulator/epuck_entity.cpp | wtrep/argos3 | 8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b | [
"MIT"
] | 1 | 2021-02-28T23:45:32.000Z | 2021-02-28T23:45:32.000Z | src/plugins/robots/e-puck/simulator/epuck_entity.cpp | wtrep/argos3 | 8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b | [
"MIT"
] | 7 | 2021-02-26T16:41:06.000Z | 2022-01-19T21:36:31.000Z | /**
* @file <argos3/plugins/robots/e-puck/simulator/epuck_entity.cpp>
*
* @author Carlo Pinciroli - <ilpincy@gmail.com>
*/
#include "epuck_entity.h"
#include <argos3/core/utility/math/matrix/rotationmatrix3.h>
#include <argos3/core/simulator/space/space.h>
#include <argos3/core/simulator/entity/controllable_entity.h>
#include <argos3/core/simulator/entity/embodied_entity.h>
#include <argos3/plugins/simulator/entities/rab_equipped_entity.h>
#include <argos3/plugins/simulator/entities/ground_sensor_equipped_entity.h>
#include <argos3/plugins/simulator/entities/led_equipped_entity.h>
#include <argos3/plugins/simulator/entities/light_sensor_equipped_entity.h>
#include <argos3/plugins/simulator/entities/proximity_sensor_equipped_entity.h>
#include <argos3/plugins/simulator/entities/battery_equipped_entity.h>
namespace argos {
/****************************************/
/****************************************/
static const Real BODY_RADIUS = 0.035f;
static const Real BODY_HEIGHT = 0.086f;
static const Real INTERWHEEL_DISTANCE = 0.053f;
static const Real HALF_INTERWHEEL_DISTANCE = INTERWHEEL_DISTANCE * 0.5f;
static const Real WHEEL_RADIUS = 0.0205f;
static const Real PROXIMITY_SENSOR_RING_ELEVATION = 0.06f;
static const Real PROXIMITY_SENSOR_RING_RADIUS = BODY_RADIUS;
static const CRadians PROXIMITY_SENSOR_RING_START_ANGLE = CRadians((2 * ARGOS_PI / 8.0f) * 0.5f);
static const Real PROXIMITY_SENSOR_RING_RANGE = 0.1f;
static const CRadians LED_RING_START_ANGLE = CRadians((ARGOS_PI / 8.0f) * 0.5f);
static const Real LED_RING_RADIUS = BODY_RADIUS + 0.007;
static const Real LED_RING_ELEVATION = 0.086f;
static const Real RAB_ELEVATION = LED_RING_ELEVATION;
/****************************************/
/****************************************/
CEPuckEntity::CEPuckEntity() :
CComposableEntity(NULL),
m_pcControllableEntity(NULL),
m_pcEmbodiedEntity(NULL),
m_pcGroundSensorEquippedEntity(NULL),
m_pcLEDEquippedEntity(NULL),
m_pcLightSensorEquippedEntity(NULL),
m_pcProximitySensorEquippedEntity(NULL),
m_pcRABEquippedEntity(NULL),
m_pcWheeledEntity(NULL),
m_pcBatteryEquippedEntity(NULL) {
}
/****************************************/
/****************************************/
CEPuckEntity::CEPuckEntity(const std::string& str_id,
const std::string& str_controller_id,
const CVector3& c_position,
const CQuaternion& c_orientation,
Real f_rab_range,
size_t un_rab_data_size,
const std::string& str_bat_model) :
CComposableEntity(NULL, str_id),
m_pcControllableEntity(NULL),
m_pcEmbodiedEntity(NULL),
m_pcGroundSensorEquippedEntity(NULL),
m_pcLEDEquippedEntity(NULL),
m_pcLightSensorEquippedEntity(NULL),
m_pcProximitySensorEquippedEntity(NULL),
m_pcRABEquippedEntity(NULL),
m_pcWheeledEntity(NULL),
m_pcBatteryEquippedEntity(NULL) {
try {
/*
* Create and init components
*/
/* Embodied entity */
m_pcEmbodiedEntity = new CEmbodiedEntity(this, "body_0", c_position, c_orientation);
AddComponent(*m_pcEmbodiedEntity);
/* Wheeled entity and wheel positions (left, right) */
m_pcWheeledEntity = new CWheeledEntity(this, "wheels_0", 2);
AddComponent(*m_pcWheeledEntity);
m_pcWheeledEntity->SetWheel(0, CVector3(0.0f, HALF_INTERWHEEL_DISTANCE, 0.0f), WHEEL_RADIUS);
m_pcWheeledEntity->SetWheel(1, CVector3(0.0f, -HALF_INTERWHEEL_DISTANCE, 0.0f), WHEEL_RADIUS);
/* LED equipped entity */
m_pcLEDEquippedEntity = new CLEDEquippedEntity(this, "leds_0");
AddComponent(*m_pcLEDEquippedEntity);
m_pcLEDEquippedEntity->AddLEDRing(
CVector3(0.0f, 0.0f, LED_RING_ELEVATION),
LED_RING_RADIUS,
LED_RING_START_ANGLE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());
/* Proximity sensor equipped entity */
m_pcProximitySensorEquippedEntity =
new CProximitySensorEquippedEntity(this,
"proximity_0");
AddComponent(*m_pcProximitySensorEquippedEntity);
/*m_pcProximitySensorEquippedEntity->AddSensorRing(
CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION),
PROXIMITY_SENSOR_RING_RADIUS,
PROXIMITY_SENSOR_RING_START_ANGLE,
PROXIMITY_SENSOR_RING_RANGE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());*/
CRadians sensor_angle[8];
sensor_angle[0] = CRadians::PI / 10.5884f;
sensor_angle[1] = CRadians::PI / 3.5999f;
sensor_angle[2] = CRadians::PI_OVER_TWO; //side sensor
sensor_angle[3] = CRadians::PI / 1.2f; // back sensor
sensor_angle[4] = CRadians::PI / 0.8571f; // back sensor
sensor_angle[5] = CRadians::PI / 0.6667f; //side sensor
sensor_angle[6] = CRadians::PI / 0.5806f;
sensor_angle[7] = CRadians::PI / 0.5247f;
CRadians cAngle;
CVector3 cOff, cDir, c_center = CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION);
for(UInt32 i = 0; i < 8; ++i)
{
cAngle = sensor_angle[i];
cAngle.SignedNormalize();
cOff.Set(PROXIMITY_SENSOR_RING_RADIUS, 0.0f, 0.0f);
cOff.RotateZ(cAngle);
cOff += c_center;
cDir.Set(PROXIMITY_SENSOR_RING_RANGE, 0.0f, 0.0f);
cDir.RotateZ(cAngle);
m_pcProximitySensorEquippedEntity->AddSensor(cOff, cDir, PROXIMITY_SENSOR_RING_RANGE, m_pcEmbodiedEntity->GetOriginAnchor());
}
/* Light sensor equipped entity */
m_pcLightSensorEquippedEntity =
new CLightSensorEquippedEntity(this,
"light_0");
AddComponent(*m_pcLightSensorEquippedEntity);
m_pcLightSensorEquippedEntity->AddSensorRing(
CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION),
PROXIMITY_SENSOR_RING_RADIUS,
PROXIMITY_SENSOR_RING_START_ANGLE,
PROXIMITY_SENSOR_RING_RANGE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());
/* Ground sensor equipped entity */
m_pcGroundSensorEquippedEntity =
new CGroundSensorEquippedEntity(this,
"ground_0");
AddComponent(*m_pcGroundSensorEquippedEntity);
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, -0.009f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, 0.0f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, 0.009f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
/* RAB equipped entity */
m_pcRABEquippedEntity = new CRABEquippedEntity(this,
"rab_0",
un_rab_data_size,
f_rab_range,
m_pcEmbodiedEntity->GetOriginAnchor(),
*m_pcEmbodiedEntity,
CVector3(0.0f, 0.0f, RAB_ELEVATION));
AddComponent(*m_pcRABEquippedEntity);
/* Battery equipped entity */
m_pcBatteryEquippedEntity = new CBatteryEquippedEntity(this, "battery_0", str_bat_model);
AddComponent(*m_pcBatteryEquippedEntity);
/* Controllable entity
It must be the last one, for actuators/sensors to link to composing entities correctly */
m_pcControllableEntity = new CControllableEntity(this, "controller_0");
AddComponent(*m_pcControllableEntity);
m_pcControllableEntity->SetController(str_controller_id);
/* Update components */
UpdateComponents();
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Failed to initialize entity \"" << GetId() << "\".", ex);
}
}
/****************************************/
/****************************************/
void CEPuckEntity::Init(TConfigurationNode& t_tree) {
try {
/*
* Init parent
*/
CComposableEntity::Init(t_tree);
/*
* Create and init components
*/
/* Embodied entity */
m_pcEmbodiedEntity = new CEmbodiedEntity(this);
AddComponent(*m_pcEmbodiedEntity);
m_pcEmbodiedEntity->Init(GetNode(t_tree, "body"));
/* Wheeled entity and wheel positions (left, right) */
m_pcWheeledEntity = new CWheeledEntity(this, "wheels_0", 2);
AddComponent(*m_pcWheeledEntity);
m_pcWheeledEntity->SetWheel(0, CVector3(0.0f, HALF_INTERWHEEL_DISTANCE, 0.0f), WHEEL_RADIUS);
m_pcWheeledEntity->SetWheel(1, CVector3(0.0f, -HALF_INTERWHEEL_DISTANCE, 0.0f), WHEEL_RADIUS);
/* LED equipped entity, with LEDs [0-11] and beacon [12] */
m_pcLEDEquippedEntity = new CLEDEquippedEntity(this, "leds_0");
AddComponent(*m_pcLEDEquippedEntity);
m_pcLEDEquippedEntity->AddLEDRing(
CVector3(0.0f, 0.0f, LED_RING_ELEVATION),
LED_RING_RADIUS,
LED_RING_START_ANGLE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());
/* Proximity sensor equipped entity */
m_pcProximitySensorEquippedEntity =
new CProximitySensorEquippedEntity(this,
"proximity_0");
AddComponent(*m_pcProximitySensorEquippedEntity);
/*m_pcProximitySensorEquippedEntity->AddSensorRing(
CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION),
PROXIMITY_SENSOR_RING_RADIUS,
PROXIMITY_SENSOR_RING_START_ANGLE,
PROXIMITY_SENSOR_RING_RANGE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());*/
CRadians sensor_angle[8];
sensor_angle[0] = CRadians::PI / 10.5884f;
sensor_angle[1] = CRadians::PI / 3.5999f;
sensor_angle[2] = CRadians::PI_OVER_TWO; //side sensor
sensor_angle[3] = CRadians::PI / 1.2f; // back sensor
sensor_angle[4] = CRadians::PI / 0.8571f; // back sensor
sensor_angle[5] = CRadians::PI / 0.6667f; //side sensor
sensor_angle[6] = CRadians::PI / 0.5806f;
sensor_angle[7] = CRadians::PI / 0.5247f;
CRadians cAngle;
CVector3 cOff, cDir, c_center = CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION);
for(UInt32 i = 0; i < 8; ++i)
{
cAngle = sensor_angle[i];
cAngle.SignedNormalize();
cOff.Set(PROXIMITY_SENSOR_RING_RADIUS, 0.0f, 0.0f);
cOff.RotateZ(cAngle);
cOff += c_center;
cDir.Set(PROXIMITY_SENSOR_RING_RANGE, 0.0f, 0.0f);
cDir.RotateZ(cAngle);
m_pcProximitySensorEquippedEntity->AddSensor(cOff, cDir, PROXIMITY_SENSOR_RING_RANGE, m_pcEmbodiedEntity->GetOriginAnchor());
}
/* Light sensor equipped entity */
m_pcLightSensorEquippedEntity =
new CLightSensorEquippedEntity(this,
"light_0");
AddComponent(*m_pcLightSensorEquippedEntity);
m_pcLightSensorEquippedEntity->AddSensorRing(
CVector3(0.0f, 0.0f, PROXIMITY_SENSOR_RING_ELEVATION),
PROXIMITY_SENSOR_RING_RADIUS,
PROXIMITY_SENSOR_RING_START_ANGLE,
PROXIMITY_SENSOR_RING_RANGE,
8,
m_pcEmbodiedEntity->GetOriginAnchor());
/* Ground sensor equipped entity */
m_pcGroundSensorEquippedEntity =
new CGroundSensorEquippedEntity(this,
"ground_0");
AddComponent(*m_pcGroundSensorEquippedEntity);
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, -0.009f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, 0.0f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
m_pcGroundSensorEquippedEntity->AddSensor(CVector2(0.03f, 0.009f),
CGroundSensorEquippedEntity::TYPE_GRAYSCALE,
m_pcEmbodiedEntity->GetOriginAnchor());
/* RAB equipped entity */
Real fRange = 0.8f;
GetNodeAttributeOrDefault(t_tree, "rab_range", fRange, fRange);
UInt32 unDataSize = 2;
GetNodeAttributeOrDefault(t_tree, "rab_data_size", unDataSize, unDataSize);
m_pcRABEquippedEntity = new CRABEquippedEntity(this,
"rab_0",
unDataSize,
fRange,
m_pcEmbodiedEntity->GetOriginAnchor(),
*m_pcEmbodiedEntity,
CVector3(0.0f, 0.0f, RAB_ELEVATION));
AddComponent(*m_pcRABEquippedEntity);
/* Battery equipped entity */
m_pcBatteryEquippedEntity = new CBatteryEquippedEntity(this, "battery_0");
if(NodeExists(t_tree, "battery"))
m_pcBatteryEquippedEntity->Init(GetNode(t_tree, "battery"));
AddComponent(*m_pcBatteryEquippedEntity);
/* Controllable entity
It must be the last one, for actuators/sensors to link to composing entities correctly */
m_pcControllableEntity = new CControllableEntity(this);
AddComponent(*m_pcControllableEntity);
m_pcControllableEntity->Init(GetNode(t_tree, "controller"));
/* Update components */
UpdateComponents();
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Failed to initialize entity \"" << GetId() << "\".", ex);
}
}
/****************************************/
/****************************************/
void CEPuckEntity::Reset() {
/* Reset all components */
CComposableEntity::Reset();
/* Update components */
UpdateComponents();
}
/****************************************/
/****************************************/
void CEPuckEntity::Destroy() {
CComposableEntity::Destroy();
}
/****************************************/
/****************************************/
#define UPDATE(COMPONENT) if(COMPONENT->IsEnabled()) COMPONENT->Update();
void CEPuckEntity::UpdateComponents() {
UPDATE(m_pcRABEquippedEntity);
UPDATE(m_pcLEDEquippedEntity);
UPDATE(m_pcBatteryEquippedEntity);
}
/****************************************/
/****************************************/
REGISTER_ENTITY(CEPuckEntity,
"e-puck",
"Carlo Pinciroli [ilpincy@gmail.com]",
"1.0",
"The e-puck robot.",
"The e-puck is a open-hardware, extensible robot intended for education. In its\n"
"simplest form, it is a two-wheeled robot equipped with proximity sensors,\n"
"ground sensors, light sensors, a microphone, a frontal camera, and a ring of\n"
"red LEDs. More information is available at http://www.epuck.org\n\n"
"REQUIRED XML CONFIGURATION\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\">\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,90,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n"
"The 'id' attribute is necessary and must be unique among the entities. If two\n"
"entities share the same id, initialization aborts.\n"
"The 'body/position' attribute specifies the position of the pucktom point of the\n"
"e-puck in the arena. When the robot is untranslated and unrotated, the\n"
"pucktom point is in the origin and it is defined as the middle point between\n"
"the two wheels on the XY plane and the lowest point of the robot on the Z\n"
"axis, that is the point where the wheels touch the floor. The attribute values\n"
"are in the X,Y,Z order.\n"
"The 'body/orientation' attribute specifies the orientation of the e-puck. All\n"
"rotations are performed with respect to the pucktom point. The order of the\n"
"angles is Z,Y,X, which means that the first number corresponds to the rotation\n"
"around the Z axis, the second around Y and the last around X. This reflects\n"
"the internal convention used in ARGoS, in which rotations are performed in\n"
"that order. Angles are expressed in degrees. When the robot is unrotated, it\n"
"is oriented along the X axis.\n"
"The 'controller/config' attribute is used to assign a controller to the\n"
"e-puck. The value of the attribute must be set to the id of a previously\n"
"defined controller. Controllers are defined in the <controllers> XML subtree.\n\n"
"OPTIONAL XML CONFIGURATION\n\n"
"You can set the emission range of the range-and-bearing system. By default, a\n"
"message sent by an e-puck can be received up to 80cm. By using the 'rab_range'\n"
"attribute, you can change it to, i.e., 4m as follows:\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\" rab_range=\"4\">\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,90,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n"
"You can also set the data sent at each time step through the range-and-bearing\n"
"system. By default, a message sent by an e-puck is 2 bytes long. By using the\n"
"'rab_data_size' attribute, you can change it to, i.e., 20 bytes as follows:\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\" rab_data_size=\"20\">\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,90,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n"
"You can also configure the battery of the robot. By default, the battery never\n"
"depletes. You can choose among several battery discharge models, such as\n"
"- time: the battery depletes by a fixed amount at each time step\n"
"- motion: the battery depletes according to how the robot moves\n"
"- time_motion: a combination of the above models.\n"
"You can define your own models too. Follow the examples in the file\n"
"argos3/src/plugins/simulator/entities/battery_equipped_entity.cpp.\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\"\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,0,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" <battery model=\"time\" factor=\"1e-5\"/>\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\"\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,0,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" <battery model=\"motion\" pos_factor=\"1e-3\"\n"
" orient_factor=\"1e-3\"/>\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n"
" <arena ...>\n"
" ...\n"
" <e-puck id=\"eb0\"\n"
" <body position=\"0.4,2.3,0.25\" orientation=\"45,0,0\" />\n"
" <controller config=\"mycntrl\" />\n"
" <battery model=\"time_motion\" time_factor=\"1e-5\"\n"
" pos_factor=\"1e-3\"\n"
" orient_factor=\"1e-3\"/>\n"
" </e-puck>\n"
" ...\n"
" </arena>\n\n",
"Under development"
);
/****************************************/
/****************************************/
REGISTER_STANDARD_SPACE_OPERATIONS_ON_COMPOSABLE(CEPuckEntity);
/****************************************/
/****************************************/
}
| 49.78022 | 137 | 0.531567 | [
"model"
] |
3af118be0e228aa3c5272a6d767ac6181cc1a610 | 2,522 | cpp | C++ | src/Input.cpp | JoeyDelp/pyjosim | c4b6fdc7a8ec9d2b08b67f4841855e4ba795b066 | [
"Apache-2.0"
] | null | null | null | src/Input.cpp | JoeyDelp/pyjosim | c4b6fdc7a8ec9d2b08b67f4841855e4ba795b066 | [
"Apache-2.0"
] | null | null | null | src/Input.cpp | JoeyDelp/pyjosim | c4b6fdc7a8ec9d2b08b67f4841855e4ba795b066 | [
"Apache-2.0"
] | null | null | null | #include "JoSIM/Input.hpp"
#include "JoSIM/Model.hpp"
#include <pybind11/pybind11.h>
//#include <pybind11/stl.h>
namespace py = pybind11;
namespace pyjosim {
void input(py::module &m)
{
using namespace JoSIM;
// Create Input class
py::class_<Input>(m, "Input")
// Initialization of the Input object
.def(py::init<AnalysisType,int,bool,bool>())
// Expose the netlist object
.def_readwrite("netlist", &Input::netlist)
// Expose the parameters object
.def_readwrite("parameters", &Input::parameters)
// Create a copy of the input for use internally
.def("clone", [](const Input &input) -> Input { return input; })
// Expose the parse_models function from the Model class
.def("parse_models", [](Input &self) {
for (const auto &model : self.netlist.models) {
auto pair =
std::make_pair(model.second, model.first.second);
Model::parse_model(pair, self.netlist.models_new,
self.parameters);
}
})
// Expose the controls object
.def_property_readonly("controls", [](Input &input) {
return input.controls;
})
// Expose the parse_input funciton
.def("parse_input", [](Input &self, std::string path) {
self.parse_input(path);
})
// Expose the identify_simulation function from Transient class
.def("identify_simulation", [](Input &self) {
Transient::identify_simulation(self.controls, self.transSim);
})
// Create a clear_all_plots function for use internally
.def("clear_all_plots", [](Input &input) {
input.controls.erase(std::remove_if(
input.controls.begin(), input.controls.end(),
[](const std::vector<std::string> &str) {
for (const auto value : {"PLOT", "SAVE", "PRINT"}) {
if (str.front().find(value) != std::string::npos) {
return true;
}
}
return false;
}), input.controls.end());
})
// Create a add_plot function for use internally
.def("add_plot", [](Input &input, const std::string &str) {
tokens_t t = Misc::tokenize(str);
t.insert(t.begin(), "PRINT");
input.controls.emplace_back(t);
});
}
} // namespace pyjosim
| 37.641791 | 75 | 0.545599 | [
"object",
"vector",
"model"
] |
3af7164d9a743bd02e5fefcae232106de53b9736 | 7,080 | cpp | C++ | device/3.2/camera_device.cpp | STMicroelectronics/hardware-peripheral-camera | 8f575f17886a38bbd348aa00b386d6623cf602c1 | [
"Apache-2.0"
] | null | null | null | device/3.2/camera_device.cpp | STMicroelectronics/hardware-peripheral-camera | 8f575f17886a38bbd348aa00b386d6623cf602c1 | [
"Apache-2.0"
] | null | null | null | device/3.2/camera_device.cpp | STMicroelectronics/hardware-peripheral-camera | 8f575f17886a38bbd348aa00b386d6623cf602c1 | [
"Apache-2.0"
] | 1 | 2020-01-26T22:52:09.000Z | 2020-01-26T22:52:09.000Z | /*
* Copyright (C) 2019 The Android Open Source Project
* Copyright (C) 2019 STMicroelectronics
*
* 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.
*/
#define LOG_TAG "android.hardware.camera.device@3.2-service.stm32mp1"
// #define LOG_NDEBUG 0
#include <utils/Log.h>
#include "camera_device.h"
#include "camera_device_session.h"
#include "CameraMetadata.h"
#include "metadata_factory.h"
namespace android {
namespace hardware {
namespace camera {
namespace device {
namespace V3_2 {
namespace implementation {
using CameraMetadataHelper =
::android::hardware::camera::common::V1_0::helper::CameraMetadata;
CameraDevice::CameraDevice(const std::string& node)
: camera_node_ { node },
init_fail_ { false },
disconnected_ { false },
session_ { nullptr },
v4l2_wrapper_ { new V4L2Wrapper(node) },
metadata_ { nullptr },
static_info_ { nullptr },
lock_ { } {
}
int CameraDevice::initialize() {
/* Get Camera Characteristics */
std::unique_ptr<Metadata> metadata;
int res = MetadataFactory::GetV4L2Metadata(v4l2_wrapper_, &metadata);
if (res) {
ALOGE("%s: failed to initialize V4L2 metadata: %d", __FUNCTION__, res);
return res;
}
metadata_ = std::move(metadata);
/* Get static metadata */
std::unique_ptr<CameraMetadataHelper> out =
std::make_unique<CameraMetadataHelper>();
res = metadata_->FillStaticMetadata(out.get());
if (res) {
ALOGE("%s: failed to get static metadata: %d", __FUNCTION__, res);
return res;
}
/* Wrap static metadata into StaticProperties */
static_info_.reset(StaticProperties::NewStaticProperties(std::move(out)));
if (!static_info_) {
ALOGE("%s: failed to initialize static properties from device metadata: %d",
__FUNCTION__, res);
return res;
}
return 0;
}
Status CameraDevice::initStatus() const {
Mutex::Autolock _l(lock_);
if (init_fail_) {
return Status::INTERNAL_ERROR;
}
if (disconnected_) {
return Status::CAMERA_DISCONNECTED;
}
return Status::OK;
}
// Methods from ::android::hardware::camera::device::V3_2::ICameraDevice follow.
Return<void> CameraDevice::getResourceCost(getResourceCost_cb _hidl_cb) {
Status status = initStatus();
CameraResourceCost res_cost;
if (status == Status::OK) {
std::vector<std::string> conflicting_devices;
int cost = 100;
res_cost.resourceCost = cost;
res_cost.conflictingDevices.resize(conflicting_devices.size());
for (size_t i = 0; i < conflicting_devices.size(); ++i) {
res_cost.conflictingDevices[i] = conflicting_devices[i];
ALOGV("CameraDevice %s is conflicting with CameraDevice %s",
camera_node_.c_str(), res_cost.conflictingDevices[i].c_str());
}
}
_hidl_cb(status, res_cost);
return Void();
}
Return<void> CameraDevice::getCameraCharacteristics(
getCameraCharacteristics_cb _hidl_cb) {
Status status = initStatus();
CameraMetadata camera_characteristics;
if (status == Status::OK) {
const camera_metadata_t* raw_metadata = static_info_->raw_metadata();
camera_characteristics.setToExternal(
const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(raw_metadata)),
get_camera_metadata_size(raw_metadata));
}
_hidl_cb(status, camera_characteristics);
return Void();
}
Return<Status> CameraDevice::setTorchMode(TorchMode /* mode */) {
Status status = initStatus();
if (status == Status::OK) {
status = Status::OPERATION_NOT_SUPPORTED;
}
return status;
}
Return<void> CameraDevice::open(const sp<ICameraDeviceCallback>& callback,
open_cb _hidl_cb) {
Status status = initStatus();
sp<CameraDeviceSession> session = nullptr;
if (callback == nullptr) {
ALOGE("%s: cannot open camera %s. callback is null!",
__FUNCTION__, camera_node_.c_str());
status = Status::ILLEGAL_ARGUMENT;
goto open_out;
}
if (status == Status::OK) {
Mutex::Autolock _l(lock_);
ALOGV("%s: initializing device for camera %s",
__FUNCTION__, camera_node_.c_str());
session = session_.promote();
if (session != nullptr && !session->isClosed()) {
ALOGE("%s: cannot open an already opened camera!", __FUNCTION__);
status = Status::CAMERA_IN_USE;
goto open_out;
}
session = this->createSession(callback);
if (session == nullptr) {
ALOGE("%s: camera device session allocation failed", __FUNCTION__);
status = Status::INTERNAL_ERROR;
goto open_out;
}
int res = session->initialize();
if (res) {
ALOGE("%s: failed to initialize camera device session: %d",
__FUNCTION__, res);
status = Status::INTERNAL_ERROR;
goto open_out;
}
/*
if (session->isInitFailed()) {
// TODO
}
*/
session_ = session;
}
open_out:
_hidl_cb(status, session);
return Void();
}
sp<CameraDeviceSession>
CameraDevice::createSession(const sp<ICameraDeviceCallback>& callback) {
sp<CameraDeviceSession> session = new CameraDeviceSession(v4l2_wrapper_,
metadata_,
static_info_,
callback);
return session;
}
Return<void> CameraDevice::dumpState(const hidl_handle& handle) {
Mutex::Autolock _l(lock_);
sp<CameraDeviceSession> session = nullptr;
int fd = -1;
if (handle.getNativeHandle() == nullptr) {
ALOGE("%s: handle must not be null", __FUNCTION__);
return Void();
}
if (handle->numFds != 1 || handle->numInts != 0) {
ALOGE("%s: handle must contain 1 FD and 0 ints! Got %d FDs and %d ints",
__FUNCTION__, handle->numFds, handle->numInts);
return Void();
}
fd = handle->data[0];
session = session_.promote();
if (session == nullptr) {
dprintf(fd, "No active camera device session instance\n");
return Void();
}
session->dumpState(handle);
return Void();
}
} // namespace implementation
} // namespace V3_2
} // namespace device
} // namespace camera
} // namespace hardware
} // namespace android
| 28.548387 | 82 | 0.623729 | [
"vector"
] |
d7029ce322e4d5d02cbbaa50ce8bb9763f99f7f5 | 6,233 | cpp | C++ | src/ParallelAlgorithms/LinearSolver/Multigrid/Hierarchy.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 1 | 2022-01-11T00:17:33.000Z | 2022-01-11T00:17:33.000Z | src/ParallelAlgorithms/LinearSolver/Multigrid/Hierarchy.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | src/ParallelAlgorithms/LinearSolver/Multigrid/Hierarchy.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "ParallelAlgorithms/LinearSolver/Multigrid/Hierarchy.hpp"
#include <array>
#include <cstddef>
#include <unordered_set>
#include <vector>
#include "Domain/Structure/ElementId.hpp"
#include "Domain/Structure/SegmentId.hpp"
#include "Domain/Structure/Side.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/StdHelpers.hpp"
namespace LinearSolver::multigrid {
template <size_t Dim>
std::vector<std::array<size_t, Dim>> coarsen(
std::vector<std::array<size_t, Dim>> initial_refinement_levels) {
for (auto& block_refinement : initial_refinement_levels) {
for (size_t d = 0; d < Dim; ++d) {
auto& refinement_level = gsl::at(block_refinement, d);
if (refinement_level > 0) {
--refinement_level;
}
}
}
return initial_refinement_levels;
}
template <size_t Dim>
ElementId<Dim> parent_id(const ElementId<Dim>& child_id) {
std::array<SegmentId, Dim> parent_segment_ids = child_id.segment_ids();
for (size_t d = 0; d < Dim; ++d) {
auto& segment_id = gsl::at(parent_segment_ids, d);
if (segment_id.refinement_level() > 0) {
segment_id = segment_id.id_of_parent();
}
}
return {child_id.block_id(), std::move(parent_segment_ids),
child_id.grid_index() + 1};
}
namespace {
template <size_t Dim>
void assert_finest_grid(
const std::array<SegmentId, Dim>& parent_segment_ids,
const std::array<size_t, Dim>& children_refinement_levels) {
for (size_t d = 0; d < Dim; ++d) {
ASSERT(gsl::at(children_refinement_levels, d) ==
gsl::at(parent_segment_ids, d).refinement_level(),
"On the finest grid, expected the children refinement levels "
<< children_refinement_levels
<< " to equal the refinement levels of the parent segment IDs "
<< parent_segment_ids << " in dimension " << d << ".");
}
}
std::unordered_set<SegmentId> child_segment_ids_impl(
const SegmentId& parent_segment_id,
const size_t children_refinement_level) {
ASSERT(parent_segment_id.refinement_level() == children_refinement_level or
(children_refinement_level > 0 and
parent_segment_id.refinement_level() ==
children_refinement_level - 1),
"The parent refinement level must be exactly 1 smaller than the "
"children refinement level, or the same. Parent refinement level: "
<< parent_segment_id.refinement_level()
<< ", children refinement level: " << children_refinement_level);
if (parent_segment_id.refinement_level() < children_refinement_level) {
return {parent_segment_id.id_of_child(Side::Lower),
parent_segment_id.id_of_child(Side::Upper)};
} else {
return {parent_segment_id};
}
}
} // namespace
template <>
std::unordered_set<ElementId<1>> child_ids<1>(
const ElementId<1>& parent_id,
const std::array<size_t, 1>& children_refinement_levels) {
if (parent_id.grid_index() == 0) {
#ifdef SPECTRE_DEBUG
assert_finest_grid(parent_id.segment_ids(), children_refinement_levels);
#endif // SPECTRE_DEBUG
return {};
}
const std::unordered_set<SegmentId> child_segment_ids =
child_segment_ids_impl(parent_id.segment_id(0),
children_refinement_levels[0]);
std::unordered_set<ElementId<1>> child_ids{};
for (const auto& child_segment_id : child_segment_ids) {
child_ids.emplace(parent_id.block_id(),
std::array<SegmentId, 1>{child_segment_id},
parent_id.grid_index() - 1);
}
return child_ids;
}
template <>
std::unordered_set<ElementId<2>> child_ids<2>(
const ElementId<2>& parent_id,
const std::array<size_t, 2>& children_refinement_levels) {
if (parent_id.grid_index() == 0) {
#ifdef SPECTRE_DEBUG
assert_finest_grid(parent_id.segment_ids(), children_refinement_levels);
#endif // SPECTRE_DEBUG
return {};
}
std::array<std::unordered_set<SegmentId>, 2> child_segment_ids{};
for (size_t d = 0; d < 2; ++d) {
gsl::at(child_segment_ids, d) = child_segment_ids_impl(
parent_id.segment_id(d), gsl::at(children_refinement_levels, d));
}
std::unordered_set<ElementId<2>> child_ids{};
for (const auto& child_segment_id_x : child_segment_ids[0]) {
for (const auto& child_segment_id_y : child_segment_ids[1]) {
child_ids.emplace(
parent_id.block_id(),
std::array<SegmentId, 2>{{child_segment_id_x, child_segment_id_y}},
parent_id.grid_index() - 1);
}
}
return child_ids;
}
template <>
std::unordered_set<ElementId<3>> child_ids<3>(
const ElementId<3>& parent_id,
const std::array<size_t, 3>& children_refinement_levels) {
if (parent_id.grid_index() == 0) {
#ifdef SPECTRE_DEBUG
assert_finest_grid(parent_id.segment_ids(), children_refinement_levels);
#endif // SPECTRE_DEBUG
return {};
}
std::array<std::unordered_set<SegmentId>, 3> child_segment_ids{};
for (size_t d = 0; d < 3; ++d) {
gsl::at(child_segment_ids, d) = child_segment_ids_impl(
parent_id.segment_id(d), gsl::at(children_refinement_levels, d));
}
std::unordered_set<ElementId<3>> child_ids{};
for (const auto& child_segment_id_x : child_segment_ids[0]) {
for (const auto& child_segment_id_y : child_segment_ids[1]) {
for (const auto& child_segment_id_z : child_segment_ids[2]) {
child_ids.emplace(
parent_id.block_id(),
std::array<SegmentId, 3>{
{child_segment_id_x, child_segment_id_y, child_segment_id_z}},
parent_id.grid_index() - 1);
}
}
}
return child_ids;
}
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATE(r, data) \
template std::vector<std::array<size_t, DIM(data)>> coarsen( \
std::vector<std::array<size_t, DIM(data)>> initial_refinement_levels); \
template ElementId<DIM(data)> parent_id(const ElementId<DIM(data)>& child_id);
GENERATE_INSTANTIATIONS(INSTANTIATE, (1, 2, 3))
#undef DIM
#undef INSTANTIATE
} // namespace LinearSolver::multigrid
| 36.028902 | 80 | 0.678004 | [
"vector"
] |
d71d9fe7f876808af1fd6d3c72f79e97f946d439 | 79,272 | cc | C++ | mysql-server/sql/log.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/log.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/log.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@brief
logging of commands
*/
#include "sql/log.h"
#include "my_config.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "my_sys.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/psi/mysql_rwlock.h"
#include "mysql_time.h"
#include "server_component/log_sink_buffer.h" // log_sink_buffer_flush()
#include "sql_string.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <new>
#include <sstream>
#include <string>
#include <utility>
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "my_base.h"
#include "my_dbug.h"
#include "my_dir.h"
#include "my_double2ulonglong.h"
#include "my_time.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_file.h"
#include "mysql/service_my_plugin_log.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_version.h"
#include "mysqld_error.h"
#include "mysys_err.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/current_thd.h"
#include "sql/debug_sync.h"
#include "sql/derror.h" // ER_DEFAULT
#include "sql/discrete_interval.h"
#include "sql/error_handler.h" // Internal_error_handler
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/mysqld.h"
#include "sql/protocol_classic.h"
#include "sql/psi_memory_key.h" // key_memory_File_query_log_name
#include "sql/query_options.h"
#include "sql/sql_audit.h" // mysql_audit_general_log
#include "sql/sql_base.h" // close_log_table
#include "sql/sql_class.h" // THD
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_parse.h" // sql_command_flags
#include "sql/sql_plugin_ref.h"
#include "sql/sql_time.h" // calc_time_from_sec
#include "sql/system_variables.h"
#include "sql/table.h" // TABLE_FIELD_TYPE
#include "thr_lock.h"
#include "thr_mutex.h"
#ifdef _WIN32
#include "sql/message.h"
#else
#endif
#include "sql/server_component/log_builtins_imp.h"
using std::max;
using std::min;
enum enum_slow_query_log_table_field {
SQLT_FIELD_START_TIME = 0,
SQLT_FIELD_USER_HOST,
SQLT_FIELD_QUERY_TIME,
SQLT_FIELD_LOCK_TIME,
SQLT_FIELD_ROWS_SENT,
SQLT_FIELD_ROWS_EXAMINED,
SQLT_FIELD_DATABASE,
SQLT_FIELD_LAST_INSERT_ID,
SQLT_FIELD_INSERT_ID,
SQLT_FIELD_SERVER_ID,
SQLT_FIELD_SQL_TEXT,
SQLT_FIELD_THREAD_ID,
SQLT_FIELD_COUNT
};
static const TABLE_FIELD_TYPE slow_query_log_table_fields[SQLT_FIELD_COUNT] = {
{{STRING_WITH_LEN("start_time")},
{STRING_WITH_LEN("timestamp(6)")},
{nullptr, 0}},
{{STRING_WITH_LEN("user_host")},
{STRING_WITH_LEN("mediumtext")},
{STRING_WITH_LEN("utf8")}},
{{STRING_WITH_LEN("query_time")},
{STRING_WITH_LEN("time(6)")},
{nullptr, 0}},
{{STRING_WITH_LEN("lock_time")},
{STRING_WITH_LEN("time(6)")},
{nullptr, 0}},
{{STRING_WITH_LEN("rows_sent")}, {STRING_WITH_LEN("int")}, {nullptr, 0}},
{{STRING_WITH_LEN("rows_examined")},
{STRING_WITH_LEN("int")},
{nullptr, 0}},
{{STRING_WITH_LEN("db")},
{STRING_WITH_LEN("varchar(512)")},
{STRING_WITH_LEN("utf8")}},
{{STRING_WITH_LEN("last_insert_id")},
{STRING_WITH_LEN("int")},
{nullptr, 0}},
{{STRING_WITH_LEN("insert_id")}, {STRING_WITH_LEN("int")}, {nullptr, 0}},
{{STRING_WITH_LEN("server_id")},
{STRING_WITH_LEN("int unsigned")},
{nullptr, 0}},
{{STRING_WITH_LEN("sql_text")},
{STRING_WITH_LEN("mediumblob")},
{nullptr, 0}},
{{STRING_WITH_LEN("thread_id")},
{STRING_WITH_LEN("bigint unsigned")},
{nullptr, 0}}};
static const TABLE_FIELD_DEF slow_query_log_table_def = {
SQLT_FIELD_COUNT, slow_query_log_table_fields};
enum enum_general_log_table_field {
GLT_FIELD_EVENT_TIME = 0,
GLT_FIELD_USER_HOST,
GLT_FIELD_THREAD_ID,
GLT_FIELD_SERVER_ID,
GLT_FIELD_COMMAND_TYPE,
GLT_FIELD_ARGUMENT,
GLT_FIELD_COUNT
};
static const TABLE_FIELD_TYPE general_log_table_fields[GLT_FIELD_COUNT] = {
{{STRING_WITH_LEN("event_time")},
{STRING_WITH_LEN("timestamp(6)")},
{nullptr, 0}},
{{STRING_WITH_LEN("user_host")},
{STRING_WITH_LEN("mediumtext")},
{STRING_WITH_LEN("utf8")}},
{{STRING_WITH_LEN("thread_id")},
{STRING_WITH_LEN("bigint unsigned")},
{nullptr, 0}},
{{STRING_WITH_LEN("server_id")},
{STRING_WITH_LEN("int unsigned")},
{nullptr, 0}},
{{STRING_WITH_LEN("command_type")},
{STRING_WITH_LEN("varchar(64)")},
{STRING_WITH_LEN("utf8")}},
{{STRING_WITH_LEN("argument")},
{STRING_WITH_LEN("mediumblob")},
{nullptr, 0}}};
static const TABLE_FIELD_DEF general_log_table_def = {GLT_FIELD_COUNT,
general_log_table_fields};
class Query_log_table_intact : public Table_check_intact {
protected:
void report_error(uint ecode, const char *fmt, ...) override
MY_ATTRIBUTE((format(printf, 3, 4))) {
longlong log_ecode = 0;
switch (ecode) {
case 0:
log_ecode = ER_SERVER_TABLE_CHECK_FAILED;
break;
case ER_CANNOT_LOAD_FROM_TABLE_V2:
log_ecode = ER_SERVER_CANNOT_LOAD_FROM_TABLE_V2;
break;
case ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2:
log_ecode = ER_SERVER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2;
break;
case ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2:
log_ecode = ER_SERVER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2;
break;
default:
DBUG_ASSERT(false);
return;
}
va_list args;
va_start(args, fmt);
LogEvent()
.type(LOG_TYPE_ERROR)
.prio(ERROR_LEVEL)
.errcode(log_ecode)
.messagev(fmt, args);
va_end(args);
}
};
/** In case of an error, a message is printed to the error log. */
static Query_log_table_intact log_table_intact;
/**
Silence all errors and warnings reported when performing a write
to a log table.
Errors and warnings are not reported to the client or SQL exception
handlers, so that the presence of logging does not interfere and affect
the logic of an application.
*/
class Silence_log_table_errors : public Internal_error_handler {
char m_message[MYSQL_ERRMSG_SIZE];
public:
Silence_log_table_errors() { m_message[0] = '\0'; }
bool handle_condition(THD *, uint, const char *,
Sql_condition::enum_severity_level *,
const char *msg) override {
strmake(m_message, msg, sizeof(m_message) - 1);
return true;
}
const char *message() const { return m_message; }
};
static void ull2timeval(ulonglong utime, struct timeval *tv) {
DBUG_ASSERT(tv != nullptr);
DBUG_ASSERT(utime > 0); /* should hold true in this context */
tv->tv_sec = static_cast<long>(utime / 1000000);
tv->tv_usec = utime % 1000000;
}
class File_query_log {
File_query_log(enum_log_table_type log_type);
~File_query_log() {
DBUG_ASSERT(!is_open());
if (name != nullptr) {
my_free(name);
name = nullptr;
}
mysql_mutex_destroy(&LOCK_log);
}
/** @return true if the file log is open, false otherwise. */
bool is_open() const { return log_open; }
/**
Open a (new) log file.
Open the logfile, init IO_CACHE and write startup messages.
@return true if error, false otherwise.
*/
bool open();
/**
Close the log file
@note One can do an open on the object at once after doing a close.
The internal structures are not freed until the destructor is called.
*/
void close();
/**
Change what file we log to
*/
bool set_file(const char *new_name);
/**
Check if we have already printed ER_ERROR_ON_WRITE and if not,
do so.
*/
void check_and_print_write_error();
/**
Write a command to traditional general log file.
Log given command to normal (not rotatable) log file.
@param event_utime Command start timestamp in micro seconds
@param thread_id Id of the thread that issued the query
@param command_type The type of the command being logged
@param command_type_len The length of the string above
@param sql_text The very text of the query being executed
@param sql_text_len The length of sql_text string
@return true if error, false otherwise.
*/
bool write_general(ulonglong event_utime, my_thread_id thread_id,
const char *command_type, size_t command_type_len,
const char *sql_text, size_t sql_text_len);
/**
Log a query to the traditional slow log file.
@param thd THD of the query
@param current_utime Current timestamp in microseconds
@param query_start_utime Command start timestamp in microseconds
@param user_host The pointer to the string with user\@host info
@param user_host_len Length of the user_host string
@param query_utime Number of microseconds query execution took
@param lock_utime Number of microseconds the query was locked
@param is_command The flag which determines whether the sql_text
is a query or an administrator command
@param sql_text The query or administrator in textual form
@param sql_text_len The length of sql_text string
@param query_start Pointer to a snapshot of thd->status_var taken
at the start of execution
@return true if error, false otherwise.
*/
bool write_slow(THD *thd, ulonglong current_utime,
ulonglong query_start_utime, const char *user_host,
size_t user_host_len, ulonglong query_utime,
ulonglong lock_utime, bool is_command, const char *sql_text,
size_t sql_text_len, struct System_status_var *query_start);
private:
/** Type of log file. */
const enum_log_table_type m_log_type;
/** Makes sure we only have one write at a time. */
mysql_mutex_t LOCK_log;
/** Log filename. */
char *name;
/** Path to log file. */
char log_file_name[FN_REFLEN];
/** Last seen current database. */
char db[NAME_LEN + 1];
/** Have we already printed ER_ERROR_ON_WRITE? */
bool write_error;
IO_CACHE log_file;
/** True if the file log is open, false otherwise. */
volatile bool log_open;
#ifdef HAVE_PSI_INTERFACE
/** Instrumentation key to use for file io in @c log_file */
PSI_file_key m_log_file_key;
#endif
friend class Log_to_file_event_handler;
friend class Query_logger;
};
File_query_log::File_query_log(enum_log_table_type log_type)
: m_log_type(log_type), name(nullptr), write_error(false), log_open(false) {
mysql_mutex_init(key_LOG_LOCK_log, &LOCK_log, MY_MUTEX_INIT_SLOW);
#ifdef HAVE_PSI_INTERFACE
if (log_type == QUERY_LOG_GENERAL)
m_log_file_key = key_file_general_log;
else if (log_type == QUERY_LOG_SLOW)
m_log_file_key = key_file_slow_log;
#endif
}
bool is_valid_log_name(const char *name, size_t len) {
if (len > 3) {
const char *tail = name + len - 4;
if (my_strcasecmp(system_charset_info, tail, ".ini") == 0 ||
my_strcasecmp(system_charset_info, tail, ".cnf") == 0) {
return false;
}
}
return true;
}
/**
Get the real log file name, and possibly reopen file.
The implementation is platform dependent due to differences in how this is
supported:
On Windows, we get the actual path based on the file descriptor. This path is
copied into the supplied buffer. The 'file' parameter is returned without
re-opening.
On other platforms, we use realpath() to get the path with symbolic links
expanded. Then, we close the file, and reopen the real path using the
O_NOFOLLOW flag. This will reject folowing symbolic links.
@param file File descriptor.
@param log_file_key Key for P_S instrumentation.
@param open_flags Flags to use for opening the file.
@param opened_file_name Name of the open fd.
@param [out] real_file_name Buffer for actual name of the fd.
@returns file descriptor to open file with 'real_file_name', or '-1'
in case of errors.
*/
static File mysql_file_real_name_reopen(File file,
#ifdef HAVE_PSI_FILE_INTERFACE
PSI_file_key log_file_key,
#endif
int open_flags,
const char *opened_file_name,
char *real_file_name) {
DBUG_ASSERT(file);
DBUG_ASSERT(opened_file_name);
DBUG_ASSERT(real_file_name);
#ifdef _WIN32
/* On Windows, O_NOFOLLOW is not supported. Verify real path from fd. */
DWORD real_length = GetFinalPathNameByHandle(
my_get_osfhandle(file), real_file_name, FN_REFLEN, FILE_NAME_OPENED);
/* May ret 0 if e.g. on a ramdisk. Ignore - return open file and name. */
if (real_length == 0) {
strcpy(real_file_name, opened_file_name);
return file;
}
if (real_length > FN_REFLEN) {
mysql_file_close(file, MYF(0));
return -1;
}
return file;
#else
/* On *nix, get realpath, open realpath with O_NOFOLLOW. */
if (realpath(opened_file_name, real_file_name) == nullptr) {
(void)mysql_file_close(file, MYF(0));
return -1;
}
if (mysql_file_close(file, MYF(0))) return -1;
/* Make sure the real path is not too long. */
if (strlen(real_file_name) > FN_REFLEN) return -1;
return mysql_file_open(log_file_key, real_file_name, open_flags | O_NOFOLLOW,
MYF(MY_WME));
#endif //_WIN32
}
bool File_query_log::set_file(const char *new_name) {
char *nn;
DBUG_ASSERT(new_name && new_name[0]);
if (!(nn = my_strdup(key_memory_File_query_log_name, new_name, MYF(MY_WME))))
return true;
if (name != nullptr) my_free(name);
name = nn;
// We can do this here since we're not actually resolving symlinks etc.
fn_format(log_file_name, name, mysql_data_home, "", MY_UNPACK_FILENAME);
return false;
}
bool File_query_log::open() {
File file = -1;
my_off_t pos = 0;
char buff[FN_REFLEN];
MY_STAT f_stat;
DBUG_TRACE;
DBUG_ASSERT(name != nullptr);
if (is_open()) return false;
write_error = false;
/* File is regular writable file */
if (my_stat(log_file_name, &f_stat, MYF(0)) && !MY_S_ISREG(f_stat.st_mode))
goto err;
db[0] = 0;
/* First, open the file to make sure it exists. */
if ((file = mysql_file_open(m_log_file_key, log_file_name,
O_CREAT | O_WRONLY | O_APPEND, MYF(MY_WME))) < 0)
goto err;
#ifdef _WIN32
char real_log_file_name[FN_REFLEN];
#else
/* File name must have room for PATH_MAX. Checked against F_REFLEN later. */
char real_log_file_name[PATH_MAX];
#endif // _Win32
/* Reopen and get real path. */
if ((file = mysql_file_real_name_reopen(file,
#ifdef HAVE_PSI_FILE_INTERFACE
m_log_file_key,
#endif
O_CREAT | O_WRONLY | O_APPEND,
log_file_name, real_log_file_name)) <
0)
goto err;
if (!is_valid_log_name(real_log_file_name, strlen(real_log_file_name))) {
LogErr(ERROR_LEVEL, ER_INVALID_ERROR_LOG_NAME, real_log_file_name);
goto err;
}
if ((pos = mysql_file_tell(file, MYF(MY_WME))) == MY_FILEPOS_ERROR) {
if (my_errno() == ESPIPE)
pos = 0;
else
goto err;
}
if (init_io_cache(&log_file, file, IO_SIZE, WRITE_CACHE, pos, false,
MYF(MY_WME | MY_NABP)))
goto err;
{
char *end;
size_t len =
snprintf(buff, sizeof(buff),
"%s, Version: %s (%s). "
#if defined(_WIN32)
"started with:\nTCP Port: %d, Named Pipe: %s\n",
my_progname, server_version, MYSQL_COMPILATION_COMMENT_SERVER,
mysqld_port, mysqld_unix_port
#else
"started with:\nTcp port: %d Unix socket: %s\n",
my_progname, server_version, MYSQL_COMPILATION_COMMENT_SERVER,
mysqld_port, mysqld_unix_port
#endif
);
end =
my_stpncpy(buff + len, "Time Id Command Argument\n",
sizeof(buff) - len);
if (my_b_write(&log_file, (uchar *)buff, (uint)(end - buff)) ||
flush_io_cache(&log_file))
goto err;
}
log_open = true;
return false;
err:
char log_open_file_error_message[96] = "";
if (strcmp(opt_slow_logname, name) == 0) {
strcpy(log_open_file_error_message,
error_message_for_error_log(ER_LOG_SLOW_CANNOT_OPEN));
} else if (strcmp(opt_general_logname, name) == 0) {
strcpy(log_open_file_error_message,
error_message_for_error_log(ER_LOG_GENERAL_CANNOT_OPEN));
}
char errbuf[MYSYS_STRERROR_SIZE];
my_strerror(errbuf, sizeof(errbuf), errno);
LogEvent()
.type(LOG_TYPE_ERROR)
.prio(ERROR_LEVEL)
.errcode(ER_LOG_FILE_CANNOT_OPEN)
.os_errno(errno)
.os_errmsg(errbuf)
.lookup(ER_LOG_FILE_CANNOT_OPEN, name, errno, errbuf,
log_open_file_error_message);
if (file >= 0) mysql_file_close(file, MYF(0));
end_io_cache(&log_file);
log_open = false;
return true;
}
void File_query_log::close() {
DBUG_TRACE;
if (!is_open()) return;
end_io_cache(&log_file);
if (mysql_file_sync(log_file.file, MYF(MY_WME)))
check_and_print_write_error();
if (mysql_file_close(log_file.file, MYF(MY_WME)))
check_and_print_write_error();
log_open = false;
}
void File_query_log::check_and_print_write_error() {
if (!write_error) {
char errbuf[MYSYS_STRERROR_SIZE];
my_strerror(errbuf, sizeof(errbuf), errno);
write_error = true;
LogEvent()
.type(LOG_TYPE_ERROR)
.prio(ERROR_LEVEL)
.errcode(ER_FAILED_TO_WRITE_TO_FILE)
.os_errno(errno)
.os_errmsg(errbuf)
.lookup(ER_FAILED_TO_WRITE_TO_FILE, name, errno, errbuf);
}
}
bool File_query_log::write_general(ulonglong event_utime,
my_thread_id thread_id,
const char *command_type,
size_t command_type_len,
const char *sql_text, size_t sql_text_len) {
char buff[32];
size_t length = 0;
mysql_mutex_lock(&LOCK_log);
DBUG_ASSERT(is_open());
/* Note that my_b_write() assumes it knows the length for this */
char local_time_buff[iso8601_size];
int time_buff_len = make_iso8601_timestamp(local_time_buff, event_utime,
iso8601_sysvar_logtimestamps);
if (my_b_write(&log_file, pointer_cast<uchar *>(local_time_buff),
time_buff_len))
goto err;
if (my_b_write(&log_file, pointer_cast<const uchar *>("\t"), 1)) goto err;
length = snprintf(buff, 32, "%5u ", thread_id);
if (my_b_write(&log_file, pointer_cast<uchar *>(buff), length)) goto err;
if (my_b_write(&log_file, pointer_cast<const uchar *>(command_type),
command_type_len))
goto err;
if (my_b_write(&log_file, pointer_cast<const uchar *>("\t"), 1)) goto err;
/* sql_text */
if (my_b_write(&log_file, pointer_cast<const uchar *>(sql_text),
sql_text_len))
goto err;
if (my_b_write(&log_file, pointer_cast<const uchar *>("\n"), 1) ||
flush_io_cache(&log_file))
goto err;
mysql_mutex_unlock(&LOCK_log);
return false;
err:
check_and_print_write_error();
mysql_mutex_unlock(&LOCK_log);
return true;
}
bool File_query_log::write_slow(THD *thd, ulonglong current_utime,
ulonglong query_start_utime,
const char *user_host, size_t,
ulonglong query_utime, ulonglong lock_utime,
bool is_command, const char *sql_text,
size_t sql_text_len,
struct System_status_var *query_start) {
char buff[80], *end;
char query_time_buff[22 + 7], lock_time_buff[22 + 7];
size_t buff_len;
end = buff;
mysql_mutex_lock(&LOCK_log);
DBUG_ASSERT(is_open());
if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT)) {
char my_timestamp[iso8601_size];
make_iso8601_timestamp(my_timestamp, current_utime,
iso8601_sysvar_logtimestamps);
buff_len = snprintf(buff, sizeof buff, "# Time: %s\n", my_timestamp);
/* Note that my_b_write() assumes it knows the length for this */
if (my_b_write(&log_file, (uchar *)buff, buff_len)) goto err;
buff_len = snprintf(buff, 32, "%5u", thd->thread_id());
if (my_b_printf(&log_file, "# User@Host: %s Id: %s\n", user_host, buff) ==
(uint)-1)
goto err;
}
/* For slow query log */
sprintf(query_time_buff, "%.6f", ulonglong2double(query_utime) / 1000000.0);
sprintf(lock_time_buff, "%.6f", ulonglong2double(lock_utime) / 1000000.0);
/*
As a general rule, if opt_log_slow_extra is set, the caller will
have saved state at the beginning of execution, and passed in a
pointer to that state in query_start. As there are exceptions to
this rule however (e.g. in store routines), and for robustness,
we test for the presence of the actual information rather than the
the flag. If the "before" state is not available for whatever
reason, we emit a traditional "short" line; if the information is
available, we generate the now, "long" line (with "extra" information).
*/
if (!query_start) {
if (my_b_printf(&log_file,
"# Query_time: %s Lock_time: %s"
" Rows_sent: %lu Rows_examined: %lu\n",
query_time_buff, lock_time_buff,
(ulong)thd->get_sent_row_count(),
(ulong)thd->get_examined_row_count()) == (uint)-1)
goto err; /* purecov: inspected */
} else {
char start_time_buff[iso8601_size];
char end_time_buff[iso8601_size];
if (query_start_utime) {
make_iso8601_timestamp(start_time_buff, query_start_utime,
iso8601_sysvar_logtimestamps);
make_iso8601_timestamp(end_time_buff, query_start_utime + query_utime,
iso8601_sysvar_logtimestamps);
} else {
start_time_buff[0] = '\0'; /* purecov: inspected */
make_iso8601_timestamp(
end_time_buff, current_utime,
iso8601_sysvar_logtimestamps); /* purecov: inspected */
}
if (my_b_printf(
&log_file,
"# Query_time: %s Lock_time: %s"
" Rows_sent: %lu Rows_examined: %lu"
" Thread_id: %lu Errno: %lu Killed: %lu"
" Bytes_received: %lu Bytes_sent: %lu"
" Read_first: %lu Read_last: %lu Read_key: %lu"
" Read_next: %lu Read_prev: %lu"
" Read_rnd: %lu Read_rnd_next: %lu"
" Sort_merge_passes: %lu Sort_range_count: %lu"
" Sort_rows: %lu Sort_scan_count: %lu"
" Created_tmp_disk_tables: %lu"
" Created_tmp_tables: %lu"
" Start: %s End: %s\n",
query_time_buff, lock_time_buff, (ulong)thd->get_sent_row_count(),
(ulong)thd->get_examined_row_count(), (ulong)thd->thread_id(),
(ulong)(thd->is_classic_protocol()
? thd->get_protocol_classic()->get_net()->last_errno
: 0),
(ulong)thd->killed,
(ulong)(thd->status_var.bytes_received -
query_start->bytes_received),
(ulong)(thd->status_var.bytes_sent - query_start->bytes_sent),
(ulong)(thd->status_var.ha_read_first_count -
query_start->ha_read_first_count),
(ulong)(thd->status_var.ha_read_last_count -
query_start->ha_read_last_count),
(ulong)(thd->status_var.ha_read_key_count -
query_start->ha_read_key_count),
(ulong)(thd->status_var.ha_read_next_count -
query_start->ha_read_next_count),
(ulong)(thd->status_var.ha_read_prev_count -
query_start->ha_read_prev_count),
(ulong)(thd->status_var.ha_read_rnd_count -
query_start->ha_read_rnd_count),
(ulong)(thd->status_var.ha_read_rnd_next_count -
query_start->ha_read_rnd_next_count),
(ulong)(thd->status_var.filesort_merge_passes -
query_start->filesort_merge_passes),
(ulong)(thd->status_var.filesort_range_count -
query_start->filesort_range_count),
(ulong)(thd->status_var.filesort_rows - query_start->filesort_rows),
(ulong)(thd->status_var.filesort_scan_count -
query_start->filesort_scan_count),
(ulong)(thd->status_var.created_tmp_disk_tables -
query_start->created_tmp_disk_tables),
(ulong)(thd->status_var.created_tmp_tables -
query_start->created_tmp_tables),
start_time_buff, end_time_buff) == (uint)-1)
goto err; /* purecov: inspected */
}
if (thd->db().str && strcmp(thd->db().str, db)) { // Database changed
if (my_b_printf(&log_file, "use %s;\n", thd->db().str) == (uint)-1)
goto err;
my_stpcpy(db, thd->db().str);
}
if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt) {
end = my_stpcpy(end, ",last_insert_id=");
end = longlong10_to_str(
(longlong)thd->first_successful_insert_id_in_prev_stmt_for_binlog, end,
-10);
}
// Save value if we do an insert.
if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0) {
if (!(specialflag & SPECIAL_SHORT_LOG_FORMAT)) {
end = my_stpcpy(end, ",insert_id=");
end = longlong10_to_str(
(longlong)thd->auto_inc_intervals_in_cur_stmt_for_binlog.minimum(),
end, -10);
}
}
/*
The timestamp used to only be set when the query had checked the
start time. Now the slow log always logs the query start time.
This ensures logs can be used to replicate queries accurately.
*/
end = my_stpcpy(end, ",timestamp=");
end = longlong10_to_str(query_start_utime / 1000000, end, 10);
if (end != buff) {
*end++ = ';';
*end = '\n';
if (my_b_write(&log_file, pointer_cast<const uchar *>("SET "), 4) ||
my_b_write(&log_file, (uchar *)buff + 1, (uint)(end - buff)))
goto err;
}
if (is_command) {
end = strxmov(buff, "# administrator command: ", NullS);
buff_len = (ulong)(end - buff);
DBUG_EXECUTE_IF("simulate_slow_log_write_error",
{ DBUG_SET("+d,simulate_file_write_error"); });
if (my_b_write(&log_file, (uchar *)buff, buff_len)) goto err;
}
if (my_b_write(&log_file, pointer_cast<const uchar *>(sql_text),
sql_text_len) ||
my_b_write(&log_file, pointer_cast<const uchar *>(";\n"), 2) ||
flush_io_cache(&log_file))
goto err;
mysql_mutex_unlock(&LOCK_log);
return false;
err:
check_and_print_write_error();
mysql_mutex_unlock(&LOCK_log);
return true;
}
bool Log_to_csv_event_handler::log_general(
THD *thd, ulonglong event_utime, const char *user_host,
size_t user_host_len, my_thread_id thread_id, const char *command_type,
size_t command_type_len, const char *sql_text, size_t sql_text_len,
const CHARSET_INFO *client_cs) {
TABLE *table = nullptr;
bool result = true;
bool need_close = false;
bool need_rnd_end = false;
uint field_index;
struct timeval tv;
/*
CSV uses TIME_to_timestamp() internally if table needs to be repaired
which will set thd->time_zone_used
*/
bool save_time_zone_used = thd->time_zone_used;
ulonglong save_thd_options = thd->variables.option_bits;
thd->variables.option_bits &= ~OPTION_BIN_LOG;
TABLE_LIST table_list(MYSQL_SCHEMA_NAME.str, MYSQL_SCHEMA_NAME.length,
GENERAL_LOG_NAME.str, GENERAL_LOG_NAME.length,
GENERAL_LOG_NAME.str, TL_WRITE_CONCURRENT_INSERT);
/*
1) open_log_table generates an error if the
table can not be opened or is corrupted.
2) "INSERT INTO general_log" can generate warning sometimes.
Suppress these warnings and errors, they can't be dealt with
properly anyway.
QQ: this problem needs to be studied in more detail.
Comment this 2 lines and run "cast.test" to see what's happening.
*/
Silence_log_table_errors error_handler;
thd->push_internal_handler(&error_handler);
Open_tables_backup open_tables_backup;
if (!(table = open_log_table(thd, &table_list, &open_tables_backup)))
goto err;
need_close = true;
if (log_table_intact.check(thd, table_list.table, &general_log_table_def))
goto err;
if (table->file->ha_extra(HA_EXTRA_MARK_AS_LOG_TABLE) ||
table->file->ha_rnd_init(false))
goto err;
need_rnd_end = true;
/* Honor next number columns if present */
table->next_number_field = table->found_next_number_field;
/*
NOTE: we do not call restore_record() here, as all fields are
filled by the Logger (=> no need to load default ones).
*/
/*
We do not set a value for table->field[0], as it will use
default value (which is CURRENT_TIMESTAMP).
*/
DBUG_ASSERT(table->field[GLT_FIELD_EVENT_TIME]->type() ==
MYSQL_TYPE_TIMESTAMP);
ull2timeval(event_utime, &tv);
table->field[GLT_FIELD_EVENT_TIME]->store_timestamp(&tv);
/* do a write */
if (table->field[GLT_FIELD_USER_HOST]->store(user_host, user_host_len,
client_cs) ||
table->field[GLT_FIELD_THREAD_ID]->store((longlong)thread_id, true) ||
table->field[GLT_FIELD_SERVER_ID]->store((longlong)server_id, true) ||
table->field[GLT_FIELD_COMMAND_TYPE]->store(command_type,
command_type_len, client_cs))
goto err;
/*
A positive return value in store() means truncation.
Still logging a message in the log in this case.
*/
if (table->field[GLT_FIELD_ARGUMENT]->store(sql_text, sql_text_len,
client_cs) < 0)
goto err;
/* mark all fields as not null */
table->field[GLT_FIELD_USER_HOST]->set_notnull();
table->field[GLT_FIELD_THREAD_ID]->set_notnull();
table->field[GLT_FIELD_SERVER_ID]->set_notnull();
table->field[GLT_FIELD_COMMAND_TYPE]->set_notnull();
table->field[GLT_FIELD_ARGUMENT]->set_notnull();
/* Set any extra columns to their default values */
for (field_index = GLT_FIELD_COUNT; field_index < table->s->fields;
field_index++) {
table->field[field_index]->set_default();
}
/* log table entries are not replicated */
if (table->file->ha_write_row(table->record[0])) goto err;
result = false;
err:
thd->pop_internal_handler();
if (result && !thd->killed) {
LogErr(ERROR_LEVEL, ER_LOG_CANNOT_WRITE, "mysql.general_log",
error_handler.message());
}
if (need_rnd_end) {
table->file->ha_rnd_end();
table->file->ha_release_auto_increment();
}
if (need_close) close_log_table(thd, &open_tables_backup);
thd->variables.option_bits = save_thd_options;
thd->time_zone_used = save_time_zone_used;
return result;
}
bool Log_to_csv_event_handler::log_slow(
THD *thd, ulonglong current_utime, ulonglong query_start_arg,
const char *user_host, size_t user_host_len, ulonglong query_utime,
ulonglong lock_utime, bool, const char *sql_text, size_t sql_text_len,
struct System_status_var *) {
TABLE *table = nullptr;
bool result = true;
bool need_close = false;
bool need_rnd_end = false;
const CHARSET_INFO *client_cs = thd->variables.character_set_client;
struct timeval tv;
const char *reason = "";
DBUG_TRACE;
/*
CSV uses TIME_to_timestamp() internally if table needs to be repaired
which will set thd->time_zone_used
*/
bool save_time_zone_used = thd->time_zone_used;
TABLE_LIST table_list(MYSQL_SCHEMA_NAME.str, MYSQL_SCHEMA_NAME.length,
SLOW_LOG_NAME.str, SLOW_LOG_NAME.length,
SLOW_LOG_NAME.str, TL_WRITE_CONCURRENT_INSERT);
Silence_log_table_errors error_handler;
thd->push_internal_handler(&error_handler);
Open_tables_backup open_tables_backup;
if (!(table = open_log_table(thd, &table_list, &open_tables_backup))) {
reason = "cannot open table for slow log";
goto err;
}
need_close = true;
if (log_table_intact.check(thd, table_list.table,
&slow_query_log_table_def)) {
reason = "slow table intact check failed";
goto err;
}
if (table->file->ha_extra(HA_EXTRA_MARK_AS_LOG_TABLE) ||
table->file->ha_rnd_init(false)) {
reason = "mark log or init failed";
goto err;
}
need_rnd_end = true;
/* Honor next number columns if present */
table->next_number_field = table->found_next_number_field;
restore_record(table, s->default_values); // Get empty record
/* store the time and user values */
DBUG_ASSERT(table->field[SQLT_FIELD_START_TIME]->type() ==
MYSQL_TYPE_TIMESTAMP);
ull2timeval(current_utime, &tv);
table->field[SQLT_FIELD_START_TIME]->store_timestamp(&tv);
table->field[SQLT_FIELD_USER_HOST]->store(user_host, user_host_len,
client_cs);
if (query_start_arg) {
ha_rows rows_examined;
/*
A TIME field can not hold the full longlong range; query_time or
lock_time may be truncated without warning here, if greater than
839 hours (~35 days)
*/
MYSQL_TIME t;
t.neg = false;
// overflow TIME-max
DBUG_EXECUTE_IF("slow_log_table_max_rows_examined", {
query_utime = (longlong)1555826389LL * 1000000 + 1;
lock_utime = query_utime;
});
/* fill in query_time field */
query_utime = min((ulonglong)query_utime,
(ulonglong)TIME_MAX_VALUE_SECONDS * 1000000LL);
calc_time_from_sec(&t, static_cast<long>(query_utime / 1000000LL),
query_utime % 1000000);
table->field[SQLT_FIELD_QUERY_TIME]->store_time(&t);
/* lock_time */
lock_utime = min((ulonglong)lock_utime,
(ulonglong)TIME_MAX_VALUE_SECONDS * 1000000LL);
calc_time_from_sec(&t, static_cast<long>(lock_utime / 1000000LL),
lock_utime % 1000000);
table->field[SQLT_FIELD_LOCK_TIME]->store_time(&t);
/* rows_sent */
table->field[SQLT_FIELD_ROWS_SENT]->store(
(longlong)thd->get_sent_row_count(), true);
/* rows_examined */
rows_examined = thd->get_examined_row_count();
DBUG_EXECUTE_IF("slow_log_table_max_rows_examined",
{ rows_examined = 4294967294LL; }); // overflow 4-byte int
table->field[SQLT_FIELD_ROWS_EXAMINED]->store((longlong)rows_examined,
true);
} else {
table->field[SQLT_FIELD_QUERY_TIME]->set_null();
table->field[SQLT_FIELD_LOCK_TIME]->set_null();
table->field[SQLT_FIELD_ROWS_SENT]->set_null();
table->field[SQLT_FIELD_ROWS_EXAMINED]->set_null();
}
/* fill database field */
if (thd->db().str) {
if (!table->field[SQLT_FIELD_DATABASE]->store(thd->db().str,
thd->db().length, client_cs))
table->field[SQLT_FIELD_DATABASE]->set_notnull();
}
if (thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt) {
if (!table->field[SQLT_FIELD_LAST_INSERT_ID]->store(
(longlong)thd->first_successful_insert_id_in_prev_stmt_for_binlog,
true))
table->field[SQLT_FIELD_LAST_INSERT_ID]->set_notnull();
}
/*
Set value if we do an insert on autoincrement column. Note that for
some engines (those for which get_auto_increment() does not leave a
table lock until the statement ends), this is just the first value and
the next ones used may not be contiguous to it.
*/
if (thd->auto_inc_intervals_in_cur_stmt_for_binlog.nb_elements() > 0) {
if (!table->field[SQLT_FIELD_INSERT_ID]->store(
(longlong)thd->auto_inc_intervals_in_cur_stmt_for_binlog.minimum(),
true))
table->field[SQLT_FIELD_INSERT_ID]->set_notnull();
}
if (!table->field[SQLT_FIELD_SERVER_ID]->store((longlong)server_id, true))
table->field[SQLT_FIELD_SERVER_ID]->set_notnull();
/*
Column sql_text.
A positive return value in store() means truncation.
Still logging a message in the log in this case.
*/
table->field[SQLT_FIELD_SQL_TEXT]->store(sql_text, sql_text_len, client_cs);
table->field[SQLT_FIELD_THREAD_ID]->store((longlong)thd->thread_id(), true);
/* log table entries are not replicated */
if (table->file->ha_write_row(table->record[0])) {
reason = "write slow table failed";
goto err;
}
result = false;
err:
thd->pop_internal_handler();
if (result && !thd->killed) {
LogErr(ERROR_LEVEL, ER_LOG_CANNOT_WRITE_EXTENDED, "mysql.slow_log",
error_handler.message(), reason);
}
if (need_rnd_end) {
table->file->ha_rnd_end();
table->file->ha_release_auto_increment();
}
if (need_close) close_log_table(thd, &open_tables_backup);
thd->time_zone_used = save_time_zone_used;
return result;
}
bool Log_to_csv_event_handler::activate_log(
THD *thd, enum_log_table_type log_table_type) {
DBUG_TRACE;
const char *log_name = nullptr;
size_t log_name_length = 0;
switch (log_table_type) {
case QUERY_LOG_GENERAL:
log_name = GENERAL_LOG_NAME.str;
log_name_length = GENERAL_LOG_NAME.length;
break;
case QUERY_LOG_SLOW:
log_name = SLOW_LOG_NAME.str;
log_name_length = SLOW_LOG_NAME.length;
break;
default:
DBUG_ASSERT(false);
}
TABLE_LIST table_list(MYSQL_SCHEMA_NAME.str, MYSQL_SCHEMA_NAME.length,
log_name, log_name_length, log_name,
TL_WRITE_CONCURRENT_INSERT);
Open_tables_backup open_tables_backup;
if (open_log_table(thd, &table_list, &open_tables_backup) != nullptr) {
close_log_table(thd, &open_tables_backup);
return false;
}
return true;
}
/**
Class responsible for file based logging.
Basically a wrapper around File_query_log.
*/
class Log_to_file_event_handler : public Log_event_handler {
File_query_log mysql_general_log;
File_query_log mysql_slow_log;
public:
/**
Wrapper around File_query_log::write_slow() for slow log.
@see Log_event_handler::log_slow().
*/
bool log_slow(THD *thd, ulonglong current_utime, ulonglong query_start_arg,
const char *user_host, size_t user_host_len,
ulonglong query_utime, ulonglong lock_utime, bool is_command,
const char *sql_text, size_t sql_text_len,
struct System_status_var *query_start_status) override;
/**
Wrapper around File_query_log::write_general() for general log.
@see Log_event_handler::log_general().
*/
bool log_general(THD *thd, ulonglong event_utime, const char *user_host,
size_t user_host_len, my_thread_id thread_id,
const char *command_type, size_t command_type_len,
const char *sql_text, size_t sql_text_len,
const CHARSET_INFO *client_cs) override;
private:
Log_to_file_event_handler()
: mysql_general_log(QUERY_LOG_GENERAL), mysql_slow_log(QUERY_LOG_SLOW) {}
/** Close slow and general log files. */
void cleanup() {
mysql_general_log.close();
mysql_slow_log.close();
}
/** @return File_query_log instance responsible for writing to slow/general
* log.*/
File_query_log *get_query_log(enum_log_table_type log_type) {
if (log_type == QUERY_LOG_SLOW) return &mysql_slow_log;
DBUG_ASSERT(log_type == QUERY_LOG_GENERAL);
return &mysql_general_log;
}
friend class Query_logger;
};
bool Log_to_file_event_handler::log_slow(
THD *thd, ulonglong current_utime, ulonglong query_start_utime,
const char *user_host, size_t user_host_len, ulonglong query_utime,
ulonglong lock_utime, bool is_command, const char *sql_text,
size_t sql_text_len, struct System_status_var *query_start_status) {
if (!mysql_slow_log.is_open()) return false;
Silence_log_table_errors error_handler;
thd->push_internal_handler(&error_handler);
bool retval = mysql_slow_log.write_slow(thd, current_utime, query_start_utime,
user_host, user_host_len, query_utime,
lock_utime, is_command, sql_text,
sql_text_len, query_start_status);
thd->pop_internal_handler();
return retval;
}
bool Log_to_file_event_handler::log_general(
THD *thd, ulonglong event_utime, const char *, size_t,
my_thread_id thread_id, const char *command_type, size_t command_type_len,
const char *sql_text, size_t sql_text_len, const CHARSET_INFO *) {
if (!mysql_general_log.is_open()) return false;
Silence_log_table_errors error_handler;
thd->push_internal_handler(&error_handler);
bool retval =
mysql_general_log.write_general(event_utime, thread_id, command_type,
command_type_len, sql_text, sql_text_len);
thd->pop_internal_handler();
return retval;
}
bool Query_logger::is_log_table_enabled(enum_log_table_type log_type) const {
if (log_type == QUERY_LOG_SLOW)
return (opt_slow_log && (log_output_options & LOG_TABLE));
else if (log_type == QUERY_LOG_GENERAL)
return (opt_general_log && (log_output_options & LOG_TABLE));
DBUG_ASSERT(false);
return false; /* make compiler happy */
}
void Query_logger::init() {
file_log_handler = new Log_to_file_event_handler; // Causes mutex init
mysql_rwlock_init(key_rwlock_LOCK_logger, &LOCK_logger);
}
void Query_logger::cleanup() {
mysql_rwlock_destroy(&LOCK_logger);
DBUG_ASSERT(file_log_handler);
file_log_handler->cleanup();
delete file_log_handler;
file_log_handler = nullptr;
}
bool Query_logger::slow_log_write(
THD *thd, const char *query, size_t query_length,
struct System_status_var *query_start_status) {
DBUG_ASSERT(thd->enable_slow_log && opt_slow_log);
if (!(*slow_log_handler_list)) return false;
/* do not log slow queries from replication threads */
if (thd->slave_thread && !opt_log_slow_slave_statements) return false;
/* fill in user_host value: the format is "%s[%s] @ %s [%s]" */
char user_host_buff[MAX_USER_HOST_SIZE + 1];
Security_context *sctx = thd->security_context();
LEX_CSTRING sctx_user = sctx->user();
LEX_CSTRING sctx_host = sctx->host();
LEX_CSTRING sctx_ip = sctx->ip();
size_t user_host_len =
(strxnmov(user_host_buff, MAX_USER_HOST_SIZE, sctx->priv_user().str, "[",
sctx_user.length ? sctx_user.str : "", "] @ ",
sctx_host.length ? sctx_host.str : "", " [",
sctx_ip.length ? sctx_ip.str : "", "]", NullS) -
user_host_buff);
ulonglong current_utime = my_micro_time();
ulonglong query_utime, lock_utime;
if (thd->start_utime) {
query_utime = (current_utime - thd->start_utime);
lock_utime = (thd->utime_after_lock - thd->start_utime);
} else {
query_utime = 0;
lock_utime = 0;
}
bool is_command = false;
if (!query) {
is_command = true;
query = command_name[thd->get_command()].str;
query_length = command_name[thd->get_command()].length;
}
mysql_rwlock_rdlock(&LOCK_logger);
bool error = false;
for (Log_event_handler **current_handler = slow_log_handler_list;
*current_handler;) {
error |=
(*current_handler++)
->log_slow(
thd, current_utime,
(thd->start_time.tv_sec * 1000000ULL) + thd->start_time.tv_usec,
user_host_buff, user_host_len, query_utime, lock_utime,
is_command, query, query_length, query_start_status);
}
mysql_rwlock_unlock(&LOCK_logger);
return error;
}
/**
Check if a given command should be logged to the general log.
@param thd Thread handle
@param command SQL command
@return true if command should be logged, false otherwise.
*/
static bool log_command(THD *thd, enum_server_command command) {
if (what_to_log & (1L << (uint)command)) {
Security_context *sctx = thd->security_context();
if ((thd->variables.option_bits & OPTION_LOG_OFF) &&
(sctx->check_access(SUPER_ACL) ||
sctx->has_global_grant(STRING_WITH_LEN("CONNECTION_ADMIN")).first)) {
/* No logging */
return false;
}
return true;
}
return false;
}
bool Query_logger::general_log_write(THD *thd, enum_server_command command,
const char *query, size_t query_length) {
/* Send a general log message to the audit API. */
mysql_audit_general_log(thd, command_name[(uint)command].str,
command_name[(uint)command].length);
/*
Do we want to log this kind of command?
Is general log enabled?
Any active handlers?
*/
if (!log_command(thd, command) || !opt_general_log ||
!(*general_log_handler_list))
return false;
char user_host_buff[MAX_USER_HOST_SIZE + 1];
size_t user_host_len =
make_user_name(thd->security_context(), user_host_buff);
ulonglong current_utime = my_micro_time();
mysql_rwlock_rdlock(&LOCK_logger);
bool error = false;
for (Log_event_handler **current_handler = general_log_handler_list;
*current_handler;) {
error |=
(*current_handler++)
->log_general(thd, current_utime, user_host_buff, user_host_len,
thd->thread_id(), command_name[(uint)command].str,
command_name[(uint)command].length, query,
query_length, thd->variables.character_set_client);
}
mysql_rwlock_unlock(&LOCK_logger);
return error;
}
bool Query_logger::general_log_print(THD *thd, enum_server_command command,
const char *format, ...) {
/*
Do we want to log this kind of command?
Is general log enabled?
Any active handlers?
*/
if (!log_command(thd, command) || !opt_general_log ||
!(*general_log_handler_list)) {
/* Send a general log message to the audit API. */
mysql_audit_general_log(thd, command_name[(uint)command].str,
command_name[(uint)command].length);
return false;
}
size_t message_buff_len = 0;
char message_buff[LOG_BUFF_MAX];
/* prepare message */
if (format) {
va_list args;
va_start(args, format);
message_buff_len =
vsnprintf(message_buff, sizeof(message_buff), format, args);
va_end(args);
message_buff_len = std::min(message_buff_len, sizeof(message_buff) - 1);
} else
message_buff[0] = '\0';
return general_log_write(thd, command, message_buff, message_buff_len);
}
void Query_logger::init_query_log(enum_log_table_type log_type,
ulonglong log_printer) {
if (log_type == QUERY_LOG_SLOW) {
if (log_printer & LOG_NONE) {
slow_log_handler_list[0] = nullptr;
return;
}
switch (log_printer) {
case LOG_FILE:
slow_log_handler_list[0] = file_log_handler;
slow_log_handler_list[1] = nullptr;
break;
case LOG_TABLE:
slow_log_handler_list[0] = &table_log_handler;
slow_log_handler_list[1] = nullptr;
break;
case LOG_TABLE | LOG_FILE:
slow_log_handler_list[0] = file_log_handler;
slow_log_handler_list[1] = &table_log_handler;
slow_log_handler_list[2] = nullptr;
break;
}
} else if (log_type == QUERY_LOG_GENERAL) {
if (log_printer & LOG_NONE) {
general_log_handler_list[0] = nullptr;
return;
}
switch (log_printer) {
case LOG_FILE:
general_log_handler_list[0] = file_log_handler;
general_log_handler_list[1] = nullptr;
break;
case LOG_TABLE:
general_log_handler_list[0] = &table_log_handler;
general_log_handler_list[1] = nullptr;
break;
case LOG_TABLE | LOG_FILE:
general_log_handler_list[0] = file_log_handler;
general_log_handler_list[1] = &table_log_handler;
general_log_handler_list[2] = nullptr;
break;
}
} else
DBUG_ASSERT(false);
}
void Query_logger::set_handlers(ulonglong log_printer) {
mysql_rwlock_wrlock(&LOCK_logger);
init_query_log(QUERY_LOG_SLOW, log_printer);
init_query_log(QUERY_LOG_GENERAL, log_printer);
mysql_rwlock_unlock(&LOCK_logger);
}
bool Query_logger::activate_log_handler(THD *thd,
enum_log_table_type log_type) {
bool res = false;
mysql_rwlock_wrlock(&LOCK_logger);
if (table_log_handler.activate_log(thd, log_type) ||
file_log_handler->get_query_log(log_type)->open())
res = true;
else
init_query_log(log_type, log_output_options);
mysql_rwlock_unlock(&LOCK_logger);
return res;
}
void Query_logger::deactivate_log_handler(enum_log_table_type log_type) {
mysql_rwlock_wrlock(&LOCK_logger);
file_log_handler->get_query_log(log_type)->close();
// table_list_handler has no state, nothing to close
mysql_rwlock_unlock(&LOCK_logger);
}
bool Query_logger::set_log_file(enum_log_table_type log_type) {
const char *log_name = nullptr;
mysql_rwlock_wrlock(&LOCK_logger);
DEBUG_SYNC(current_thd, "log_set_file_holds_lock");
if (log_type == QUERY_LOG_SLOW)
log_name = opt_slow_logname;
else if (log_type == QUERY_LOG_GENERAL)
log_name = opt_general_logname;
else
DBUG_ASSERT(false);
bool res = file_log_handler->get_query_log(log_type)->set_file(log_name);
mysql_rwlock_unlock(&LOCK_logger);
return res;
}
bool Query_logger::reopen_log_file(enum_log_table_type log_type) {
mysql_rwlock_wrlock(&LOCK_logger);
file_log_handler->get_query_log(log_type)->close();
bool res = file_log_handler->get_query_log(log_type)->open();
mysql_rwlock_unlock(&LOCK_logger);
return res;
}
enum_log_table_type Query_logger::check_if_log_table(
TABLE_LIST *table_list, bool check_if_opened) const {
if (table_list->db_length == MYSQL_SCHEMA_NAME.length &&
!my_strcasecmp(system_charset_info, table_list->db,
MYSQL_SCHEMA_NAME.str)) {
if (table_list->table_name_length == GENERAL_LOG_NAME.length &&
!my_strcasecmp(system_charset_info, table_list->table_name,
GENERAL_LOG_NAME.str)) {
if (!check_if_opened || is_log_table_enabled(QUERY_LOG_GENERAL))
return QUERY_LOG_GENERAL;
return QUERY_LOG_NONE;
}
if (table_list->table_name_length == SLOW_LOG_NAME.length &&
!my_strcasecmp(system_charset_info, table_list->table_name,
SLOW_LOG_NAME.str)) {
if (!check_if_opened || is_log_table_enabled(QUERY_LOG_SLOW))
return QUERY_LOG_SLOW;
return QUERY_LOG_NONE;
}
}
return QUERY_LOG_NONE;
}
bool Query_logger::is_log_file_enabled(enum_log_table_type log_type) const {
return file_log_handler->get_query_log(log_type)->is_open();
}
Query_logger query_logger;
char *make_query_log_name(char *buff, enum_log_table_type log_type) {
const char *log_ext = "";
if (log_type == QUERY_LOG_GENERAL)
log_ext = ".log";
else if (log_type == QUERY_LOG_SLOW)
log_ext = "-slow.log";
else
DBUG_ASSERT(false);
strmake(buff, default_logfile_name, FN_REFLEN - 5);
return fn_format(buff, buff, mysql_real_data_home, log_ext,
MYF(MY_UNPACK_FILENAME | MY_REPLACE_EXT));
}
bool log_slow_applicable(THD *thd) {
DBUG_TRACE;
/*
The following should never be true with our current code base,
but better to keep this here so we don't accidently try to log a
statement in a trigger or stored function
*/
if (unlikely(thd->in_sub_stmt)) return false; // Don't set time for sub stmt
/*
Do not log administrative statements unless the appropriate option is
set.
*/
if (thd->enable_slow_log && opt_slow_log) {
bool warn_no_index =
((thd->server_status &
(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
opt_log_queries_not_using_indexes &&
!(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND));
bool log_this_query =
((thd->server_status & SERVER_QUERY_WAS_SLOW) || warn_no_index) &&
(thd->get_examined_row_count() >=
thd->variables.min_examined_row_limit);
bool suppress_logging = log_throttle_qni.log(thd, warn_no_index);
if (!suppress_logging && log_this_query) return true;
}
return false;
}
/**
Unconditionally writes the current statement (or its rewritten version if it
exists) to the slow query log.
@param thd thread handle
@param query_start_status Pointer to a snapshot of thd->status_var taken
at the start of execution
*/
void log_slow_do(THD *thd, struct System_status_var *query_start_status) {
THD_STAGE_INFO(thd, stage_logging_slow_query);
thd->status_var.long_query_count++;
if (thd->rewritten_query().length())
query_logger.slow_log_write(thd, thd->rewritten_query().ptr(),
thd->rewritten_query().length(),
query_start_status);
else
query_logger.slow_log_write(thd, thd->query().str, thd->query().length,
query_start_status);
}
/**
Check whether we need to write the current statement to the slow query
log. If so, do so. This is a wrapper for the two functions above;
most callers should use this wrapper. Only use the above functions
directly if you have expensive rewriting that you only need to do if
the query actually needs to be logged (e.g. SP variables / NAME_CONST
substitution when executing a PROCEDURE).
A digest of suppressed statements may be logged instead of the current
statement.
@param thd thread handle
@param query_start_status Pointer to a snapshot of thd->status_var taken
at the start of execution
*/
void log_slow_statement(THD *thd,
struct System_status_var *query_start_status) {
if (log_slow_applicable(thd)) log_slow_do(thd, query_start_status);
}
void Log_throttle::new_window(ulonglong now) {
count = 0;
window_end = now + window_size;
}
void Slow_log_throttle::new_window(ulonglong now) {
Log_throttle::new_window(now);
total_exec_time = 0;
total_lock_time = 0;
}
Slow_log_throttle::Slow_log_throttle(ulong *threshold, mysql_mutex_t *lock,
ulong window_usecs,
bool (*logger)(THD *, const char *, size_t,
struct System_status_var *),
const char *msg)
: Log_throttle(window_usecs, msg),
total_exec_time(0),
total_lock_time(0),
rate(threshold),
log_summary(logger),
LOCK_log_throttle(lock) {}
ulong Log_throttle::prepare_summary(ulong rate) {
ulong ret = 0;
/*
Previous throttling window is over or rate changed.
Return the number of lines we throttled.
*/
if (count > rate) {
ret = count - rate;
count = 0; // prevent writing it again.
}
return ret;
}
void Slow_log_throttle::print_summary(THD *thd, ulong suppressed,
ulonglong print_lock_time,
ulonglong print_exec_time) {
/*
We synthesize these values so the totals in the log will be
correct (just in case somebody analyses them), even if the
start/stop times won't be (as they're an aggregate which will
usually mostly lie within [ window_end - window_size ; window_end ]
*/
ulonglong save_start_utime = thd->start_utime;
ulonglong save_utime_after_lock = thd->utime_after_lock;
Security_context *save_sctx = thd->security_context();
char buf[128];
snprintf(buf, sizeof(buf), summary_template, suppressed);
mysql_mutex_lock(&thd->LOCK_thd_data);
thd->start_utime = my_micro_time() - print_exec_time;
thd->utime_after_lock = thd->start_utime + print_lock_time;
thd->set_security_context(&aggregate_sctx);
mysql_mutex_unlock(&thd->LOCK_thd_data);
(*log_summary)(thd, buf, strlen(buf), nullptr); /* purecov: inspected */
mysql_mutex_lock(&thd->LOCK_thd_data);
thd->set_security_context(save_sctx);
thd->start_utime = save_start_utime;
thd->utime_after_lock = save_utime_after_lock;
mysql_mutex_unlock(&thd->LOCK_thd_data);
}
bool Slow_log_throttle::flush(THD *thd) {
// Write summary if we throttled.
mysql_mutex_lock(LOCK_log_throttle);
ulonglong print_lock_time = total_lock_time;
ulonglong print_exec_time = total_exec_time;
ulong suppressed_count = prepare_summary(*rate);
mysql_mutex_unlock(LOCK_log_throttle);
if (suppressed_count > 0) {
print_summary(thd, suppressed_count, print_lock_time, print_exec_time);
return true;
}
return false;
}
bool Slow_log_throttle::log(THD *thd, bool eligible) {
bool suppress_current = false;
/*
If throttling is enabled, we might have to write a summary even if
the current query is not of the type we handle.
*/
if (*rate > 0) {
mysql_mutex_lock(LOCK_log_throttle);
ulong suppressed_count = 0;
ulonglong print_lock_time = total_lock_time;
ulonglong print_exec_time = total_exec_time;
ulonglong end_utime_of_query = my_micro_time();
/*
If the window has expired, we'll try to write a summary line.
The subroutine will know whether we actually need to.
*/
if (!in_window(end_utime_of_query)) {
suppressed_count = prepare_summary(*rate);
// start new window only if this is the statement type we handle
if (eligible) new_window(end_utime_of_query);
}
if (eligible && inc_log_count(*rate)) {
/*
Current query's logging should be suppressed.
Add its execution time and lock time to totals for the current window.
*/
total_exec_time += (end_utime_of_query - thd->start_utime);
total_lock_time += (thd->utime_after_lock - thd->start_utime);
suppress_current = true;
}
mysql_mutex_unlock(LOCK_log_throttle);
/*
print_summary() is deferred until after we release the locks to
avoid congestion. All variables we hand in are local to the caller,
so things would even be safe if print_summary() hadn't finished by the
time the next one comes around (60s later at the earliest for now).
The current design will produce correct data, but does not guarantee
order (there is a theoretical race condition here where the above
new_window()/unlock() may enable a different thread to print a warning
for the new window before the current thread gets to print_summary().
If the requirements ever change, add a print_lock to the object that
is held during print_summary(), AND that is briefly locked before
returning from this function if(eligible && !suppress_current).
This should ensure correct ordering of summaries with regard to any
follow-up summaries as well as to any (non-suppressed) warnings (of
the type we handle) from the next window.
*/
if (suppressed_count > 0)
print_summary(thd, suppressed_count, print_lock_time, print_exec_time);
}
return suppress_current;
}
bool Error_log_throttle::log() {
ulonglong end_utime_of_query = my_micro_time();
DBUG_EXECUTE_IF(
"simulate_error_throttle_expiry",
end_utime_of_query += Log_throttle::LOG_THROTTLE_WINDOW_SIZE;);
/*
If the window has expired, we'll try to write a summary line.
The subroutine will know whether we actually need to.
*/
if (!in_window(end_utime_of_query)) {
ulong suppressed_count = prepare_summary(1);
new_window(end_utime_of_query);
if (suppressed_count > 0) print_summary(suppressed_count);
}
/*
If this is a first error in the current window then do not suppress it.
*/
return inc_log_count(1);
}
bool Error_log_throttle::flush() {
// Write summary if we throttled.
ulong suppressed_count = prepare_summary(1);
if (suppressed_count > 0) {
print_summary(suppressed_count);
return true;
}
return false;
}
static bool slow_log_write(THD *thd, /* purecov: inspected */
const char *query, size_t query_length,
struct System_status_var *query_start_status) {
return opt_slow_log && /* purecov: inspected */
query_logger /* purecov: inspected */
.slow_log_write( /* purecov: inspected */
thd, query, query_length, /* purecov: inspected */
query_start_status); /* purecov: inspected */
}
Slow_log_throttle log_throttle_qni(&opt_log_throttle_queries_not_using_indexes,
&LOCK_log_throttle_qni,
Log_throttle::LOG_THROTTLE_WINDOW_SIZE,
slow_log_write,
"throttle: %10lu 'index "
"not used' warning(s) suppressed.");
////////////////////////////////////////////////////////////
//
// Error Log
//
////////////////////////////////////////////////////////////
static bool error_log_initialized = false;
// This mutex prevents fprintf from different threads from being interleaved.
// It also prevents reopen while we are in the process of logging.
static mysql_mutex_t LOCK_error_log;
// This variable is different from log_error_dest.
// E.g. log_error_dest is "stderr" if we are not logging to file.
static const char *error_log_file = nullptr;
void discard_error_log_messages() {
log_sink_buffer_flush(LOG_BUFFER_DISCARD_ONLY);
}
void flush_error_log_messages() {
log_sink_buffer_flush(LOG_BUFFER_PROCESS_AND_DISCARD);
}
bool init_error_log() {
DBUG_ASSERT(!error_log_initialized);
mysql_mutex_init(key_LOCK_error_log, &LOCK_error_log, MY_MUTEX_INIT_FAST);
/*
ready the default filter/sink so they'll be available before/without
the component system
*/
error_log_initialized = true;
if (log_builtins_init() < 0) {
log_write_errstream(
STRING_WITH_LEN("failed to initialize basic error logging"));
return true;
} else
return false;
}
bool open_error_log(const char *filename, bool get_lock) {
DBUG_ASSERT(filename);
int retries = 2, errors = 0;
MY_STAT f_stat;
/**
Make sure, file is writable if it exists. If file does not exists
then make sure directory path exists and it is writable.
*/
if (my_stat(filename, &f_stat, MYF(0))) {
if (my_access(filename, W_OK)) {
goto fail;
}
} else {
char path[FN_REFLEN];
size_t path_length;
dirname_part(path, filename, &path_length);
if (path_length && my_access(path, (F_OK | W_OK))) goto fail;
}
do {
errors = 0;
if (!my_freopen(filename, "a", stderr)) errors++;
if (!my_freopen(filename, "a", stdout)) errors++;
} while (retries-- && errors);
if (errors) goto fail;
/* The error stream must be unbuffered. */
setbuf(stderr, nullptr);
error_log_file = filename; // Remember name for later reopen
return false;
fail : {
char errbuf[MYSYS_STRERROR_SIZE];
if (get_lock) mysql_mutex_unlock(&LOCK_error_log);
LogErr(ERROR_LEVEL, ER_CANT_OPEN_ERROR_LOG, filename, ": ",
my_strerror(errbuf, sizeof(errbuf), errno));
flush_error_log_messages();
if (get_lock) mysql_mutex_lock(&LOCK_error_log);
}
return true;
}
void destroy_error_log() {
// We should have flushed before this...
// ... but play it safe on release builds
flush_error_log_messages();
if (error_log_initialized) {
error_log_initialized = false;
error_log_file = nullptr;
mysql_mutex_destroy(&LOCK_error_log);
log_builtins_exit();
}
}
bool reopen_error_log() {
bool result = false;
DBUG_ASSERT(error_log_initialized);
// reload all error logging services
log_builtins_error_stack_flush();
if (error_log_file) {
mysql_mutex_lock(&LOCK_error_log);
result = open_error_log(error_log_file, true);
mysql_mutex_unlock(&LOCK_error_log);
if (result)
my_error(ER_DA_CANT_OPEN_ERROR_LOG, MYF(0), error_log_file, ".",
""); /* purecov: inspected */
}
return result;
}
void log_write_errstream(const char *buffer, size_t length) {
DBUG_TRACE;
DBUG_PRINT("enter", ("buffer: %s", buffer));
/*
This must work even if the mutex has not been initialized yet.
At that point we should still be single threaded so that it is
safe to write without mutex.
*/
if (error_log_initialized) mysql_mutex_lock(&LOCK_error_log);
fprintf(stderr, "%.*s\n", (int)length, buffer);
fflush(stderr);
if (error_log_initialized) mysql_mutex_unlock(&LOCK_error_log);
}
my_thread_id log_get_thread_id(THD *thd) { return thd->thread_id(); }
/**
Variadic convenience function for logging.
This fills in the array that is used by the filter and log-writer services.
Where missing, timestamp, priority, and thread-ID (if any) are added.
Log item source services, log item filters, and log item writers are called.
For convenience, any number of fields may be added:
- "well-known" field types require a type tag and the payload:
LOG_ITEM_LOG_LABEL, "ohai"
- "generic" field types require a type tag, a key (C-string),
and the payload:
LOG_ITEM_GEN_FLOAT, "myPi", 3.1415926927
Newer items (further to the right/bottom) overwrite older ones (further
to the left/top).
If a message is given, it must be the last tag in the argument list.
The message may be given verbatim as a C format string, followed by
its arguments:
LOG_ITEM_LOG_MESSAGE, "format string %s %d abc", "arg1", 12345
To avoid substitutions, use
LOG_ITEM_LOG_VERBATIM, "message from other subsys containing %user input"
Alternatively, an error code may be specified -- the corresponding error
message will be looked up and inserted --, followed by any arguments
required by the error message:
LOG_ITEM_LOG_LOOKUP, ER_CANT_SET_DATA_DIR, filename, errno, strerror(errno)
If no message is to be included (this should never be the case for the
erorr log), LOG_ITEM_END may be used instead to terminate the list.
@param log_type what log should this go to?
@param fili field list:
LOG_ITEM_* tag, [[key], value]
@retval int return value of log_line_submit()
*/
int log_vmessage(int log_type MY_ATTRIBUTE((unused)), va_list fili) {
char buff[LOG_BUFF_MAX];
log_item_class lic;
log_line ll;
bool dedup;
int wk;
DBUG_TRACE;
ll.count = 0;
ll.seen = 0;
do {
dedup = false;
log_line_item_init(&ll);
ll.item[ll.count].type = (log_item_type)va_arg(fili, int);
if (ll.item[ll.count].type == LOG_ITEM_END) break;
if ((wk = log_item_wellknown_by_type(ll.item[ll.count].type)) < 0)
lic = LOG_UNTYPED;
else
lic = log_item_wellknown_get_class(wk);
ll.item[ll.count].item_class = lic;
// if it's not a well-known item, read the key name from va_list
if (log_item_generic_type(ll.item[ll.count].type))
ll.item[ll.count].key = va_arg(fili, char *);
else if (wk >= 0)
ll.item[ll.count].key = log_item_wellknown_get_name(wk);
else {
ll.item[ll.count].key = "???";
DBUG_ASSERT(false);
}
// if we've already got one of this type, de-duplicate later
if ((ll.seen & ll.item[ll.count].type) ||
log_item_generic_type(ll.item[ll.count].type))
dedup = true;
// read the payload
switch (lic) {
case LOG_LEX_STRING:
ll.item[ll.count].data.data_string.str = va_arg(fili, char *);
ll.item[ll.count].data.data_string.length = va_arg(fili, size_t);
if (ll.item[ll.count].data.data_string.str == nullptr) continue;
break;
case LOG_CSTRING: {
char *p = va_arg(fili, char *);
if (p == nullptr) continue;
ll.item[ll.count].data.data_string.str = p;
ll.item[ll.count].data.data_string.length = strlen(p);
ll.item[ll.count].item_class = LOG_LEX_STRING;
} break;
case LOG_INTEGER:
ll.item[ll.count].data.data_integer = va_arg(fili, longlong);
break;
case LOG_FLOAT:
ll.item[ll.count].data.data_float = va_arg(fili, double);
break;
default:
log_message(LOG_TYPE_ERROR, LOG_ITEM_LOG_MESSAGE,
"log_vmessage: unknown class %d/%d for type %d", (int)lic,
(int)ll.item[ll.count].item_class,
(int)ll.item[ll.count].type);
log_message(LOG_TYPE_ERROR, LOG_ITEM_LOG_MESSAGE,
"log_vmessage: seen: 0x%lx. "
"trying to dump preceding %d item(s)",
(long)ll.seen, (int)ll.count);
{
int i = 0;
while (i < ll.count) {
if (ll.item[i].item_class == LOG_INTEGER)
log_message(LOG_TYPE_ERROR, LOG_ITEM_LOG_MESSAGE,
"log_vmessage: \"%s\": %lld", ll.item[i].key,
(long long)ll.item[ll.count].data.data_integer);
else if (ll.item[i].item_class == LOG_FLOAT)
log_message(LOG_TYPE_ERROR, LOG_ITEM_LOG_MESSAGE,
"log_vmessage: \"%s\": %lf", ll.item[i].key,
(double)ll.item[ll.count].data.data_float);
else if (ll.item[i].item_class == LOG_LEX_STRING)
log_message(LOG_TYPE_ERROR, LOG_ITEM_LOG_MESSAGE,
"log_vmessage: \"%s\": \"%.*s\"", ll.item[i].key,
ll.item[ll.count].data.data_string.length,
ll.item[ll.count].data.data_string.str == nullptr
? ""
: ll.item[ll.count].data.data_string.str);
i++;
}
}
va_end(fili);
/*
Bail. As the input is clearly badly broken, we don't dare try
to free anything here.
*/
DBUG_ASSERT(false);
return -1;
}
/*
errno is only of interest if unequal 0.
*/
if ((ll.item[ll.count].type == LOG_ITEM_SYS_ERRNO) &&
(ll.item[ll.count].data.data_integer == 0))
continue;
/*
MySQL error can be set numerically or symbolically, so they need to
reset each other. Submitting both is a really strange idea, mind.
*/
const log_item_type_mask errcode_mask =
LOG_ITEM_SQL_ERRSYMBOL | LOG_ITEM_SQL_ERRCODE;
if ((ll.item[ll.count].type & errcode_mask) && (ll.seen & errcode_mask)) {
size_t dd = ll.count;
while (dd > 0) {
dd--;
if ((ll.item[dd].type & errcode_mask) != 0) {
log_line_item_free(&ll, dd);
dedup = false;
ll.item[dd] = ll.item[ll.count];
ll.count--;
}
}
}
/*
For well-known messages, we replace the error code with the
error message (and adjust the metadata accordingly).
*/
if (ll.item[ll.count].type == LOG_ITEM_LOG_LOOKUP) {
size_t ec = ll.item[ll.count].data.data_integer;
const char *msg = error_message_for_error_log(ec),
*key = log_item_wellknown_get_name(
log_item_wellknown_by_type(LOG_ITEM_LOG_MESSAGE));
if ((msg == nullptr) || (*msg == '\0')) msg = "invalid error code";
ll.item[ll.count].type = LOG_ITEM_LOG_MESSAGE;
ll.item[ll.count].item_class = LOG_LEX_STRING;
ll.item[ll.count].data.data_string.str = msg;
ll.item[ll.count].data.data_string.length = strlen(msg);
ll.item[ll.count].key = key;
/*
If no errcode and no errsymbol were set, errcode is set from
the one used for the message (they should be the same, anyway).
Whichever items are still missing at the point will be added
below.
*/
if (!(ll.seen & LOG_ITEM_SQL_ERRCODE) &&
!(ll.seen & LOG_ITEM_SQL_ERRSYMBOL) && !log_line_full(&ll)) {
// push up message so it remains the last item
ll.item[ll.count + 1] = ll.item[ll.count];
log_line_item_set(&ll, LOG_ITEM_SQL_ERRCODE)->data_integer = ec;
}
/*
Currently, this can't happen (as LOG_ITEM_LOG_MESSAGE ends
the loop), but this may change later.
*/
if (ll.seen & ll.item[ll.count].type) dedup = true;
}
// message is a format string optionally followed by args
if (ll.item[ll.count].type == LOG_ITEM_LOG_MESSAGE) {
size_t msg_len = vsnprintf(buff, sizeof(buff),
ll.item[ll.count].data.data_string.str, fili);
if (msg_len > (sizeof(buff) - 1)) msg_len = sizeof(buff) - 1;
buff[sizeof(buff) - 1] = '\0';
ll.item[ll.count].data.data_string.str = buff;
ll.item[ll.count].data.data_string.length = msg_len;
} else if (ll.item[ll.count].type == LOG_ITEM_LOG_VERBATIM) {
int wellknown = log_item_wellknown_by_type(LOG_ITEM_LOG_MESSAGE);
ll.item[ll.count].key = log_item_wellknown_get_name(wellknown);
ll.item[ll.count].type = LOG_ITEM_LOG_MESSAGE;
ll.item[ll.count].item_class = LOG_LEX_STRING;
dedup = (ll.seen & ll.item[ll.count].type);
}
// element is given repeatedly; newer overwrites older
if (dedup) {
int dd = 0;
/*
Above, we only check whether an item of the same type already
exists. Generic types used repeatedly will only be deduped if
the key is the same, so there might be nothing to dedup here
after all. (To be clear howeer, generic items of different type
intentionally overwrite each other as long as the key is the
same. You can NOT have a generic integer and a generic string
both named "foo"!
*/
while ((dd < ll.count) &&
(log_item_generic_type(ll.item[ll.count].type)
? (native_strcasecmp(ll.item[dd].key,
ll.item[ll.count].key) != 0)
: (ll.item[dd].type != ll.item[ll.count].type)))
dd++;
// if it's a genuine duplicate, replace older with newer
if (dd < ll.count) {
log_line_item_free(&ll, dd);
ll.item[dd] = ll.item[ll.count];
ll.count--;
}
} else {
/*
Remember we've seen this item type. Not necessary above, even
if the potential dedup turned out to be unnecessary (same generic,
different key).
*/
ll.seen |= ll.item[ll.count].type;
}
ll.count++;
} while (!log_line_full(&ll) && !(ll.seen & LOG_ITEM_LOG_MESSAGE));
va_end(fili);
return log_line_submit(&ll);
}
/**
Prints a printf style message to the error log.
A thin wrapper around log_message() for local_message_hook,
Table_check_intact::report_error, and others.
@param level The level of the msg significance
@param ecode Error code of the error message.
@param args va_list list of arguments for the message
*/
void error_log_print(enum loglevel level, uint ecode, va_list args) {
DBUG_TRACE;
LogEvent()
.type(LOG_TYPE_ERROR)
.errcode(ecode)
.prio(level)
.messagev(EE(ecode), args);
}
/**
Variadic convenience function for logging.
This fills in the array that is used by the filter and log-writer services.
Where missing, timestamp, priority, and thread-ID (if any) are added.
Log item source services, log item filters, and log item writers are called.
see log_vmessage() for more information.
@param log_type what log should this go to?
@param ... fields: LOG_ITEM_* tag, [[key], value]
@retval int return value of log_vmessage()
*/
int log_message(int log_type, ...) {
va_list fili;
int ret;
va_start(fili, log_type);
ret = log_vmessage(log_type, fili);
va_end(fili);
return ret;
}
/*
For use by plugins that wish to write a message to the error log.
New plugins should use the service structure.
*/
int my_plugin_log_message(MYSQL_PLUGIN *plugin_ptr, plugin_log_level level,
const char *format, ...) {
char format2[LOG_BUFF_MAX];
char msg[LOG_BUFF_MAX];
loglevel lvl;
struct st_plugin_int *plugin = static_cast<st_plugin_int *>(*plugin_ptr);
va_list args;
DBUG_ASSERT(level >= MY_ERROR_LEVEL && level <= MY_INFORMATION_LEVEL);
switch (level) {
case MY_ERROR_LEVEL:
lvl = ERROR_LEVEL;
break;
case MY_WARNING_LEVEL:
lvl = WARNING_LEVEL;
break;
case MY_INFORMATION_LEVEL:
lvl = INFORMATION_LEVEL;
break;
default:
return 1;
}
snprintf(format2, sizeof(format2) - 1, "Plugin %.*s reported: '%s'",
(int)plugin->name.length, plugin->name.str, format);
va_start(args, format);
vsnprintf(msg, sizeof(msg) - 1, format2, args);
va_end(args);
LogEvent()
.type(LOG_TYPE_ERROR)
.prio(lvl)
/*
We're not setting LOG_ITEM_SRC_LINE and LOG_ITEM_SRC_FILE
here as we'd be interested in the location in the plugin,
not in the plugin interface, so rather than give confusing
or useless information, we give none. Plugins using the
richer (service) interface can use that to add such
information.
*/
.component(plugin->name.str)
.verbatim(msg);
return 0;
}
| 33.3496 | 80 | 0.658518 | [
"object"
] |
d71fc7c73c98a4f9630e9d20dca03faeca4c34f8 | 1,051 | cpp | C++ | nowcoder/0722/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | nowcoder/0722/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | nowcoder/0722/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define min(a,b) (a > b ? b : a)
using namespace std;
using LL = long long;
int queen[] = {1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712};
LL fib[100], x, m;
LL solve(LL x, int m, int n) {
LL ans = 0;
while(x) {
ans += x / m;
x /= m;
}
return ans / n;
}
int main() {
bool flag = 0;
fib[0] = fib[1] = 1;
for(int i = 2; i <= 11111111; ++i) {
if(fib[i - 1] + fib[i - 2] > 1e18)
break;
fib[i] = fib[i - 1] + fib[i - 2];
}
cin >> x >> m;
for(int i = 0; i < 90; ++i) {
if(fib[i] == x) {
flag = 1;
break;
}
}
if(flag == 0) {
printf("%d\n", queen[x % min(13, m)]);
}
else {
vector< pair<int, int> > div;
for(int i = 2; i * i <= m; ++i) {
if(m % i == 0)
div.push_back(make_pair(i, 0));
while(m % i == 0) {
div[div.size() - 1].second++;
m /= i;
}
}
if(m != 1)
div.push_back(make_pair(m, 1));
LL ans = 1e18;
for(int i = 0; i < div.size(); ++i) {
ans = min(ans, solve(x, div[i].first, div[i].second));
}
printf("%lld\n", ans);
}
return 0;
} | 18.438596 | 72 | 0.47098 | [
"vector"
] |
d720094fe4b785b5f54b618b8328b503adfc6c2c | 42,610 | cxx | C++ | inetcore/mshtml/src/site/base/elemlyt.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/mshtml/src/site/base/elemlyt.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/mshtml/src/site/base/elemlyt.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //==================================================================
//
// File : ElemLyt.cxx
//
// Contents : The CElement functions related to handling their layouts
//
//==================================================================
#include "headers.hxx"
#pragma MARK_DATA(__FILE__)
#pragma MARK_CODE(__FILE__)
#pragma MARK_CONST(__FILE__)
#ifndef X_ELEMENT_HXX_
#define X_ELEMENT_HXX_
#include "element.hxx"
#endif
#ifndef X_INPUTTXT_HXX_
#define X_INPUTTXT_HXX_
#include "inputtxt.hxx"
#endif
#ifndef X_FLOWLYT_HXX_
#define X_FLOWLYT_HXX_
#include "flowlyt.hxx"
#endif
#ifndef X_INPUTLYT_HXX_
#define X_INPUTLYT_HXX_
#include "inputlyt.hxx"
#endif
#ifndef X_CKBOXLYT_HXX_
#define X_CKBOXLYT_HXX_
#include "ckboxlyt.hxx"
#endif
#ifndef X_FSLYT_HXX_
#define X_FSLYT_HXX_
#include "fslyt.hxx"
#endif
#ifndef X_FRAMELYT_HXX_
#define X_FRAMELYT_HXX_
#include "framelyt.hxx"
#endif
#ifndef X_SELLYT_HXX_
#define X_SELLYT_HXX_
#include "sellyt.hxx"
#endif
#ifndef X_OLELYT_HXX_
#define X_OLELYT_HXX_
#include "olelyt.hxx"
#endif
#ifndef X_LTABLE_HXX_
#define X_LTABLE_HXX_
#include "ltable.hxx"
#endif
#ifndef X_LTROW_HXX_
#define X_LTROW_HXX_
#include "ltrow.hxx"
#endif
#ifndef X_LTCELL_HXX_
#define X_LTCELL_HXX_
#include "ltcell.hxx"
#endif
#ifndef X_BODYLYT_HXX_
#define X_BODYLYT_HXX_
#include "bodylyt.hxx"
#endif
#ifndef X_BTNLYT_HXX_
#define X_BTNLYT_HXX_
#include "btnlyt.hxx"
#endif
#ifndef X_TAREALYT_HXX_
#define X_TAREALYT_HXX_
#include "tarealyt.hxx"
#endif
#ifndef X_IMGLYT_HXX_
#define X_IMGLYT_HXX_
#include "imglyt.hxx"
#endif
#ifndef X_HRLYT_HXX_
#define X_HRLYT_HXX_
#include "hrlyt.hxx"
#endif
#ifndef X_HTMLLYT_HXX_
#define X_HTMLLYT_HXX_
#include "htmllyt.hxx"
#endif
#ifndef X_MARQLYT_HXX_
#define X_MARQLYT_HXX_
#include "marqlyt.hxx"
#endif
#ifndef X_CONTLYT_HXX_
#define X_CONTLYT_HXX_
#include "contlyt.hxx"
#endif
#ifndef X_IEXTAG_HXX_
#define X_IEXTAG_HXX_
#include "iextag.h"
#endif
#ifndef X_PEER_HXX_
#define X_PEER_HXX_
#include "peer.hxx"
#endif
#ifndef X_EVNTPRM_HXX_
#define X_EVNTPRM_HXX_
#include "evntprm.hxx"
#endif
ExternTag(tagNotifyPath);
DeclareTag(tagLayoutAry, "Layout: Layout Ary", "Trace CLayoutAry fns");
//+--------------------------------------------------------------------------------------
//+--------------------------------------------------------------------------------------
//
// General CElement Layout related functions
//
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//+-------------------------------------------------------------------------
//
// Method: GetLayoutFromFactory
//
// Synopsis: Creates the layout object to be associated with the current element
//
//--------------------------------------------------------------------------
HRESULT GetLayoutFromFactory(CElement * pElement, CLayoutContext *pLayoutContext, DWORD dwFlags, CLayout ** ppLayout)
{
CLayout * pLayout = NULL;
HRESULT hr = S_OK;
BOOL fCreateGenericLayout;
if (!ppLayout)
return E_POINTER;
*ppLayout = NULL;
#if DBG
if ( pLayoutContext )
{
AssertSz( pLayoutContext->IsValid(), "Context should have an owner at this point. Unowned contexts shouldn't be used to create layouts." );
// Contexts must be defined by either LAYOUTRECTs or DEVICERECTs. In the former case,
// the element that wants a layout in the context must be in a difference markup,
// in the latter, it must be in the same markup (the template).
Assert( ( pLayoutContext->GetLayoutOwner()->ElementOwner()->IsLinkedContentElement()
&& pLayoutContext->GetLayoutOwner()->GetOwnerMarkup() != pElement->GetMarkup() )
|| ( !FormsStringICmp(pLayoutContext->GetLayoutOwner()->ElementOwner()->TagName(), _T("DEVICERECT") )
&& pLayoutContext->GetLayoutOwner()->GetOwnerMarkup() == pElement->GetMarkup() ) );
}
#endif
if (!pElement || pElement->HasMasterPtr())
return E_INVALIDARG;
#ifdef TEMP_UNASSERT // temporarily removing this to help test. we should fix this situation in V4
Assert(!pElement->IsPassivating());
#endif
Assert(!pElement->IsPassivated());
Assert(!pElement->IsDestructing());
fCreateGenericLayout = pElement->HasSlavePtr();
// this is our basic LayoutFactory. It will match the appropriate default
// layout with the tag. the generic C1DLayout is used for tags which do not
// have their own specific layout.
switch (pElement->TagType())
{
case ETAG_INPUT:
{
switch (DYNCAST(CInput, pElement)->GetType())
{
case htmlInputButton:
case htmlInputReset:
case htmlInputSubmit:
Assert(fCreateGenericLayout);
fCreateGenericLayout = FALSE;
pLayout = new CInputButtonLayout(pElement, pLayoutContext);
break;
case htmlInputFile:
Assert(fCreateGenericLayout);
fCreateGenericLayout = FALSE;
pLayout = new CInputFileLayout(pElement, pLayoutContext);
break;
case htmlInputText:
case htmlInputPassword:
case htmlInputHidden:
Assert(fCreateGenericLayout);
fCreateGenericLayout = FALSE;
pLayout = new CInputTextLayout(pElement, pLayoutContext);
break;
case htmlInputCheckbox:
case htmlInputRadio:
if (!fCreateGenericLayout)
{
pLayout = new CCheckboxLayout(pElement, pLayoutContext);
}
break;
case htmlInputImage:
if (!fCreateGenericLayout)
{
pLayout = new CInputImageLayout(pElement, pLayoutContext);
}
break;
default:
AssertSz(FALSE, "Illegal Input Type");
}
}
break;
case ETAG_IMG:
if (!fCreateGenericLayout)
{
pLayout = new CImgElementLayout(pElement, pLayoutContext);
}
break;
case ETAG_HTML:
fCreateGenericLayout = FALSE;
pLayout = new CHtmlLayout(pElement, pLayoutContext);
break;
case ETAG_BODY:
fCreateGenericLayout = FALSE;
pLayout = new CBodyLayout(pElement, pLayoutContext);
break;
case ETAG_BUTTON:
fCreateGenericLayout = FALSE;
pLayout = new CButtonLayout(pElement, pLayoutContext);
break;
case ETAG_MARQUEE:
fCreateGenericLayout = FALSE;
pLayout = new CMarqueeLayout(pElement, pLayoutContext);
break;
case ETAG_TABLE:
if (pElement->HasLayoutAry())
{
// If this is a view chain case create block layout
pLayout = new CTableLayoutBlock(pElement, pLayoutContext);
}
else
{
pLayout = new CTableLayout(pElement, pLayoutContext);
}
break;
case ETAG_TD:
case ETAG_TC:
case ETAG_TH:
case ETAG_CAPTION:
fCreateGenericLayout = FALSE;
pLayout = new CTableCellLayout(pElement, pLayoutContext);
break;
case ETAG_TEXTAREA:
fCreateGenericLayout = FALSE;
pLayout = new CTextAreaLayout(pElement, pLayoutContext);
break;
case ETAG_TR:
if (pElement->HasLayoutAry())
{
pLayout = new CTableRowLayoutBlock(pElement, pLayoutContext);
}
else
{
pLayout = new CTableRowLayout(pElement, pLayoutContext);
}
break;
case ETAG_LEGEND:
fCreateGenericLayout = FALSE;
pLayout = new CLegendLayout(pElement, pLayoutContext);
break;
case ETAG_FIELDSET:
fCreateGenericLayout = FALSE;
pLayout = new CFieldSetLayout(pElement, pLayoutContext);
break;
case ETAG_SELECT:
pLayout = new CSelectLayout(pElement, pLayoutContext);
break;
case ETAG_HR:
pLayout = new CHRLayout(pElement, pLayoutContext);
break;
case ETAG_FRAMESET:
pLayout = new CFrameSetLayout(pElement, pLayoutContext);
break;
case ETAG_IFRAME:
case ETAG_FRAME:
fCreateGenericLayout = TRUE;
break;
case ETAG_OBJECT:
case ETAG_EMBED:
case ETAG_APPLET:
pLayout = new COleLayout(pElement, pLayoutContext);
break;
case ETAG_GENERIC:
if (pElement->IsLinkedContentElement())
{
fCreateGenericLayout = FALSE;
pLayout = new CContainerLayout(pElement, pLayoutContext);
}
else
{
fCreateGenericLayout = TRUE;
}
break;
default:
fCreateGenericLayout = TRUE;
break;
}
if (fCreateGenericLayout)
{
Assert(!pLayout);
pLayout = new C1DLayout(pElement, pLayoutContext);
if (pLayout)
{
pElement->_fOwnsRuns = TRUE;
}
}
if (!pLayout)
hr = E_OUTOFMEMORY;
else
{
pLayout->Init(); // For now, this can be called at creation time.
}
*ppLayout = pLayout;
RRETURN(hr);
}
CLayout *
CElement::CreateLayout( CLayoutContext * pLayoutContext )
{
CLayout * pLayout = NULL;
HRESULT hr;
Assert( ( pLayoutContext && !CurrentlyHasLayoutInContext( pLayoutContext ) )
|| ( !HasLayoutPtr() && !HasLayoutAry() ) );
// GetLayoutFromFactory is a static function in this file.
hr = THR(GetLayoutFromFactory(this, pLayoutContext, 0, &pLayout));
if( SUCCEEDED( hr ) )
{
Assert( pLayout );
if ( pLayoutContext )
{
CLayoutAry *pLA = EnsureLayoutAry();
Assert( pLA && pLA == _pLayoutAryDbg );
if ( !pLA )
{
return NULL;
}
Assert( pLayout->LayoutContext() == pLayoutContext );
pLA->AddLayoutWithContext( pLayout );
}
else
{
SetLayoutPtr(pLayout);
}
CPeerHolder * pPeerHolder = GetRenderPeerHolder();
if (pPeerHolder)
{
hr = THR(pPeerHolder->OnLayoutAvailable(pLayout));
}
}
return pLayout;
}
CFlowLayout *
CTreeNode::GetFlowLayout( CLayoutContext * pLayoutContext )
{
CTreeNode * pNode = this;
CFlowLayout * pFL;
while(pNode)
{
if (pNode->Element()->HasMasterPtr())
{
pNode = pNode->Element()->GetMasterIfSlave()->GetFirstBranch();
if (!pNode)
break;
}
pFL = pNode->HasFlowLayout( pLayoutContext );
if (pFL)
return pFL;
pNode = pNode->Parent();
}
return NULL;
}
CTreeNode *
CTreeNode::GetFlowLayoutNode( CLayoutContext * pLayoutContext )
{
CTreeNode * pNode = this;
while(pNode)
{
if (pNode->Element()->HasMasterPtr())
{
pNode = pNode->Element()->GetMasterIfSlave()->GetFirstBranch();
if (!pNode)
break;
}
if(pNode->HasFlowLayout( pLayoutContext ))
return pNode;
pNode = pNode->Parent();
}
return NULL;
}
// TODO (MohanB, KTam): why weren't the rest of the GetUpdated*Layout* fns changed to also
// climb out of the slave tree?
CTreeNode *
CTreeNode::GetUpdatedParentLayoutNode()
{
CTreeNode * pNode = this;
/*
Element()->HasMasterPtr() ?
Element()->GetMasterPtr()->GetFirstBranch() :
this;
*/
for(;;)
{
Assert(pNode);
if (pNode->Element()->HasMasterPtr())
{
pNode = pNode->Element()->GetMasterIfSlave()->GetFirstBranch();
}
else
{
pNode = pNode->Parent();
}
if (!pNode)
break;
if (pNode->ShouldHaveLayout())
return pNode;
}
return NULL;
}
//+----------------------------------------------------------------------------
//+----------------------------------------------------------------------------
//
// CLayoutAry implementation
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CLayoutAry::CLayoutAry( CElement *pElementOwner ) :
CLayoutInfo( pElementOwner )
{
_fHasMarkupPtr = FALSE;
// $$ktam: CLayoutAry doesn't have lookasides right now; if it ever does, we
// should assert a _pDocDbg->AreLookasidesClear() check here.
}
CLayoutAry::~CLayoutAry()
{
// Clean up all the CLayout's we're holding onto
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
for ( i=0 ; i < nLayouts ; ++i)
{
pLayout = _aryLE[i];
Assert( pLayout && "Layout array shouldn't have NULL entries!" );
pLayout->Detach();
pLayout->Release();
}
if (nLayouts)
{
_aryLE.DeleteMultiple(0, nLayouts-1);
}
__pvChain = NULL;
_fHasMarkupPtr = FALSE;
#if DBG == 1
_snLast = 0;
_pDocDbg = NULL;
_pMarkupDbg = NULL;
#endif
}
void
CLayoutAry::DelMarkupPtr()
{
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
for ( i = nLayouts-1 ; i >= 0 ; --i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
pLayout->DelMarkupPtr();
}
Assert(_fHasMarkupPtr);
Assert( _pMarkup == _pMarkupDbg);
WHEN_DBG(_pMarkupDbg = NULL );
// Delete out CMarkup *
_pDoc = _pMarkup->Doc();
_fHasMarkupPtr = FALSE;
}
void
CLayoutAry::SetMarkupPtr(CMarkup *pMarkup)
{
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
for ( i = nLayouts-1 ; i >= 0 ; --i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
pLayout->SetMarkupPtr(pMarkup);
}
Assert( !_fHasMarkupPtr );
Assert( pMarkup );
Assert( pMarkup->Doc() == _pDocDbg );
_pMarkup = pMarkup;
WHEN_DBG( _pMarkupDbg = pMarkup );
_fHasMarkupPtr = TRUE;
}
//+-------------------------------------------------------------------------
//
// Method: AddLayoutWithContext
//
//--------------------------------------------------------------------------
void
CLayoutAry::AddLayoutWithContext( CLayout *pLayout )
{
TraceTagEx((tagLayoutAry, TAG_NONAME,
"CLytAry::AddLayoutWithContext lyt=0x%x, lc=0x%x, e=[0x%x,%d] (%S)",
pLayout,
pLayout->LayoutContext(),
pLayout->ElementOwner(),
pLayout->ElementOwner()->SN(),
pLayout->ElementOwner()->TagName()));
AssertSz( pLayout->LayoutContext() && pLayout->LayoutContext()->IsValid(),
"Illegal to add a layout w/o valid context to a layout array!" );
#if DBG == 1
// Assert that a layout with the same context doesn't already exist in the array.
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayoutIter;
for ( i=0 ; i < nLayouts ; ++i)
{
pLayoutIter = _aryLE[i];
Assert( !(pLayoutIter->LayoutContext()->IsEqual( pLayout->LayoutContext() )) );
}
#endif
_aryLE.AppendIndirect( &pLayout );
// NOTE (KTam): There's general concern here that layouts should
// probably be ref-counted. Think about doing this.. they aren't
// CBase derived right now, so we have no current support for it.
Assert( ! pLayout->_fHasMarkupPtr ); // new layout shouldn't already have a markup
// Layouts within an array share the same _pvChain info
pLayout->__pvChain = __pvChain;
pLayout->_fHasMarkupPtr = _fHasMarkupPtr;
#if DBG ==1
if ( _fHasMarkupPtr )
{
Assert( _pMarkupDbg );
pLayout->_pMarkupDbg = _pMarkupDbg;
}
#endif
}
//+-------------------------------------------------------------------------
//
// Method: GetLayoutWithContext
//
//--------------------------------------------------------------------------
CLayout *
CLayoutAry::GetLayoutWithContext( CLayoutContext *pLayoutContext )
{
int i;
int nLayouts = Size();
CLayout *pLayout;
// TODO (KTam): Remove this when we no longer support "allowing GUL bugs".
if ( !pLayoutContext )
{
Assert( Size() );
pLayout = _aryLE[0];
Assert( pLayout && "Layout array shouldn't have NULL entries!" );
return pLayout;
}
AssertSz( pLayoutContext->IsValid(), "Should not be asking for a layout using an invalid context!" );
// Linear seach array to see if there's a layout associated with this
// context.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
Assert( pLayout->LayoutContext() && "Layouts in array must have context!" );
if ( pLayout->LayoutContext()->IsEqual( pLayoutContext ) )
return pLayout;
}
// No layout corresponding to this context
return NULL;
}
//+-------------------------------------------------------------------------
//
// Method: RemoveLayoutWithContext
//
// Synopsis: Searches for a layout that is associated with pLayoutContext,
// removing it from the array and returning it if found.
//
// NOTE: The test for association is currently layout context
// pointer equality: this means 2 contexts w/ the same layout
// owner are not equal, and thus compatible contexts need to be
// treated separately.
//
//--------------------------------------------------------------------------
CLayout *
CLayoutAry::RemoveLayoutWithContext( CLayoutContext *pLayoutContext )
{
int i;
int nLayouts = Size();
CLayout *pLayout = NULL;
Assert( pLayoutContext );
// Depending on how we use this function, this assert may not be true.
// We may for example choose to use this fn to remove layouts that have
// invalid contexts!
Assert( pLayoutContext->IsValid() );
// Linear seach array to see if there's a layout associated with this
// context.
for ( i=0 ; i < nLayouts ; ++i )
{
CLayout *pL = _aryLE[i];
Assert( pL->LayoutContext() && "Layouts in array must have context!" );
if ( pL->LayoutContext()->IsEqual( pLayoutContext ) )
{
// Remove the layout from the array, and return it
Verify(_aryLE.DeleteByValueIndirect( &pL ));
pLayout = pL;
goto Cleanup;
}
}
Cleanup:
TraceTagEx((tagLayoutAry, TAG_NONAME,
"CLytAry::RemoveLayoutWithContext lyt=0x%x, lc=0x%x, e=[0x%x,%d] (%S)",
pLayout,
pLayout ? pLayout->LayoutContext() : NULL,
pLayout ? pLayout->ElementOwner() : NULL,
pLayout ? pLayout->ElementOwner()->SN() : -1,
pLayout ? pLayout->ElementOwner()->TagName() : TEXT("")));
return pLayout;
}
//+----------------------------------------------------------------------------
// Helpers delegated from CElement
//-----------------------------------------------------------------------------
BOOL
CLayoutAry::ContainsRelative()
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Linear seach array to see if there's a layout that contains relative stuff.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
if ( pLayout->_fContainsRelative )
return TRUE;
}
}
return FALSE;
}
BOOL
CLayoutAry::GetEditableDirty()
{
Assert( _aryLE.Size() );
BOOL fEditableDirty = (_aryLE[GetFirstValidLayoutIndex()])->_fEditableDirty;
#if DBG
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// All layouts in collection should have same value for fEditableDirty
// Linear seach array to assert this is true.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
Assert( !!pLayout->_fEditableDirty == !!fEditableDirty );
}
}
#endif
return fEditableDirty;
}
void
CLayoutAry::SetEditableDirty( BOOL fEditableDirty )
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Linear seach array to set flag on each of them.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
pLayout->_fEditableDirty = fEditableDirty;
}
}
}
CLayoutAry::WantsMinMaxNotification()
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Linear seach array.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
// If any layout wants minmax notifications, then the array wants to be notified.
// Make sure "if" condition stays in sync with what's in CElement::MinMaxElement
if ( pLayout->_fMinMaxValid )
{
return TRUE;
}
}
}
// No layouts in the array wants a resize notification
return FALSE;
}
BOOL
CLayoutAry::WantsResizeNotification()
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Linear seach array.
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
// If any layout wants resize notifications, then the array wants to be notified.
// Make sure "if" condition stays in sync with what's in CElement::ResizeElement
// TODO (KTam): THIS CONDITION IS NO LONGER IN SYNC, but that's OK for IE5.5.
// NOTE (KTam): consider unifying condition in a CLayout::WantsResizeNotification() fn
if ( !pLayout->IsSizeThis() && !pLayout->IsCalcingSize() )
{
return TRUE;
}
}
}
// No layouts in the array wants a resize notification
return FALSE;
}
void
CLayoutAry::Notify(
CNotification * pnf)
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Most notifications that come to the layout array should be passed on to each layout.
// However, some are actually mean for the array.
switch ( pnf->Type() )
{
case NTYPE_MULTILAYOUT_CLEANUP:
{
// Iterate over array deleting layouts with invalid contexts. Do it in
// reverse to simplify iteration during deletion.
for ( i = nLayouts-1 ; i >= 0 ; --i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( !pLayout->LayoutContext()->IsValid() )
{
// Remove the layout from the array
_aryLE.Delete(i);
// Get rid of the layout
pLayout->Detach();
pLayout->Release();
}
}
break;
}
case NTYPE_ELEMENT_ZCHANGE:
case NTYPE_ELEMENT_REPOSITION:
if (pnf->LayoutContext())
{
// Iterate over array finding specified layout. Do it in
// reverse because in most cases this is a last layout added.
for ( i = nLayouts-1 ; i >= 0 ; --i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid()
&& pLayout->LayoutContext() == pnf->LayoutContext() )
{
TraceTagEx((tagNotifyPath, TAG_NONAME,
"NotifyPath: (%d) sent to pLayout(0x%x, %S) via layout array",
pnf->_sn,
pLayout,
pLayout->ElementOwner()->TagName()));
pLayout->Notify( pnf );
break;
}
}
//
// Getting here means that this elementOwner has no layout in the context of the
// notification. If the ElemetnOwner is a LayoutRect then that means the notification
// has come from somewhere inside us and we do not want this to continue to bubble
// up through the view link to the outside document
//
if (ElementOwner()->IsLinkedContentElement())
{
pnf->SetHandler(ElementOwner());
}
break;
}
// do not insert other cases here !!! previous case is sensitive to position of default case !!!
default:
// Notification meant for individual layouts: tell each layout in the array about it
{
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
TraceTagEx((tagNotifyPath, TAG_NONAME,
"NotifyPath: (%d) sent to pLayout(0x%x, %S) via layout array",
pnf->_sn,
pLayout,
pLayout->ElementOwner()->TagName()));
pLayout->Notify( pnf );
}
}
break;
}
}
}
//////////////////////////////////////////////////////
//
// CLayoutInfo overrides
//
//////////////////////////////////////////////////////
// $$ktam: It might be a good idea to implement some kind of CLayoutAry iterator class.
// Most of these overrides iterate the array..
HRESULT
CLayoutAry::OnPropertyChange( DISPID dispid, DWORD dwFlags )
{
Assert( _aryLE.Size() );
HRESULT hr = S_OK;
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Tell each layout in the array about the property change
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
hr = pLayout->OnPropertyChange(dispid, dwFlags);
Assert( SUCCEEDED(hr) );
}
}
return hr;
}
HRESULT
CLayoutAry::OnExitTree()
{
Assert( _aryLE.Size() );
HRESULT hr = S_OK;
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Tell each layout in the array that it's exiting the tree
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
// We deliberately ignore the valid state on the layout's context; since we're
// exiting the tree, it's OK to let invalid layouts know.
// TODO (KTam): it shouldn't make a difference either way, maybe be consistent?
hr = pLayout->OnExitTree();
Assert( SUCCEEDED(hr) );
}
return hr;
}
// Currently all implementations of OnFormatsChange actually only do work
// on their element (not on the layout). This means that even in a multi-
// layout world, we only want to call on one of the layouts. It also suggests
// that OnFormatsChange ought to be on CElement rather than CLayout.
HRESULT
CLayoutAry::OnFormatsChange(DWORD dwFlags)
{
int i = GetFirstValidLayoutIndex();
if ( _aryLE.Size() )
return _aryLE[i]->OnFormatsChange(dwFlags);
return E_FAIL;
}
void
CLayoutAry::Dirty( DWORD grfLayout )
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
// Tell each layout in the array that it's dirty
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
{
pLayout->Dirty( grfLayout );
}
}
}
BOOL
CLayoutAry::IsFlowLayout()
{
// CLayoutAry's are homogenous - delegate to the first layout in the array
int i = GetFirstValidLayoutIndex();
return ( _aryLE.Size()
&& _aryLE[i]->IsFlowLayout() );
}
BOOL
CLayoutAry::IsFlowOrSelectLayout()
{
// CLayoutAry's are homogenous - delegate to the first layout in the array
int i = GetFirstValidLayoutIndex();
return ( _aryLE.Size()
&& _aryLE[i]->IsFlowOrSelectLayout() );
}
// You should set the var pointed by *pnLayoutCookie to 0 to start the iterations
// It will be set to -1 if there are no more layouts or an error occured
CLayout *
CLayoutAry::GetNextLayout(int *pnLayoutCookie)
{
CLayout * pLayout;
Assert(pnLayoutCookie);
int nArySize = Size();
Assert(*pnLayoutCookie >= 0);
if(*pnLayoutCookie < 0 || *pnLayoutCookie >= nArySize)
{
*pnLayoutCookie = -1;
return NULL;
}
do
{
pLayout = _aryLE[*pnLayoutCookie];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
(*pnLayoutCookie)++;
if ( pLayout->LayoutContext()->IsValid() )
return pLayout;
}
while(*pnLayoutCookie < nArySize);
*pnLayoutCookie = -1;
return NULL;
}
#if DBG
void
CLayoutAry::DumpLayoutInfo( BOOL fDumpLines )
{
Assert( _aryLE.Size() );
int i;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
WriteHelp(g_f, _T("CLayoutAry: 0x<0x> - <1d> layouts\r\n"), this, (long)nLayouts );
// Dump each layout
for ( i=0 ; i < nLayouts ; ++i )
{
pLayout = _aryLE[i];
pLayout->DumpLayoutInfo( fDumpLines );
}
}
#endif
int
CLayoutAry::GetFirstValidLayoutIndex()
{
Assert( _aryLE.Size() );
int i = 0;
int nLayouts = _aryLE.Size();
CLayout *pLayout;
while ( i < nLayouts )
{
pLayout = _aryLE[i];
AssertSz( pLayout->LayoutContext(), "Layouts in array must have a context" );
if ( pLayout->LayoutContext()->IsValid() )
return i;
++i;
}
AssertSz( FALSE, "Shouldn't have an array that doesn't have a valid layout" );
return 0;
}
//+----------------------------------------------------------------------------
//
// Member: CElement::IsLinkedContentElement
//
// Synopsis: Returns true if this is a linkable-content element false otherwise.
// in IE6M1, only the Layout:rect identity behavior will utilize this
// functionality.
//
//-----------------------------------------------------------------------------
BOOL
CElement::IsLinkedContentElement()
{
// TODO (alexz) this heavily hits perf - up to 2% across the board.
// This is a tag name comparison performed very often. Even though it is
// unsuccessfull in most cases and the string comparison itself is fast,
// it still requires an attr array search to get the tagname.
// Instead, workout issues why the peer is not there when layout rolls.
// TODO (ktam) the Tag() check should make us a lot more efficient;
// we'll do what Alex suggests if it's still necessary.
#ifdef MULTI_LAYOUT
// We no longer rely on QI'ing the peer holder for ILayoutRect,
// because a) the peer holder isn't instantiated quickly enough
// (ie it doesn't exist at parse time), and b) this is more
// efficient and just as functional since we don't plan to expose
// ILayoutRect as a 3rd party interface.
if (Tag() != ETAG_GENERIC )
return FALSE;
return !FormsStringICmp(TagName(), _T("LAYOUTRECT"));
#else
return FALSE;
#endif
}
//+----------------------------------------------------------------------------
//
// Member: CElement::GetLinkedContentAttr
//
// Synopsis: Gets attributes from layout rects. Assumes that the
// attribute named by pszAttr is a string; returns S_OK if the
// attribute exists and its value is a non-empty string, S_FALSE
// if it exists but its value is an empty string, E_* if any other
// failure occurs.
//
//-----------------------------------------------------------------------------
HRESULT
CElement::GetLinkedContentAttr( LPCTSTR pszAttr, CVariant *pVarRet /*[out]*/ )
{
BSTR bstrAttribute = NULL;
HRESULT hr = E_FAIL;
Assert( pszAttr && pVarRet );
pVarRet->ZeroVariant(); // always zero "out" param.
// Bail immediately if this isn't a linked content element.
if (!IsLinkedContentElement())
goto Cleanup;
bstrAttribute = SysAllocString( pszAttr );
if ( !bstrAttribute )
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
hr = getAttribute( bstrAttribute, 0, pVarRet );
// Fail if couldn't get attribute, or if attribute type isn't BSTR.
if ( FAILED(hr) )
{
hr = E_UNEXPECTED;
goto Cleanup;
}
if (V_VT(pVarRet) == VT_BSTR)
{
// Return S_FALSE if attribute exists but is empty string.
hr = V_BSTR(pVarRet) ? S_OK : S_FALSE;
}
else if ( V_VT(pVarRet) == VT_DISPATCH
|| V_VT(pVarRet) == VT_UNKNOWN)
{
hr = S_OK;
}
else
{
hr = E_UNEXPECTED;
goto Cleanup;
}
Cleanup:
if ( bstrAttribute )
{
SysFreeString( bstrAttribute );
}
return hr;
}
//+----------------------------------------------------------------------------
//
// Member: CElement::GetNextLinkedContentElem
//
// Synopsis: returns the element that this element overflows to, but only if
// this is a valid linkable element.
//
//-----------------------------------------------------------------------------
CElement *
CElement::GetNextLinkedContentElem()
{
BSTR bstrLinkName = NULL;
CElement * pElement = NULL;
CMarkup * pMarkup = NULL;
CVariant cvarName;
if ( GetLinkedContentAttr( _T("nextRect"), &cvarName ) != S_OK )
goto Cleanup;
pMarkup = GetMarkup();
if (!pMarkup)
goto Cleanup;
if (FAILED(pMarkup->GetElementByNameOrID((LPTSTR)(V_BSTR(&cvarName)),
&pElement)))
{
// before we bail it it possible that the "nextRectElement" attribute
// may have our element.
cvarName.Clear();
SysFreeString(bstrLinkName);
bstrLinkName = SysAllocString(_T("nextRectElement"));
if (!bstrLinkName)
goto Cleanup;
Assert(pElement == NULL);
if (FAILED(getAttribute(bstrLinkName, 0, &cvarName)))
goto Cleanup;
if (V_VT(&cvarName) != VT_DISPATCH)
goto Cleanup;
// To get a CElement we need to either QI for the clsid,
// this doesn't Addref, so just clear the variant to transfer
// ownership of the dispatch pointer.
if (pElement)
IGNORE_HR(pElement->QueryInterface(CLSID_CElement, (void**) &pElement));
}
if (!pElement)
goto Cleanup;
// now that we have the element, lets verify that it is indeed linkable
//---------------------------------------------------------------------
if (!pElement->IsLinkedContentElement())
{
// ERROR, we linked to something that isn't linkable
pElement = NULL;
}
Cleanup:
if (bstrLinkName)
SysFreeString(bstrLinkName);
return (pElement);
}
//+----------------------------------------------------------------------------
//
// Member: CElement::ConnectLinkedContentElems
//
// Synopsis: Connects a "new" layout rect element (that doesn't belong to a
// viewchain) to an existing layout rect (the "src" elem), hooking the
// new element up to the viewchain of the src elem.
//
//-----------------------------------------------------------------------------
HRESULT
CElement::ConnectLinkedContentElems( CElement *pSrcElem, CElement *pNewElem )
{
Assert( pSrcElem && pNewElem );
Assert( pSrcElem->IsLinkedContentElement() && pNewElem->IsLinkedContentElement() );
// NOTE (KTam): Layout iterators here, to handle layout rect elements having
// multiple layouts?
CLayout * pSrcLayout = pSrcElem->EnsureLayoutInDefaultContext();
CLayout * pNewLayout = pNewElem->EnsureLayoutInDefaultContext();
AssertSz( pSrcLayout, "Source element for linking must have layout" );
AssertSz( pSrcLayout->ViewChain(), "Source element for linking must have view chain" );
AssertSz( pNewLayout, "New element for linking must have layout" );
AssertSz( (!pNewLayout->ViewChain() || (pNewLayout->ViewChain() == pSrcLayout->ViewChain()) ),
"New elem should either not already have a view chain, or its viewchain should match what we're about to give it" );
pNewLayout->SetViewChain(pSrcLayout->ViewChain(),
pSrcLayout->DefinedLayoutContext());
return S_OK;
}
//+----------------------------------------------------------------------------
//
// Member: CElement::UpdateLinkedContentChain()
//
// Synopsis: Called when a link chain is invalid this function makes sure that
// all of the slave markup pointers for the genericElements and viewChains
// for the associated CContainerLayouts are upto date.
//
// Note : for future usage, this function assumes that when a chain is invalidated,
// (e.g. the contentSrc property of the head container is changed), then the
// viewChain pointers for the whole list will have been cleared. If they are
// marked invalid instead then this function will need to be updated.
//
// TODO (KTam): Need to find/notify other chains (redundant displays). So far
// we still only have one master, so notifications from the content tree will be
// directed to the single master element -- perhaps it needs to be able to know
// about all chains?
//
//-----------------------------------------------------------------------------
HRESULT
CElement::UpdateLinkedContentChain()
{
CElement * pNextElem;
CElement * pPrevElem;
// Assert that this fn is only called on heads of chains
WHEN_DBG( CVariant cvarAttr );
AssertSz( GetLinkedContentAttr( _T("contentSrc"), &cvarAttr ) == S_OK, "UpdateLinkedContentChain() called for elem w/o contentSrc" );
AssertSz( HasSlavePtr(), "Head of chain must have slave by now" );
// Remeasure the head
RemeasureElement(NFLAGS_FORCE);
// Iterate through the chain, hooking up elements to the chain/setting slave
// ptrs as needed, and then ask each element of the chain to remeasure.
pPrevElem = this;
pNextElem = GetNextLinkedContentElem();
while ( pNextElem )
{
ConnectLinkedContentElems( pPrevElem, pNextElem );
// Remeasure this link in the chain by forcing container to recalculate its size.
pNextElem->RemeasureElement(NFLAGS_FORCE);
pPrevElem = pNextElem;
pNextElem = pNextElem->GetNextLinkedContentElem();
}
return S_OK;
}
//+-------------------------------------------------------------------
//
// Member : Fire_onlayoutcomplete
//
// Synopsis : event firing helper, this is called asynch from the layout
// process. it is responsible for creating the eventparam object, and
// setting up the properties on it.
//
//--------------------------------------------------------------------
void
CElement::Fire_onlayoutcomplete(BOOL fMoreContent, DWORD dwExtra)
{
Assert(dwExtra == 0 || fMoreContent);
EVENTPARAM param(Doc(), this, NULL, FALSE, TRUE);
param._pNode = GetFirstBranch();
param._fOverflow = fMoreContent;
param._overflowType = (OVERFLOWTYPE)dwExtra;
param.SetType(_T("layoutcomplete"));
FireEvent( &s_propdescCElementonlayoutcomplete, FALSE );
}
#if DBG==1
void
CElement::DumpLayouts()
{
CLayoutInfo *pLI = NULL;
if ( CurrentlyHasAnyLayout() )
pLI = GetLayoutInfo();
if ( pLI )
pLI->DumpLayoutInfo( TRUE );
}
#endif
| 29.714086 | 149 | 0.542666 | [
"object"
] |
d720a0de6af22d6f834e2acf46c7c108a0b8a415 | 486 | cpp | C++ | src/places/retirement_home.cpp | Dynamical-Systems-Laboratory/ABM-Multitown | 517de26074feaf13f9b8478eaf464a14d6b33b4a | [
"MIT"
] | 3 | 2020-11-04T03:58:49.000Z | 2021-01-14T22:16:24.000Z | src/places/retirement_home.cpp | Dynamical-Systems-Laboratory/ABM-Multitown | 517de26074feaf13f9b8478eaf464a14d6b33b4a | [
"MIT"
] | 1 | 2021-01-12T14:59:59.000Z | 2021-01-12T14:59:59.000Z | src/places/retirement_home.cpp | Dynamical-Systems-Laboratory/ABM-Multitown | 517de26074feaf13f9b8478eaf464a14d6b33b4a | [
"MIT"
] | 2 | 2020-11-03T17:18:41.000Z | 2021-01-15T04:13:03.000Z | #include "../../include/places/retirement_home.h"
/*****************************************************
* class: RetirementHome
*
* Defines and stores attributes of a single
* retirement home
*
*****************************************************/
//
// I/O
//
// Save information about a RetirementHome object
void RetirementHome::print_basic(std::ostream& where) const
{
Place::print_basic(where);
where << " " << beta_emp << " " << beta_ih << " " << psi_emp;
}
| 21.130435 | 63 | 0.502058 | [
"object"
] |
d720fc4913a302c560d6cd0407ae9451336eaf97 | 3,839 | inl | C++ | aeh/src/main_loop/demo_crtp_base.inl | asielorz/aeh | 6dbcce0970a558fb7f164b8880a3e834f9f6c8c9 | [
"MIT"
] | null | null | null | aeh/src/main_loop/demo_crtp_base.inl | asielorz/aeh | 6dbcce0970a558fb7f164b8880a3e834f9f6c8c9 | [
"MIT"
] | null | null | null | aeh/src/main_loop/demo_crtp_base.inl | asielorz/aeh | 6dbcce0970a558fb7f164b8880a3e834f9f6c8c9 | [
"MIT"
] | null | null | null | namespace aeh::main_loop
{
namespace detail
{
template <typename ExtendedInput, typename BaseInput, typename ... InputExtensions, typename ... NonEmptyInputExtensions>
ExtendedInput make_extended_input(BaseInput base, std::tuple<InputExtensions...> extensions, type_list<NonEmptyInputExtensions...>)
{
return ExtendedInput{base, std::move(std::get<NonEmptyInputExtensions>(extensions))...};
}
template <typename PluginLocals, typename ImplementationLocals>
struct CRTPBaseLocals
{
CRTPBaseLocals(PluginLocals && p, ImplementationLocals && i)
: plugin_locals(std::forward<PluginLocals>(p))
, implementation_locals(std::forward<ImplementationLocals>(i))
{}
PluginLocals plugin_locals;
ImplementationLocals implementation_locals;
};
}
template <typename Impl, typename ... Plugins>
void CRTPBase<Impl, Plugins...>::initialize(SDL_Window * window)
{
for_each_in_tuple(plugins, [window](auto & plugin) { detail::call_initialize(plugin, window); });
detail::call_initialize_impl(implementation(), window);
}
template <typename Impl, typename ... Plugins>
auto CRTPBase<Impl, Plugins...>::start_frame()
{
auto plugin_locals = transform_tuple(plugins, [](auto & plugin) { return detail::call_start_frame(plugin); });
auto implementation_locals = detail::call_start_frame_impl(implementation());
return detail::CRTPBaseLocals(std::move(plugin_locals), std::move(implementation_locals));
}
template <typename Impl, typename ... Plugins>
template <typename Locals>
void CRTPBase<Impl, Plugins...>::update(aeh::main_loop::UpdateInput input, Locals && locals)
{
auto input_extensions = transform_tuple(plugins, locals.plugin_locals,
[input](auto & plugin, auto & locals) { return detail::call_update(plugin, input, locals); });
UpdateInput extended_input = detail::make_extended_input<UpdateInput>(input, std::move(input_extensions), detail::keep_non_empty<detail::plugin_update_input_extension<Plugins>...>());
detail::call_update_impl(implementation(), extended_input, locals.implementation_locals);
}
template <typename Impl, typename ... Plugins>
template <typename Locals>
void CRTPBase<Impl, Plugins...>::render(aeh::main_loop::RenderInput input, Locals && locals) const
{
auto input_extensions = transform_tuple(plugins,
[input](auto const & plugin) { return detail::call_pre_render(plugin, input); });
RenderInput extended_input = detail::make_extended_input<RenderInput>(input, std::move(input_extensions), detail::keep_non_empty<detail::plugin_render_input_extension<Plugins>...>());
detail::call_render_impl(implementation(), extended_input, locals.implementation_locals);
for_each_in_tuple_reversed(plugins, [input](auto const & plugin) { detail::call_post_render(plugin, input); });
}
template <typename Impl, typename ... Plugins>
template <typename Locals>
void CRTPBase<Impl, Plugins...>::process_event(SDL_Event const & event, Locals && locals)
{
for_each_in_tuple(plugins, locals.plugin_locals,
[&event](auto & plugin, auto & locals) { detail::call_process_event(plugin, event, locals); });
detail::call_process_event_impl(implementation(), event, locals.implementation_locals);
}
template <typename Impl, typename ... Plugins>
void CRTPBase<Impl, Plugins...>::shutdown()
{
detail::call_shutdown_impl(implementation());
for_each_in_tuple_reversed(plugins, [](auto & plugin) { detail::call_shutdown(plugin); });
}
template <typename Impl, typename ... Plugins>
template <typename Plugin>
Plugin & CRTPBase<Impl, Plugins...>::get_plugin() noexcept
{
return std::get<Plugin>(plugins);
}
template <typename Impl, typename ... Plugins>
template <typename Plugin>
Plugin const & CRTPBase<Impl, Plugins...>::get_plugin() const noexcept
{
return std::get<Plugin>(plugins);
}
} // namespace aeh::main_loop | 41.728261 | 185 | 0.748632 | [
"render"
] |
d723c6795a749368debe5107d133228c54f30f4f | 672 | cpp | C++ | test/container/indirect_container.cpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | test/container/indirect_container.cpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | test/container/indirect_container.cpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #include <test/test.hpp>
#include <falcon/container/indirect_container.hpp>
#include <falcon/container/reference_vector.hpp>
#include "indirect_container.hpp"
void indirect_container_test()
{
struct A
{
int i;
A& operator=(int n)
{
i = n;
return *this;
}
};
A i{0};
falcon::container::vector<A&> v({i});
i = 5;
A i2{3};
v.push_back(i2);
i2 = 40;
std::vector<A*> vv({&i2});
//falcon::indirect_container(v).begin() = v.begin()->get()
//falcon::indirect_container(vv).begin() = *vv.begin()
CHECK(50 == v[0].i + falcon::indirect_container(v).begin()->i + falcon::indirect_container(vv).begin()->i);
}
FALCON_TEST_TO_MAIN(indirect_container_test)
| 21.677419 | 108 | 0.666667 | [
"vector"
] |
d723e014a7df205dd850f6554e4f81f07bc26645 | 6,934 | hpp | C++ | data-server/include/bluetooth_sensor_data_recv.hpp | jackrwoods/pilot-health-monitoring-capstone | 25fa9ee1f851832744d4a3fb55b087020c3acb32 | [
"MIT"
] | null | null | null | data-server/include/bluetooth_sensor_data_recv.hpp | jackrwoods/pilot-health-monitoring-capstone | 25fa9ee1f851832744d4a3fb55b087020c3acb32 | [
"MIT"
] | null | null | null | data-server/include/bluetooth_sensor_data_recv.hpp | jackrwoods/pilot-health-monitoring-capstone | 25fa9ee1f851832744d4a3fb55b087020c3acb32 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <thread>
#include "../include/bluetooth/bluetooth_con.hpp"
#include "datasource.hpp"
#include "../include/bluetooth_utils.hpp"
#define MITIGATE_SENSOR_MALFUNCTION 1
class BluetoothReceiver : public Datasource
{
private:
bool quit_receive_thread{false};
int received_samples{0};
PHMS_Bluetooth::Communicator c;
std::string bluetooth_address;
std::thread callback_thread;
bool connection_initialized{false};
void run_receive();
int pilot_state{0};
public:
BluetoothReceiver();
~BluetoothReceiver();
void initializeConnection();
void send_pilot_state(uint8_t state);
void set_bt_address(const std::string &s);
};
void BluetoothReceiver::run_receive()
{
// crash if no connection was made
if (!connection_initialized)
{
std::cerr << "(BluetoothReceiver) Connection uninitialized at call to run_receive" << std::endl;
exit(1);
}
int samples_before_analysis{100};
int errors[16]{0};
bool sensor_seen[16]{false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false};
bool sensor_valid[16] = {true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true};
int error_threshold{500};
int active_sensor{0};
while (!quit_receive_thread)
{
if (c.available())
{
// grab all available bluetooth packets
std::vector<PHMS_Bluetooth::Packet> v = c.get_all();
received_samples += v.size();
long time = (long)std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch().count();
// for each bluetooth packet received, get the samples
// keep track of errors at each sensor
for (auto i : v)
{
auto smp = sample_buffer_from_bt_packet(i);
std::vector<Sample> samples = smp.samples;
int source = smp.src;
if (!sensor_seen[source])
{
std::cout << "New connected sensor: " << source << std::endl;
sensor_seen[source] = true;
}
// quickly disable error checking
#ifdef MITIGATE_SENSOR_MALFUNCTION
// mitigate sensor malfunction
for (auto s : samples)
{
bool er{false};
if (samples_before_analysis == 0)
{
// do error checking calculions - if a sample is outside of normal range, increment error count and move on
// ranges are based on calculations on recorded data
if (s.spo2 > 14200 || s.spo2 < 13700)
{
// std::cout << "spo2 error was found in sensor " << source << " total errors from this sensor: " << errors[source] << std::endl;
errors[source] += 1;
er = true;
}
if (s.irLED > 14400 || s.irLED < 13660)
{
// std::cout << "irled error was found in sensor " << source << " total errors from this sensor: " << errors[source] << std::endl;
errors[source] += 1;
er = true;
}
if (s.redLED > 14400 || s.redLED < 13660)
{
// std::cout << "redled error was found in sensor " << source << " total errors from this sensor: " << errors[source] << std::endl;
errors[source] += 1;
er = true;
}
}
else
{
// std::cout << "sba: " << samples_before_analysis << std::endl;
samples_before_analysis--;
}
// slowly roll back erroring sensors
if (errors[source] >= 10 && !er)
errors[source] -= 10;
// std::cout << "errors at " << source << " " << errors[source] << std::endl;
// if a sensor is past the error threshold do not consider its samples
// reassign active sensor if errors are detected
if (!sensor_valid[active_sensor])
{
bool found{false};
for (int i = 0; i < 16; i++)
{
if (sensor_seen[i] && sensor_valid[i])
{
found = true;
active_sensor = i;
break;
}
}
if (!found)
{
std::cerr << "No valid sensors attached (fatal)\n";
exit(1);
}
else
{
std::cout << "responding to invalid sensor: new primary sensor is " << active_sensor << std::endl;
}
}
if (errors[source] > error_threshold && sensor_valid[source])
{
std::cout << "sensor " << source << " errored out\n";
sensor_valid[source] = false;
continue;
}
if (source != active_sensor)
continue;
#endif
// for each sample, call all of the callback functions
uint16_t last_spo2{95};
for (auto s : samples)
{
// calculate spo2 for each sample based on irled and redled - https://github.com/oxullo/Arduino-MAX30100/blob/master/src/MAX30100_SpO2Calculator.cpp
const uint8_t spO2LUT[43] = {100, 100, 100, 100, 99, 99, 99, 99, 99, 99, 98, 98, 98, 98,
98, 97, 97, 97, 97, 97, 97, 96, 96, 96, 96, 96, 96, 95, 95,
95, 95, 95, 95, 94, 94, 94, 94, 94, 93, 93, 93, 93, 93};
float acSqRatio = 100.0 * log(s.redLED / received_samples) / log(s.irLED / received_samples);
uint8_t index = 0;
if (acSqRatio > 66)
{
index = (uint8_t)acSqRatio - 66;
}
else if (acSqRatio > 50)
{
index = (uint8_t)acSqRatio - 50;
}
if (index > 42 || index < 0)
s.spo2 = last_spo2;
else
s.spo2 = spO2LUT[index];
last_spo2 = s.spo2;
// insert last received pilot state value
if (s.bpm > 70)
s.pilot_state = pilot_state;
s.timestamp = time;
// Pass a pointer to the latest data to all of the callback functions.
for (auto clb : callbacks)
clb(&s);
}
}
}
}
}
}
BluetoothReceiver::BluetoothReceiver()
{
std::cout << "Bluetooth Sample Reciever ('hcitool dev' in terminal returns the bluetooth address of this device)" << std::endl;
}
BluetoothReceiver::~BluetoothReceiver()
{
std::cout << "Killing bluetooth thread...\n";
quit_receive_thread = true;
c.quit();
callback_thread.join();
}
void BluetoothReceiver::initializeConnection()
{
if (bluetooth_address.empty())
{
std::cerr << "(BluetoothReceiver) call to InitializeConnection with no bluetooth address set" << std::endl;
exit(1);
}
// run a thread that sits and receives packets until the application quits
if (c.open_con(bluetooth_address, 5) == 0)
{
connection_initialized = true;
c.run();
}
else
{
std::cerr << "(BluetoothReceiver) an error occurred opening connection to " << bluetooth_address << std::endl;
exit(1);
}
callback_thread = std::thread(&BluetoothReceiver::run_receive, this);
}
/**
* send_pilot_state: Send a stressed or unstressed pilot state to the connected collection device
* @param state: 1 if the pilot is stressed, 0 if the pilot is unstressed
*/
void BluetoothReceiver::send_pilot_state(uint8_t state)
{
printf("sending pilot state: %s\n", (state ? "stressed" : "unstressed"));
pilot_state = state;
c.push(&pilot_state, 1);
}
void BluetoothReceiver::set_bt_address(const std::string &s)
{
bluetooth_address = s;
} | 27.299213 | 154 | 0.630372 | [
"vector"
] |
c01581bafc6d79d305036255bb3f37dce00fd472 | 26,237 | cpp | C++ | src/test-apps/nlweavebdxserver.cpp | lanyuwen/openweave-core | fbed1743a7b62657f5d310b98909c59474a6404d | [
"Apache-2.0"
] | null | null | null | src/test-apps/nlweavebdxserver.cpp | lanyuwen/openweave-core | fbed1743a7b62657f5d310b98909c59474a6404d | [
"Apache-2.0"
] | null | null | null | src/test-apps/nlweavebdxserver.cpp | lanyuwen/openweave-core | fbed1743a7b62657f5d310b98909c59474a6404d | [
"Apache-2.0"
] | 1 | 2020-11-04T06:58:12.000Z | 2020-11-04T06:58:12.000Z | /*
*
* Copyright (c) 2013-2017 Nest Labs, Inc.
* 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 "nlassert.h"
#include "nlweavebdxserver.h"
#include <unistd.h>
#include <fcntl.h>
namespace nl {
namespace Weave {
namespace Profiles {
BulkDataTransferServer::BulkDataTransferServer()
{
ExchangeMgr = NULL;
mpAppState = NULL;
OnBDXReceiveInitRequestReceived = NULL;
OnBDXBlockQueryRequestReceived = NULL;
OnBDXBlockEOFAckReceived = NULL;
OnBDXTransferFailed = NULL;
OnBDXTransferSucceeded = NULL;
}
BulkDataTransferServer::~BulkDataTransferServer()
{
Shutdown();
}
WEAVE_ERROR BulkDataTransferServer::Init(WeaveExchangeManager *exchangeMgr, void *appState,
const char *hostedFileName, const char *receivedFileLocation)
{
// Error if already initialized.
if (ExchangeMgr != NULL)
return WEAVE_ERROR_INCORRECT_STATE;
ExchangeMgr = exchangeMgr;
mpAppState = appState;
mHostedFileName = hostedFileName;
mReceivedFileLocation = receivedFileLocation;
// Initialize connection pool
memset(mTransferPool, 0, sizeof(mTransferPool));
for (int i = 0; i < MAX_NUM_BDX_TRANSFERS; i++)
{
mTransferPool[i].FD = -1;
}
// Register to receive unsolicited ReceiveInitiation messages from the exchange manager.
ExchangeMgr->RegisterUnsolicitedMessageHandler(kWeaveProfile_BDX, kMsgType_ReceiveInit, HandleReceiveInitRequest, this);
ExchangeMgr->RegisterUnsolicitedMessageHandler(kWeaveProfile_BDX, kMsgType_SendInit, HandleSendInitRequest, this);
return WEAVE_NO_ERROR;
}
WEAVE_ERROR BulkDataTransferServer::Shutdown()
{
printf("0 BDX Shutdown entering\n");
if (ExchangeMgr != NULL)
{
// Shutdown actions to perform only if BDX server initialized:
ExchangeMgr->UnregisterUnsolicitedMessageHandler(kWeaveProfile_BDX, kMsgType_ReceiveInit);
ExchangeMgr->UnregisterUnsolicitedMessageHandler(kWeaveProfile_BDX, kMsgType_SendInit);
ExchangeMgr = NULL;
// Explicitly shut down transfers to free any held Weave resources
for (int i = 0; i < MAX_NUM_BDX_TRANSFERS; i++)
{
ShutdownTransfer(&mTransferPool[i], true);
}
}
// Shutdown actions to perform even if BDX server uninitialized:
mpAppState = NULL;
OnBDXReceiveInitRequestReceived = NULL;
OnBDXBlockQueryRequestReceived = NULL;
OnBDXBlockEOFAckReceived = NULL;
OnBDXTransferFailed = NULL;
OnBDXTransferSucceeded = NULL;
printf("1 BDX Shutdown exiting\n");
return WEAVE_NO_ERROR;
}
BulkDataTransferServer::BDXTransfer *BulkDataTransferServer::NewTransfer()
{
for (int i = 0; i < MAX_NUM_BDX_TRANSFERS; i++)
{
if (!mTransferPool[i].BdxApp)
{
mTransferPool[i].BdxApp = this;
return &mTransferPool[i];
}
}
return NULL;
}
void BulkDataTransferServer::ShutdownTransfer(BDXTransfer *xfer, bool closeCon)
{
if (xfer->BdxApp == NULL)
{
// Suppress log spew if iterating through entire connection pool as part of Shutdown()
return;
}
printf("0 BDX ShutdownTransfer entering\n");
uint64_t peerNodeId = kNodeIdNotSpecified;
IPAddress peerAddr = IPAddress::Any;
// Get values to send application callback
if (xfer->EC && xfer->EC->Con)
{
peerNodeId = xfer->EC->Con->PeerNodeId;
peerAddr = xfer->EC->Con->PeerAddr;
}
// Fire application callback
if (false == xfer->CompletedSuccessfully)
{
if (OnBDXTransferFailed)
{
OnBDXTransferFailed(peerNodeId, peerAddr, mpAppState);
}
}
else
{
if (OnBDXTransferSucceeded)
{
OnBDXTransferSucceeded(peerNodeId, peerAddr, mpAppState);
}
}
/* Reset and release transfer object. This needs to be done before the Weave connection
is closed because closing a Weave connection will call EC->OnConnectionClosed which in turn will
call our OnConnectionClosed handler which will then call ShutdownTranser() again.
Because xfer->BdxApp is NULL the second time ShutdownTranser() is called it will exit right away */
xfer->MaxBlockSize = 0;
xfer->CompletedSuccessfully = false;
xfer->BdxApp = NULL;
// Release Weave resources
if (xfer->EC)
{
printf("1 BDX ShutdownTransfer closing EC\n");
if (closeCon && xfer->EC->Con)
{
printf("2 BDX ShutdownTransfer closing Con\n");
xfer->EC->Con->Close();
xfer->EC->Con = NULL;
}
xfer->EC->Close();
xfer->EC = NULL;
}
// Free pbuf
if (xfer->BlockBuffer)
{
printf("3 BDX ShutdownTransfer closing BlockBuffer\n");
PacketBuffer::Free(xfer->BlockBuffer);
xfer->BlockBuffer = NULL;
}
// Close file
if (xfer->FD != -1)
{
printf("4 BDX ShutdownTransfer closing FD\n");
close(xfer->FD);
xfer->FD = -1;
}
printf("5 BDX ShutdownTransfer exiting");
}
void BulkDataTransferServer::HandleReceiveInitRequest(ExchangeContext *ec, const IPPacketInfo *packetInfo,
const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *payloadReceiveInit)
{
// We're guaranteed of the right message profile and type by the ExchangeMgr.
printf("0 BDX HandleReceiveInitRequest entering\n");
WEAVE_ERROR ret = WEAVE_NO_ERROR;
const uint8_t BDX_SERVER_TRANSFER_MODE = 0x02U; //ASYNC==0, RDRIVE==1, SDRIVE==0
BulkDataTransferServer *bdxApp = NULL;
BDXTransfer *xfer = NULL;
PacketBuffer *payload = NULL;
char *fileDesignator = NULL;
ReceiveAccept receiveAccept;
ReceiveReject receiveReject;
ReceiveInit receiveInit;
nlREQUIRE_ACTION(ec != NULL, handle_receive_init_request_failed,
printf("0.5 BDX HandleReceiveInitRequest failed, null EC\n"));
bdxApp = (BulkDataTransferServer *) ec->AppState;
// Parse init request and discard payload buffer
ret = ReceiveInit::parse(payloadReceiveInit, receiveInit);
nlREQUIRE(ret == WEAVE_NO_ERROR, handle_receive_init_request_failed);
PacketBuffer::Free(payloadReceiveInit);
payloadReceiveInit = NULL;
// Grab BDXTransfer object for this transfer
xfer = bdxApp->NewTransfer();
if (!xfer)
{
printf("1 BDX HandleReceiveInitRequest (transfer alloc failed)\n");
SendTransferError(ec, kWeaveProfile_Common, kStatus_OutOfMemory);
goto handle_receive_init_request_failed;
}
// Hang new BDXTransfer on exchange context
ec->AppState = xfer;
// Initialize xfer struct (move to init function?)
xfer->EC = ec;
xfer->FD = -1; // memset(0) doesn't set us up for ShutdownTransfer()
if (receiveInit.theMaxBlockSize <= 0) {
printf("2 BDX HandleReceiveInitRequest (maxBlockSize <= 0)\n");
// Send rejection status message
receiveReject.init(kWeaveProfile_Common, kStatus_BadRequest);
if ((payload = PacketBuffer::New()) == NULL)
{
printf("2.5 BDX HandleReceiveInitRequest (PacketBuffer alloc failed)\n");
goto handle_receive_init_request_failed;
}
receiveReject.pack(payload);
ret = ec->SendMessage(kWeaveProfile_Common, kMsgType_ReceiveReject, payload);
if (ret != WEAVE_NO_ERROR)
{
printf("3 BDX HandleReceiveInitRequest err=%d\n", ret);
}
payload = NULL;
goto handle_receive_init_request_failed;
}
xfer->MaxBlockSize = receiveInit.theMaxBlockSize;
if (receiveInit.theFileDesignator.theLength <= 0) {
printf("4 BDX HandleReceiveInitRequest (bad FileDesignator)\n");
SendTransferError(ec, kWeaveProfile_Common, kStatus_LengthTooShort);
goto handle_receive_init_request_failed;
}
// Copy file name onto C-string
// NOTE: the original string is not NUL terminated, but we know its length.
fileDesignator = (char*)malloc(1 + receiveInit.theFileDesignator.theLength);
memcpy(fileDesignator, receiveInit.theFileDesignator.theString, receiveInit.theFileDesignator.theLength);
fileDesignator[receiveInit.theFileDesignator.theLength] = '\0';
// TODO Validate requested file path with value from nlhlfirmware.plist
// Future: delegate path security validation
// nlclient will open() this path as root, so we must be conservative in our validation.
if (0 != strcmp(fileDesignator, bdxApp->mHostedFileName))
{
printf("5 BDX HandleReceiveInitRequest (forbidden FileDesignator)\n");
SendTransferError(ec, kWeaveProfile_Common, kStatus_UnknownFile); //TODO add 'forbidden' Weave status code
free(fileDesignator);
fileDesignator = NULL;
goto handle_receive_init_request_failed;
}
// Open file to send
xfer->FD = open(fileDesignator, O_RDONLY);
free(fileDesignator);
fileDesignator = NULL;
if (xfer->FD == -1)
{
printf("6 BDX HandleReceiveInitRequest (open FAIL)\n");
SendTransferError(ec, kWeaveProfile_Common, kStatus_InternalServerProblem);
goto handle_receive_init_request_failed;
}
// Send a ReceiveAccept response back to the receiver.
printf("7 BDX HandleReceiveInitRequest validated request\n");
// Fire application callback once we've validated the request (TODO: call earlier? feels like semantic abuse)
if (bdxApp->OnBDXReceiveInitRequestReceived)
{
bdxApp->OnBDXReceiveInitRequestReceived(ec->PeerNodeId, ec->PeerAddr, payloadReceiveInit, bdxApp->mpAppState);
}
// Set up response timeout and connection closed handler
ec->Con->AppState = xfer;
ec->OnConnectionClosed = HandleBDXConnectionClosed;
ec->OnResponseTimeout = HandleResponseTimeout;
ec->ResponseTimeout = BDX_RESPONSE_TIMEOUT_MS;
// Set ourselves up to handle first BlockQueryRequest.
ec->OnMessageReceived = HandleBlockQueryRequest;
receiveAccept.init(BDX_SERVER_TRANSFER_MODE, receiveInit.theMaxBlockSize, receiveInit.theLength, NULL);
if ((payload = PacketBuffer::New()) == NULL)
{
printf("7.5 BDX HandleReceiveInitRequest (PacketBuffer alloc failed)\n");
goto handle_receive_init_request_failed;
}
receiveAccept.theMaxBlockSize = receiveInit.theMaxBlockSize;
ret = receiveAccept.pack(payload);
nlREQUIRE(ret == WEAVE_NO_ERROR, handle_receive_init_request_failed);
ret = ec->SendMessage(kWeaveProfile_BDX, kMsgType_ReceiveAccept, payload, ExchangeContext::kSendFlag_ExpectResponse);
payload = NULL;
if (ret != WEAVE_NO_ERROR)
{
printf("8 BDX HandleReceiveInitRequest err=%d\n", ret);
goto handle_receive_init_request_failed;
}
printf("9 BDX HandleReceiveInitRequest exiting (success)\n");
return;
handle_receive_init_request_failed:
printf("10 BDX HandleReceiveInitRequest exiting (failure)\n");
if (payload)
{
PacketBuffer::Free(payload);
payload = NULL;
}
if (payloadReceiveInit)
{
PacketBuffer::Free(payloadReceiveInit);
payloadReceiveInit = NULL;
}
if (xfer)
{
bdxApp->ShutdownTransfer(xfer, true);
}
else
{
// Transfer object uninitialized, so we do this manually
if (ec)
{
if (ec->Con)
{
ec->Con->Close();
ec->Con = NULL;
}
ec->Close();
ec = NULL;
}
}
}
void BulkDataTransferServer::HandleSendInitRequest(ExchangeContext *ec, const IPPacketInfo *packetInfo, const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *payload)
{
printf("BDX HandleSendInitRequest entering\n");
WEAVE_ERROR err = WEAVE_NO_ERROR;
BulkDataTransferServer *bdxApp = NULL;
BDXTransfer *xfer = NULL;
SendInit sendInit;
SendAccept sendAccept;
SendReject sendReject;
char *filename = NULL;
uint8_t offset = 0;
char *fileDesignator = NULL;
PacketBuffer *SendInitResponsePayload = NULL;
nlREQUIRE(ec, handle_send_init_request_failed);
bdxApp = static_cast<BulkDataTransferServer *>(ec->AppState);
xfer = bdxApp->NewTransfer();
nlREQUIRE(xfer, handle_send_init_request_failed);
xfer->EC = ec;
xfer->FD = -1;
xfer->CompletedSuccessfully = false;
ec->AppState = (void*)xfer;
err = SendInit::parse(payload, sendInit);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_send_init_request_failed);
xfer->MaxBlockSize = sendInit.theMaxBlockSize;
PacketBuffer::Free(payload);
payload = NULL;
/**
* Allocate PacketBuffer
*/
SendInitResponsePayload = PacketBuffer::New();
nlREQUIRE_ACTION(SendInitResponsePayload != NULL, handle_send_init_request_failed,
printf("Error: BDX HandleSendInitRequest: PacketBuffer alloc failed\n"));
// get the received file and location and name
filename = strrchr(sendInit.theFileDesignator.theString, '/');
if (filename == NULL)
{
filename = sendInit.theFileDesignator.theString;
}
else
{
filename++; //skip over '/'
}
fileDesignator = (char*)malloc(strlen(bdxApp->mReceivedFileLocation) + strlen(filename) + 2);
nlREQUIRE(fileDesignator != NULL, handle_send_init_request_failed);
memcpy(fileDesignator, bdxApp->mReceivedFileLocation, strlen(bdxApp->mReceivedFileLocation));
if (bdxApp->mReceivedFileLocation[strlen(bdxApp->mReceivedFileLocation) - 1] != '/')
{
// if it doesn't end with '/', add one
fileDesignator[strlen(bdxApp->mReceivedFileLocation)] = '/';
offset++;
}
memcpy(fileDesignator + strlen(bdxApp->mReceivedFileLocation) + offset, filename, strlen(filename));
fileDesignator[strlen(bdxApp->mReceivedFileLocation) + offset + strlen(filename)] = '\0';
printf("File being saved to: %s\n", fileDesignator);
xfer->FD = open(fileDesignator, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
free(fileDesignator);
if (xfer->FD == -1)
{
printf("Couldn't open file %s for writing...\n", filename);
err = sendReject.init(kWeaveProfile_BDX, kStatus_UnknownFile);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_send_init_request_failed);
err = sendReject.pack(SendInitResponsePayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_send_init_request_failed);
err = ec->SendMessage(kWeaveProfile_BDX, kMsgType_SendReject, SendInitResponsePayload, ExchangeContext::kSendFlag_ExpectResponse);
SendInitResponsePayload = NULL;
goto handle_send_init_request_failed;
}
// Finish up configuring and then send the SendInitResponse message
sendAccept.theMaxBlockSize = xfer->MaxBlockSize;
err = sendAccept.init(kMode_SenderDrive, xfer->MaxBlockSize, NULL);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_send_init_request_failed);
err = sendAccept.pack(SendInitResponsePayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_send_init_request_failed);
ec->OnMessageReceived = HandleBlockSend;
err = ec->SendMessage(kWeaveProfile_BDX, kMsgType_SendAccept, SendInitResponsePayload,
ExchangeContext::kSendFlag_ExpectResponse);
SendInitResponsePayload = NULL;
nlREQUIRE_ACTION(err == WEAVE_NO_ERROR, handle_send_init_request_failed,
printf("SendInitResponse error sending accept message: %d", err));
return;
handle_send_init_request_failed:
printf("BDX HandleSendInitRequest exiting (failure)\n");
if (SendInitResponsePayload)
{
PacketBuffer::Free(SendInitResponsePayload);
SendInitResponsePayload = NULL;
}
if (payload)
{
PacketBuffer::Free(payload);
payload = NULL;
}
if (xfer)
{
bdxApp->ShutdownTransfer(xfer, true);
}
else
{
// Transfer object uninitialized, so we do this manually
if (ec)
{
if (ec->Con)
{
ec->Con->Close();
ec->Con = NULL;
}
ec->Close();
ec = NULL;
}
}
}
void BulkDataTransferServer::HandleBlockSend(ExchangeContext *ec, const IPPacketInfo *packetInfo, const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *payload)
{
printf("BDX HandleBlockSend entering\n");
WEAVE_ERROR err = WEAVE_NO_ERROR;
int len = 0;
BlockSend blockSend;
BDXTransfer *xfer = static_cast<BDXTransfer *>(ec->AppState);
BulkDataTransferServer *bdxApp = xfer->BdxApp;
// Parse message data to get the block counter later
err = BlockSend::parse(payload, blockSend);
//NOTE: we skip over the block counter so it doesn't appear in the file
len = write(xfer->FD, blockSend.theData + sizeof(blockSend.theBlockCounter),
blockSend.theLength - sizeof(blockSend.theBlockCounter));
nlREQUIRE_ACTION(len >= 0, handle_block_send_failed,
printf("Error: HandleBlockSend: Unable to read image into block\n"));
PacketBuffer::Free(payload);
payload = NULL;
// Always need to ACK a BlockEOF
if (msgType == kMsgType_BlockEOF)
{
printf("Sending BlockEOFAck");
BlockEOFAck blockEOFAck;
PacketBuffer* blockEOFAckPayload = PacketBuffer::New();
nlREQUIRE_ACTION(blockEOFAckPayload, handle_block_send_failed,
err = WEAVE_ERROR_NO_MEMORY;
printf("Error: BDX HandleBlockSend: PacketBuffer alloc failed\n"));
err = blockEOFAck.init(blockSend.theBlockCounter-1); //final ack uses same block-counter of last block-query request
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
err = blockEOFAck.pack(blockEOFAckPayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
err = ec->SendMessage(kWeaveProfile_BDX, kMsgType_BlockEOFAck, blockEOFAckPayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
blockEOFAckPayload = NULL;
bdxApp->ShutdownTransfer(xfer, true);
}
// currently we only support synchronous mode, so send BlockAck
else {
printf("Sending BlockAck\n");
BlockAck blockAck;
PacketBuffer* blockAckPayload = PacketBuffer::New();
nlREQUIRE_ACTION(blockAckPayload, handle_block_send_failed,
err = WEAVE_ERROR_NO_MEMORY;
printf("Error: BDX HandleBlockSend: PacketBuffer alloc failed\n"));
err = blockAck.init(blockSend.theBlockCounter);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
err = blockAck.pack(blockAckPayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
err = ec->SendMessage(kWeaveProfile_BDX, kMsgType_BlockAck, blockAckPayload);
nlREQUIRE(err == WEAVE_NO_ERROR, handle_block_send_failed);
blockAckPayload = NULL;
}
handle_block_send_failed:
if (err != WEAVE_NO_ERROR)
{
bdxApp->ShutdownTransfer(xfer, true);
}
printf("HandleBlockSend exiting");
return;
}
static int read_n(int fd, char *buf, int n)
{
int nread, left = n;
printf("0 read_n entering\n");
while (left > 0)
{
printf("1 read_n (left: %d)\n", left);
if ((nread = read(fd, buf, left)) > 0)
{
left -= nread;
buf += nread;
printf("2 read_n (nread: %d, left: %d)\n", nread, left);
}
else
{
printf("3 read_n (nread: 0, left: %d)\n", left);
return n - left;
}
}
printf("4 read_n (n: %d, left: %d) exiting\n", n, left);
return n;
}
void BulkDataTransferServer::HandleBlockQueryRequest(ExchangeContext *ec, const IPPacketInfo *packetInfo,
const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *payloadBlockQuery)
{
printf("0 BDX HandleBlockQueryRequest entering\n");
WEAVE_ERROR ret = WEAVE_NO_ERROR;
char *block = NULL;
int len = 0;
BlockQuery blockQuery;
BDXTransfer *xfer = (BDXTransfer* ) ec->AppState;
BulkDataTransferServer *bdxApp = xfer->BdxApp;
// Parse message data to get the block counter later
BlockQuery::parse(payloadBlockQuery, blockQuery);
PacketBuffer::Free(payloadBlockQuery);
payloadBlockQuery = NULL;
if (kWeaveProfile_BDX != profileId || kMsgType_BlockQuery != msgType)
{
printf("1 BDX HandleBlockQueryRequest bad msg type (%d, %d)\n", profileId, msgType);
SendTransferError(ec, kWeaveProfile_Common, kStatus_BadRequest);
goto handle_block_query_request_failed;
}
if ((xfer->BlockBuffer = PacketBuffer::New()) == NULL)
{
printf("2 BDX HandleBlockQueryRequest (PacketBuffer alloc failed)\n");
SendTransferError(ec, kWeaveProfile_Common, kStatus_InternalServerProblem);
goto handle_block_query_request_failed;
}
printf("3 BDX HandleBlockQueryRequest (xfer->FD: %d)\n", xfer->FD);
block = (char *) xfer->BlockBuffer->Start();
*block = blockQuery.theBlockCounter;
len = read_n(xfer->FD, block + 1, xfer->MaxBlockSize);
if (len == xfer->MaxBlockSize)
{
printf("4 BDX HandleBlockQueryRequest (len = %d)\n", len);
xfer->BlockBuffer->SetDataLength((uint16_t) len + 1);
// Prepare to handle next BlockQueryRequest.
ec->OnMessageReceived = HandleBlockQueryRequest;
// Send a BlockSend Response back to the sender.
ret = ec->SendMessage(kWeaveProfile_BDX, kMsgType_BlockSend, xfer->BlockBuffer, ExchangeContext::kSendFlag_ExpectResponse);
if (ret != WEAVE_NO_ERROR)
{
printf("5 BDX HandleBlockQueryRequest (SendMessage failed, err=%d)\n", ret);
goto handle_block_query_request_failed;
}
xfer->BlockBuffer = NULL;
}
else if ((len >= 0) && (len < xfer-> MaxBlockSize))
{
printf("6 BDX HandleBlockQueryRequest (len == 0)\n");
// At EOF, so send empty payload.
xfer->BlockBuffer->SetDataLength((uint16_t) len + 1);
// Prepare to handle BlockEOF ACK.
ec->OnMessageReceived = HandleBlockEOFAck;
// Send a BlockEOF Response back to the sender.
ret = ec->SendMessage(kWeaveProfile_BDX, kMsgType_BlockEOF, xfer->BlockBuffer, ExchangeContext::kSendFlag_ExpectResponse);
if (ret != WEAVE_NO_ERROR)
{
printf("7 BDX HandleBlockQueryRequest\n");
goto handle_block_query_request_failed;
}
xfer->BlockBuffer = NULL;
}
else
{
printf("8 BDX HandleBlockQueryRequest read failed (len < 0)\n");
// read() failed
SendTransferError(ec, kWeaveProfile_Common, kStatus_InternalServerProblem);
goto handle_block_query_request_failed;
}
printf("9 BDX HandleBlockQueryRequest exiting (success)\n");
return;
handle_block_query_request_failed:
printf("10 BDX HandleBlockQueryRequest exiting (failure)\n");
bdxApp->ShutdownTransfer(xfer, true);
}
void BulkDataTransferServer::HandleBlockEOFAck(ExchangeContext *ec, const IPPacketInfo *packetInfo,
const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *payload)
{
printf("0 BDX HandleBlockEOFAck entering\n");
BDXTransfer *xfer = (BDXTransfer* ) ec->AppState;
BulkDataTransferServer *bdxApp = xfer->BdxApp;
// Free unused query payload.
PacketBuffer::Free(payload);
payload = NULL;
if (kWeaveProfile_BDX != profileId || kMsgType_BlockEOFAck != msgType)
{
printf("1 BDX HandleBlockEOFAck bad msg type (%d, %d)\n", profileId, msgType);
SendTransferError(ec, kWeaveProfile_Common, kStatus_BadRequest);
}
else
{
// Set flag for connection closed handler
xfer->CompletedSuccessfully = true;
// Fire application callback
if (bdxApp->OnBDXBlockEOFAckReceived)
{
bdxApp->OnBDXBlockEOFAckReceived(ec->PeerNodeId, ec->PeerAddr, payload, bdxApp->mpAppState);
}
}
// Either way it's the end of the line
bdxApp->ShutdownTransfer(xfer, true);
printf("2 BDX HandleBlockEOFAck exiting\n");
}
void BulkDataTransferServer::HandleBDXConnectionClosed(ExchangeContext *ec, WeaveConnection *con, WEAVE_ERROR conErr)
{
printf("0 BDX HandleBDXConnectionClosed entering (conErr = %d)\n", conErr);
BDXTransfer *xfer = (BDXTransfer* ) ec->AppState;
BulkDataTransferServer *bdxApp = xfer->BdxApp;
bdxApp->ShutdownTransfer(xfer, false);
printf("1 BDX HandleBDXConnectionClosed exiting\n");
}
void BulkDataTransferServer::HandleResponseTimeout(ExchangeContext *ec)
{
printf("0 BDX HandleResponseTimeout entering\n");
BDXTransfer *xfer = (BDXTransfer* ) ec->AppState;
BulkDataTransferServer *bdxApp = xfer->BdxApp;
bdxApp->ShutdownTransfer(xfer, true);
printf("1 BDX HandleResponseTimeout exiting\n");
}
void BulkDataTransferServer::SendTransferError(ExchangeContext *ec, uint32_t aProfileId, uint16_t aStatusCode)
{
TransferError transferError;
transferError.init(aProfileId, aStatusCode);
PacketBuffer* payloadTransferError = PacketBuffer::New();
if (payloadTransferError == NULL)
{
printf("BDX SendTransferError (PacketBuffer alloc failed)\n");
return;
}
transferError.pack(payloadTransferError);
ec->SendMessage(kWeaveProfile_BDX, kMsgType_TransferError, payloadTransferError);
payloadTransferError = NULL;
}
} // namespace Profiles
} // namespace Weave
} // namespace nl
| 33.59411 | 196 | 0.676983 | [
"object"
] |
c019ff5b374ded60ab0b5129d8ac068e322ab117 | 165,414 | hpp | C++ | src/netxs/console/terminal.hpp | o-sdn-o/VTM | 19f7dd2741c9547bb94e9c38c665f0915638332f | [
"MIT"
] | 2 | 2020-11-24T05:32:41.000Z | 2020-11-25T07:52:55.000Z | src/netxs/console/terminal.hpp | monotty/VTM | 00641148fabfe27901805e9fe144c16aabb55e83 | [
"MIT"
] | null | null | null | src/netxs/console/terminal.hpp | monotty/VTM | 00641148fabfe27901805e9fe144c16aabb55e83 | [
"MIT"
] | null | null | null | // Copyright (c) NetXS Group.
// Licensed under the MIT license.
#ifndef NETXS_TERMINAL_HPP
#define NETXS_TERMINAL_HPP
#include "../ui/controls.hpp"
namespace netxs::events::userland
{
struct uiterm
{
EVENTPACK( uiterm, netxs::events::userland::root::custom )
{
GROUP_XS( layout, iota ),
SUBSET_XS( layout )
{
EVENT_XS( align , bias ),
EVENT_XS( wrapln, wrap ),
};
};
};
}
// terminal: Terminal UI control.
namespace netxs::ui
{
class term
: public ui::form<term>
{
static constexpr iota def_length = 20000; // term: Default scrollback history length.
static constexpr iota def_growup = 0; // term: Default scrollback history grow step.
static constexpr iota def_tablen = 8; // term: Default tab length.
public:
using events = netxs::events::userland::uiterm;
struct commands
{
struct erase
{
struct line
{
enum : iota
{
right = 0,
left = 1,
all = 2,
};
};
struct display
{
enum : iota
{
below = 0,
above = 1,
viewport = 2,
scrollback = 3,
};
};
};
struct ui
{
enum commands : iota
{
right,
left,
center,
wrapon,
wrapoff,
togglewrp,
reset,
clear,
};
};
struct cursor // See pro::caret.
{
enum : iota
{
def_style = 0, // blinking box
blinking_box = 1, // blinking box (default)
steady_box = 2, // steady box
blinking_underline = 3, // blinking underline
steady_underline = 4, // steady underline
blinking_I_bar = 5, // blinking I-bar
steady_I_bar = 6, // steady I-bar
};
};
};
private:
// term: VT-buffer status.
struct term_state
{
using buff = ansi::esc;
iota size = 0;
iota peak = 0;
iota step = 0;
twod area;
buff data;
template<class bufferbase>
auto update(bufferbase const& scroll)
{
if (scroll.update_status(*this))
{
data.clear();
data.jet(bias::right).add(size,
"/", peak,
"+", step,
" ", area.x, ":", area.y);
return true;
}
else return faux;
}
};
// term: VT-style mouse tracking functionality.
struct m_tracking
{
enum mode
{
none = 0,
bttn = 1 << 0,
drag = 1 << 1,
move = 1 << 2,
over = 1 << 3,
buttons_press = bttn,
buttons_drags = bttn | drag,
all_movements = bttn | drag | move,
negative_args = bttn | drag | move | over,
};
enum prot
{
x11,
sgr,
};
m_tracking(term& owner)
: owner{ owner }
{ }
void enable (mode m)
{
state |= m;
if (state && !token.count()) // Do not subscribe if it is already subscribed
{
owner.SUBMIT_T(tier::release, hids::events::mouse::scroll::any, token, gear)
{
gear.dismiss();
};
owner.SUBMIT_T(tier::release, hids::events::mouse::any, token, gear)
{
auto& console = *owner.target;
auto c = gear.coord;
c.y -= console.get_basis();
moved = coord((state & mode::over) ? c
: std::clamp(c, dot_00, console.panel - dot_11));
auto cause = owner.bell::protos<tier::release>();
if (proto == sgr) serialize<sgr>(gear, cause);
else serialize<x11>(gear, cause);
owner.answer(queue);
};
owner.SUBMIT_T(tier::general, hids::events::die, token, gear)
{
log("term: hids::events::die, id = ", gear.id);
auto cause = hids::events::die.id;
if (proto == sgr) serialize<sgr>(gear, cause);
else serialize<x11>(gear, cause);
owner.answer(queue);
};
}
}
void disable(mode m) { state &= ~(m); if (!state) token.clear(); }
void setmode(prot p) { proto = p; }
private:
term& owner; // m_tracking: Terminal object reference.
testy<twod> coord; // m_tracking: Last coord of mouse cursor.
ansi::esc queue; // m_tracking: Buffer.
subs token; // m_tracking: Subscription token.
bool moved = faux;
iota proto = prot::x11;
iota state = mode::none;
void capture(hids& gear)
{
gear.capture(owner.id);
gear.dismiss();
}
void release(hids& gear)
{
if (gear.captured(owner.id)) gear.release(faux);
gear.dismiss();
}
template<prot PROT>
void proceed(hids& gear, iota meta, bool ispressed = faux)
{
meta |= gear.meta(hids::SHIFT | hids::ALT | hids::CTRL);
meta |= gear.meta(hids::RCTRL) ? hids::CTRL : 0;
switch (PROT)
{
case prot::x11: queue.mouse_x11(meta, coord); break;
case prot::sgr: queue.mouse_sgr(meta, coord, ispressed); break;
default: break;
}
}
// m_tracking: Serialize mouse state.
template<prot PROT>
void serialize(hids& gear, id_t cause)
{
using m = hids::events::mouse;
using b = hids::events::mouse::button;
constexpr static iota left = 0;
constexpr static iota mddl = 1;
constexpr static iota rght = 2;
constexpr static iota btup = 3;
constexpr static iota idle = 32;
constexpr static iota wheel_up = 64;
constexpr static iota wheel_dn = 65;
constexpr static iota up_left = PROT == sgr ? left : btup;
constexpr static iota up_rght = PROT == sgr ? rght : btup;
constexpr static iota up_mddl = PROT == sgr ? mddl : btup;
auto ismove = moved && state & mode::move;
auto isdrag = moved && state & mode::drag;
switch (cause)
{
// Move
case b::drag::pull::leftright.id:
case b::drag::pull::left .id: if (isdrag) proceed<PROT>(gear, idle + left, true); break;
case b::drag::pull::middle .id: if (isdrag) proceed<PROT>(gear, idle + mddl, true); break;
case b::drag::pull::right .id: if (isdrag) proceed<PROT>(gear, idle + rght, true); break;
case m::move .id: if (ismove) proceed<PROT>(gear, idle + btup, faux); break;
// Press
case b::down::leftright.id: capture(gear); break;
case b::down::left .id: capture(gear); proceed<PROT>(gear, left, true); break;
case b::down::middle .id: capture(gear); proceed<PROT>(gear, mddl, true); break;
case b::down::right .id: capture(gear); proceed<PROT>(gear, rght, true); break;
// Release
case b::up::leftright.id: release(gear); break;
case b::up::left .id: release(gear); proceed<PROT>(gear, up_left); break;
case b::up::middle .id: release(gear); proceed<PROT>(gear, up_mddl); break;
case b::up::right .id: release(gear); proceed<PROT>(gear, up_rght); break;
// Wheel
case m::scroll::up .id: proceed<PROT>(gear, wheel_up, true); break;
case m::scroll::down.id: proceed<PROT>(gear, wheel_dn, true); break;
// Gone
case hids::events::die.id:
release(gear);
if (auto buttons = gear.buttons())
{
// Release pressed mouse buttons.
if (buttons | sysmouse::left) proceed<PROT>(gear, up_left);
if (buttons | sysmouse::middle) proceed<PROT>(gear, up_mddl);
if (buttons | sysmouse::right) proceed<PROT>(gear, up_rght);
}
break;
default:
break;
}
}
};
// term: Keyboard focus tracking functionality.
struct f_tracking
{
f_tracking(term& owner)
: owner{ owner },
state{ faux }
{ }
operator bool () { return token.operator bool(); }
void set(bool enable)
{
if (enable)
{
if (!token) // Do not subscribe if it is already subscribed.
{
owner.SUBMIT_T(tier::release, hids::events::notify::keybd::any, token, gear)
{
switch (owner.bell::protos<tier::release>())
{
case hids::events::notify::keybd::got .id: queue.fcs(true); break;
case hids::events::notify::keybd::lost.id: queue.fcs(faux); break;
default: break;
}
owner.answer(queue);
};
}
}
else token.reset();
}
private:
term& owner; // f_tracking: Terminal object reference.
hook token; // f_tracking: Subscription token.
ansi::esc queue; // f_tracking: Buffer.
bool state; // f_tracking: Current focus state.
};
// term: Terminal title tracking functionality.
struct w_tracking
{
term& owner; // w_tracking: Terminal object reference.
std::map<text, text> props;
std::map<text, std::vector<text>> stack;
ansi::esc queue;
w_tracking(term& owner)
: owner{ owner }
{ }
// w_tracking: Get terminal window property.
auto& get(text const& property)
{
return props[property];
}
// w_tracking: Set terminal window property.
void set(text const& property, view txt)
{
static auto jet_left = ansi::jet(bias::left);
owner.target->flush();
if (property == ansi::OSC_LABEL_TITLE)
{
props[ansi::OSC_LABEL] = txt;
auto& utf8 = (props[ansi::OSC_TITLE] = txt);
utf8 = jet_left + utf8;
owner.base::riseup<tier::preview>(e2::form::prop::header, utf8);
}
else
{
auto& utf8 = (props[property] = txt);
if (property == ansi::OSC_TITLE)
{
utf8 = jet_left + utf8;
owner.base::riseup<tier::preview>(e2::form::prop::header, utf8);
}
}
}
// w_tracking: CSI n n Device status report (DSR).
void report(iota n)
{
switch(n)
{
default:
case 6: queue.report(owner.target->coord); break;
case 5: queue.add("OK"); break;
}
owner.answer(queue);
}
// w_tracking: Manage terminal window props (XTWINOPS).
void manage(fifo& q)
{
owner.target->flush();
static constexpr iota get_label = 20; // Report icon label. (Report as OSC L label ST).
static constexpr iota get_title = 21; // Report window title. (Report as OSC l title ST).
static constexpr iota put_stack = 22; // Push icon label and window title to stack.
static constexpr iota pop_stack = 23; // Pop icon label and window title from stack.
static constexpr iota all_title = 0; // Sub commands.
static constexpr iota label = 1; // Sub commands.
static constexpr iota title = 2; // Sub commands.
switch (auto option = q(0))
{
// Return an empty string for security reasons
case get_label: owner.answer(queue.osc(ansi::OSC_LABEL_REPORT, "")); break;
case get_title: owner.answer(queue.osc(ansi::OSC_TITLE_REPORT, "")); break;
case put_stack:
{
auto push = [&](auto const& property){
stack[property].push_back(props[property]);
};
switch (q(all_title))
{
case title: push(ansi::OSC_TITLE); break;
case label: push(ansi::OSC_LABEL); break;
case all_title: push(ansi::OSC_TITLE);
push(ansi::OSC_LABEL); break;
default: break;
}
break;
}
case pop_stack:
{
auto pop = [&](auto const& property){
auto& s = stack[property];
if (s.size())
{
set(property, s.back());
s.pop_back();
}
};
switch (q(all_title))
{
case title: pop(ansi::OSC_TITLE); break;
case label: pop(ansi::OSC_LABEL); break;
case all_title: pop(ansi::OSC_TITLE);
pop(ansi::OSC_LABEL); break;
default: break;
}
break;
}
default:
log("CSI ", option, "... t (XTWINOPS) is not supported");
break;
}
}
};
// term: Terminal 16/256 color palette tracking functionality.
struct c_tracking
{
using pals = std::remove_const_t<decltype(rgba::color256)>;
using func = std::unordered_map<text, std::function<void(view)>>;
term& owner; // c_tracking: Terminal object reference.
pals color; // c_tracking: 16/256 colors palette.
func procs; // c_tracking: Handlers.
void reset()
{
std::copy(std::begin(rgba::color256), std::end(rgba::color256), std::begin(color));
}
auto to_byte(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return 0;
}
std::optional<ui32> record(view& data) // ; rgb:00/00/00
{
//todo implement request "?"
utf::trim_front(data, " ;");
if (data.length() >= 12 && data.starts_with("rgb:"))
{
auto r1 = to_byte(data[ 4]);
auto r2 = to_byte(data[ 5]);
auto g1 = to_byte(data[ 7]);
auto g2 = to_byte(data[ 8]);
auto b1 = to_byte(data[10]);
auto b2 = to_byte(data[11]);
data.remove_prefix(12); // rgb:00/00/00
return { (r1 << 4 ) + (r2 )
+ (g1 << 12) + (g2 << 8 )
+ (b1 << 20) + (b2 << 16)
+ 0xFF000000 };
}
return {};
}
void notsupported(text const& property, view data)
{
log(" Not supported: OSC=", property, " DATA=", data, " SIZE=", data.length(), " HEX=", utf::to_hex(data));
}
c_tracking(term& owner)
: owner{ owner }
{
reset();
procs[ansi::OSC_LINUX_COLOR] = [&](view data) // ESC ] P Nrrggbb
{
if (data.length() >= 7)
{
auto n = to_byte(data[0]);
auto r1 = to_byte(data[1]);
auto r2 = to_byte(data[2]);
auto g1 = to_byte(data[3]);
auto g2 = to_byte(data[4]);
auto b1 = to_byte(data[5]);
auto b2 = to_byte(data[6]);
color[n] = (r1 << 4 ) + (r2 )
+ (g1 << 12) + (g2 << 8 )
+ (b1 << 20) + (b2 << 16)
+ 0xFF000000;
}
};
procs[ansi::OSC_RESET_COLOR] = [&](view data) // ESC ] 104 ; 0; 1;...
{
auto empty = true;
while(data.length())
{
utf::trim_front_if(data, [](char c){ return c >= '0' && c <= '9'; });
if (auto v = utf::to_int(data))
{
auto n = std::clamp(v.value(), 0, 255);
color[n] = rgba::color256[n];
empty = faux;
}
}
if (empty) reset();
};
procs[ansi::OSC_SET_PALETTE] = [&](view data) // ESC ] 4 ; 0;rgb:00/00/00;1;rgb:00/00/00;...
{
auto fails = faux;
while (data.length())
{
utf::trim_front(data, " ;");
if (auto v = utf::to_int(data))
{
auto n = std::clamp(v.value(), 0, 255);
if (auto r = record(data))
{
color[n] = r.value();
}
else
{
fails = true;
break;
}
}
else
{
fails = true;
break;
}
}
if (fails) notsupported(ansi::OSC_SET_PALETTE, data);
};
procs[ansi::OSC_LINUX_RESET] = [&](view data) // ESC ] R
{
reset();
};
procs[ansi::OSC_SET_FGCOLOR] = [&](view data) // ESC ] 10 ;rgb:00/00/00
{
if (auto r = record(data))
{
owner.target->brush.sfg(r.value());
}
else notsupported(ansi::OSC_SET_FGCOLOR, data);
};
procs[ansi::OSC_SET_BGCOLOR] = [&](view data) // ESC ] 11 ;rgb:00/00/00
{
if (auto r = record(data))
{
owner.target->brush.sbg(r.value());
}
else notsupported(ansi::OSC_SET_BGCOLOR, data);
};
procs[ansi::OSC_RESET_FGCLR] = [&](view data)
{
owner.target->brush.sfg(0);
};
procs[ansi::OSC_RESET_BGCLR] = [&](view data)
{
owner.target->brush.sbg(0);
};
}
void set(text const& property, view data)
{
auto proc = procs.find(property);
if (proc != procs.end())
{
proc->second(data);
}
else log(" Not supported: OSC=", property, " DATA=", data, " HEX=", utf::to_hex(data));
}
void fgc(tint c) { owner.target->brush.fgc(color[c]); }
void bgc(tint c) { owner.target->brush.bgc(color[c]); }
};
// term: Generic terminal buffer.
struct bufferbase
: public ansi::parser
{
template<class T>
static void parser_config(T& vt)
{
using namespace netxs::ansi;
vt.csier.table_space[CSI_SPC_SRC] = VT_PROC{ p->na("CSI n SP A Shift right n columns(s)."); }; // CSI n SP A Shift right n columns(s).
vt.csier.table_space[CSI_SPC_SLC] = VT_PROC{ p->na("CSI n SP @ Shift left n columns(s)."); }; // CSI n SP @ Shift left n columns(s).
vt.csier.table_space[CSI_SPC_CST] = VT_PROC{ p->owner.cursor.style(q(1)); }; // CSI n SP q Set cursor style (DECSCUSR).
vt.csier.table_hash [CSI_HSH_SCP] = VT_PROC{ p->na("CSI n # P Push current palette colors onto stack. n default is 0."); }; // CSI n # P Push current palette colors onto stack. n default is 0.
vt.csier.table_hash [CSI_HSH_RCP] = VT_PROC{ p->na("CSI n # Q Pop current palette colors onto stack. n default is 0."); }; // CSI n # Q Pop current palette colors onto stack. n default is 0.
vt.csier.table_excl [CSI_EXL_RST] = VT_PROC{ p->owner.decstr( ); }; // CSI ! p Soft terminal reset (DECSTR)
vt.csier.table[CSI_SGR][SGR_FG_BLK ] = VT_PROC{ p->owner.ctrack.fgc(tint::blackdk ); };
vt.csier.table[CSI_SGR][SGR_FG_RED ] = VT_PROC{ p->owner.ctrack.fgc(tint::reddk ); };
vt.csier.table[CSI_SGR][SGR_FG_GRN ] = VT_PROC{ p->owner.ctrack.fgc(tint::greendk ); };
vt.csier.table[CSI_SGR][SGR_FG_YLW ] = VT_PROC{ p->owner.ctrack.fgc(tint::yellowdk ); };
vt.csier.table[CSI_SGR][SGR_FG_BLU ] = VT_PROC{ p->owner.ctrack.fgc(tint::bluedk ); };
vt.csier.table[CSI_SGR][SGR_FG_MGT ] = VT_PROC{ p->owner.ctrack.fgc(tint::magentadk); };
vt.csier.table[CSI_SGR][SGR_FG_CYN ] = VT_PROC{ p->owner.ctrack.fgc(tint::cyandk ); };
vt.csier.table[CSI_SGR][SGR_FG_WHT ] = VT_PROC{ p->owner.ctrack.fgc(tint::whitedk ); };
vt.csier.table[CSI_SGR][SGR_FG_BLK_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::blacklt ); };
vt.csier.table[CSI_SGR][SGR_FG_RED_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::redlt ); };
vt.csier.table[CSI_SGR][SGR_FG_GRN_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::greenlt ); };
vt.csier.table[CSI_SGR][SGR_FG_YLW_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::yellowlt ); };
vt.csier.table[CSI_SGR][SGR_FG_BLU_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::bluelt ); };
vt.csier.table[CSI_SGR][SGR_FG_MGT_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::magentalt); };
vt.csier.table[CSI_SGR][SGR_FG_CYN_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::cyanlt ); };
vt.csier.table[CSI_SGR][SGR_FG_WHT_LT] = VT_PROC{ p->owner.ctrack.fgc(tint::whitelt ); };
vt.csier.table[CSI_SGR][SGR_BG_BLK ] = VT_PROC{ p->owner.ctrack.bgc(tint::blackdk ); };
vt.csier.table[CSI_SGR][SGR_BG_RED ] = VT_PROC{ p->owner.ctrack.bgc(tint::reddk ); };
vt.csier.table[CSI_SGR][SGR_BG_GRN ] = VT_PROC{ p->owner.ctrack.bgc(tint::greendk ); };
vt.csier.table[CSI_SGR][SGR_BG_YLW ] = VT_PROC{ p->owner.ctrack.bgc(tint::yellowdk ); };
vt.csier.table[CSI_SGR][SGR_BG_BLU ] = VT_PROC{ p->owner.ctrack.bgc(tint::bluedk ); };
vt.csier.table[CSI_SGR][SGR_BG_MGT ] = VT_PROC{ p->owner.ctrack.bgc(tint::magentadk); };
vt.csier.table[CSI_SGR][SGR_BG_CYN ] = VT_PROC{ p->owner.ctrack.bgc(tint::cyandk ); };
vt.csier.table[CSI_SGR][SGR_BG_WHT ] = VT_PROC{ p->owner.ctrack.bgc(tint::whitedk ); };
vt.csier.table[CSI_SGR][SGR_BG_BLK_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::blacklt ); };
vt.csier.table[CSI_SGR][SGR_BG_RED_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::redlt ); };
vt.csier.table[CSI_SGR][SGR_BG_GRN_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::greenlt ); };
vt.csier.table[CSI_SGR][SGR_BG_YLW_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::yellowlt ); };
vt.csier.table[CSI_SGR][SGR_BG_BLU_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::bluelt ); };
vt.csier.table[CSI_SGR][SGR_BG_MGT_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::magentalt); };
vt.csier.table[CSI_SGR][SGR_BG_CYN_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::cyanlt ); };
vt.csier.table[CSI_SGR][SGR_BG_WHT_LT] = VT_PROC{ p->owner.ctrack.bgc(tint::whitelt ); };
vt.csier.table[CSI_CUU] = VT_PROC{ p->up ( q(1)); }; // CSI n A (CUU)
vt.csier.table[CSI_CUD] = VT_PROC{ p->dn ( q(1)); }; // CSI n B (CUD)
vt.csier.table[CSI_CUF] = VT_PROC{ p->cuf( q(1)); }; // CSI n C (CUF)
vt.csier.table[CSI_CUB] = VT_PROC{ p->cuf(-q(1)); }; // CSI n D (CUB)
vt.csier.table[CSI_CHT] = VT_PROC{ p->tab( q(1)); }; // CSI n I Caret forward n tabs, default n=1.
vt.csier.table[CSI_CBT] = VT_PROC{ p->tab(-q(1)); }; // CSI n Z Caret backward n tabs, default n=1.
vt.csier.table[CSI_TBC] = VT_PROC{ p->tbc( q(1)); }; // CSI n g Reset tabstop value.
vt.csier.table[CSI_CUD2]= VT_PROC{ p->dn ( q(1)); }; // CSI n e Vertical position relative. Move cursor down (VPR).
vt.csier.table[CSI_CNL] = vt.csier.table[CSI_CUD]; // CSI n E
vt.csier.table[CSI_CPL] = vt.csier.table[CSI_CUU]; // CSI n F
vt.csier.table[CSI_CHX] = VT_PROC{ p->chx( q(1)); }; // CSI n G Move cursor hz absolute.
vt.csier.table[CSI_CHY] = VT_PROC{ p->chy( q(1)); }; // CSI n d Move cursor vt absolute.
vt.csier.table[CSI_CUP] = VT_PROC{ p->cup( q ); }; // CSI y ; x H (1-based)
vt.csier.table[CSI_HVP] = VT_PROC{ p->cup( q ); }; // CSI y ; x f (1-based)
vt.csier.table[CSI_DCH] = VT_PROC{ p->dch( q(1)); }; // CSI n P Delete n chars (DCH).
vt.csier.table[CSI_ECH] = VT_PROC{ p->ech( q(1)); }; // CSI n X Erase n chars (ECH).
vt.csier.table[CSI_ICH] = VT_PROC{ p->ins( q(1)); }; // CSI n @ Insert n chars (ICH).
vt.csier.table[CSI__ED] = VT_PROC{ p->ed ( q(0)); }; // CSI n J
vt.csier.table[CSI__EL] = VT_PROC{ p->el ( q(0)); }; // CSI n K
vt.csier.table[CSI__IL] = VT_PROC{ p->il ( q(1)); }; // CSI n L Insert n lines (IL).
vt.csier.table[CSI__DL] = VT_PROC{ p->dl ( q(1)); }; // CSI n M Delete n lines (DL).
vt.csier.table[CSI__SD] = VT_PROC{ p->scl( q(1)); }; // CSI n T Scroll down by n lines, scrolled out lines are lost.
vt.csier.table[CSI__SU] = VT_PROC{ p->scl(-q(1)); }; // CSI n S Scroll up by n lines, scrolled out lines are pushed to the scrollback.
vt.csier.table[CSI_SCP] = VT_PROC{ p->scp( ); }; // CSI s Save cursor position.
vt.csier.table[CSI_RCP] = VT_PROC{ p->rcp( ); }; // CSI u Restore cursor position.
vt.csier.table[DECSTBM] = VT_PROC{ p->scr( q ); }; // CSI r; b r Set scrolling region (t/b: top+bottom).
vt.csier.table[CSI_WIN] = VT_PROC{ p->owner.wtrack.manage(q ); }; // CSI n;m;k t Terminal window options (XTWINOPS).
vt.csier.table[CSI_DSR] = VT_PROC{ p->owner.wtrack.report(q(6)); }; // CSI n n Device status report (DSR).
vt.csier.table[CSI_CCC][CCC_SBS] = VT_PROC{ p->owner.sbsize(q); }; // CCC_SBS: Set scrollback size.
vt.csier.table[CSI_CCC][CCC_EXT] = VT_PROC{ p->owner.native(q(1)); }; // CCC_EXT: Setup extended functionality.
vt.csier.table[CSI_CCC][CCC_RST] = VT_PROC{ p->style.glb(); p->style.wrp(deco::defwrp); }; // fx_ccc_rst
vt.intro[ctrl::ESC][ESC_IND] = VT_PROC{ p->lf(1); }; // ESC D Index. Caret down and scroll if needed (IND).
vt.intro[ctrl::ESC][ESC_IR ] = VT_PROC{ p->ri (); }; // ESC M Reverse index (RI).
vt.intro[ctrl::ESC][ESC_HTS] = VT_PROC{ p->stb(); }; // ESC H Place tabstop at the current cursor posistion.
vt.intro[ctrl::ESC][ESC_SC ] = VT_PROC{ p->scp(); }; // ESC 7 (same as CSI s) Save cursor position.
vt.intro[ctrl::ESC][ESC_RC ] = VT_PROC{ p->rcp(); }; // ESC 8 (same as CSI u) Restore cursor position.
vt.intro[ctrl::ESC][ESC_RIS] = VT_PROC{ p->owner.decstr(); }; // ESC c Reset to initial state (same as DECSTR).
vt.intro[ctrl::BS ] = VT_PROC{ p->cuf(-q.pop_all(ctrl::BS )); };
vt.intro[ctrl::DEL] = VT_PROC{ p->del( q.pop_all(ctrl::DEL)); };
vt.intro[ctrl::TAB] = VT_PROC{ p->tab( q.pop_all(ctrl::TAB)); };
vt.intro[ctrl::EOL] = VT_PROC{ p->lf ( q.pop_all(ctrl::EOL)); }; // LF.
vt.intro[ctrl::CR ] = VT_PROC{ p->cr (); }; // CR.
vt.csier.table_quest[DECSET] = VT_PROC{ p->owner.decset(q); };
vt.csier.table_quest[DECRST] = VT_PROC{ p->owner.decrst(q); };
vt.oscer[OSC_LABEL_TITLE] = VT_PROC{ p->owner.wtrack.set(OSC_LABEL_TITLE, q); };
vt.oscer[OSC_LABEL] = VT_PROC{ p->owner.wtrack.set(OSC_LABEL, q); };
vt.oscer[OSC_TITLE] = VT_PROC{ p->owner.wtrack.set(OSC_TITLE, q); };
vt.oscer[OSC_XPROP] = VT_PROC{ p->owner.wtrack.set(OSC_XPROP, q); };
vt.oscer[OSC_LINUX_COLOR] = VT_PROC{ p->owner.ctrack.set(OSC_LINUX_COLOR, q); };
vt.oscer[OSC_LINUX_RESET] = VT_PROC{ p->owner.ctrack.set(OSC_LINUX_RESET, q); };
vt.oscer[OSC_SET_PALETTE] = VT_PROC{ p->owner.ctrack.set(OSC_SET_PALETTE, q); };
vt.oscer[OSC_SET_FGCOLOR] = VT_PROC{ p->owner.ctrack.set(OSC_SET_FGCOLOR, q); };
vt.oscer[OSC_SET_BGCOLOR] = VT_PROC{ p->owner.ctrack.set(OSC_SET_BGCOLOR, q); };
vt.oscer[OSC_RESET_COLOR] = VT_PROC{ p->owner.ctrack.set(OSC_RESET_COLOR, q); };
vt.oscer[OSC_RESET_FGCLR] = VT_PROC{ p->owner.ctrack.set(OSC_RESET_FGCLR, q); };
vt.oscer[OSC_RESET_BGCLR] = VT_PROC{ p->owner.ctrack.set(OSC_RESET_BGCLR, q); };
// Log all unimplemented CSI commands.
for (auto i = 0; i < 0x100; ++i)
{
auto& proc = vt.csier.table[i];
if (!proc)
{
proc = [i](auto& q, auto& p) { p->not_implemented_CSI(i, q); };
}
}
}
term& owner; // bufferbase: Terminal object reference.
twod panel; // bufferbase: Viewport size.
twod coord; // bufferbase: Viewport cursor position; 0-based.
twod saved; // bufferbase: Saved cursor position.
iota sctop; // bufferbase: Precalculated scrolling region top height.
iota scend; // bufferbase: Precalculated scrolling region bottom height.
iota y_top; // bufferbase: Precalculated 0-based scrolling region top vertical pos.
iota y_end; // bufferbase: Precalculated 0-based scrolling region bottom vertical pos.
iota n_top; // bufferbase: Original 1-based scrolling region top vertical pos (use 0 if it is not set).
iota n_end; // bufferbase: Original 1-based scrolling region bottom vertical pos (use 0 if it is not set).
iota tabsz; // bufferbase: Tabstop current value.
bufferbase(term& master)
: owner{ master },
panel{ dot_11 },
coord{ dot_00 },
saved{ dot_00 },
sctop{ 0 },
scend{ 0 },
y_top{ 0 },
y_end{ 0 },
n_top{ 0 },
n_end{ 0 },
tabsz{ def_tablen }
{
parser::style = ansi::def_style;
}
virtual void output(face& canvas) = 0;
virtual void scroll_region(iota top, iota end, iota n, bool use_scrollback) = 0;
virtual bool recalc_pads(side& oversz) = 0;
virtual iota height() = 0;
virtual void del_above() = 0;
virtual void del_below() = 0;
virtual iota get_size() const = 0;
virtual iota get_peak() const = 0;
virtual iota get_step() const = 0;
auto get_view() const { return panel; }
// bufferbase: .
virtual bool is_need_to_correct()
{
return faux;
}
// bufferbase: .
virtual iota get_basis()
{
return 0;
}
// bufferbase: .
virtual iota get_slide()
{
return 0;
}
// bufferbase: .
virtual bool force_basis()
{
return true;
}
// bufferbase: .
virtual iota set_slide(iota)
{
return 0;
}
// bufferbase: .
void update_region()
{
sctop = std::max(0, n_top - 1);
scend = n_end != 0 ? std::max(1, panel.y - n_end)
: 0;
auto y_max = panel.y - 1;
y_end = std::clamp(y_max - scend, 0, y_max);
y_top = std::clamp(sctop , 0, y_end);
}
// bufferbase: .
virtual void resize_viewport(twod const& new_sz)
{
panel = std::max(new_sz, dot_11);
update_region();
}
// bufferbase: Reset coord and set the scrolling region using 1-based top and bottom. Use 0 to reset.
virtual void set_scroll_region(iota top, iota bottom)
{
// Sanity check.
top = std::clamp(top , 0, panel.y);
bottom = std::clamp(bottom, 0, panel.y);
if (top != 0 &&
//bottom != 0 && top > bottom) top = bottom; //todo Nobody respects that.
bottom != 0 && top >= bottom) top = bottom = 0;
coord = dot_00;
n_top = top == 1 ? 0 : top;
n_end = bottom == panel.y ? 0 : bottom;
update_region();
}
// bufferbase: .
virtual void set_coord(twod const& new_coord)
{
coord = new_coord;
}
// bufferbase: Return current 0-based cursor position in the viewport.
virtual twod get_coord(twod const& origin)
{
return coord;
}
// bufferbase: Base-CSI contract (see ansi::csi_t).
// task(...), meta(...), data(...)
void task(ansi::rule const& property)
{
parser::flush();
log("bufferbase: locus extensions are not supported");
//auto& cur_line = batch.current();
//if (cur_line.busy())
//{
// add_lines(1);
// batch.index(batch.length() - 1);
//}
//batch->locus.push(property);
}
// bufferbase: .
virtual void meta(deco const& old_style) override
{
if (parser::style.wrp() != old_style.wrp())
{
auto status = parser::style.wrp() == wrap::none ? deco::defwrp
: parser::style.wrp();
owner.SIGNAL(tier::release, ui::term::events::layout::wrapln, status);
}
if (parser::style.jet() != old_style.jet())
{
auto status = parser::style.jet() == bias::none ? bias::left
: parser::style.jet();
owner.SIGNAL(tier::release, ui::term::events::layout::align, status);
}
}
// bufferbase: .
template<class T>
void na(T&& note)
{
log("not implemented: ", note);
}
void not_implemented_CSI(iota i, fifo& q)
{
text params;
while (q)
{
params += std::to_string(q(0));
if (q)
{
auto is_sub_arg = q.issub(q.front());
auto delim = is_sub_arg ? ':' : ';';
params.push_back(delim);
}
}
log("CSI ", params, " ", (unsigned char)i, "(", std::to_string(i), ") is not implemented.");
}
// bufferbase: .
virtual void clear_all()
{
parser::state = {};
}
// bufferbase: ESC H Place tabstop at the current cursor posistion.
void stb()
{
parser::flush();
tabsz = std::max(1, coord.x + 1);
}
// bufferbase: TAB Horizontal tab.
virtual void tab(iota n)
{
parser::flush();
if (n > 0)
{
auto new_pos = coord.x + n * tabsz - coord.x % tabsz;
if (new_pos < panel.x) coord.x = new_pos;
}
else if (n < 0)
{
n = -n - 1;
auto count = n * tabsz + coord.x % tabsz;
coord.x = std::max(0, coord.x - count);
}
}
// bufferbase: CSI n g Reset tabstop value.
void tbc(iota n)
{
parser::flush();
tabsz = def_tablen;
}
// bufferbase: ESC 7 or CSU s Save cursor position.
void scp()
{
parser::flush();
saved = coord;
}
// bufferbase: ESC 8 or CSU u Restore cursor position.
void rcp()
{
parser::flush();
set_coord(saved);
}
// bufferbase: CSI n T/S Scroll down/up, scrolled up lines are pushed to the scrollback buffer.
virtual void scl(iota n)
{
parser::flush();
scroll_region(y_top, y_end, n, n > 0 ? faux : true);
}
// bufferbase: CSI n L Insert n lines. Place cursor to the begining of the current.
virtual void il(iota n)
{
parser::flush();
/* Works only if cursor is in the scroll region.
* Inserts n lines at the current row and removes n lines at the scroll bottom.
*/
if (n > 0 && coord.y >= y_top
&& coord.y <= y_end)
{
scroll_region(coord.y, y_end, n, faux);
coord.x = 0;
}
}
// bufferbase: CSI n M Delete n lines. Place cursor to the begining of the current.
virtual void dl(iota n)
{
parser::flush();
/* Works only if cursor is in the scroll region.
* Deletes n lines at the current row and add n lines at the scroll bottom.
*/
if (n > 0 && coord.y >= y_top
&& coord.y <= y_end)
{
scroll_region(coord.y, y_end, -n, faux);
coord.x = 0;
}
}
// bufferbase: ESC M Reverse index.
virtual void ri()
{
parser::flush();
/*
* Reverse index
* - move cursor one line up if it is outside of scrolling region or below the top line of scrolling region.
* - one line scroll down if cursor is on the top line of scroll region.
*/
if (coord.y != y_top)
{
coord.y--;
}
else scroll_region(y_top, y_end, 1, true);
}
// bufferbase: CSI t;b r - Set scrolling region (t/b: top+bottom).
void scr(fifo& queue)
{
auto top = queue(0);
auto end = queue(0);
set_scroll_region(top, end);
}
// bufferbase: CSI n @ ICH. Insert n blanks after cursor. Don't change cursor pos.
virtual void ins(iota n) = 0;
// bufferbase: Shift left n columns(s).
void shl(iota n)
{
log("bufferbase: SHL(n=", n, ") is not implemented.");
}
// bufferbase: CSI n X Erase/put n chars after cursor. Don't change cursor pos.
virtual void ech(iota n) = 0;
// bufferbase: CSI n P Delete (not Erase) letters under the cursor.
virtual void dch(iota n) = 0;
// bufferbase: '\x7F' Delete characters backwards.
void del(iota n)
{
log("bufferbase: not implemented: '\\x7F' Delete characters backwards.");
}
// bufferbase: Move cursor forward by n.
virtual void cuf(iota n)
{
parser::flush();
coord.x += n;
}
// bufferbase: CSI n G Absolute horizontal cursor position (1-based).
virtual void chx(iota n)
{
parser::flush();
coord.x = n - 1;
}
// bufferbase: CSI n d Absolute vertical cursor position (1-based).
virtual void chy(iota n)
{
parser::flush();
coord.y = std::clamp(n, 1, panel.y) - 1;
assert(panel.inside(coord));
}
// bufferbase: CSI y; x H/F Caret position (1-based).
virtual void cup(fifo& queue)
{
parser::flush();
auto y = queue(1);
auto x = queue(1);
auto p = twod{ x, y };
coord = std::clamp(p, dot_11, panel) - dot_11;
}
// bufferbase: Move cursor up.
virtual void up(iota n)
{
parser::flush();
auto new_coord_y = coord.y - n;
if (new_coord_y < y_top
&& coord.y >= y_top)
{
coord.y = y_top;
}
else coord.y = std::clamp(new_coord_y, 0, panel.y - 1);
}
// bufferbase: Move cursor down.
virtual void dn(iota n)
{
parser::flush();
auto new_coord_y = coord.y + n;
if (new_coord_y > y_end
&& coord.y <= y_end)
{
coord.y = y_end;
}
else coord.y = std::clamp(new_coord_y, 0, panel.y - 1);
}
// bufferbase: Line feed. Index. Scroll region up if new_coord_y > end.
virtual void lf(iota n)
{
parser::flush();
auto new_coord_y = coord.y + n;
if (new_coord_y > y_end
&& coord.y <= y_end)
{
auto n = y_end - new_coord_y;
scroll_region(y_top, y_end, n, true);
coord.y = y_end;
}
else coord.y = std::clamp(new_coord_y, 0, panel.y - 1);
}
// bufferbase: '\r' CR Cursor return. Go to home of visible line instead of home of paragraph.
virtual void cr()
{
parser::flush();
coord.x = 0;
}
// bufferbase: CSI n J Erase display.
void ed(iota n)
{
parser::flush();
switch (n)
{
case commands::erase::display::below: // n = 0 (default) Erase viewport after cursor.
del_below();
break;
case commands::erase::display::above: // n = 1 Erase viewport before cursor.
del_above();
break;
case commands::erase::display::viewport: // n = 2 Erase viewport.
set_coord(dot_00);
ed(commands::erase::display::below);
break;
case commands::erase::display::scrollback: // n = 3 Erase scrollback.
clear_all();
break;
default:
break;
}
}
// bufferbase: CSI n K Erase line (don't move cursor).
virtual void el(iota n) = 0;
bool update_status(term_state& status) const
{
bool changed = faux;
if (status.size != get_size()) { changed = true; status.size = get_size(); }
if (status.peak != get_peak()) { changed = true; status.peak = get_peak(); }
if (status.step != get_step()) { changed = true; status.step = get_step(); }
if (status.area != get_view()) { changed = true; status.area = get_view(); }
return changed;
}
};
// term: Alternate screen buffer implementation.
struct alt_screen
: public bufferbase
{
rich canvas; // alt_screen: Terminal screen.
alt_screen(term& boss)
: bufferbase{ boss }
{ }
iota get_size() const override { return panel.y; }
iota get_peak() const override { return panel.y; }
iota get_step() const override { return 0; }
// alt_screen: Resize viewport.
void resize_viewport(twod const& new_sz) override
{
bufferbase::resize_viewport(new_sz);
coord = std::clamp(coord, dot_00, panel - dot_11);
canvas.crop(panel);
}
// alt_screen: Return viewport height.
iota height() override
{
return panel.y;
}
// alt_screen: Recalc left and right oversize (Always 0 for altbuf).
bool recalc_pads(side& oversz) override
{
auto left = 0;
auto rght = 0;
if (oversz.r != rght
|| oversz.l != left)
{
oversz.r = rght;
oversz.l = left;
return true;
}
else return faux;
}
static void _el(iota n, core& canvas, twod const& coord, twod const& panel, cell const& blank)
{
assert(coord.y < panel.y);
assert(coord.x >= 0);
auto size = canvas.size();
auto head = canvas.iter() + coord.y * size.x;
auto tail = head;
switch (n)
{
default:
case commands::erase::line::right: // n = 0 (default) Erase to Right.
head += std::min(panel.x, coord.x);
tail += panel.x;
break;
case commands::erase::line::left: // n = 1 Erase to Left.
tail += std::min(panel.x, coord.x);
break;
case commands::erase::line::all: // n = 2 Erase All.
tail += panel.x;
break;
}
while (head != tail) *head++ = blank;
}
// alt_screen: CSI n K Erase line (don't move cursor).
void el(iota n) override
{
bufferbase::flush();
_el(n, canvas, coord, panel, brush.spc());
}
// alt_screen: CSI n @ ICH. Insert n blanks after cursor. No wrap. Existing chars after cursor shifts to the right. Don't change cursor pos.
void ins(iota n) override
{
bufferbase::flush();
assert(coord.y < panel.y);
assert(coord.x >= 0);
auto blank = brush.spc();//.bgc(reddk).bga(0x7f);
canvas.insert(coord, n, blank);
}
// alt_screen: CSI n P Delete (not Erase) letters under the cursor.
void dch(iota n) override
{
bufferbase::flush();
auto blank = brush.spc();//.bgc(cyandk).bga(0x7f);
canvas.cutoff(coord, n, blank);
}
// alt_screen: CSI n X Erase/put n chars after cursor. Don't change cursor pos.
void ech(iota n) override
{
parser::flush();
auto blank = brush.spc();//.bgc(greendk).bga(0x7f);
canvas.splice(coord, n, blank);
}
// alt_screen: Parser callback.
void data(iota count, grid const& proto) override
{
assert(coord.y >= 0 && coord.y < panel.y);
auto saved = coord;
coord.x += count;
//todo apply line adjusting (necessity is not clear)
if (coord.x <= panel.x)//todo styles! || ! curln.wrapped())
{
auto n = std::min(count, panel.x - std::max(0, saved.x));
canvas.splice(saved, n, proto);
}
else
{
coord.y += (coord.x + panel.x - 1) / panel.x - 1;
coord.x = (coord.x - 1) % panel.x + 1;
if (saved.y < y_top)
{
if (coord.y >= y_top)
{
auto n = coord.x + (coord.y - y_top) * panel.x;
count -= n;
set_coord({ 0, y_top });
data(n, proto); // Reversed fill using the last part of the proto.
}
auto data = proto.begin();
auto seek = saved.x + saved.y * panel.x;
auto dest = canvas.iter() + seek;
auto tail = dest + count;
rich::forward_fill_proc(data, dest, tail);
}
else if (saved.y <= y_end)
{
if (coord.y > y_end)
{
auto dy = y_end - coord.y;
coord.y = y_end;
canvas.scroll(y_top, y_end + 1, dy, brush.spare);
}
auto seek = coord.x + coord.y * panel.x;
auto miny = seek - y_top * panel.x;
if (count > miny) count = miny;
auto dest = canvas.iter() + seek;
auto tail = dest - count;
auto data = proto.end();
rich::reverse_fill_proc(data, dest, tail);
}
else
{
if (coord.y >= panel.y) coord.y = panel.y - 1;
auto data = proto.begin();
auto size = count;
auto seek = saved.x + saved.y * panel.x;
auto dest = canvas.iter() + seek;
auto tail = canvas.iend();
auto back = panel.x;
rich::unlimit_fill_proc(data, size, dest, tail, back);
}
}
}
// alt_screen: Clear viewport.
void clear_all() override
{
saved = dot_00;
coord = dot_00;
canvas.wipe();
set_scroll_region(0, 0);
bufferbase::clear_all();
}
// alt_screen: Render to the target.
void output(face& target) override
{
auto full = target.full();
canvas.move(full.coor);
target.plot(canvas, cell::shaders::fuse);
}
// alt_screen: Remove all lines below except the current. "ED2 Erase viewport" keeps empty lines.
void del_below() override
{
canvas.del_below(coord, brush.spare);
}
// alt_screen: Clear all lines from the viewport top line to the current line.
void del_above() override
{
canvas.del_above(coord, brush.spare);
}
// alt_screen: Shift by n the scroll region.
void scroll_region(iota top, iota end, iota n, bool use_scrollback = faux) override
{
canvas.scroll(top, end + 1, n, brush.spare);
}
};
// term: Scrollback buffer implementation.
struct scroll_buf
: public bufferbase
{
struct line
: public rich
{
using rich::rich;
using type = deco::type;
using id_t = ui32;
line(line&& l)
: rich { std::forward<rich>(l) },
index{ l.index }
{
style = l.style;
_size = l._size;
_kind = l._kind;
l._size = {};
l._kind = {};
}
line(line const& l)
: rich { l },
index{ l.index },
style{ l.style }
{ }
line(id_t newid, deco const& style = {})
: index{ newid },
style{ style }
{ }
line(id_t newid, deco const& style, span const& dt, twod const& sz)
: rich { dt,sz },
index{ newid },
style{ style }
{ }
line& operator = (line&&) = default;
line& operator = (line const&) = default;
id_t index{};
ui64 accum{};
deco style{};
iota _size{};
type _kind{};
friend void swap(line& lhs, line& rhs)
{
std::swap<rich>(lhs, rhs);
std::swap(lhs.index, rhs.index);
std::swap(lhs.style, rhs.style);
std::swap(lhs._size, rhs._size);
std::swap(lhs._kind, rhs._kind);
}
void wipe()
{
rich::kill();
_size = {};
_kind = {};
}
auto wrapped() const
{
assert(_kind == style.get_kind());
return _kind == type::autowrap;
}
iota height(iota width) const
{
auto len = length();
assert(_kind == style.get_kind());
return len > width
&& wrapped() ? (len + width - 1) / width
: 1;
}
auto to_txt() // for debug
{
utf::text utf8;
each([&](cell& c){ utf8 += c.txt(); });
return utf8;
}
};
struct index_item
{
using id_t = line::id_t;
id_t index;
iota start;
iota width;
index_item() = default;
index_item(id_t index, iota start, iota width)
: index{ index },
start{ start },
width{ width }
{ }
};
using ring = generics::ring<std::vector<line>, true>;
using indx = generics::ring<std::vector<index_item>>;
struct buff : public ring
{
using ring::ring;
using type = line::type;
iota caret{}; // buff: Current line caret horizontal position.
iota vsize{}; // buff: Scrollback vertical size (height).
iota width{}; // buff: Viewport width.
id_t taken{}; // buff: The index up to which the cells are already counted.
ui64 accum{}; // buff: The total number of cells in the stored lines.
bool dirty{}; // buff: Indicator that not all available cells have been counted (lazy counting).
iota basis{}; // buff: Working area basis. Vertical position of O(0, 0) in the scrollback.
iota slide{}; // buff: Viewport vertical position in the scrollback.
id_t anchor_id{}; // the nearest id to the slide
iota anchor_dy{}; // distance to the slide.
bool need_to_correct{};
bool round{};
static constexpr id_t threshold = 1000;
static constexpr ui64 lnpadding = 40; // Padding to improve accuracy.
//todo optimize for large lines, use std::unordered_map<iota, iota>
// buff: Line length accounting database.
struct maxs : public std::vector<iota>
{
iota max = 0;
maxs() : std::vector<iota>(1) { }
void prev_max() { while (max > 0 && !at(--max)); }
}
lens[type::count];
// buff: Decrease the height.
void dec_height(iota& vsize, type kind, iota size)
{
if (size > width && kind == type::autowrap) vsize -= (size + width - 1) / width;
else vsize -= 1;
}
// buff: Increase the height.
void add_height(iota& vsize, type kind, iota size)
{
if (size > width && kind == type::autowrap) vsize += (size + width - 1) / width;
else vsize += 1;
}
// buff: Recalc the height for unlimited scrollback without using reflow.
void set_width(iota new_width)
{
vsize = 0;
width = std::max(1, new_width);
for (auto kind : { type::leftside,
type::rghtside,
type::centered })
{
auto& cur_lens = lens[kind];
auto head = cur_lens.begin();
auto tail = head + cur_lens.max + 1;
do vsize += *head++;
while (head != tail);
}
auto kind = type::autowrap;
auto& cur_lens = lens[kind];
auto head = cur_lens.begin();
auto tail = head + cur_lens.max + 1;
auto c = 0;
auto h = 1;
do
{
if (auto count = *head++) vsize += h * count;
if (++c > width)
{
c = 1;
++h;
}
}
while (head != tail);
}
// buff: Check buffer size.
void check_size(twod const new_size)
{
set_width(new_size.x);
if (ring::peak <= new_size.y)
{
static constexpr auto BOTTOM_ANCHORED = true;
ring::resize<BOTTOM_ANCHORED>(new_size.y, ring::step);
}
}
// buff: Register new line.
void invite(type& kind, iota& size, type new_kind, iota new_size)
{
auto& new_lens = lens[new_kind];
if (new_lens.size() <= new_size) new_lens.resize(new_size * 2 + 1);
++new_lens[new_size];
add_height(vsize, new_kind, new_size);
if (new_lens.max < new_size) new_lens.max = new_size;
size = new_size;
kind = new_kind;
}
// buff: Refresh scrollback height.
void recalc(type& kind, iota& size, type new_kind, iota new_size)
{
if (size != new_size
|| kind != new_kind)
{
auto& new_lens = lens[new_kind];
if (new_lens.size() <= new_size) new_lens.resize(new_size * 2 + 1);
if (new_size < size
|| new_kind != kind)
{
undock(kind, size);
}
else
{
--lens[kind][size];
dec_height(vsize, kind, size);
}
++new_lens[new_size];
add_height(vsize, new_kind, new_size);
if (new_lens.max < new_size) new_lens.max = new_size;
size = new_size;
kind = new_kind;
}
}
// buff: Discard the specified metrics.
void undock(type kind, iota size)
{
auto& cur_lens = lens[kind];
auto cur_count = --cur_lens[size];
if (size == cur_lens.max && cur_count == 0)
{
cur_lens.prev_max();
}
dec_height(vsize, kind, size);
}
// buff: Push back the specified line.
void invite(line& l)
{
dirty = true;
invite(l._kind, l._size, l.style.get_kind(), l.length());
}
// buff: Push back the new line.
template<class ...Args>
auto& invite(Args&&... args)
{
dirty = true;
auto& l = ring::push_back(std::forward<Args>(args)...);
invite(l._kind, l._size, l.style.get_kind(), l.length());
return l;
}
// buff: Insert the new line at the specified position.
template<class ...Args>
auto& insert(iota at, Args&&... args)
{
dirty = true;
auto& l = *ring::insert(at, std::forward<Args>(args)...);
invite(l._kind, l._size, l.style.get_kind(), l.length());
return l;
}
// buff: Remove the specified line info from accounting and update the metrics based on the scrollback height.
void undock_base_front(line& l) override
{
auto kind = l._kind;
auto size = l._size;
undock(kind, size);
dec_height(basis, kind, size);
dec_height(slide, kind, size);
if (basis < 0) basis = 0;
if (slide < 0)
{
anchor_id = l.index + 1;
anchor_dy = 0;
slide = 0;
}
need_to_correct = true;
}
// buff: Remove information about the specified line from accounting.
void undock_base_back (line& l) override { undock(l._kind, l._size); }
// buff: Return an item position in the scrollback using its id.
template<auto N> auto max() { return lens[N].max; }
auto index_by_id(ui32 id)
{
//No need to disturb distant objects, it may already be in the swap.
auto count = length();
return static_cast<iota>(count - 1 - (back().index - id)); // ring buffer size is never larger than max_int32.
}
// buff: Return an iterator pointing to the item with the specified id.
auto iter_by_id(ui32 id)
{
return begin() + index_by_id(id);
}
// buff: Return an item reference using its id.
auto& item_by_id(ui32 id)
{
return ring::at(index_by_id(id));
}
// buff: Refresh the scrollback size in cells, starting at the specified index.
void recalc_size(iota taken_index)
{
auto head = begin() + std::max(0, taken_index);
auto tail = end();
auto& curln = *head;
auto accum = curln.accum;
//auto i = 0;
//log(" i=", i++, " curln.accum=", accum);
accum += curln.length() + lnpadding;
while (++head != tail)
{
auto& curln = *head;
curln.accum = accum;
//log(" i=", i++, " curln.accum=", accum);
accum += curln.length() + lnpadding;
}
dirty = faux;
//log( " recalc_size taken_index=", taken_index);
}
// buff: Return the scrollback size in cells.
auto get_size_in_cells()
{
auto& endln = back();
auto& endid = endln.index;
auto count = length();
auto taken_index = static_cast<iota>(count - 1 - (endid - taken));
if (taken != endid || dirty)
{
auto& topln = front();
recalc_size(taken_index);
taken = endln.index;
accum = endln.accum
+ endln.length() + lnpadding
- topln.accum;
//log(" topln.accum=", topln.accum,
// " endln.accum=", endln.accum,
// " vsize=", vsize,
// " accum=", accum);
}
return accum;
}
// buff: Refresh metrics due to the specified modified line.
void recalc(line& l)
{
recalc(l._kind, l._size, l.style.get_kind(), l.length());
dirty = true;
auto taken_index = index_by_id(taken);
auto curln_index = index_by_id(l.index);
if (curln_index < taken_index)
{
taken = l.index;
taken_index = curln_index;
}
if (ring::size - taken_index > threshold)
{
recalc_size(taken_index);
taken = back().index;
}
}
// buff: Rewrite the indices from the specified position to the end.
void reindex(iota from)
{
auto head = begin() + from;
auto tail = end();
auto indx = from == 0 ? 0
: (head - 1)->index + 1;
while (head != tail)
{
head->index = indx++;
++head;
}
}
// buff: Remove the specified number of lines at the specified position (inclusive).
auto remove(iota at, iota count)
{
count = ring::remove(at, count);
reindex(at);
return count;
}
// buff: Clear scrollback, add one empty line, and reset all metrics.
void clear()
{
ring::clear();
caret = 0;
basis = 0;
accum = 0;
slide = 0;
dirty = 0;
taken = 0;
invite(0); // At least one line must exist.
anchor_id = back().index;
anchor_dy = 0;
set_width(width);
}
};
// For debug
friend auto& operator<< (std::ostream& s, scroll_buf& c)
{
return s << "{ " << c.batch.max<line::type::leftside>() << ","
<< c.batch.max<line::type::rghtside>() << ","
<< c.batch.max<line::type::centered>() << ","
<< c.batch.max<line::type::autowrap>() << " }";
}
buff batch; // scroll_buf: Scrollback container.
indx index; // scroll_buf: Viewport line index.
iota arena; // scroll_buf: Scrollable region height.
face upbox; // scroll_buf: Top margin canvas.
face dnbox; // scroll_buf: Bottom margin canvas.
twod upmin; // scroll_buf: Top margin minimal size.
twod dnmin; // scroll_buf: Bottom margin minimal size.
scroll_buf(term& boss, iota buffer_size, iota grow_step)
: bufferbase{ boss },
batch{ buffer_size, grow_step },
index{ 0 },
arena{ 1 }
{
batch.invite(0); // At least one line must exist.
batch.set_width(1);
index_rebuild();
}
iota get_size() const override { return batch.size; }
iota get_peak() const override { return batch.peak - 1; }
iota get_step() const override { return batch.step; }
void print_slide(text msg)
{
log(msg, ": ", " batch.basis=", batch.basis, " batch.slide=", batch.slide,
" anchor_id=", batch.anchor_id, " anchor_dy=", batch.anchor_dy, " round=", batch.round ? 1:0);
}
void print_index(text msg)
{
log(" ", msg, " index.size=", index.size, " basis=", batch.basis);
for (auto n = 0; auto& l : index)
{
log(" ", n++,". id=", l.index," offset=", l.start, " width=", l.width);
if (l.start % panel.x != 0) throw;
}
auto& mapln = index.back();
auto& curln = batch.item_by_id(mapln.index);
log(" last ln id=", curln.index, " curln.length()=", curln.length());
log(" -----------------");
}
void print_batch(text msg)
{
log(" ", msg,
" batch.size=", batch.size,
" batch.vsize=", batch.vsize,
" batch.basis=", batch.basis,
" batch.slide=", batch.slide,
" coord=", coord
);
for (auto n = 0; auto& l : batch)
{
log(" ", n++,". id=", l.index, " length()=", l.length(), " wrapped=", l.wrapped() ? "true" : "faux");
}
log(" -----------------");
}
bool test_index()
{
auto m = index.front().index;
for (auto& i : index)
{
auto step = i.index - m;
assert(step >= 0 && step < 2);
m = i.index;
}
return true;
}
bool test_futures()
{
auto stash = batch.vsize - batch.basis - index.size;
assert(stash >= 0);
return true;
}
auto test_resize()
{
auto c = batch.caret;
sync_coord();
assert(c == batch.caret);
return true;
}
auto test_height()
{
auto test_vsize = 0;
for (auto& l : batch) test_vsize += l.height(panel.x);
if (test_vsize != batch.vsize) log(" ERROR! test_vsize=", test_vsize, " vsize=", batch.vsize);
return test_vsize == batch.vsize;
}
// scroll_buf: .
bool is_need_to_correct() override
{
auto result = batch.need_to_correct;
batch.need_to_correct = faux;
return result;
}
// scroll_buf: .
iota get_basis() override
{
return batch.basis;
}
// scroll_buf: .
iota get_slide() override
{
return batch.slide;
}
// scroll_buf: .
bool force_basis() override
{
return batch.slide == batch.basis;
}
// scroll_buf: .
iota set_slide(iota new_slide) override
{
//log(" new_slide=", new_slide);
if (batch.slide == new_slide)
{
//log("delta == 0");
return new_slide;
}
if (batch.basis == new_slide)
{
batch.round = faux;
auto& mapln = index.front();
batch.anchor_id = mapln.index;
batch.anchor_dy = mapln.start / panel.x;
batch.slide = batch.basis;
}
else
{
auto vtpos = batch.slide - batch.anchor_dy; // current pos of anchor_id
auto delta = new_slide - vtpos;
//if (std::abs(delta) > recalc_threshold) // calc approx
//{
//auto a = new_slide < recalc_threshold;
//auto b = new_slide < std::abs(batch.vsize - new_slide);
//if (!round && (a || b))
//{
// // Calculate the slide accurately.
// // ...
//}
//else
//{
// round = true;
// ...
//auto bytesz = batch.get_size_in_cells();
//auto curpos = batch.slide;
//auto height = batch.vsize;
//auto length = batch.size;
//auto approx_index = (ui64)length * curpos / height;
//auto approx_bytes = (ui64)bytesz * curpos / height;
//auto exactly = curpos;
//auto& curln = batch[approx_index];
//auto accum = curln.accum;
//}
//else // calc exactly
{
auto idpos = batch.index_by_id(batch.anchor_id);
//log(" idpos=", idpos, " batch.size=", batch.size);
auto start = batch.begin() + idpos;
auto found = faux;
if (delta < 0) // Look up.
{
//log(" delta < 0 new_slide=", new_slide);
auto limit = start - std::min(std::abs(delta), idpos);
while (start != limit)
{
auto& curln = *--start;
auto height = curln.height(panel.x);
vtpos -= height;
if (vtpos <= new_slide)
{
batch.anchor_id = curln.index;
batch.anchor_dy = new_slide - vtpos;
//log(" delta < 0 new_slide=", new_slide, " batch.slide=", batch.slide, " anchor_id=", batch.anchor_id);
batch.slide = new_slide;
found = true;
break;
}
}
//if (!found)
//{
// ///log(" 0.1. slide reset old_slide", batch.slide, " new_slide=", batch.basis );
// batch.anchor_id = batch.back().index - (batch.size - 1);
// batch.anchor_dy = 0;
// batch.slide = 0;
// assert(batch.anchor_id == batch.front().index);
//}
}
else if (delta > 0) // Look down.
{
//log(" delta > 0 new_slide=", new_slide);
auto limit = start + std::min(delta, batch.size - idpos - 1);
do
{
auto& curln = *start;
auto curpos = vtpos;
auto height = curln.height(panel.x);
vtpos += height;
if (vtpos > new_slide)
{
batch.anchor_id = curln.index;
batch.anchor_dy = new_slide - curpos;
//log(" delta > 0 new_slide=", new_slide, " batch.slide=", batch.slide, " anchor_id=", batch.anchor_id);
batch.slide = new_slide;
found = true;
break;
}
}
while (start++ != limit);
//if (!found)
//{
// //log(" 0.2. slide reset old_slide", batch.slide, " new_slide=", batch.basis );
// auto& mapln = index.front();
// batch.anchor_id = mapln.index;
// batch.anchor_dy = mapln.start / panel.x;
// batch.slide = batch.basis;
//}
}
else
{
batch.slide = new_slide;
batch.anchor_dy = 0;
found = true;
}
if (batch.round)
{
auto a = new_slide < batch.threshold;
auto b = new_slide < std::abs(batch.vsize - new_slide);
if (a || b)
{
batch.round = faux;
// Calculate the slide accurately.
// ...
}
}
}
}
//print_slide(" set_slide");
return new_slide;
}
void recalc_slide(bool away)
{
if (away)
{
//log(" away");
// Recalc batch.slide using anchoring by para_id + para_offset
// PoC: (para_id + para_offset) => (batch.slide)
// naive imp, bruteforce (within threshold)
//todo calculate it approximately
auto endid = batch.back().index;
auto count = static_cast<iota>(endid - batch.anchor_id) + 1;
if (count <= batch.size)
{
batch.slide = batch.vsize + batch.anchor_dy;
auto head = batch.end();
auto tail = head - count;
while (head != tail)
{
auto& curln = *--head;
auto height = curln.height(panel.x);
batch.slide -= height;
}
if (batch.slide > batch.basis) batch.slide = batch.basis;
else if (batch.slide <= 0) // Overflow.
{
//log(" Overflow on resize. batch.slide=", batch.slide);
//log(" 1. slide reset old_slide", batch.slide, " new_slide=", 0 );
batch.slide = 0;
batch.anchor_dy = 0;
batch.anchor_id = endid - (batch.size - 1);
assert(batch.anchor_id == batch.front().index);
}
}
else // Overflow.
{
//log(" Overflow on resize. Anchor id is outside. batch.slide=", batch.slide,
//" anchor_id=", anchor_id, " batch.front().index=", batch.front().index);
//log(" 2. slide reset old_slide", batch.slide, " new_slide=", 0 );
batch.anchor_dy = 0;
batch.anchor_id = endid - (batch.size - 1);
batch.slide = 0;
assert(batch.anchor_id == batch.front().index);
}
}
else
{
//log(" 3. slide reset old_slide", batch.slide, " new_slide=", batch.basis );
batch.round = faux;
batch.slide = batch.basis;
auto& mapln = index.front();
batch.anchor_id = mapln.index;
batch.anchor_dy = mapln.start / panel.x;
}
//print_slide(" resize");
}
// scroll_buf: Resize viewport.
void resize_viewport(twod const& new_sz) override
{
if (new_sz == panel) return;
auto in_top = y_top - coord.y;
auto in_end = coord.y - y_end;
bufferbase::resize_viewport(new_sz);
batch.check_size(panel);
index.clear();
// Preserve original content. The app that changed the margins is responsible for updating the content.
auto upnew = std::max(upmin, twod{ panel.x, sctop });
auto dnnew = std::max(dnmin, twod{ panel.x, scend });
upbox.crop(upnew);
dnbox.crop(dnnew);
arena = y_end - y_top + 1;
index.resize(arena); // Use a fixed ring because new lines are added much more often than a futures feed.
auto away = batch.basis != batch.slide;
auto& curln = batch.current();
if (curln.wrapped() && batch.caret > curln.length()) // Dangling cursor.
{
auto blank = brush.spc();
curln.crop(batch.caret, blank);
batch.recalc(curln);
}
if (in_top > 0 || in_end > 0) // The cursor is outside the scrolling region.
{
if (in_top > 0) coord.y = std::max(0 , y_top - in_top);
else coord.y = std::min(panel.y - 1, y_end + in_end);
coord.x = std::clamp(coord.x, 0, panel.x - 1);
batch.basis = std::max(0, batch.vsize - arena);
index_rebuild();
recalc_slide(away);
return;
}
batch.basis = batch.vsize;
auto lnid = curln.index;
auto head = batch.end();
auto maxn = batch.size - batch.index();
auto tail = head - std::max(maxn, std::min(batch.size, arena));
auto push = [&](auto i, auto o, auto r) { --batch.basis; index.push_front(i, o, r); };
auto unknown = true;
while (head != tail && (index.size < arena || unknown))
{
auto& curln = *--head;
auto curid = curln.index;
auto length = curln.length();
auto active = curid == lnid;
if (curln.wrapped())
{
auto offset = length;
auto remain = length ? (length - 1) % panel.x + 1
: 0;
do
{
offset -= remain;
push(curid, offset, remain);
if (unknown && active && offset <= batch.caret)
{
auto eq = batch.caret && length == batch.caret;
unknown = faux;
coord.y = index.size;
coord.x = eq ? (batch.caret - 1) % panel.x + 1
: batch.caret % panel.x;
}
remain = panel.x;
}
while (offset > 0 && (index.size < arena || unknown));
}
else
{
push(curid, 0, length);
if (active)
{
unknown = faux;
coord.y = index.size;
coord.x = batch.caret;
}
}
}
coord.y = index.size - coord.y + y_top;
recalc_slide(away);
assert(batch.basis >= 0);
assert(test_futures());
assert(test_resize());
}
// scroll_buf: Rebuild the next avail indexes from the known index (mapln).
template<class ITER, class INDEX_T>
void reindex(iota avail, ITER curit, INDEX_T const& mapln)
{
auto& curln =*curit;
auto width = curln.length();
auto wraps = curln.wrapped();
auto curid = curln.index;
auto start = mapln.start + mapln.width;
assert(curid == mapln.index);
if (start == width) // Go to the next line.
{
assert(curit != batch.end() - 1);
auto& curln = *++curit;
width = curln.length();
wraps = curln.wrapped();
curid = curln.index;
start = 0;
}
else assert(mapln.width == panel.x);
assert(start % panel.x == 0);
while (true)
{
if (wraps)
{
auto trail = width - panel.x;
while (start < trail && avail-- > 0)
{
index.push_back(curid, start, panel.x);
start += panel.x;
}
}
if (avail-- <= 0) break;
assert(start == 0 || wraps);
index.push_back(curid, start, width - start);
if (avail == 0) break;
assert(curit != batch.end() - 1);
auto& curln = *++curit;
width = curln.length();
wraps = curln.wrapped();
curid = curln.index;
start = 0;
}
assert(test_index());
assert(test_futures());
}
// scroll_buf: Rebuild index from the known index at y_pos.
void index_rebuild_from(iota y_pos)
{
assert(y_pos >= 0 && y_pos < index.size);
auto& mapln = index[y_pos];
auto curit = batch.iter_by_id(mapln.index);
auto avail = std::min(batch.vsize - batch.basis, arena) - y_pos - 1;
auto count = index.size - y_pos - 1;
while (count-- > 0) index.pop_back();
if (avail > 0) reindex(avail, curit, mapln);
}
// scroll_buf: Rebuild index up to basis.
void index_rebuild()
{
if (batch.basis >= batch.vsize)
{
assert((log(" batch.basis >= batch.vsize batch.basis=", batch.basis, " batch.vsize=", batch.vsize), true));
batch.basis = batch.vsize - 1;
}
index.clear();
auto coor = batch.vsize;
auto head = batch.end();
while (coor != batch.basis)
{
auto& curln = *--head;
auto curid = curln.index;
auto length = curln.length();
if (curln.wrapped())
{
auto remain = length ? (length - 1) % panel.x + 1 : 0;
length -= remain;
index.push_front(curid, length, remain);
--coor;
while (length > 0 && coor != batch.basis)
{
length -= panel.x;
index.push_front(curid, length, panel.x);
--coor;
}
}
else
{
index.push_front(curid, 0, length);
--coor;
}
}
assert(test_futures());
}
// scroll_buf: Return scrollback height.
iota height() override
{
assert(test_height());
return batch.vsize;
}
// scroll_buf: Recalc left and right oversize.
bool recalc_pads(side& oversz) override
{
auto rght = std::max({0, batch.max<line::type::leftside>() - panel.x, coord.x - panel.x + 1 }); // Take into account the cursor position.
auto left = std::max( 0, batch.max<line::type::rghtside>() - panel.x );
auto cntr = std::max( 0, batch.max<line::type::centered>() - panel.x );
auto bttm = std::max( 0, batch.vsize - (batch.basis + arena) );
auto both = cntr >> 1;
left = std::max(left, both);
rght = std::max(rght, both + (cntr & 1));
if (oversz.r != rght || oversz.l != left || oversz.b != bttm)
{
oversz.r = rght;
oversz.l = left;
oversz.b = bttm;
return true;
}
else return faux;
}
// scroll_buf: Check if there are futures, use them when scrolling regions.
auto feed_futures(iota query)
{
assert(test_futures());
assert(query > 0);
auto stash = batch.vsize - batch.basis - index.size;
iota avail;
if (stash > 0)
{
avail = std::min(stash, query);
batch.basis += avail;
auto& mapln = index.back();
auto curit = batch.iter_by_id(mapln.index);
reindex(avail, curit, mapln);
}
else avail = 0;
return avail;
}
// scroll_buf: Return current 0-based cursor position in the scrollback.
twod get_coord(twod const& origin) override
{
auto coor = coord;
if (coord.y >= y_top
&& coord.y <= y_end)
{
coor.y += batch.basis;
auto visible = coor.y + origin.y;
if (visible < y_top // Do not show cursor behind margins when the scroll region is dragged by mouse.
|| visible > y_end)
{
coor.y = dot_mx.y;
}
auto& curln = batch.current();
auto align = curln.style.jet();
if (align == bias::left
|| align == bias::none) return coor;
auto curidx = coord.y - y_top;
auto remain = index[curidx].width;
if (remain == panel.x && curln.wrapped()) return coor;
if (align == bias::right ) coor.x += panel.x - remain - 1;
else /*align == bias::center*/ coor.x += panel.x / 2 - remain / 2;
}
else
{
coor -= origin;
}
return coor;
}
// scroll_buf: Set cursor position and sync it with buffer.
void set_coord(twod const& new_coord) override
{
bufferbase::set_coord(new_coord);
sync_coord();
}
// scroll_buf: Map the current cursor position to the scrollback.
void sync_coord()
{
coord.y = std::clamp(coord.y, 0, panel.y - 1);
if (coord.x < 0) coord.x = 0;
if (coord.y >= y_top
&& coord.y <= y_end)
{
auto& curln = batch.current();
auto wraps = curln.wrapped();
auto curid = curln.index;
if (coord.x > panel.x && wraps) coord.x = panel.x;
coord.y -= y_top;
if (index.size <= coord.y)
{
auto add_count = coord.y - (index.size - 1);
add_lines(add_count);
}
auto& mapln = index[coord.y];
batch.caret = mapln.start + coord.x;
if (curid != mapln.index)
{
auto newix = batch.index_by_id(mapln.index);
batch.index(newix);
if (batch->style != parser::style)
{
_set_style(parser::style);
assert(newix == batch.index_by_id(index[coord.y].index));
}
}
coord.y += y_top;
assert((batch.caret - coord.x) % panel.x == 0);
}
else // Always wraps inside margins.
{
if (coord.x > panel.x) coord.x = panel.x;
}
}
void cup (fifo& q) override { bufferbase::cup (q); sync_coord(); }
void tab (iota n) override { bufferbase::tab (n); sync_coord(); }
void scl (iota n) override { bufferbase::scl (n); sync_coord(); }
void cuf (iota n) override { bufferbase::cuf (n); sync_coord(); }
void chx (iota n) override { bufferbase::chx (n); sync_coord(); }
void chy (iota n) override { bufferbase::chy (n); sync_coord(); }
void il (iota n) override { bufferbase::il (n); sync_coord(); }
void dl (iota n) override { bufferbase::dl (n); sync_coord(); }
void up (iota n) override { bufferbase::up (n); sync_coord(); }
void dn (iota n) override { bufferbase::dn (n); sync_coord(); }
void lf (iota n) override { bufferbase::lf (n); sync_coord(); }
void ri () override { bufferbase::ri ( ); sync_coord(); }
void cr () override { bufferbase::cr ( ); sync_coord(); }
// scroll_buf: Reset the scrolling region.
void reset_scroll_region()
{
upmin = dot_00;
dnmin = dot_00;
upbox.crop(upmin);
dnbox.crop(dnmin);
arena = panel.y;
index.resize(arena);
index_rebuild();
bufferbase::set_scroll_region(0, 0);
}
// scroll_buf: Set the scrolling region using 1-based top and bottom. Use 0 to reset.
void set_scroll_region(iota top, iota bottom) override
{
auto old_sctop = sctop;
auto old_scend = scend;
bufferbase::set_scroll_region(top, bottom);
if (old_sctop == sctop && old_scend == scend) return;
// Trim the existing margin content if any. The app that changed the margins is responsible for updating the content.
upmin = { panel.x, sctop };
dnmin = { panel.x, scend };
auto delta_top = sctop - old_sctop;
auto delta_end = scend - old_scend;
// Take lines from the scrollback.
auto pull = [&](face& block, twod origin, iota begin, iota limit)
{
if (begin >= index.size) return;
limit = std::min(limit, index.size);
dissect(begin);
dissect(limit);
auto from = index[begin ].index;
auto upto = index[limit - 1].index + 1;
auto base = batch.index_by_id(from);
auto head = batch.begin() + base;
auto size = static_cast<iota>(upto - from);
auto tail = head + size;
auto view = rect{ origin, { panel.x, limit - begin }};
auto full = rect{ dot_00, block.core::size() };
block.full(full);
block.view(view);
block.ac(view.coor);
do
{
auto& curln = *head;
block.output(curln);
block.nl(1);
}
while (++head != tail);
batch.remove(base, size);
};
// Return lines to the scrollback iif margin is disabled.
auto push = [&](face& block, bool at_bottom)
{
auto size = block.size();
if (size.y <= 0) return;
iota start;
if (at_bottom)
{
auto stash = batch.vsize - batch.basis - arena;
if (stash > 0)
{
dissect(arena);
start = batch.index_by_id(index.back().index) + 1;
}
else // Add new lines if needed.
{
auto count = arena - index.size;
auto curid = batch.back().index;
while (count-- > 0) batch.invite(++curid, parser::style);
start = batch.size;
}
}
else
{
dissect(0);
start = batch.index_by_id(index.front().index);
}
auto curit = block.iter();
auto width = twod{ size.x, 1 };
auto curid = start == 0 ? batch.front().index
: batch[start - 1].index + 1;
auto style = ansi::def_style;
style.wrp(wrap::off);
while (size.y-- > 0)
{
auto oldsz = batch.size;
auto proto = core::span{ &(*curit), static_cast<size_t>(size.x) }; // Apple Clang doesn't accept an iterator as an arg in the span ctor.
auto curln = line{ curid++, style, proto, width };
curln.shrink(block.mark());
batch.insert(start, std::move(curln));
start += batch.size - oldsz; // Due to circulation in the ring.
assert(start <= batch.size);
curit += size.x;
}
batch.reindex(start);
};
if (delta_end > 0)
{
if (old_scend == 0) dnbox.mark(brush.spare);
dnbox.crop<true>(dnmin);
pull(dnbox, dot_00, arena - delta_end, arena);
}
else
{
if (scend == 0 && old_scend > 0) push(dnbox, true);
dnbox.crop<true>(dnmin);
}
if (delta_top > 0)
{
if (old_sctop == 0) upbox.mark(brush.spare);
upbox.crop<faux>(upmin);
pull(upbox, { 0, old_sctop }, 0, delta_top);
if (batch.size == 0) batch.invite(0, parser::style);
}
else
{
if (sctop == 0 && old_sctop > 0) push(upbox, faux);
upbox.crop<faux>(upmin);
}
arena = panel.y - (scend + sctop);
index.clear();
index.resize(arena);
index_rebuild();
sync_coord();
}
// scroll_buf: Push lines to the scrollback bottom.
void add_lines(iota amount)
{
assert(amount >= 0);
auto newid = batch.back().index;
while (amount-- > 0)
{
auto& l = batch.invite(++newid, parser::style);
index.push_back(newid, 0, 0);
}
}
// scroll_buf: . (! Check coord.y context)
void _set_style(deco const& new_style)
{
auto& curln = batch.current();
auto wraps = curln.wrapped();
auto width = curln.length();
curln.style = new_style;
if (batch.caret > width) // Dangling cursor.
{
auto blank = brush.spc();
width = batch.caret;
curln.crop(width, blank);
}
batch.recalc(curln);
if (wraps != curln.wrapped())
{
if (batch.caret >= panel.x)
{
if (wraps)
{
if (coord.x == 0) coord.y -= 1;
coord.x = batch.caret;
coord.y -= (batch.caret - 1) / panel.x;
if (coord.y < 0)
{
batch.basis -= std::abs(coord.y);
assert(batch.basis >= 0);
coord.y = 0;
}
}
else
{
if (batch.caret == width)
{
coord.x = (batch.caret - 1) % panel.x + 1;
coord.y += (batch.caret - 1) / panel.x;
}
else
{
coord.x = batch.caret % panel.x;
coord.y += batch.caret / panel.x;
}
if (coord.y >= arena)
{
auto limit = arena - 1;
auto delta = coord.y - limit;
batch.basis += delta;
coord.y = limit;
}
}
index_rebuild();
}
else
{
auto& mapln = index[coord.y];
auto wraps = curln.wrapped();
mapln.start = 0;
mapln.width = wraps ? std::min(panel.x, width)
: width;
index_rebuild_from(coord.y);
}
}
assert(test_index());
}
// scroll_buf: Proceed style update (parser callback).
void meta(deco const& old_style) override
{
if (batch->style != parser::style)
{
if (coord.y >= y_top
&& coord.y <= y_end)
{
coord.y -= y_top;
_set_style(parser::style);
coord.y += y_top;
}
}
bufferbase::meta(old_style);
}
[[ nodiscard ]]
auto get_context(twod& pos)
{
struct qt
{
twod& c;
iota t;
bool b;
rich& block;
qt(twod& cy, iota ct, bool cb, scroll_buf& cs)
: c{ cy },
t{ ct },
b{ cb },
block{ c.y > cs.y_end ? (void)(t = cs.y_end + 1), cs.dnbox
: cs.upbox }
{ c.y -= t; }
~qt() { c.y += t; }
operator bool () { return b; }
};
auto inside = coord.y >= y_top
&& coord.y <= y_end;
return qt{ pos, inside ? y_top : 0, inside, *this };
}
// scroll_buf: CSI n K Erase line (don't move cursor).
void el(iota n) override
{
bufferbase::flush();
auto blank = brush.spc();
if (auto ctx = get_context(coord))
{
iota start;
iota count;
auto caret = std::max(0, batch.caret);
auto& curln = batch.current();
auto width = curln.length();
auto wraps = curln.wrapped();
switch (n)
{
default:
case commands::erase::line::right: // n = 0 (default) Erase to Right.
start = caret;
count = wraps ? coord.x == panel.x ? 0 : panel.x - (caret + panel.x) % panel.x
: std::max(0, std::max(panel.x, width) - caret);
break;
case commands::erase::line::left: // n = 1 Erase to Left.
start = wraps ? caret - caret % panel.x
: 0;
count = caret - start;
break;
case commands::erase::line::all: // n = 2 Erase All.
start = wraps ? caret - caret % panel.x
: 0;
count = wraps ? panel.x
: std::max(panel.x, batch->length());
break;
}
if (count)
{
curln.splice<true>(start, count, blank);
batch.recalc(curln);
width = curln.length();
auto& mapln = index[coord.y];
mapln.width = wraps ? std::min(panel.x, width - mapln.start)
: width;
//curln.shrink(blank); //todo revise: It kills wrapped lines and as a result requires the viewport to be rebuilt.
//batch.recalc(curln); // The cursor may be misplaced when resizing because curln.length is less than batch.caret.
//index_rebuild();
//print_batch(" el");
}
}
else alt_screen::_el(n, ctx.block, coord, panel, blank);
}
// scroll_buf: CSI n @ ICH. Insert n blanks after cursor. Existing chars after cursor shifts to the right. Don't change cursor pos.
void ins(iota n) override
{
bufferbase::flush();
auto blank = brush.spc();
if (auto ctx = get_context(coord))
{
n = std::min(n, panel.x - coord.x);
auto& curln = batch.current();
curln.insert(batch.caret, n, blank, panel.x);
batch.recalc(curln); // Line front is filled by blanks. No wrapping.
auto width = curln.length();
auto wraps = curln.wrapped();
auto& mapln = index[coord.y];
mapln.width = wraps ? std::min(panel.x, width - mapln.start)
: width;
}
else ctx.block.insert(coord, n, blank);
}
// scroll_buf: CSI n P Delete (not Erase) letters under the cursor. Line end is filled by blanks. Length is preserved. No wrapping.
void dch(iota n) override
{
bufferbase::flush();
auto blank = brush.spc();
if (auto ctx = get_context(coord))
{
auto& curln = batch.current();
curln.cutoff(batch.caret, n, blank, panel.x);
batch.recalc(curln);
}
else ctx.block.cutoff(coord, n, blank);
}
// scroll_buf: CSI n X Erase/put n chars after cursor. Don't change cursor pos.
void ech(iota n) override
{
parser::flush();
auto blank = brush.spc();
if (auto ctx = get_context(coord))
{
n = std::min(n, panel.x - coord.x);
auto& curln = batch.current();
curln.splice(batch.caret, n, blank);
batch.recalc(curln);
auto& mapln = index[coord.y];
auto width = curln.length();
auto wraps = curln.wrapped();
mapln.width = wraps ? std::min(panel.x, curln.length() - mapln.start)
: width;
}
else ctx.block.splice(coord, n, blank);
}
// scroll_buf: Proceed new text (parser callback).
void data(iota count, grid const& proto) override
{
assert(coord.y >= 0 && coord.y < panel.y);
assert(test_futures());
if (coord.y < y_top)
{
auto saved = coord;
coord.x += count;
//todo apply line adjusting (necessity is not clear)
if (coord.x <= panel.x)//todo styles! || ! curln.wrapped())
{
auto n = std::min(count, panel.x - std::max(0, saved.x));
upbox.splice(saved, n, proto);
}
else
{
coord.y += (coord.x + panel.x - 1) / panel.x - 1;
coord.x = (coord.x - 1) % panel.x + 1;
if (coord.y >= y_top)
{
auto n = coord.x + (coord.y - y_top) * panel.x;
count -= n;
set_coord(twod{ 0, y_top });
data(n, proto); // Reversed fill using the last part of the proto.
}
auto data = proto.begin();
auto seek = saved.x + saved.y * panel.x;
auto dest = upbox.iter() + seek;
auto tail = dest + count;
rich::forward_fill_proc(data, dest, tail);
}
}
else if (coord.y <= y_end)
{
coord.y -= y_top;
auto& curln = batch.current();
auto start = batch.caret;
batch.caret += count;
coord.x += count;
if (batch.caret <= panel.x || ! curln.wrapped()) // case 0.
{
curln.splice(start, count, proto);
auto& mapln = index[coord.y];
assert(coord.x == batch.caret && mapln.index == curln.index);
if (coord.x > mapln.width)
{
mapln.width = coord.x;
batch.recalc(curln);
}
else assert(curln._size == curln.length());
} // case 0 - done.
else
{
auto max_y = arena - 1;
auto saved = coord.y + batch.basis;
coord.y += (coord.x + panel.x - 1) / panel.x - 1;
coord.x = (coord.x - 1) % panel.x + 1;
auto query = coord.y - (index.size - 1);
if (query > 0)
{
auto avail = feed_futures(query);
query -= avail;
coord.y -= avail;
}
curln.splice(start, count, proto);
auto curid = curln.index;
if (query > 0) // case 3 - complex: Cursor is outside the viewport.
{ // cursor overlaps some lines below and placed below the viewport.
batch.recalc(curln);
if (auto count = static_cast<iota>(batch.back().index - curid))
{
assert(count > 0);
while (count-- > 0) batch.pop_back();
}
auto width = curln.length();
auto trail = width - panel.x;
saved -= batch.basis;
if (saved > 0)
{
auto count = index.size - saved - 1;
while (count-- > 0) index.pop_back();
auto& mapln = index.back();
mapln.width = panel.x;
start = mapln.start + panel.x;
}
else // saved has scrolled out.
{
index.clear();
start = std::abs(saved) * panel.x;
}
while (start < trail)
{
index.push_back(curid, start, panel.x);
start += panel.x;
}
index.push_back(curid, start, width - start);
if (coord.y > max_y)
{
batch.basis += coord.y - max_y;
coord.y = max_y;
}
assert(test_futures());
} // case 3 done
else
{
auto& mapln = index[coord.y];
if (curid == mapln.index) // case 1 - plain: cursor is inside the current paragraph.
{
if (batch.caret - coord.x == mapln.start)
{
if (coord.x > mapln.width)
{
mapln.width = coord.x;
batch.recalc(curln);
}
else assert(curln._size == curln.length());
}
else // Case when arena == 1
{
assert(arena == 1);
mapln.start = batch.caret - coord.x;
mapln.width = coord.x;
batch.recalc(curln);
}
assert(test_futures());
} // case 1 done.
else // case 2 - fusion: cursor overlaps lines below but stays inside the viewport.
{
auto& target = batch.item_by_id(mapln.index);
auto shadow = target.wrapped() ? target.substr(mapln.start + coord.x)
: target.substr(mapln.start + coord.x, std::min(panel.x, mapln.width) - coord.x);
curln.splice(curln.length(), shadow);
batch.recalc(curln);
auto width = curln.length();
auto spoil = static_cast<iota>(mapln.index - curid);
assert(spoil > 0);
auto after = batch.index() + 1;
spoil = batch.remove(after, spoil);
// Update index.
{
assert(test_index());
saved -= batch.basis;
auto indit = index.begin() + saved;
auto endit = index.end();
auto start = indit->start;
auto trail = width - panel.x;
while (indit != endit && start < trail) // Update for current line.
{
auto& i =*indit;
i.index = curid;
i.start = start;
i.width = panel.x;
start += panel.x;
++indit;
}
if (indit != endit)
{
auto& i =*indit;
i.index = curid;
i.start = start;
i.width = width - start;
++indit;
while (indit != endit) // Update the rest.
{
auto& i = *indit;
i.index -= spoil;
++indit;
}
}
assert(test_index());
}
assert(test_futures());
} // case 2 done.
}
}
assert(coord.y >= 0 && coord.y < arena);
//log(" bufferbase size in cells = ", batch.get_size_in_cells());
coord.y += y_top;
}
else
{
coord.y -= y_end + 1;
auto saved = coord;
coord.x += count;
//todo apply line adjusting
if (coord.x <= panel.x)//todo styles! || ! curln.wrapped())
{
auto n = std::min(count, panel.x - std::max(0, saved.x));
dnbox.splice(saved, n, proto);
}
else
{
coord.y += (coord.x + panel.x - 1) / panel.x - 1;
coord.x = (coord.x - 1) % panel.x + 1;
auto data = proto.begin();
auto size = count;
auto seek = saved.x + saved.y * panel.x;
auto dest = dnbox.iter() + seek;
auto tail = dnbox.iend();
auto back = panel.x;
rich::unlimit_fill_proc(data, size, dest, tail, back);
}
coord.y = std::min(coord.y + y_end + 1, panel.y - 1);
}
}
// scroll_buf: Clear scrollback.
void clear_all() override
{
saved = dot_00;
coord = dot_00;
batch.clear();
reset_scroll_region();
bufferbase::clear_all();
}
// scroll_buf: Set scrollback limits.
void resize_history(iota new_size, iota grow_by = 0)
{
static constexpr auto BOTTOM_ANCHORED = true;
batch.resize<BOTTOM_ANCHORED>(new_size, grow_by);
index_rebuild();
}
// scroll_buf: Render to the canvas.
void output(face& canvas) override
{
canvas.vsize(batch.vsize + sctop + scend); // Include margins and bottom oversize.
auto view = canvas.view();
auto full = canvas.full();
auto coor = twod{ 0, batch.slide - batch.anchor_dy + y_top };
auto stop = view.coor.y + view.size.y;
auto head = batch.iter_by_id(batch.anchor_id);
auto tail = batch.end();
auto fill = [&](auto& area, auto chr)
{
if (auto r = view.clip(area))
canvas.fill(r, [&](auto& c){ c.txt(chr).fgc(tint::greenlt); });
};
auto left_edge = view.coor.x;
auto rght_edge = view.coor.x + view.size.x;
auto half_size = full.size.x / 2;
auto left_rect = rect{{ left_edge, full.coor.y + coor.y }, dot_11 };
auto rght_rect = left_rect;
rght_rect.coor.x += view.size.x - 1;
//print_slide(" output");
while (head != tail && rght_rect.coor.y < stop)
{
auto& curln = *head;
auto height = curln.height(panel.x);
auto length = curln.length();
auto adjust = curln.style.jet();
canvas.output(curln, coor);
if (length > 0) // Highlight the lines that are not shown in full.
{
rght_rect.size.y = left_rect.size.y = height;
if (height == 1)
{
auto lt_dot = full.coor.x;
if (adjust == bias::center) lt_dot += half_size - length / 2;
else if (adjust == bias::right) lt_dot += full.size.x - length;
if (left_edge > lt_dot ) fill(left_rect, '<');
if (rght_edge < lt_dot + length) fill(rght_rect, '>');
}
else
{
auto lt_dot = full.coor.x;
auto rt_dot = lt_dot + view.size.x;
auto remain = (length - 1) % view.size.x + 1;
if (left_edge > lt_dot)
{
if ((adjust == bias::right && left_edge <= rt_dot - remain)
|| (adjust == bias::center && left_edge <= lt_dot + half_size - remain / 2))
{
--left_rect.size.y;
}
fill(left_rect, '<');
}
if (rght_edge < rt_dot)
{
if ((adjust == bias::left && rght_edge >= lt_dot + remain)
|| (adjust == bias::center && rght_edge >= lt_dot + remain + half_size - remain / 2))
{
--rght_rect.size.y;
}
fill(rght_rect, '>');
}
}
}
coor.y += height;
rght_rect.coor.y += height;
left_rect.coor.y = rght_rect.coor.y;
++head;
}
auto top_coor = twod{ view.coor.x, view.coor.y + y_top - sctop };
auto end_coor = twod{ view.coor.x, view.coor.y + y_end + 1 };
upbox.move(top_coor);
dnbox.move(end_coor);
//todo make translucency configurable
canvas.plot(upbox, [](auto& dst, auto& src){ dst.fuse(src); dst.bga(0xC0); });
canvas.plot(dnbox, [](auto& dst, auto& src){ dst.fuse(src); dst.bga(0xC0); });
//canvas.plot(upbox, cell::shaders::flat);
//canvas.plot(dnbox, cell::shaders::flat);
}
// scroll_buf: Remove all lines below (including futures) except the current. "ED2 Erase viewport" keeps empty lines.
void del_below() override
{
auto blank = brush.spc();
auto clear = [&](twod const& coor)
{
auto i = batch.index_by_id(index[coor.y].index);
auto n = batch.size - 1 - i;
auto m = index.size - 1 - coor.y;
auto p = arena - 1 - coor.y;
if (coor.x == 0 && batch.caret != 0) // Remove the index of the current line if the entire visible line is to be removed.
{
++m;
++p;
}
assert(n >= 0 && n < batch.size);
assert(m >= 0 && m <= index.size);
assert(p >= 0 && p <= arena);
while (n--) batch.pop_back();
while (m--) index.pop_back();
add_lines(p);
auto& curln = batch[i];
auto& mapln = index[coor.y];
mapln.width = coor.x;
curln.trimto(batch.caret);
batch.recalc(curln);
assert(mapln.start == 0 || curln.wrapped());
sync_coord();
dnbox.wipe(blank);
};
auto coor = coord;
if (coor.y < y_top)
{
assert(coor.x + coor.y * upbox.size().x < sctop * upbox.size().x);
upbox.del_below(coor, blank);
clear(dot_00);
}
else if (coor.y <= y_end)
{
coor.y -= y_top;
clear(coor);
}
else
{
coor.y -= y_end + 1;
assert(coor.x + coor.y * dnbox.size().x < scend * dnbox.size().x);
dnbox.del_below(coor, blank);
}
assert(test_futures());
}
// scroll_buf: Clear all lines from the viewport top line to the current line.
void del_above() override
{
auto blank = brush.spc();
auto clear = [&](twod const& coor)
{
// The dirtiest and fastest solution. Just fill existing lines by blank cell.
auto i = batch.index_by_id(index[coor.y].index);
auto& mapln = index[coor.y];
auto caret = mapln.start + coor.x;
auto& curln = batch[i];
auto& topln = index.front();
auto curit = batch.iter_by_id(topln.index);
auto endit = batch.iter_by_id(curln.index);
auto start = topln.start;
auto blank = brush.spc();
if (curit == endit)
{
auto width = std::min(curln.length(), caret);
curln.splice(start, width - start, blank);
}
else
{
auto& curln =*curit;
auto width = curln.length();
curln.splice(start, width - start, blank);
while(++curit != endit) curit->core::wipe(blank);
if (coord.x > 0)
{
auto& curln =*curit;
auto max_x = std::min<iota>(curln.length(), caret);
if (max_x > 0)
{
auto max_w = curln.wrapped() ? (max_x - 1) % panel.x + 1
: max_x;
auto width = std::min<iota>(max_w, coord.x);
auto start = caret - coord.x;
curln.splice(start, width, blank);
}
}
}
upbox.wipe(blank);
};
auto coor = coord;
if (coor.y < y_top)
{
assert(coor.x + coor.y * upbox.size().x < sctop * upbox.size().x);
upbox.del_above(coor, blank);
}
else if (coor.y <= y_end)
{
coor.y -= y_top;
clear(coor);
}
else
{
coor.y -= y_end + 1;
assert(coor.x + coor.y * dnbox.size().x < scend * dnbox.size().x);
dnbox.del_above(coor, blank);
clear(twod{ panel.x , arena - 1 });
}
}
// scroll_buf: Dissect auto-wrapped lines above the specified row in scroll region (incl last line+1).
void dissect(iota y_pos)
{
assert(y_pos >= 0 && y_pos <= arena);
auto split = [&](id_t curid, iota start)
{
auto after = batch.index_by_id(curid);
auto tmpln = std::move(batch[after]);
auto curit = batch.ring::insert(after + 1, tmpln.index, tmpln.style);
auto endit = batch.end();
auto& newln = *curit;
newln.splice(0, tmpln.substr(start));
batch.undock_base_back(tmpln);
batch.invite(newln);
if (curit != batch.begin())
{
auto& curln = *(curit - 1);
curln = std::move(tmpln);
curln.trimto(start);
batch.invite(curln);
}
do ++(curit++->index);
while (curit != endit);
assert(test_index());
};
if (y_pos < index.size)
{
auto& mapln = index[y_pos];
auto start = mapln.start;
auto curid = mapln.index;
if (start == 0) return;
split(curid, start);
mapln.index++;
mapln.start = 0;
index_rebuild_from(y_pos);
sync_coord();
}
else if (y_pos == arena
&& y_pos < batch.vsize - batch.basis)
{
auto stash = batch.vsize - batch.basis - index.size;
assert(stash >= 0);
if (stash == 0) return;
auto& mapln = index.back();
auto curid = mapln.index;
auto& curln = batch.item_by_id(curid);
auto start = mapln.start + mapln.width;
if (start < curln.length())
{
split(curid, start);
}
}
assert(test_futures());
}
// scroll_buf: Scroll the specified region by n lines. The scrollback can only be used with the whole scrolling region.
void scroll_region(iota top, iota end, iota n, bool use_scrollback) override
{
assert(top >= y_top && end <= y_end);
if (n == 0) return;
auto stash = arena - (batch.vsize - batch.basis);
if (stash > 0) add_lines(stash); // Fill-up the scrolling region in order to simplify implementation (dissect() requirement).
assert(arena == index.size);
auto count = std::abs(n);
if (n < 0) // Scroll text up.
{
if (top == y_top &&
end == y_end && use_scrollback)
{
count -= feed_futures(count);
if (count > 0)
{
add_lines(count);
// Cut, as the ring is used.
batch.basis = std::min(batch.basis + count, batch.vsize - arena);
}
}
else
{
top -= y_top;
end -= y_top - 1;
auto max = end - top;
if (count > max) count = max;
auto mdl = top + count;
dissect(top);
dissect(mdl);
dissect(end);
// Delete block.
auto topid = index[top ].index;
auto mdlid = index[mdl - 1].index + 1;
auto endid = index[end - 1].index + 1;
auto start = batch.index_by_id(topid);
auto range = static_cast<iota>(mdlid - topid);
auto floor = batch.index_by_id(endid) - range;
batch.remove(start, range);
// Insert block.
while (count-- > 0) batch.insert(floor, id_t{}, parser::style);
batch.reindex(start);
index_rebuild();
}
}
else // Scroll text down.
{
top -= y_top;
end -= y_top - 1;
auto max = end - top;
if (count > max) count = max;
auto mdl = end - count;
dissect(top);
dissect(mdl);
dissect(end);
// Delete block.
auto topid = index[top ].index;
auto mdlid = index[mdl - 1].index + 1;
auto endid = index[end - 1].index + 1;
auto start = batch.index_by_id(topid);
auto range = static_cast<iota>(endid - mdlid);
auto floor = batch.index_by_id(endid) - range;
batch.remove(floor, range);
// Insert block.
while (count-- > 0) batch.insert(start, id_t{}, parser::style);
batch.reindex(start);
index_rebuild();
}
assert(test_futures());
}
};
using buffer_ptr = bufferbase*;
pro::caret cursor; // term: Text cursor controller.
term_state status; // term: Screen buffer status info.
w_tracking wtrack; // term: Terminal title tracking object.
f_tracking ftrack; // term: Keyboard focus tracking object.
m_tracking mtrack; // term: VT-style mouse tracking object.
c_tracking ctrack; // term: Custom terminal palette tracking object.
scroll_buf normal; // term: Normal screen buffer.
alt_screen altbuf; // term: Alternate screen buffer.
buffer_ptr target; // term: Current screen buffer pointer.
os::ptydev ptycon; // term: PTY device.
text cmdarg; // term: Startup command line arguments.
twod initsz; // term: Initial PTY size (pty inited in the parallel thread).
hook oneoff; // term: One-shot token for the first resize and shutdown events.
twod origin; // term: Viewport position.
bool active; // term: Terminal lifetime.
bool decckm; // term: Cursor keys Application(true)/ANSI(faux) mode.
bool bpmode; // term: Bracketed paste mode.
// term: Soft terminal reset (DECSTR).
void decstr()
{
target->flush();
normal.clear_all();
altbuf.clear_all();
target = &normal;
}
// term: Set termnail parameters. (DECSET).
void decset(fifo& queue)
{
target->flush();
while (auto q = queue(0))
{
switch (q)
{
case 1: // Cursor keys application mode.
decckm = true;
break;
case 7: // Enable auto-wrap.
target->style.wrp(wrap::on);
break;
case 12: // Enable cursor blinking.
cursor.blink_period();
break;
case 25: // Caret on.
cursor.show();
break;
case 9: // Enable X10 mouse reporting protocol.
log("decset: CSI ? 9 h X10 Mouse reporting protocol is not supported");
break;
case 1000: // Enable mouse buttons reporting mode.
mtrack.enable(m_tracking::buttons_press);
break;
case 1001: // Use Hilite mouse tracking mode.
log("decset: CSI ? 1001 h Hilite mouse tracking mode is not supported");
break;
case 1002: // Enable mouse buttons and drags reporting mode.
mtrack.enable(m_tracking::buttons_drags);
break;
case 1003: // Enable all mouse events reporting mode.
mtrack.enable(m_tracking::all_movements);
break;
case 1004: // Enable focus tracking.
ftrack.set(true);
break;
case 1005: // Enable UTF-8 mouse reporting protocol.
log("decset: CSI ? 1005 h UTF-8 mouse reporting protocol is not supported");
break;
case 1006: // Enable SGR mouse reporting protocol.
mtrack.setmode(m_tracking::sgr);
break;
case 10060:// Enable mouse reporting outside the viewport (outside+negative coordinates).
mtrack.enable(m_tracking::negative_args);
break;
case 1015: // Enable URXVT mouse reporting protocol.
log("decset: CSI ? 1015 h URXVT mouse reporting protocol is not supported");
break;
case 1016: // Enable Pixels (subcell) mouse mode.
log("decset: CSI ? 1016 h Pixels (subcell) mouse mode is not supported");
break;
case 1048: // Save cursor pos.
target->scp();
break;
case 1047: // Use alternate screen buffer.
case 1049: // Save cursor pos and use alternate screen buffer, clearing it first. This control combines the effects of the 1047 and 1048 modes.
altbuf.style = target->style;
altbuf.clear_all();
altbuf.resize_viewport(target->panel); // Reset viewport to the basis.
target = &altbuf;
base::resize(altbuf.panel);
break;
case 2004: // Set bracketed paste mode.
bpmode = true;
break;
default:
break;
}
}
}
// term: Reset termnail parameters. (DECRST).
void decrst(fifo& queue)
{
target->flush();
while (auto q = queue(0))
{
switch (q)
{
case 1: // Cursor keys ANSI mode.
decckm = faux;
break;
case 7: // Disable auto-wrap.
target->style.wrp(wrap::off);
break;
case 12: // Disable cursor blinking.
cursor.blink_period(period::zero());
break;
case 25: // Caret off.
cursor.hide();
break;
case 9: // Disable X10 mouse reporting protocol.
log("decset: CSI ? 9 l X10 Mouse tracking protocol is not supported");
break;
case 1000: // Disable mouse buttons reporting mode.
mtrack.disable(m_tracking::buttons_press);
break;
case 1001: // Don't use Hilite(c) mouse tracking mode.
log("decset: CSI ? 1001 l Hilite mouse tracking mode is not supported");
break;
case 1002: // Disable mouse buttons and drags reporting mode.
mtrack.disable(m_tracking::buttons_drags);
break;
case 1003: // Disable all mouse events reporting mode.
mtrack.disable(m_tracking::all_movements);
break;
case 1004: // Disable focus tracking.
ftrack.set(faux);
break;
case 1005: // Disable UTF-8 mouse reporting protocol.
log("decset: CSI ? 1005 l UTF-8 mouse reporting protocol is not supported");
break;
case 1006: // Disable SGR mouse reporting protocol (set X11 mode).
mtrack.setmode(m_tracking::x11);
break;
case 10060:// Disable mouse reporting outside the viewport (allow reporting inside the viewport only).
mtrack.disable(m_tracking::negative_args);
break;
case 1015: // Disable URXVT mouse reporting protocol.
log("decset: CSI ? 1015 l URXVT mouse reporting protocol is not supported");
break;
case 1016: // Disable Pixels (subcell) mouse mode.
log("decset: CSI ? 1016 l Pixels (subcell) mouse mode is not supported");
break;
case 1048: // Restore cursor pos.
target->rcp();
break;
case 1047: // Use normal screen buffer.
case 1049: // Use normal screen buffer and restore cursor.
normal.style = target->style;
normal.resize_viewport(target->panel); // Reset viewport to the basis.
target = &normal;
base::resize(normal.panel);
break;
case 2004: // Disable bracketed paste mode.
bpmode = faux;
break;
default:
break;
}
}
}
// term: Set scrollback buffer size and grow step.
void sbsize(fifo& queue)
{
target->flush();
auto ring_size = queue(def_length);
auto grow_step = queue(def_growup);
normal.resize_history(ring_size, grow_step);
}
// term: Extended functionality response.
void native(bool are_u)
{
auto response = ansi::ext(are_u);
answer(response);
}
// term: Write tty data and flush the queue.
void answer(ansi::esc& queue)
{
if (queue.length())
{
ptycon.write(queue);
queue.clear();
}
}
bool follow_cursor = faux;
// term: Reset viewport position.
void scroll(bool force_basis = true)
{
auto& console = *target;
auto basis = console.get_basis();
auto adjust_pads = console.recalc_pads(oversz);
auto scroll_size = console.panel;
scroll_size.y += basis;
if (force_basis)
{
if (follow_cursor)
{
follow_cursor = faux;
auto c = console.get_coord(dot_00);
if (origin.x != 0 || c.x != console.panel.x)
{
if (c.x >= 0 && c.x < console.panel.x) origin.x = 0;
else if (c.x >= -origin.x + console.panel.x) origin.x = -c.x + console.panel.x - 1;
else if (c.x < -origin.x ) origin.x = -c.x;
}
origin.y = -basis;
SIGNAL(tier::release, e2::coor::set, origin);
SIGNAL(tier::release, e2::size::set, scroll_size); // Update scrollbars.
return;
}
//todo check the case: arena == batch.peak - 1
origin.y = -basis;
SIGNAL(tier::release, e2::coor::set, origin);
SIGNAL(tier::release, e2::size::set, scroll_size); // Update scrollbars.
return;
}
else if (console.is_need_to_correct())
{
auto cur_pos = -origin.y;
if (cur_pos >=0 && cur_pos < basis)
if (auto slide = -console.get_slide(); origin.y != slide)
{
//todo optimize
//todo separate the viewport position from the slide
origin.y = slide;
SIGNAL(tier::release, e2::coor::set, origin);
SIGNAL(tier::release, e2::size::set, scroll_size); // Update scrollbars.
return;
}
}
if (scroll_size != base::size() || adjust_pads)
{
SIGNAL(tier::release, e2::size::set, scroll_size); // Update scrollbars.
}
}
// term: Proceed terminal input.
void ondata(view data)
{
while (active)
{
netxs::events::try_sync guard;
if (guard)
{
SIGNAL(tier::general, e2::debug::output, data); // Post for the Logs.
auto force_basis = target->force_basis();
ansi::parse(data, target);
scroll(force_basis);
base::deface();
break;
}
else std::this_thread::yield();
}
}
// term: Shutdown callback handler.
void onexit(iota code)
{
log("term: exit code ", code);
if (code)
{
text error = ansi::bgc(reddk).fgc(whitelt).add("\nterm: exit code ", code, " ");
ondata(error);
}
else
{
log("term: submit for destruction on next frame/tick");
SUBMIT_T(tier::general, e2::tick, oneoff, t)
{
oneoff.reset();
this->base::riseup<tier::release>(e2::form::quit, This());
};
}
}
public:
void exec_cmd(commands::ui::commands cmd)
{
log("term: tier::preview, ui::commands, ", cmd);
scroll();
switch (cmd)
{
case commands::ui::left:
target->style.jet(bias::left);
break;
case commands::ui::center:
target->style.jet(bias::center);
break;
case commands::ui::right:
target->style.jet(bias::right);
break;
case commands::ui::togglewrp:
target->style.wrp(target->style.wrp() == wrap::on ? wrap::off : wrap::on);
break;
case commands::ui::reset:
decstr();
break;
case commands::ui::clear:
target->ed(commands::erase::display::viewport);
break;
default:
break;
}
ondata("");
}
void data_in(view data)
{
log("term: app::term::data::in, ", utf::debase(data));
scroll();
ondata(data);
}
void data_out(view data)
{
log("term: app::term::data::out, ", utf::debase(data));
scroll();
ptycon.write(data);
}
//todo temp
bool started = faux;
void start()
{
//todo move it to the another thread (slow init)
//initsz = base::size();
//std::thread{ [&]( )
//{
//todo async command queue
ptycon.start(cmdarg, initsz, [&](auto utf8_shadow) { ondata(utf8_shadow); },
[&](auto exit_reason) { onexit(exit_reason); } );
started = true;
//} }.detach();
}
~term(){ active = faux; }
term(text command_line, iota max_scrollback_size = def_length, iota grow_step = def_growup)
//term(text command_line, iota max_scrollback_size = 50, iota grow_step = 0)
: normal{ *this, max_scrollback_size, grow_step },
altbuf{ *this },
cursor{ *this },
mtrack{ *this },
ftrack{ *this },
wtrack{ *this },
ctrack{ *this },
active{ true },
decckm{ faux },
bpmode{ faux }
{
cmdarg = command_line;
target = &normal;
//cursor.style(commands::cursor::def_style); // default=blinking_box
cursor.style(commands::cursor::blinking_underline);
cursor.show(); //todo revise (possible bug)
form::keybd.accept(true); // Subscribe to keybd offers.
SUBMIT(tier::release, e2::coor::set, new_coor)
{
//todo use tier::preview bcz approx viewport position can be corrected
origin = new_coor;
origin.y = -target->set_slide(-origin.y);
//preview: new_coor = origin;
};
SUBMIT(tier::release, e2::form::upon::vtree::attached, parent)
{
this->base::riseup<tier::request>(e2::form::prop::header, wtrack.get(ansi::OSC_TITLE));
//todo deprecated
this->SUBMIT_T(tier::release, e2::size::set, oneoff, new_sz)
{
if (new_sz.y > 0)
{
oneoff.reset();
auto& console = *target;
new_sz = std::max(new_sz, dot_11);
console.resize_viewport(new_sz);
this->SUBMIT(tier::preview, e2::size::set, new_sz)
{
auto& console = *target;
new_sz = std::max(new_sz, dot_11);
auto force_basis = console.force_basis();
console.resize_viewport(new_sz);
if (!force_basis)
{
auto slide = -console.get_slide();
if (origin.y != slide)
{
origin.y = slide;
this->SIGNAL(tier::release, e2::coor::set, origin);
}
}
else scroll();
initsz = new_sz;
//std::thread{ [&]()
//{
//todo async command queue
if (started) ptycon.resize(initsz);
//} }.detach();
new_sz.y = console.get_basis() + new_sz.y;
};
//todo move it to the another thread (slow init)
// initsz = new_sz;
// //std::thread{ [&]( )
// //{
// //todo async command queue
// ptycon.start(cmdarg, initsz, [&](auto utf8_shadow) { ondata(utf8_shadow); },
// [&](auto exit_reason) { onexit(exit_reason); } );
//} }.detach();
}
};
};
SUBMIT(tier::release, hids::events::keybd::any, gear)
{
//todo stop/finalize scrolling animations
scroll(true);
follow_cursor = true;
#ifndef PROD
return;
#endif
//todo optimize/unify
auto data = gear.keystrokes;
if (!bpmode)
{
utf::change(data, "\033[200~", "");
utf::change(data, "\033[201~", "");
}
if (decckm)
{
utf::change(data, "\033[A", "\033OA");
utf::change(data, "\033[B", "\033OB");
utf::change(data, "\033[C", "\033OC");
utf::change(data, "\033[D", "\033OD");
utf::change(data, "\033[1A", "\033OA");
utf::change(data, "\033[1B", "\033OB");
utf::change(data, "\033[1C", "\033OC");
utf::change(data, "\033[1D", "\033OD");
}
// Linux console specific.
utf::change(data, "\033[[A", "\033OP"); // F1
utf::change(data, "\033[[B", "\033OQ"); // F2
utf::change(data, "\033[[C", "\033OR"); // F3
utf::change(data, "\033[[D", "\033OS"); // F4
utf::change(data, "\033[[E", "\033[15~"); // F5
utf::change(data, "\033[25~", "\033[1;2P"); // Shift+F1
utf::change(data, "\033[26~", "\033[1;2Q"); // Shift+F2
utf::change(data, "\033[28~", "\033[1;2R"); // Shift+F3
utf::change(data, "\033[29~", "\033[1;2S"); // Shift+F4
utf::change(data, "\033[31~", "\033[15;2~"); // Shift+F5
utf::change(data, "\033[32~", "\033[17;2~"); // Shift+F6
utf::change(data, "\033[33~", "\033[18;2~"); // Shift+F7
utf::change(data, "\033[34~", "\033[19;2~"); // Shift+F8
ptycon.write(data);
#ifdef KEYLOG
std::stringstream d;
view v = gear.keystrokes;
log("key strokes raw: ", utf::debase(v));
while (v.size())
{
d << (int)v.front() << " ";
v.remove_prefix(1);
}
log("key strokes bin: ", d.str());
#endif
};
SUBMIT(tier::release, e2::form::prop::brush, brush)
{
target->brush.reset(brush);
};
SUBMIT(tier::release, e2::render::any, parent_canvas)
{
auto& console = *target;
if (status.update(console))
{
this->base::riseup<tier::preview>(e2::form::prop::footer, status.data);
}
auto view = parent_canvas.view();
auto full = parent_canvas.full();
auto base = full.coor - view.coor;
cursor.coor(console.get_coord(base));
console.output(parent_canvas);
if (oversz.b > 0) // Shade the viewport bottom oversize (futures).
{
auto bottom_oversize = parent_canvas.full();
bottom_oversize.coor.y += console.get_basis() + console.panel.y - console.scend;//scroll_size.y;
bottom_oversize.size.y = oversz.b;
bottom_oversize = bottom_oversize.clip(parent_canvas.view());
parent_canvas.fill(bottom_oversize, cell::shaders::xlight);
}
// Debug: Shade active viewport.
//{
// auto size = console.panel;
// size.y -= console.sctop + console.scend;
// auto vp = rect{ { 0,console.get_basis() + console.sctop }, size };
// vp.coor += parent_canvas.full().coor;
// vp = vp.clip(parent_canvas.view());
// parent_canvas.fill(vp, [](auto& c){ c.fuse(cell{}.bgc(magentalt).bga(50)); });
//}
};
}
};
}
#endif // NETXS_TERMINAL_HPP | 43.667899 | 210 | 0.395789 | [
"render",
"object",
"vector"
] |
c01a0df309270ddbdd9ae6b626cc1acfe13f2ec5 | 55,503 | cpp | C++ | third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp | 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 | third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp | 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 | third_party/WebKit/Source/core/layout/compositing/CompositedLayerMappingTest.cpp | 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 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/layout/compositing/CompositedLayerMapping.h"
#include "core/frame/FrameView.h"
#include "core/layout/LayoutBoxModelObject.h"
#include "core/layout/LayoutTestHelper.h"
#include "core/layout/api/LayoutViewItem.h"
#include "core/page/scrolling/TopDocumentRootScrollerController.h"
#include "core/paint/PaintLayer.h"
#include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h"
#include "public/platform/WebContentLayer.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
typedef bool TestParamRootLayerScrolling;
class CompositedLayerMappingTest
: public testing::WithParamInterface<TestParamRootLayerScrolling>,
private ScopedRootLayerScrollingForTest,
public RenderingTest {
public:
CompositedLayerMappingTest()
: ScopedRootLayerScrollingForTest(GetParam()),
RenderingTest(SingleChildFrameLoaderClient::create()) {}
protected:
IntRect recomputeInterestRect(const GraphicsLayer* graphicsLayer) {
return static_cast<CompositedLayerMapping*>(graphicsLayer->client())
->recomputeInterestRect(graphicsLayer);
}
IntRect computeInterestRect(
const CompositedLayerMapping* compositedLayerMapping,
GraphicsLayer* graphicsLayer,
IntRect previousInterestRect) {
return compositedLayerMapping->computeInterestRect(graphicsLayer,
previousInterestRect);
}
bool shouldFlattenTransform(const GraphicsLayer& layer) const {
return layer.shouldFlattenTransform();
}
bool interestRectChangedEnoughToRepaint(const IntRect& previousInterestRect,
const IntRect& newInterestRect,
const IntSize& layerSize) {
return CompositedLayerMapping::interestRectChangedEnoughToRepaint(
previousInterestRect, newInterestRect, layerSize);
}
IntRect previousInterestRect(const GraphicsLayer* graphicsLayer) {
return graphicsLayer->m_previousInterestRect;
}
private:
void SetUp() override {
RenderingTest::SetUp();
enableCompositing();
}
void TearDown() override { RenderingTest::TearDown(); }
};
#define EXPECT_RECT_EQ(expected, actual) \
do { \
const IntRect& actualRect = actual; \
EXPECT_EQ(expected.x(), actualRect.x()); \
EXPECT_EQ(expected.y(), actualRect.y()); \
EXPECT_EQ(expected.width(), actualRect.width()); \
EXPECT_EQ(expected.height(), actualRect.height()); \
} while (false)
INSTANTIATE_TEST_CASE_P(All, CompositedLayerMappingTest, ::testing::Bool());
TEST_P(CompositedLayerMappingTest, SimpleInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 200, 200),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, TallLayerInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer->graphicsLayerBacking());
// Screen-space visible content rect is [8, 8, 200, 600]. Mapping back to
// local, adding 4000px in all directions, then clipping, yields this rect.
EXPECT_RECT_EQ(IntRect(0, 0, 200, 4592),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, TallLayerWholeDocumentInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform'></div>");
document().settings()->setMainFrameClipsContent(false);
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer->graphicsLayerBacking());
ASSERT_TRUE(paintLayer->compositedLayerMapping());
// Clipping is disabled in recomputeInterestRect.
EXPECT_RECT_EQ(IntRect(0, 0, 200, 10000),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
EXPECT_RECT_EQ(
IntRect(0, 0, 200, 10000),
computeInterestRect(paintLayer->compositedLayerMapping(),
paintLayer->graphicsLayerBacking(), IntRect()));
}
TEST_P(CompositedLayerMappingTest, VerticalRightLeftWritingModeDocument) {
setBodyInnerHTML(
"<style>html,body { margin: 0px } html { -webkit-writing-mode: "
"vertical-rl}</style> <div id='target' style='width: 10000px; height: "
"200px;'></div>");
document().view()->updateAllLifecyclePhases();
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(-5000, 0), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
PaintLayer* paintLayer = document().layoutViewItem().layer();
ASSERT_TRUE(paintLayer->graphicsLayerBacking());
ASSERT_TRUE(paintLayer->compositedLayerMapping());
// A scroll by -5000px is equivalent to a scroll by (10000 - 5000 - 800)px =
// 4200px in non-RTL mode. Expanding the resulting rect by 4000px in each
// direction yields this result.
EXPECT_RECT_EQ(IntRect(200, 0, 8800, 600),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, RotatedInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform; transform: rotateZ(45deg)'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 200, 200),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, RotatedInterestRectNear90Degrees) {
setBodyInnerHTML(
"<div id='target' style='width: 10000px; height: 200px; will-change: "
"transform; transform: rotateY(89.9999deg)'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
// Because the layer is rotated to almost 90 degrees, floating-point error
// leads to a reverse-projected rect that is much much larger than the
// original layer size in certain dimensions. In such cases, we often fall
// back to the 4000px interest rect padding amount.
EXPECT_RECT_EQ(IntRect(0, 0, 4000, 200),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, 3D90DegRotatedTallInterestRect) {
// It's rotated 90 degrees about the X axis, which means its visual content
// rect is empty, and so the interest rect is the default (0, 0, 4000, 4000)
// intersected with the layer bounds.
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateY(90deg)'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 200, 4000),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, 3D45DegRotatedTallInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateY(45deg)'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 200, 4592),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, RotatedTallInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 10000px; will-change: "
"transform; transform: rotateZ(45deg)'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 200, 4000),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, WideLayerInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 10000px; height: 200px; will-change: "
"transform'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
// Screen-space visible content rect is [8, 8, 800, 200] (the screen is
// 800x600). Mapping back to local, adding 4000px in all directions, then
// clipping, yields this rect.
EXPECT_RECT_EQ(IntRect(0, 0, 4792, 200),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, FixedPositionInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 300px; height: 400px; will-change: "
"transform; position: fixed; top: 100px; left: 200px;'></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
EXPECT_RECT_EQ(IntRect(0, 0, 300, 400),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, LayerOffscreenInterestRect) {
setBodyInnerHTML(
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform; position: absolute; top: 9000px; left: 0px;'>"
"</div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(!!paintLayer->graphicsLayerBacking());
// Offscreen layers are painted as usual.
EXPECT_RECT_EQ(IntRect(0, 0, 200, 200),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, ScrollingLayerInterestRect) {
setBodyInnerHTML(
"<style>div::-webkit-scrollbar{ width: 5px; }</style>"
"<div id='target' style='width: 200px; height: 200px; will-change: "
"transform; overflow: scroll'>"
"<div style='width: 100px; height: 10000px'></div></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer->graphicsLayerBacking());
// Offscreen layers are painted as usual.
ASSERT_TRUE(paintLayer->compositedLayerMapping()->scrollingLayer());
EXPECT_RECT_EQ(IntRect(0, 0, 195, 4592),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, ClippedBigLayer) {
setBodyInnerHTML(
"<div style='width: 1px; height: 1px; overflow: hidden'>"
"<div id='target' style='width: 10000px; height: 10000px; will-change: "
"transform'></div></div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer->graphicsLayerBacking());
// Offscreen layers are painted as usual.
EXPECT_RECT_EQ(IntRect(0, 0, 4001, 4001),
recomputeInterestRect(paintLayer->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, ClippingMaskLayer) {
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
return;
const AtomicString styleWithoutClipping =
"backface-visibility: hidden; width: 200px; height: 200px";
const AtomicString styleWithBorderRadius =
styleWithoutClipping + "; border-radius: 10px";
const AtomicString styleWithClipPath =
styleWithoutClipping + "; -webkit-clip-path: inset(10px)";
setBodyInnerHTML("<video id='video' src='x' style='" + styleWithoutClipping +
"'></video>");
document().view()->updateAllLifecyclePhases();
Element* videoElement = document().getElementById("video");
GraphicsLayer* graphicsLayer =
toLayoutBoxModelObject(videoElement->layoutObject())
->layer()
->graphicsLayerBacking();
EXPECT_FALSE(graphicsLayer->maskLayer());
EXPECT_FALSE(graphicsLayer->contentsClippingMaskLayer());
videoElement->setAttribute(HTMLNames::styleAttr, styleWithBorderRadius);
document().view()->updateAllLifecyclePhases();
EXPECT_FALSE(graphicsLayer->maskLayer());
EXPECT_TRUE(graphicsLayer->contentsClippingMaskLayer());
videoElement->setAttribute(HTMLNames::styleAttr, styleWithClipPath);
document().view()->updateAllLifecyclePhases();
EXPECT_TRUE(graphicsLayer->maskLayer());
EXPECT_FALSE(graphicsLayer->contentsClippingMaskLayer());
videoElement->setAttribute(HTMLNames::styleAttr, styleWithoutClipping);
document().view()->updateAllLifecyclePhases();
EXPECT_FALSE(graphicsLayer->maskLayer());
EXPECT_FALSE(graphicsLayer->contentsClippingMaskLayer());
}
TEST_P(CompositedLayerMappingTest, ScrollContentsFlattenForScroller) {
setBodyInnerHTML(
"<style>div::-webkit-scrollbar{ width: 5px; }</style>"
"<div id='scroller' style='width: 100px; height: 100px; overflow: "
"scroll; will-change: transform'>"
"<div style='width: 1000px; height: 1000px;'>Foo</div>Foo</div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("scroller");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
CompositedLayerMapping* compositedLayerMapping =
paintLayer->compositedLayerMapping();
ASSERT_TRUE(compositedLayerMapping);
EXPECT_FALSE(
shouldFlattenTransform(*compositedLayerMapping->mainGraphicsLayer()));
EXPECT_FALSE(
shouldFlattenTransform(*compositedLayerMapping->scrollingLayer()));
EXPECT_TRUE(shouldFlattenTransform(
*compositedLayerMapping->scrollingContentsLayer()));
}
TEST_P(CompositedLayerMappingTest, InterestRectChangedEnoughToRepaintEmpty) {
IntSize layerSize(1000, 1000);
// Both empty means there is nothing to do.
EXPECT_FALSE(
interestRectChangedEnoughToRepaint(IntRect(), IntRect(), layerSize));
// Going from empty to non-empty means we must re-record because it could be
// the first frame after construction or Clear.
EXPECT_TRUE(interestRectChangedEnoughToRepaint(IntRect(), IntRect(0, 0, 1, 1),
layerSize));
// Going from non-empty to empty is not special-cased.
EXPECT_FALSE(interestRectChangedEnoughToRepaint(IntRect(0, 0, 1, 1),
IntRect(), layerSize));
}
TEST_P(CompositedLayerMappingTest,
InterestRectChangedEnoughToRepaintNotBigEnough) {
IntSize layerSize(1000, 1000);
IntRect previousInterestRect(100, 100, 100, 100);
EXPECT_FALSE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(100, 100, 90, 90), layerSize));
EXPECT_FALSE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(100, 100, 100, 100), layerSize));
EXPECT_FALSE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(1, 1, 200, 200), layerSize));
}
TEST_P(CompositedLayerMappingTest,
InterestRectChangedEnoughToRepaintNotBigEnoughButNewAreaTouchesEdge) {
IntSize layerSize(500, 500);
IntRect previousInterestRect(100, 100, 100, 100);
// Top edge.
EXPECT_TRUE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(100, 0, 100, 200), layerSize));
// Left edge.
EXPECT_TRUE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(0, 100, 200, 100), layerSize));
// Bottom edge.
EXPECT_TRUE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(100, 100, 100, 400), layerSize));
// Right edge.
EXPECT_TRUE(interestRectChangedEnoughToRepaint(
previousInterestRect, IntRect(100, 100, 400, 100), layerSize));
}
// Verifies that having a current viewport that touches a layer edge does not
// force re-recording.
TEST_P(CompositedLayerMappingTest,
InterestRectChangedEnoughToRepaintCurrentViewportTouchesEdge) {
IntSize layerSize(500, 500);
IntRect newInterestRect(100, 100, 300, 300);
// Top edge.
EXPECT_FALSE(interestRectChangedEnoughToRepaint(IntRect(100, 0, 100, 100),
newInterestRect, layerSize));
// Left edge.
EXPECT_FALSE(interestRectChangedEnoughToRepaint(IntRect(0, 100, 100, 100),
newInterestRect, layerSize));
// Bottom edge.
EXPECT_FALSE(interestRectChangedEnoughToRepaint(IntRect(300, 400, 100, 100),
newInterestRect, layerSize));
// Right edge.
EXPECT_FALSE(interestRectChangedEnoughToRepaint(IntRect(400, 300, 100, 100),
newInterestRect, layerSize));
}
TEST_P(CompositedLayerMappingTest,
InterestRectChangedEnoughToRepaintScrollScenarios) {
IntSize layerSize(1000, 1000);
IntRect previousInterestRect(100, 100, 100, 100);
IntRect newInterestRect(previousInterestRect);
newInterestRect.move(512, 0);
EXPECT_FALSE(interestRectChangedEnoughToRepaint(previousInterestRect,
newInterestRect, layerSize));
newInterestRect.move(0, 512);
EXPECT_FALSE(interestRectChangedEnoughToRepaint(previousInterestRect,
newInterestRect, layerSize));
newInterestRect.move(1, 0);
EXPECT_TRUE(interestRectChangedEnoughToRepaint(previousInterestRect,
newInterestRect, layerSize));
newInterestRect.move(-1, 1);
EXPECT_TRUE(interestRectChangedEnoughToRepaint(previousInterestRect,
newInterestRect, layerSize));
}
TEST_P(CompositedLayerMappingTest, InterestRectChangeOnViewportScroll) {
setBodyInnerHTML(
"<style>"
" ::-webkit-scrollbar { width: 0; height: 0; }"
" body { margin: 0; }"
"</style>"
"<div id='div' style='width: 100px; height: 10000px'>Text</div>");
document().view()->updateAllLifecyclePhases();
GraphicsLayer* rootScrollingLayer =
document().layoutViewItem().layer()->graphicsLayerBacking();
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4600),
previousInterestRect(rootScrollingLayer));
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 300), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
// Still use the previous interest rect because the recomputed rect hasn't
// changed enough.
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4900),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4600),
previousInterestRect(rootScrollingLayer));
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 600), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
// Use recomputed interest rect because it changed enough.
EXPECT_RECT_EQ(IntRect(0, 0, 800, 5200),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 800, 5200),
previousInterestRect(rootScrollingLayer));
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 5400), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 1400, 800, 8600),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 1400, 800, 8600),
previousInterestRect(rootScrollingLayer));
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 9000), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
// Still use the previous interest rect because it contains the recomputed
// interest rect.
EXPECT_RECT_EQ(IntRect(0, 5000, 800, 5000),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 1400, 800, 8600),
previousInterestRect(rootScrollingLayer));
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 2000), ProgrammaticScroll);
// Use recomputed interest rect because it changed enough.
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 0, 800, 6600),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 800, 6600),
previousInterestRect(rootScrollingLayer));
}
TEST_P(CompositedLayerMappingTest, InterestRectChangeOnShrunkenViewport) {
setBodyInnerHTML(
"<style>"
" ::-webkit-scrollbar { width: 0; height: 0; }"
" body { margin: 0; }"
"</style>"
"<div id='div' style='width: 100px; height: 10000px'>Text</div>");
document().view()->updateAllLifecyclePhases();
GraphicsLayer* rootScrollingLayer =
document().layoutViewItem().layer()->graphicsLayerBacking();
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4600),
previousInterestRect(rootScrollingLayer));
document().view()->setFrameRect(IntRect(0, 0, 800, 60));
document().view()->updateAllLifecyclePhases();
// Repaint required, so interest rect should be updated to shrunken size.
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4060),
recomputeInterestRect(rootScrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 800, 4060),
previousInterestRect(rootScrollingLayer));
}
TEST_P(CompositedLayerMappingTest, InterestRectChangeOnScroll) {
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
setBodyInnerHTML(
"<style>"
" ::-webkit-scrollbar { width: 0; height: 0; }"
" body { margin: 0; }"
"</style>"
"<div id='scroller' style='width: 400px; height: 400px; overflow: "
"scroll'>"
" <div id='content' style='width: 100px; height: 10000px'>Text</div>"
"</div");
document().view()->updateAllLifecyclePhases();
Element* scroller = document().getElementById("scroller");
GraphicsLayer* scrollingLayer =
scroller->layoutBox()->layer()->graphicsLayerBacking();
EXPECT_RECT_EQ(IntRect(0, 0, 400, 4600),
previousInterestRect(scrollingLayer));
scroller->setScrollTop(300);
document().view()->updateAllLifecyclePhases();
// Still use the previous interest rect because the recomputed rect hasn't
// changed enough.
EXPECT_RECT_EQ(IntRect(0, 0, 400, 4900),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 400, 4600),
previousInterestRect(scrollingLayer));
scroller->setScrollTop(600);
document().view()->updateAllLifecyclePhases();
// Use recomputed interest rect because it changed enough.
EXPECT_RECT_EQ(IntRect(0, 0, 400, 5200),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 400, 5200),
previousInterestRect(scrollingLayer));
scroller->setScrollTop(5400);
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 1400, 400, 8600),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 1400, 400, 8600),
previousInterestRect(scrollingLayer));
scroller->setScrollTop(9000);
document().view()->updateAllLifecyclePhases();
// Still use the previous interest rect because it contains the recomputed
// interest rect.
EXPECT_RECT_EQ(IntRect(0, 5000, 400, 5000),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 1400, 400, 8600),
previousInterestRect(scrollingLayer));
scroller->setScrollTop(2000);
// Use recomputed interest rect because it changed enough.
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 0, 400, 6600),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 0, 400, 6600),
previousInterestRect(scrollingLayer));
}
TEST_P(CompositedLayerMappingTest,
InterestRectShouldChangeOnPaintInvalidation) {
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
setBodyInnerHTML(
"<style>"
" ::-webkit-scrollbar { width: 0; height: 0; }"
" body { margin: 0; }"
"</style>"
"<div id='scroller' style='width: 400px; height: 400px; overflow: "
"scroll'>"
" <div id='content' style='width: 100px; height: 10000px'>Text</div>"
"</div");
document().view()->updateAllLifecyclePhases();
Element* scroller = document().getElementById("scroller");
GraphicsLayer* scrollingLayer =
scroller->layoutBox()->layer()->graphicsLayerBacking();
scroller->setScrollTop(5400);
document().view()->updateAllLifecyclePhases();
scroller->setScrollTop(9400);
// The above code creates an interest rect bigger than the interest rect if
// recomputed now.
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 5400, 400, 4600),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 1400, 400, 8600),
previousInterestRect(scrollingLayer));
// Paint invalidation and repaint should change previous paint interest rect.
document().getElementById("content")->setTextContent("Change");
document().view()->updateAllLifecyclePhases();
EXPECT_RECT_EQ(IntRect(0, 5400, 400, 4600),
recomputeInterestRect(scrollingLayer));
EXPECT_RECT_EQ(IntRect(0, 5400, 400, 4600),
previousInterestRect(scrollingLayer));
}
TEST_P(CompositedLayerMappingTest,
InterestRectOfSquashingLayerWithNegativeOverflow) {
setBodyInnerHTML(
"<style>body { margin: 0; font-size: 16px; }</style>"
"<div style='position: absolute; top: -500px; width: 200px; height: "
"700px; will-change: transform'></div>"
"<div id='squashed' style='position: absolute; top: 190px;'>"
" <div id='inside' style='width: 100px; height: 100px; text-indent: "
"-10000px'>text</div>"
"</div>");
EXPECT_EQ(document()
.getElementById("inside")
->layoutBox()
->visualOverflowRect()
.size()
.height(),
100);
CompositedLayerMapping* groupedMapping = document()
.getElementById("squashed")
->layoutBox()
->layer()
->groupedMapping();
// The squashing layer is at (-10000, 190, 10100, 100) in viewport
// coordinates.
// The following rect is at (-4000, 190, 4100, 100) in viewport coordinates.
EXPECT_RECT_EQ(IntRect(6000, 0, 4100, 100),
groupedMapping->computeInterestRect(
groupedMapping->squashingLayer(), IntRect()));
}
TEST_P(CompositedLayerMappingTest,
InterestRectOfSquashingLayerWithAncestorClip) {
setBodyInnerHTML(
"<style>body { margin: 0; }</style>"
"<div style='overflow: hidden; width: 400px; height: 400px'>"
" <div style='position: relative; backface-visibility: hidden'>"
" <div style='position: absolute; top: -500px; width: 200px; height: "
"700px; backface-visibility: hidden'></div>"
// Above overflow:hidden div and two composited layers make the squashing
// layer a child of an ancestor clipping layer.
" <div id='squashed' style='height: 1000px; width: 10000px; right: 0; "
"position: absolute'></div>"
" </div>"
"</div>");
CompositedLayerMapping* groupedMapping = document()
.getElementById("squashed")
->layoutBox()
->layer()
->groupedMapping();
// The squashing layer is at (-9600, 0, 10000, 1000) in viewport coordinates.
// The following rect is at (-4000, 0, 4400, 1000) in viewport coordinates.
EXPECT_RECT_EQ(IntRect(5600, 0, 4400, 1000),
groupedMapping->computeInterestRect(
groupedMapping->squashingLayer(), IntRect()));
}
TEST_P(CompositedLayerMappingTest, InterestRectOfIframeInScrolledDiv) {
document().setBaseURLOverride(KURL(ParsedURLString, "http://test.com"));
setBodyInnerHTML(
"<style>body { margin: 0; }</style>"
"<div style='width: 200; height: 8000px'></div>"
"<iframe src='http://test.com' width='500' height='500' "
"frameBorder='0'>"
"</iframe>");
setChildFrameHTML(
"<style>body { margin: 0; } #target { width: 200px; height: 200px; "
"will-change: transform}</style><div id=target></div>");
// Scroll 8000 pixels down to move the iframe into view.
document().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0.0, 8000.0), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
Element* target = childDocument().getElementById("target");
ASSERT_TRUE(target);
EXPECT_RECT_EQ(
IntRect(0, 0, 200, 200),
recomputeInterestRect(
target->layoutObject()->enclosingLayer()->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, InterestRectOfScrolledIframe) {
document().setBaseURLOverride(KURL(ParsedURLString, "http://test.com"));
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
setBodyInnerHTML(
"<style>body { margin: 0; } ::-webkit-scrollbar { display: none; "
"}</style>"
"<iframe src='http://test.com' width='500' height='500' "
"frameBorder='0'>"
"</iframe>");
setChildFrameHTML(
"<style>body { margin: 0; } #target { width: 200px; "
"height: 8000px;}</style><div id=target></div>");
document().view()->updateAllLifecyclePhases();
// Scroll 7500 pixels down to bring the scrollable area to the bottom.
childDocument().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0.0, 7500.0), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
ASSERT_TRUE(childDocument().view()->layoutViewItem().hasLayer());
EXPECT_RECT_EQ(IntRect(0, 3500, 500, 4500),
recomputeInterestRect(childDocument()
.view()
->layoutViewItem()
.enclosingLayer()
->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest, InterestRectOfIframeWithContentBoxOffset) {
document().setBaseURLOverride(KURL(ParsedURLString, "http://test.com"));
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
// Set a 10px border in order to have a contentBoxOffset for the iframe
// element.
setBodyInnerHTML(
"<style>body { margin: 0; } #frame { border: 10px solid black; } "
"::-webkit-scrollbar { display: none; }</style>"
"<iframe src='http://test.com' width='500' height='500' "
"frameBorder='0'>"
"</iframe>");
setChildFrameHTML(
"<style>body { margin: 0; } #target { width: 200px; "
"height: 8000px;}</style> <div id=target></div>");
document().view()->updateAllLifecyclePhases();
// Scroll 3000 pixels down to bring the scrollable area to somewhere in the
// middle.
childDocument().view()->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0.0, 3000.0), ProgrammaticScroll);
document().view()->updateAllLifecyclePhases();
ASSERT_TRUE(childDocument().view()->layoutViewItem().hasLayer());
// The width is 485 pixels due to the size of the scrollbar.
EXPECT_RECT_EQ(IntRect(0, 0, 500, 7500),
recomputeInterestRect(childDocument()
.view()
->layoutViewItem()
.enclosingLayer()
->graphicsLayerBacking()));
}
TEST_P(CompositedLayerMappingTest,
ScrollingContentsAndForegroundLayerPaintingPhase) {
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
setBodyInnerHTML(
"<div id='container' style='position: relative; z-index: 1; overflow: "
"scroll; width: 300px; height: 300px'>"
" <div id='negative-composited-child' style='background-color: red; "
"width: 1px; height: 1px; position: absolute; backface-visibility: "
"hidden; z-index: -1'></div>"
" <div style='background-color: blue; width: 2000px; height: 2000px; "
"position: relative; top: 10px'></div>"
"</div>");
CompositedLayerMapping* mapping =
toLayoutBlock(getLayoutObjectByElementId("container"))
->layer()
->compositedLayerMapping();
ASSERT_TRUE(mapping->scrollingContentsLayer());
EXPECT_EQ(static_cast<GraphicsLayerPaintingPhase>(
GraphicsLayerPaintOverflowContents |
GraphicsLayerPaintCompositedScroll),
mapping->scrollingContentsLayer()->paintingPhase());
ASSERT_TRUE(mapping->foregroundLayer());
EXPECT_EQ(
static_cast<GraphicsLayerPaintingPhase>(
GraphicsLayerPaintForeground | GraphicsLayerPaintOverflowContents),
mapping->foregroundLayer()->paintingPhase());
Element* negativeCompositedChild =
document().getElementById("negative-composited-child");
negativeCompositedChild->parentNode()->removeChild(negativeCompositedChild);
document().view()->updateAllLifecyclePhases();
mapping = toLayoutBlock(getLayoutObjectByElementId("container"))
->layer()
->compositedLayerMapping();
ASSERT_TRUE(mapping->scrollingContentsLayer());
EXPECT_EQ(
static_cast<GraphicsLayerPaintingPhase>(
GraphicsLayerPaintOverflowContents |
GraphicsLayerPaintCompositedScroll | GraphicsLayerPaintForeground),
mapping->scrollingContentsLayer()->paintingPhase());
EXPECT_FALSE(mapping->foregroundLayer());
}
TEST_P(CompositedLayerMappingTest,
DecorationOutlineLayerOnlyCreatedInCompositedScrolling) {
setBodyInnerHTML(
"<style>"
"#target { overflow: scroll; height: 200px; width: 200px; will-change: "
"transform; background: white local content-box; "
"outline: 1px solid blue; outline-offset: -2px;}"
"#scrolled { height: 300px; }"
"</style>"
"<div id=\"parent\">"
" <div id=\"target\"><div id=\"scrolled\"></div></div>"
"</div>");
document().view()->updateAllLifecyclePhases();
Element* element = document().getElementById("target");
PaintLayer* paintLayer =
toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer);
// Decoration outline layer is created when composited scrolling.
EXPECT_TRUE(paintLayer->hasCompositedLayerMapping());
EXPECT_TRUE(paintLayer->needsCompositedScrolling());
CompositedLayerMapping* mapping = paintLayer->compositedLayerMapping();
EXPECT_TRUE(mapping->decorationOutlineLayer());
// No decoration outline layer is created when not composited scrolling.
element->setAttribute(HTMLNames::styleAttr, "overflow: visible;");
document().view()->updateAllLifecyclePhases();
paintLayer = toLayoutBoxModelObject(element->layoutObject())->layer();
ASSERT_TRUE(paintLayer);
mapping = paintLayer->compositedLayerMapping();
EXPECT_FALSE(paintLayer->needsCompositedScrolling());
EXPECT_FALSE(mapping->decorationOutlineLayer());
}
TEST_P(CompositedLayerMappingTest,
DecorationOutlineLayerCreatedAndDestroyedInCompositedScrolling) {
setBodyInnerHTML(
"<style>"
"#scroller { overflow: scroll; height: 200px; width: 200px; background: "
"white local content-box; outline: 1px solid blue; contain: paint; }"
"#scrolled { height: 300px; }"
"</style>"
"<div id=\"parent\">"
" <div id=\"scroller\"><div id=\"scrolled\"></div></div>"
"</div>");
document().view()->updateAllLifecyclePhases();
Element* scroller = document().getElementById("scroller");
PaintLayer* paintLayer =
toLayoutBoxModelObject(scroller->layoutObject())->layer();
ASSERT_TRUE(paintLayer);
CompositedLayerMapping* mapping = paintLayer->compositedLayerMapping();
EXPECT_FALSE(mapping->decorationOutlineLayer());
// The decoration outline layer is created when composited scrolling
// with an outline drawn over the composited scrolling region.
scroller->setAttribute(HTMLNames::styleAttr, "outline-offset: -2px;");
document().view()->updateAllLifecyclePhases();
paintLayer = toLayoutBoxModelObject(scroller->layoutObject())->layer();
ASSERT_TRUE(paintLayer);
mapping = paintLayer->compositedLayerMapping();
EXPECT_TRUE(paintLayer->needsCompositedScrolling());
EXPECT_TRUE(mapping->decorationOutlineLayer());
// The decoration outline layer is destroyed when the scrolling region
// will not be covered up by the outline.
scroller->removeAttribute(HTMLNames::styleAttr);
document().view()->updateAllLifecyclePhases();
paintLayer = toLayoutBoxModelObject(scroller->layoutObject())->layer();
ASSERT_TRUE(paintLayer);
mapping = paintLayer->compositedLayerMapping();
EXPECT_FALSE(mapping->decorationOutlineLayer());
}
TEST_P(CompositedLayerMappingTest,
BackgroundPaintedIntoGraphicsLayerIfNotCompositedScrolling) {
document().frame()->settings()->setPreferCompositingToLCDTextEnabled(true);
setBodyInnerHTML(
"<div id='container' style='overflow: scroll; width: 300px; height: "
"300px; border-radius: 5px; background: white; will-change: transform;'>"
" <div style='background-color: blue; width: 2000px; height: "
"2000px;'></div>"
"</div>");
PaintLayer* layer =
toLayoutBlock(getLayoutObjectByElementId("container"))->layer();
EXPECT_EQ(BackgroundPaintInScrollingContents,
layer->backgroundPaintLocation());
// We currently don't use composited scrolling when the container has a
// border-radius so even though we can paint the background onto the scrolling
// contents layer we don't have a scrolling contents layer to paint into in
// this case.
CompositedLayerMapping* mapping = layer->compositedLayerMapping();
EXPECT_FALSE(mapping->hasScrollingLayer());
EXPECT_FALSE(mapping->backgroundPaintsOntoScrollingContentsLayer());
}
// Make sure that clipping layers are removed or their masking bit turned off
// when they're an ancestor of the root scroller element.
TEST_P(CompositedLayerMappingTest, RootScrollerAncestorsNotClipped) {
NonThrowableExceptionState nonThrow;
TopDocumentRootScrollerController& rootScrollerController =
document().frameHost()->globalRootScrollerController();
setBodyInnerHTML(
// The container DIV is composited with scrolling contents and a
// non-composited parent that clips it.
"<div id='clip' style='overflow: hidden; width: 200px; height: 200px; "
"position: absolute; left: 0px; top: 0px;'>"
" <div id='container' style='transform: translateZ(0); overflow: "
"scroll; width: 300px; height: 300px'>"
" <div style='width: 2000px; height: 2000px;'>lorem ipsum</div>"
" <div id='innerScroller' style='width: 800px; height: 600px; "
"left: 0px; top: 0px; position: absolute; overflow: scroll'>"
" <div style='height: 2000px; width: 2000px'></div>"
" </div>"
" </div>"
"</div>"
// The container DIV is composited with scrolling contents and a
// composited parent that clips it.
"<div id='clip2' style='transform: translateZ(0); position: absolute; "
"left: 0px; top: 0px; overflow: hidden; width: 200px; height: 200px'>"
" <div id='container2' style='transform: translateZ(0); overflow: "
"scroll; width: 300px; height: 300px'>"
" <div style='width: 2000px; height: 2000px;'>lorem ipsum</div>"
" <div id='innerScroller2' style='width: 800px; height: 600px; "
"left: 0px; top: 0px; position: absolute; overflow: scroll'>"
" <div style='height: 2000px; width: 2000px'></div>"
" </div>"
" </div>"
"</div>"
// The container DIV is composited without scrolling contents but
// composited children that it clips.
"<div id='container3' style='translateZ(0); position: absolute; left: "
"0px; top: 0px; z-index: 1; overflow: hidden; width: 300px; height: "
"300px'>"
" <div style='transform: translateZ(0); z-index: -1; width: 2000px; "
"height: 2000px;'>lorem ipsum</div>"
" <div id='innerScroller3' style='width: 800px; height: 600px; "
"left: 0px; top: 0px; position: absolute; overflow: scroll'>"
" <div style='height: 2000px; width: 2000px'></div>"
" </div>"
"</div>");
CompositedLayerMapping* mapping =
toLayoutBlock(getLayoutObjectByElementId("container"))
->layer()
->compositedLayerMapping();
CompositedLayerMapping* mapping2 =
toLayoutBlock(getLayoutObjectByElementId("container2"))
->layer()
->compositedLayerMapping();
CompositedLayerMapping* mapping3 =
toLayoutBlock(getLayoutObjectByElementId("container3"))
->layer()
->compositedLayerMapping();
Element* innerScroller = document().getElementById("innerScroller");
Element* innerScroller2 = document().getElementById("innerScroller2");
Element* innerScroller3 = document().getElementById("innerScroller3");
ASSERT_TRUE(mapping);
ASSERT_TRUE(mapping2);
ASSERT_TRUE(mapping3);
ASSERT_TRUE(innerScroller);
ASSERT_TRUE(innerScroller2);
ASSERT_TRUE(innerScroller3);
// Since there's no need to composite the clip and we prefer LCD text, the
// mapping should create an ancestorClippingLayer.
ASSERT_TRUE(mapping->scrollingLayer());
ASSERT_TRUE(mapping->ancestorClippingLayer());
// Since the clip has a transform it should be composited so there's no
// need for an ancestor clipping layer.
ASSERT_TRUE(mapping2->scrollingLayer());
// The third <div> should have a clipping layer since it's composited and
// clips composited children.
ASSERT_TRUE(mapping3->clippingLayer());
// All scrolling and clipping layers should have masksToBounds set on them.
{
EXPECT_TRUE(mapping->scrollingLayer()->platformLayer()->masksToBounds());
EXPECT_TRUE(
mapping->ancestorClippingLayer()->platformLayer()->masksToBounds());
EXPECT_TRUE(mapping2->scrollingLayer()->platformLayer()->masksToBounds());
EXPECT_TRUE(mapping3->clippingLayer()->platformLayer()->masksToBounds());
}
// Set the inner scroller in the first container as the root scroller. Its
// clipping layer should be removed and the scrolling layer should not
// mask.
{
document().setRootScroller(innerScroller, nonThrow);
document().view()->updateAllLifecyclePhases();
ASSERT_EQ(innerScroller, rootScrollerController.globalRootScroller());
EXPECT_FALSE(mapping->ancestorClippingLayer());
EXPECT_FALSE(mapping->scrollingLayer()->platformLayer()->masksToBounds());
}
// Set the inner scroller in the second container as the root scroller. Its
// scrolling layer should no longer mask. The clipping and scrolling layers
// on the first container should now reset back.
{
document().setRootScroller(innerScroller2, nonThrow);
document().view()->updateAllLifecyclePhases();
ASSERT_EQ(innerScroller2, rootScrollerController.globalRootScroller());
EXPECT_TRUE(mapping->ancestorClippingLayer());
EXPECT_TRUE(
mapping->ancestorClippingLayer()->platformLayer()->masksToBounds());
EXPECT_TRUE(mapping->scrollingLayer()->platformLayer()->masksToBounds());
EXPECT_FALSE(mapping2->scrollingLayer()->platformLayer()->masksToBounds());
}
// Set the inner scroller in the third container as the root scroller. Its
// clipping layer should be removed.
{
document().setRootScroller(innerScroller3, nonThrow);
document().view()->updateAllLifecyclePhases();
ASSERT_EQ(innerScroller3, rootScrollerController.globalRootScroller());
EXPECT_TRUE(mapping2->scrollingLayer()->platformLayer()->masksToBounds());
EXPECT_FALSE(mapping3->clippingLayer());
}
// Unset the root scroller. The clipping layer on the third container should
// be restored.
{
document().setRootScroller(nullptr, nonThrow);
document().view()->updateAllLifecyclePhases();
ASSERT_EQ(document().documentElement(),
rootScrollerController.globalRootScroller());
EXPECT_TRUE(mapping3->clippingLayer());
EXPECT_TRUE(mapping3->clippingLayer()->platformLayer()->masksToBounds());
}
}
TEST_P(CompositedLayerMappingTest,
ScrollingLayerWithPerspectivePositionedCorrectly) {
// Test positioning of a scrolling layer within an offset parent, both with
// and without perspective.
//
// When a box shadow is used, the main graphics layer position is offset by
// the shadow. The scrolling contents then need to be offset in the other
// direction to compensate. To make this a little clearer, for the first
// example here the layer positions are calculated as:
//
// m_graphicsLayer x = left_pos - shadow_spread + shadow_x_offset
// = 50 - 10 - 10
// = 30
//
// m_graphicsLayer y = top_pos - shadow_spread + shadow_y_offset
// = 50 - 10 + 0
// = 40
//
// contents x = 50 - m_graphicsLayer x = 50 - 30 = 20
// contents y = 50 - m_graphicsLayer y = 50 - 40 = 10
//
// The reason that perspective matters is that it affects which 'contents'
// layer is offset; m_childTransformLayer when using perspective, or
// m_scrollingLayer when there is no perspective.
setBodyInnerHTML(
"<div id='scroller' style='position: absolute; top: 50px; left: 50px; "
"width: 400px; height: 245px; overflow: auto; will-change: transform; "
"box-shadow: -10px 0 0 10px; perspective: 1px;'>"
" <div style='position: absolute; top: 50px; bottom: 0; width: 200px; "
"height: 200px;'></div>"
"</div>"
"<div id='scroller2' style='position: absolute; top: 400px; left: 50px; "
"width: 400px; height: 245px; overflow: auto; will-change: transform; "
"box-shadow: -10px 0 0 10px;'>"
" <div style='position: absolute; top: 50px; bottom: 0; width: 200px; "
"height: 200px;'></div>"
"</div>");
CompositedLayerMapping* mapping =
toLayoutBlock(getLayoutObjectByElementId("scroller"))
->layer()
->compositedLayerMapping();
CompositedLayerMapping* mapping2 =
toLayoutBlock(getLayoutObjectByElementId("scroller2"))
->layer()
->compositedLayerMapping();
ASSERT_TRUE(mapping);
ASSERT_TRUE(mapping2);
// The perspective scroller should have a child transform containing the
// positional offset, and a scrolling layer that has no offset.
GraphicsLayer* scrollingLayer = mapping->scrollingLayer();
GraphicsLayer* childTransformLayer = mapping->childTransformLayer();
GraphicsLayer* mainGraphicsLayer = mapping->mainGraphicsLayer();
ASSERT_TRUE(scrollingLayer);
ASSERT_TRUE(childTransformLayer);
EXPECT_FLOAT_EQ(30, mainGraphicsLayer->position().x());
EXPECT_FLOAT_EQ(40, mainGraphicsLayer->position().y());
EXPECT_FLOAT_EQ(0, scrollingLayer->position().x());
EXPECT_FLOAT_EQ(0, scrollingLayer->position().y());
EXPECT_FLOAT_EQ(20, childTransformLayer->position().x());
EXPECT_FLOAT_EQ(10, childTransformLayer->position().y());
// The non-perspective scroller should have no child transform and the
// offset on the scroller layer directly.
GraphicsLayer* scrollingLayer2 = mapping2->scrollingLayer();
GraphicsLayer* mainGraphicsLayer2 = mapping2->mainGraphicsLayer();
ASSERT_TRUE(scrollingLayer2);
ASSERT_FALSE(mapping2->childTransformLayer());
EXPECT_FLOAT_EQ(30, mainGraphicsLayer2->position().x());
EXPECT_FLOAT_EQ(390, mainGraphicsLayer2->position().y());
EXPECT_FLOAT_EQ(20, scrollingLayer2->position().x());
EXPECT_FLOAT_EQ(10, scrollingLayer2->position().y());
}
TEST_P(CompositedLayerMappingTest, AncestorClippingMaskLayerUpdates) {
setBodyInnerHTML(
"<style>"
"#ancestor { width: 100px; height: 100px; overflow: hidden; }"
"#child { width: 120px; height: 120px; background-color: green; }"
"</style>"
"<div id='ancestor'><div id='child'></div></div>");
document().view()->updateAllLifecyclePhases();
Element* ancestor = document().getElementById("ancestor");
ASSERT_TRUE(ancestor);
PaintLayer* ancestorPaintLayer =
toLayoutBoxModelObject(ancestor->layoutObject())->layer();
ASSERT_TRUE(ancestorPaintLayer);
CompositedLayerMapping* ancestorMapping =
ancestorPaintLayer->compositedLayerMapping();
ASSERT_FALSE(ancestorMapping);
Element* child = document().getElementById("child");
ASSERT_TRUE(child);
PaintLayer* childPaintLayer =
toLayoutBoxModelObject(child->layoutObject())->layer();
ASSERT_FALSE(childPaintLayer);
// Making the child conposited causes creation of an AncestorClippingLayer.
child->setAttribute(HTMLNames::styleAttr, "will-change: transform");
document().view()->updateAllLifecyclePhases();
childPaintLayer = toLayoutBoxModelObject(child->layoutObject())->layer();
ASSERT_TRUE(childPaintLayer);
CompositedLayerMapping* childMapping =
childPaintLayer->compositedLayerMapping();
ASSERT_TRUE(childMapping);
EXPECT_TRUE(childMapping->ancestorClippingLayer());
EXPECT_FALSE(childMapping->ancestorClippingLayer()->maskLayer());
EXPECT_FALSE(childMapping->ancestorClippingMaskLayer());
// Adding border radius to the ancestor requires an
// ancestorClippingMaskLayer for the child
ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
document().view()->updateAllLifecyclePhases();
childPaintLayer = toLayoutBoxModelObject(child->layoutObject())->layer();
ASSERT_TRUE(childPaintLayer);
childMapping = childPaintLayer->compositedLayerMapping();
ASSERT_TRUE(childMapping);
EXPECT_TRUE(childMapping->ancestorClippingLayer());
EXPECT_TRUE(childMapping->ancestorClippingLayer()->maskLayer());
EXPECT_TRUE(childMapping->ancestorClippingMaskLayer());
// Removing the border radius should remove the ancestorClippingMaskLayer
// for the child
ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 0px;");
document().view()->updateAllLifecyclePhases();
childPaintLayer = toLayoutBoxModelObject(child->layoutObject())->layer();
ASSERT_TRUE(childPaintLayer);
childMapping = childPaintLayer->compositedLayerMapping();
ASSERT_TRUE(childMapping);
EXPECT_TRUE(childMapping->ancestorClippingLayer());
EXPECT_FALSE(childMapping->ancestorClippingLayer()->maskLayer());
EXPECT_FALSE(childMapping->ancestorClippingMaskLayer());
// Add border radius back so we can test one more case
ancestor->setAttribute(HTMLNames::styleAttr, "border-radius: 40px;");
document().view()->updateAllLifecyclePhases();
// Now change the overflow to remove the need for an ancestor clip
// on the child
ancestor->setAttribute(HTMLNames::styleAttr, "overflow: visible");
document().view()->updateAllLifecyclePhases();
childPaintLayer = toLayoutBoxModelObject(child->layoutObject())->layer();
ASSERT_TRUE(childPaintLayer);
childMapping = childPaintLayer->compositedLayerMapping();
ASSERT_TRUE(childMapping);
EXPECT_FALSE(childMapping->ancestorClippingLayer());
EXPECT_FALSE(childMapping->ancestorClippingMaskLayer());
}
TEST_P(CompositedLayerMappingTest, StickyPositionContentOffset) {
setBodyInnerHTML(
"<div style='width: 400px; height: 400px; overflow: auto; "
"will-change: transform;' >"
" <div id='sticky1' style='position: sticky; top: 0px; width: 100px; "
"height: 100px; box-shadow: -5px -5px 5px 0 black; "
"will-change: transform;'></div>"
" <div style='height: 2000px;'></div>"
"</div>"
"<div style='width: 400px; height: 400px; overflow: auto; "
"will-change: transform;' >"
" <div id='sticky2' style='position: sticky; top: 0px; width: 100px; "
"height: 100px; will-change: transform;'>"
" <div style='position: absolute; top: -50px; left: -50px; "
"width: 5px; height: 5px; background: red;'></div></div>"
" <div style='height: 2000px;'></div>"
"</div>");
document().view()->updateLifecycleToCompositingCleanPlusScrolling();
CompositedLayerMapping* sticky1 =
toLayoutBlock(getLayoutObjectByElementId("sticky1"))
->layer()
->compositedLayerMapping();
CompositedLayerMapping* sticky2 =
toLayoutBlock(getLayoutObjectByElementId("sticky2"))
->layer()
->compositedLayerMapping();
// Box offsets the content by the combination of the shadow offset and blur
// radius plus an additional pixel of anti-aliasing.
ASSERT_TRUE(sticky1);
WebLayerStickyPositionConstraint constraint1 =
sticky1->mainGraphicsLayer()
->contentLayer()
->layer()
->stickyPositionConstraint();
EXPECT_EQ(IntPoint(-11, -11),
IntPoint(constraint1.parentRelativeStickyBoxOffset));
// Since the nested div will be squashed into the same composited layer the
// sticky element is offset by the nested element's offset.
ASSERT_TRUE(sticky2);
WebLayerStickyPositionConstraint constraint2 =
sticky2->mainGraphicsLayer()
->contentLayer()
->layer()
->stickyPositionConstraint();
EXPECT_EQ(IntPoint(-50, -50),
IntPoint(constraint2.parentRelativeStickyBoxOffset));
}
} // namespace blink
| 42.596316 | 80 | 0.688143 | [
"transform",
"solid"
] |
c01dd7dd5345c228daa4fb1a28450c1ada50bbfb | 5,177 | cpp | C++ | CSE 232/assignment3/assignment3/assignment3.cpp | Gocnak/ou-schoolwork | 0fe3441b664d304d2de7d2fd8e9e5ff9758da13a | [
"MIT"
] | null | null | null | CSE 232/assignment3/assignment3/assignment3.cpp | Gocnak/ou-schoolwork | 0fe3441b664d304d2de7d2fd8e9e5ff9758da13a | [
"MIT"
] | null | null | null | CSE 232/assignment3/assignment3/assignment3.cpp | Gocnak/ou-schoolwork | 0fe3441b664d304d2de7d2fd8e9e5ff9758da13a | [
"MIT"
] | null | null | null | // assignment2.cpp : Defines the entry point for the console application.
//
#include <vector>
#include <algorithm>
#include <iostream>
#include <random>
#include <map>
#include <chrono>
#include <unordered_map>
using namespace std;
using namespace chrono;
#define VECTOR_SIZE 1000 // The size of the numbers of vectors
#define RANDOM_RANGE 300 // 1 to this number is the range of numbers that can be generated
void sortMethod(vector<int> *v, int &_min, int &_max, int &_mode)
{
// Sort the array using at most [O(n lg n)] time complexity
sort(v->begin(), v->end());
// Ay, if it's sorted, these values should be fairly simple to find [O(1)]
int min = v->front();
int max = v->back();
// Now we do some simple scanning for our mode [O(VECTOR_SIZE)] ~= [O(n)]
int mode = min, highest_mode = min;
int count = 1, highest_count = 0;
// Since our list is in order, we can scan along the numbers and count how often the number appears
// Upon changing numbers, we refresh the count, comparing against the highest stored count to see if there is
// an element that appears more in the list than the previous mode.
for (auto i : *v)
{
if (i == mode)
{
count++;
// Note: If this is changed to >=, we will consider the mode of highest value.
// Ex: If a list contains 1, 1, 1, 2, 2, 2 and is executed on the following code,
// the highest mode will be 1, unless the following code is changed to >=.
if (count > highest_count)
{
highest_count = count;
highest_mode = mode;
}
}
else
{
count = 1;
mode = i;
}
}
// Return our values
_min = min;
_max = max;
_mode = highest_mode;
}
void hashMapMethod(vector<int> *v, int &_min, int &_max, int &_mode)
{
// The idea for the (hash)map method is to store counts of each number as the value.
// Each time the same number is found (collision), we update the count of that number, while
// simulataneously keeping track of the highest number/count keyvalue pair, minimum number, and maximum number.
// It should be noted that if implemented correctly, a runtime of O(N) + C should be achieved, where C is some arbitrary
// constant value (due to allocation, comparisons, etc; this is a very small number in relation to N).
unordered_map<int, int> hashmap = unordered_map<int, int>();
int min_num = INT_MAX, max_num = INT_MIN;
int max_count = 0, mode = min_num;
for (auto i : *v)
{
// Is this number the smallest?
min_num = min<int>(min_num, i);
// Is this number the largest?
max_num = max<int>(max_num, i);
// How many times does this number exist in the map?
int count;
// Does this number even exist in the hashmap?
auto it = hashmap.find(i);
if (it != hashmap.end()) // Exists in the hashmap
{
count = hashmap[i]; // Set our count to the current in the map
count++; // Increase our count (this number adds one)
}
else // doesn't exist
{
count = 1; // This is our first instance of this number
}
hashmap[i] = count; // Update our count
// But wait a minute, is this higher than our max count?
if (count > max_count)
{
// So it seems. Let's update the mode to this number, along with the max_count.
mode = i;
max_count = count;
}
}
// At this point we really don't care for the hashmap. So I suppose we could clear it to cleanup resources.
hashmap.clear();
// Return our values
_min = min_num;
_max = max_num;
_mode = mode;
}
int main()
{
// Initialize our random number generator
srand(time(nullptr));
// Initialize our vector
vector<int> v;
// Add numbers to our vector
for (int i = 0; i < VECTOR_SIZE; i++)
{
// Add the random number
v.push_back(rand() % RANDOM_RANGE + 1);
}
// Initialize our min, max, and mode variables.
int min, max, mode;
// Begin timing our sorting method
auto start_sort = high_resolution_clock::now();
// Run our sorting method
sortMethod(&v, min, max, mode);
// Calculate the time elapsed (in seconds)
duration<double> time_span = duration_cast<duration<double>>(high_resolution_clock::now() - start_sort);
cout << "(Min, Max, Mode): (" << min << ", " << max << ", " << mode << ")" << endl;
cout << "Found in: " << time_span.count() << " seconds." << endl;
// Begin timing our hashmap method
auto start_hash = high_resolution_clock::now();
// Run our hashmap method
hashMapMethod(&v, min, max, mode);
// Calculate the time elapsed (in seconds)
time_span = duration_cast<duration<double>>(high_resolution_clock::now() - start_hash);
cout << "(Min, Max, Mode): (" << min << ", " << max << ", " << mode << ")" << endl;
cout << "Found in: " << time_span.count() << " seconds." << endl;
return 0;
} | 32.974522 | 124 | 0.598802 | [
"vector"
] |
c021958e0cc90e995d24cbda10c5fdb2dd26fbfc | 766 | hpp | C++ | include/dave/core/engine.hpp | daveengine/dave | c9162003dd18ca6e5f30f58bb40f1d35229f0c95 | [
"MIT"
] | 2 | 2018-01-19T08:15:17.000Z | 2018-06-19T04:55:15.000Z | include/dave/core/engine.hpp | daveengine/dave | c9162003dd18ca6e5f30f58bb40f1d35229f0c95 | [
"MIT"
] | 1 | 2017-04-05T00:43:09.000Z | 2017-04-05T07:16:48.000Z | include/dave/core/engine.hpp | PterabyteGames/dave | c9162003dd18ca6e5f30f58bb40f1d35229f0c95 | [
"MIT"
] | null | null | null | #pragma once
#include "dave/core/platform.hpp"
#include "dave/core/system.hpp"
#include "dave/core/task_scheduler.hpp"
#include <memory>
#include <vector>
namespace dave::core
{
class system;
class engine
{
public:
DAVEAPI engine();
DAVEAPI ~engine();
DAVEAPI void run();
DAVEAPI void stop();
DAVEAPI void add_system(std::shared_ptr<system> s, bool repeating, bool background);
DAVEAPI void initialise_systems();
struct stop_event
{
};
void operator()(stop_event const& event);
template <typename Function>
DAVEAPI void add_job(Function&& function, bool repeating, bool background)
{
scheduler.add_task(std::move(function), repeating, background);
}
private:
task_scheduler scheduler;
std::vector<std::shared_ptr<system>> systems;
};
}
| 17.022222 | 85 | 0.736292 | [
"vector"
] |
c021c9313a59949d749a7604ccef3b57401ff1d3 | 14,180 | cpp | C++ | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AssetRegistry/Private/PackageReader.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2016-10-01T21:35:52.000Z | 2016-10-01T21:35:52.000Z | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AssetRegistry/Private/PackageReader.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | null | null | null | UnrealEngine-4.11.2-release/Engine/Source/Runtime/AssetRegistry/Private/PackageReader.cpp | armroyce/Unreal | ea1cdebe70407d59af4e8366d7111c52ce4606df | [
"MIT"
] | 1 | 2021-04-27T08:48:33.000Z | 2021-04-27T08:48:33.000Z | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "AssetRegistryPCH.h"
FPackageReader::FPackageReader()
{
Loader = NULL;
ArIsLoading = true;
ArIsPersistent = true;
}
FPackageReader::~FPackageReader()
{
if (Loader)
{
delete Loader;
}
}
bool FPackageReader::OpenPackageFile(const FString& InPackageFilename)
{
PackageFilename = InPackageFilename;
Loader = IFileManager::Get().CreateFileReader( *PackageFilename );
if( Loader == NULL )
{
// Couldn't open the file
return false;
}
// Read package file summary from the file
*this << PackageFileSummary;
// Validate the summary.
// Make sure this is indeed a package
if( PackageFileSummary.Tag != PACKAGE_FILE_TAG )
{
// Unrecognized or malformed package file
return false;
}
// Don't read packages that are too old
if( PackageFileSummary.GetFileVersionUE4() < VER_UE4_OLDEST_LOADABLE_PACKAGE )
{
return false;
}
// Don't read packages that were saved with an package version newer than the current one.
if( (PackageFileSummary.GetFileVersionUE4() > GPackageFileUE4Version) || (PackageFileSummary.GetFileVersionLicenseeUE4() > GPackageFileLicenseeUE4Version) )
{
return false;
}
// Check serialized custom versions against latest custom versions.
const FCustomVersionContainer& LatestCustomVersions = FCustomVersionContainer::GetRegistered();
const FCustomVersionSet& PackageCustomVersions = PackageFileSummary.GetCustomVersionContainer().GetAllVersions();
for (const FCustomVersion& SerializedCustomVersion : PackageCustomVersions)
{
auto* LatestVersion = LatestCustomVersions.GetVersion(SerializedCustomVersion.Key);
if (!LatestVersion || SerializedCustomVersion.Version > LatestVersion->Version)
{
return false;
}
}
// check if this is a compressed package and decompress header
if ( !!(PackageFileSummary.PackageFlags & PKG_StoreCompressed) )
{
check(PackageFileSummary.CompressedChunks.Num() > 0);
int64 CurPos = Loader->Tell();
if ( !Loader->SetCompressionMap(&PackageFileSummary.CompressedChunks, (ECompressionFlags)PackageFileSummary.CompressionFlags) )
{
delete Loader;
Loader = new FArchiveAsync(*PackageFilename);
check(!Loader->IsError());
verify(Loader->SetCompressionMap(&PackageFileSummary.CompressedChunks, (ECompressionFlags)PackageFileSummary.CompressionFlags));
}
Seek(Loader->Tell());
}
//make sure the filereader gets the correct version number (it defaults to latest version)
SetUE4Ver(PackageFileSummary.GetFileVersionUE4());
SetLicenseeUE4Ver(PackageFileSummary.GetFileVersionLicenseeUE4());
SetEngineVer(PackageFileSummary.SavedByEngineVersion);
Loader->SetUE4Ver(PackageFileSummary.GetFileVersionUE4());
Loader->SetLicenseeUE4Ver(PackageFileSummary.GetFileVersionLicenseeUE4());
Loader->SetEngineVer(PackageFileSummary.SavedByEngineVersion);
const FCustomVersionContainer& PackageFileSummaryVersions = PackageFileSummary.GetCustomVersionContainer();
SetCustomVersions(PackageFileSummaryVersions);
Loader->SetCustomVersions(PackageFileSummaryVersions);
return true;
}
bool FPackageReader::ReadAssetRegistryData (TArray<FAssetData*>& AssetDataList)
{
check(Loader);
// Does the package contain asset registry tags
if( PackageFileSummary.AssetRegistryDataOffset == 0 )
{
// No Tag Table!
return false;
}
// Seek the the part of the file where the asset registry tags live
Seek( PackageFileSummary.AssetRegistryDataOffset );
// Determine the package name and path
FString PackageName = FPackageName::FilenameToLongPackageName(PackageFilename);
FString PackagePath = FPackageName::GetLongPackagePath(PackageName);
const bool bIsMapPackage = (PackageFileSummary.PackageFlags & PKG_ContainsMap) != 0;
// Assets do not show up in map packages unless we launch with -WorldAssets
static const bool bUsingWorldAssets = FAssetRegistry::IsUsingWorldAssets();
if ( bIsMapPackage && !bUsingWorldAssets )
{
return true;
}
// Load the object count
int32 ObjectCount = 0;
*this << ObjectCount;
// Worlds that were saved before they were marked public do not have asset data so we will synthesize it here to make sure we see all legacy umaps
// We will also do this for maps saved after they were marked public but no asset data was saved for some reason. A bug caused this to happen for some maps.
if (bUsingWorldAssets && bIsMapPackage)
{
const bool bLegacyPackage = PackageFileSummary.GetFileVersionUE4() < VER_UE4_PUBLIC_WORLDS;
const bool bNoMapAsset = (ObjectCount == 0);
if (bLegacyPackage || bNoMapAsset)
{
FString AssetName = FPackageName::GetLongPackageAssetName(PackageName);
AssetDataList.Add(new FAssetData(FName(*PackageName), FName(*PackagePath), FName(), MoveTemp(FName(*AssetName)), FName(TEXT("World")), TMap<FName, FString>(), PackageFileSummary.ChunkIDs, PackageFileSummary.PackageFlags));
}
}
// UAsset files only have one object, but legacy or map packages may have more.
for(int32 ObjectIdx = 0; ObjectIdx < ObjectCount; ++ObjectIdx)
{
FString ObjectPath;
FString ObjectClassName;
int32 TagCount = 0;
*this << ObjectPath;
*this << ObjectClassName;
*this << TagCount;
TMap<FName, FString> TagsAndValues;
TagsAndValues.Reserve(TagCount);
for(int32 TagIdx = 0; TagIdx < TagCount; ++TagIdx)
{
FString Key;
FString Value;
*this << Key;
*this << Value;
TagsAndValues.Add(FName(*Key), Value);
}
FString GroupNames;
FString AssetName;
if ( ObjectPath.Contains(TEXT("."), ESearchCase::CaseSensitive))
{
ObjectPath.Split(TEXT("."), &GroupNames, &AssetName, ESearchCase::CaseSensitive, ESearchDir::FromEnd);
}
else
{
AssetName = ObjectPath;
}
// Before world were RF_Public, other non-public assets were added to the asset data table in map packages.
// Here we simply skip over them
if ( bIsMapPackage && PackageFileSummary.GetFileVersionUE4() < VER_UE4_PUBLIC_WORLDS )
{
if ( AssetName != FPackageName::GetLongPackageAssetName(PackageName) )
{
continue;
}
}
// Create a new FAssetData for this asset and update it with the gathered data
AssetDataList.Add(new FAssetData(FName(*PackageName), FName(*PackagePath), MoveTemp(FName(*GroupNames)), MoveTemp(FName(*AssetName)), MoveTemp(FName(*ObjectClassName)), MoveTemp(TagsAndValues), PackageFileSummary.ChunkIDs, PackageFileSummary.PackageFlags));
}
return true;
}
bool FPackageReader::ReadAssetDataFromThumbnailCache(TArray<FAssetData*>& AssetDataList)
{
check(Loader);
// Does the package contain a thumbnail table?
if( PackageFileSummary.ThumbnailTableOffset == 0 )
{
return false;
}
// Seek the the part of the file where the thumbnail table lives
Seek( PackageFileSummary.ThumbnailTableOffset );
// Determine the package name and path
FString PackageName = FPackageName::FilenameToLongPackageName(PackageFilename);
FString PackagePath = FPackageName::GetLongPackagePath(PackageName);
// Load the thumbnail count
int32 ObjectCount = 0;
*this << ObjectCount;
// Iterate over every thumbnail entry and harvest the objects classnames
for(int32 ObjectIdx = 0; ObjectIdx < ObjectCount; ++ObjectIdx)
{
// Serialize the classname
FString AssetClassName;
*this << AssetClassName;
// Serialize the object path.
FString ObjectPathWithoutPackageName;
*this << ObjectPathWithoutPackageName;
// Serialize the rest of the data to get at the next object
int32 FileOffset = 0;
*this << FileOffset;
FString GroupNames;
FString AssetName;
if ( ObjectPathWithoutPackageName.Contains(TEXT("."), ESearchCase::CaseSensitive) )
{
ObjectPathWithoutPackageName.Split(TEXT("."), &GroupNames, &AssetName, ESearchCase::CaseSensitive, ESearchDir::FromEnd);
}
else
{
AssetName = ObjectPathWithoutPackageName;
}
// Create a new FAssetData for this asset and update it with the gathered data
AssetDataList.Add(new FAssetData(FName(*PackageName), FName(*PackagePath), MoveTemp(FName(*GroupNames)), MoveTemp(FName(*AssetName)), MoveTemp(FName(*AssetClassName)), TMap<FName, FString>(), PackageFileSummary.ChunkIDs, PackageFileSummary.PackageFlags));
}
return true;
}
bool FPackageReader::ReadAssetRegistryDataIfCookedPackage(TArray<FAssetData*>& AssetDataList, TArray<FString>& CookedPackageNamesWithoutAssetData)
{
if (!!(GetPackageFlags() & PKG_FilterEditorOnly))
{
const FString PackageName = FPackageName::FilenameToLongPackageName(PackageFilename);
bool bFoundAtLeastOneAsset = false;
// If the packaged is saved with the right version we have the information
// which of the objects in the export map as the asset.
// Otherwise we need to store a temp minimal data and then force load the asset
// to re-generate its registry data
if (UE4Ver() >= VER_UE4_COOKED_ASSETS_IN_EDITOR_SUPPORT)
{
const FString PackagePath = FPackageName::GetLongPackagePath(PackageName);
TArray<FObjectImport> ImportMap;
TArray<FObjectExport> ExportMap;
SerializeNameMap();
SerializeImportMap(ImportMap);
SerializeExportMap(ExportMap);
for (FObjectExport& Export : ExportMap)
{
if (Export.bIsAsset)
{
FString GroupNames; // Not used for anything
TMap<FName, FString> Tags; // Not used for anything
TArray<int32> ChunkIDs; // Not used for anything
// We need to get the class name from the import/export maps
FName ObjectClassName;
if (Export.ClassIndex.IsNull())
{
ObjectClassName = UClass::StaticClass()->GetFName();
}
else if (Export.ClassIndex.IsExport())
{
const FObjectExport& ClassExport = ExportMap[Export.ClassIndex.ToExport()];
ObjectClassName = ClassExport.ObjectName;
}
else if (Export.ClassIndex.IsImport())
{
const FObjectImport& ClassImport = ImportMap[Export.ClassIndex.ToImport()];
ObjectClassName = ClassImport.ObjectName;
}
new(AssetDataList) FAssetData(FName(*PackageName), FName(*PackagePath), FName(*GroupNames), Export.ObjectName, ObjectClassName, Tags, ChunkIDs, GetPackageFlags());
bFoundAtLeastOneAsset = true;
}
}
}
if (!bFoundAtLeastOneAsset)
{
CookedPackageNamesWithoutAssetData.Add(PackageName);
}
return true;
}
return false;
}
bool FPackageReader::ReadDependencyData (FPackageDependencyData& OutDependencyData)
{
OutDependencyData.PackageName = FName(*FPackageName::FilenameToLongPackageName(PackageFilename));
SerializeNameMap();
SerializeImportMap(OutDependencyData.ImportMap);
SerializeStringAssetReferencesMap(OutDependencyData.StringAssetReferencesMap);
return true;
}
void FPackageReader::SerializeNameMap()
{
if( PackageFileSummary.NameCount > 0 )
{
Seek( PackageFileSummary.NameOffset );
for ( int32 NameMapIdx = 0; NameMapIdx < PackageFileSummary.NameCount; ++NameMapIdx )
{
// Read the name entry from the file.
FNameEntry NameEntry(ENAME_LinkerConstructor);
*this << NameEntry;
NameMap.Add(
NameEntry.IsWide() ?
FName(ENAME_LinkerConstructor, NameEntry.GetWideName()) :
FName(ENAME_LinkerConstructor, NameEntry.GetAnsiName())
);
}
}
}
void FPackageReader::SerializeImportMap(TArray<FObjectImport>& OutImportMap)
{
if( PackageFileSummary.ImportCount > 0 )
{
Seek( PackageFileSummary.ImportOffset );
for ( int32 ImportMapIdx = 0; ImportMapIdx < PackageFileSummary.ImportCount; ++ImportMapIdx )
{
FObjectImport* Import = new(OutImportMap)FObjectImport;
*this << *Import;
}
}
}
void FPackageReader::SerializeExportMap(TArray<FObjectExport>& OutExportMap)
{
if (PackageFileSummary.ExportCount > 0)
{
Seek(PackageFileSummary.ExportOffset);
for (int32 ExportMapIdx = 0; ExportMapIdx < PackageFileSummary.ExportCount; ++ExportMapIdx)
{
FObjectExport* Export = new(OutExportMap)FObjectExport;
*this << *Export;
}
}
}
void FPackageReader::SerializeStringAssetReferencesMap(TArray<FString>& OutStringAssetReferencesMap)
{
if (UE4Ver() >= VER_UE4_ADD_STRING_ASSET_REFERENCES_MAP && PackageFileSummary.StringAssetReferencesCount > 0)
{
Seek(PackageFileSummary.StringAssetReferencesOffset);
if (UE4Ver() < VER_UE4_KEEP_ONLY_PACKAGE_NAMES_IN_STRING_ASSET_REFERENCES_MAP)
{
for (int32 ReferenceIdx = 0; ReferenceIdx < PackageFileSummary.StringAssetReferencesCount; ++ReferenceIdx)
{
FString Buf;
*this << Buf;
if (GetIniFilenameFromObjectsReference(Buf) != nullptr)
{
OutStringAssetReferencesMap.AddUnique(MoveTemp(Buf));
}
else
{
FString NormalizedPath = FPackageName::GetNormalizedObjectPath(MoveTemp(Buf));
if (!NormalizedPath.IsEmpty())
{
OutStringAssetReferencesMap.AddUnique(
FPackageName::ObjectPathToPackageName(
NormalizedPath
)
);
}
}
}
}
else
{
for (int32 ReferenceIdx = 0; ReferenceIdx < PackageFileSummary.StringAssetReferencesCount; ++ReferenceIdx)
{
FString Buf;
*this << Buf;
OutStringAssetReferencesMap.Add(MoveTemp(Buf));
}
}
}
}
void FPackageReader::Serialize( void* V, int64 Length )
{
check(Loader);
Loader->Serialize( V, Length );
}
bool FPackageReader::Precache( int64 PrecacheOffset, int64 PrecacheSize )
{
check(Loader);
return Loader->Precache( PrecacheOffset, PrecacheSize );
}
void FPackageReader::Seek( int64 InPos )
{
check(Loader);
Loader->Seek( InPos );
}
int64 FPackageReader::Tell()
{
check(Loader);
return Loader->Tell();
}
int64 FPackageReader::TotalSize()
{
check(Loader);
return Loader->TotalSize();
}
uint32 FPackageReader::GetPackageFlags() const
{
return PackageFileSummary.PackageFlags;
}
FArchive& FPackageReader::operator<<( FName& Name )
{
check(Loader);
NAME_INDEX NameIndex;
FArchive& Ar = *this;
Ar << NameIndex;
if( !NameMap.IsValidIndex(NameIndex) )
{
UE_LOG(LogAssetRegistry, Fatal, TEXT("Bad name index %i/%i"), NameIndex, NameMap.Num() );
}
// if the name wasn't loaded (because it wasn't valid in this context)
if (NameMap[NameIndex] == NAME_None)
{
int32 TempNumber;
Ar << TempNumber;
Name = NAME_None;
}
else
{
int32 Number;
Ar << Number;
// simply create the name from the NameMap's name and the serialized instance number
Name = FName(NameMap[NameIndex], Number);
}
return *this;
}
| 29.541667 | 259 | 0.745205 | [
"object"
] |
c0241b9679e84054bf2d2d52be23c62209d7851e | 24,336 | cpp | C++ | plugin/AL_USDMayaTestPlugin/test_usdmaya.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | plugin/AL_USDMayaTestPlugin/test_usdmaya.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | plugin/AL_USDMayaTestPlugin/test_usdmaya.cpp | AlexSchwank/AL_USDMaya | 99413e2c5d1c93e4c58a63ebc8b07e23cf072e86 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2017 Animal Logic
//
// 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 "test_usdmaya.h"
#include "maya/MFloatMatrix.h"
#include "maya/MFnAttribute.h"
#include "maya/MFnCompoundAttribute.h"
#include "maya/MFnEnumAttribute.h"
#include "maya/MFnMatrixAttribute.h"
#include "maya/MFnMatrixData.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MFnNumericData.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnUnitAttribute.h"
#include "maya/MGlobal.h"
#include "maya/MFileIO.h"
#include "maya/MMatrix.h"
#include "maya/MFnAnimCurve.h"
#include "maya/MFnDagNode.h"
//----------------------------------------------------------------------------------------------------------------------
const char* buildTempPath(const char* const filename)
{
static char temp_file[512];
static size_t length = 0;
if(!length)
{
#ifdef _WIN32
length = GetTempPath(512, temp_file);
if(temp_file[length - 1] != '\\')
{
temp_file[length++] = '\\';
}
#else
const char* const TMPDIRs[4] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
for(int i = 0; !length && i < 4; ++i)
{
const char* const temp = getenv(TMPDIRs[i]);
if(temp)
{
realpath(temp, temp_file);
length = std::strlen(temp_file);
if(temp_file[length - 1] != '/')
{
temp_file[length++] = '/';
}
}
}
if(!length)
{
temp_file[0] = '/';
temp_file[1] = 't';
temp_file[2] = 'm';
temp_file[3] = 'p';
temp_file[4] = '/';
length = 5;
}
#endif
}
std::strcpy(temp_file + length, filename);
return temp_file;
}
//----------------------------------------------------------------------------------------------------------------------
void comparePlugs(const MPlug& plugA, const MPlug& plugB, bool usdTesting)
{
SCOPED_TRACE(MString("plugA: ") + plugA.name() + " - plugB: " + plugB.name());
EXPECT_EQ(plugA.isArray(), plugB.isArray());
EXPECT_EQ(plugA.isElement(), plugB.isElement());
EXPECT_EQ(plugA.isCompound(), plugB.isCompound());
EXPECT_EQ(plugA.isChild(), plugB.isChild());
EXPECT_EQ(plugA.partialName(false, true, true, true, true, true), plugB.partialName(false, true, true, true, true, true));
/// I need to special case the testing of the Time, Angle, and Distance attribute types. These are converted to doubles in USD,
/// so if plugA is one of those types, plugB should be a double.
/// \TODO I would have thought that there would be a way to flag the units used in the USD attributes?
if(usdTesting && (plugA.attribute().apiType() != plugB.attribute().apiType()))
{
if(plugA.attribute().apiType() == MFn::kTimeAttribute ||
plugA.attribute().apiType() == MFn::kDoubleAngleAttribute ||
plugA.attribute().apiType() == MFn::kDoubleLinearAttribute)
{
if(plugA.isArray())
{
EXPECT_EQ(plugA.numElements(), plugB.numElements());
for(uint32_t i = 0; i < plugA.numElements(); ++i)
{
EXPECT_NEAR(plugA.elementByLogicalIndex(i).asDouble(), plugB.elementByLogicalIndex(i).asDouble(), 1e-5f);
}
}
else
{
EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f);
}
}
return;
}
// make sure the unit types match
EXPECT_EQ(plugA.attribute().apiType(), plugB.attribute().apiType());
if(plugB.isArray())
{
// for arrays, just make sure the array sizes match, and then compare each of the element plugs
EXPECT_EQ(plugA.numElements(), plugB.numElements());
for(uint32_t i = 0; i < plugA.numElements(); ++i)
{
comparePlugs(plugA.elementByLogicalIndex(i), plugB.elementByLogicalIndex(i));
}
}
else
if(plugB.isCompound())
{
// for compound attrs, make sure child counts match, and then compare each of the child plugs
EXPECT_EQ(plugA.numChildren(), plugB.numChildren());
for(uint32_t i = 0; i < plugA.numChildren(); ++i)
{
comparePlugs(plugA.child(i), plugB.child(i));
}
}
else
{
switch(plugA.attribute().apiType())
{
case MFn::kTypedAttribute:
{
MFnTypedAttribute fnA(plugA.attribute());
MFnTypedAttribute fnB(plugB.attribute());
EXPECT_EQ(fnA.attrType(), fnB.attrType());
switch(fnA.attrType())
{
case MFnData::kString:
EXPECT_EQ(plugA.asString(), plugB.asString());
break;
default:
std::cout << ("Unknown typed attribute type \"") << plugA.name().asChar() << "\" " << fnA.attrType() << std::endl;
break;
}
}
break;
case MFn::kNumericAttribute:
{
// when we get here, the attributes represent a single value
// make sure the types match, and compare the values to make sure they
// are the same.
MFnNumericAttribute unAttrA(plugA.attribute());
MFnNumericAttribute unAttrB(plugB.attribute());
EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType());
switch(unAttrA.unitType())
{
case MFnNumericData::kBoolean:
EXPECT_EQ(plugA.asBool(), plugB.asBool());
break;
case MFnNumericData::kByte:
EXPECT_EQ(plugA.asChar(), plugB.asChar());
break;
case MFnNumericData::kChar:
EXPECT_EQ(plugA.asChar(), plugB.asChar());
break;
case MFnNumericData::kShort:
EXPECT_EQ(plugA.asShort(), plugB.asShort());
break;
case MFnNumericData::k2Short:
EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort());
EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort());
break;
case MFnNumericData::k3Short:
EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort());
EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort());
EXPECT_EQ(plugA.child(2).asShort(), plugB.child(2).asShort());
break;
case MFnNumericData::kLong:
EXPECT_EQ(plugA.asInt(), plugB.asInt());
break;
case MFnNumericData::kInt64:
EXPECT_EQ(plugA.asInt64(), plugB.asInt64());
break;
case MFnNumericData::k2Long:
EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt());
EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt());
break;
case MFnNumericData::k3Long:
EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt());
EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt());
EXPECT_EQ(plugA.child(2).asInt(), plugB.child(2).asInt());
break;
case MFnNumericData::kFloat:
EXPECT_NEAR(plugA.asFloat(), plugB.asFloat(), 1e-5f);
break;
case MFnNumericData::k2Float:
EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f);
EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f);
break;
case MFnNumericData::k3Float:
EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f);
EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f);
EXPECT_NEAR(plugA.child(2).asFloat(), plugB.child(2).asFloat(), 1e-5f);
break;
case MFnNumericData::kDouble:
EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f);
break;
case MFnNumericData::k2Double:
EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f);
break;
case MFnNumericData::k3Double:
EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f);
break;
case MFnNumericData::k4Double:
EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f);
EXPECT_NEAR(plugA.child(3).asDouble(), plugB.child(3).asDouble(), 1e-5f);
break;
default:
std::cout << ("Unknown numeric attribute type \"") << plugA.name().asChar() << "\" " << std::endl;
break;
}
}
break;
case MFn::kUnitAttribute:
{
MFnUnitAttribute unAttrA(plugA.attribute());
MFnUnitAttribute unAttrB(plugB.attribute());
EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType());
switch(unAttrA.unitType())
{
case MFnUnitAttribute::kAngle:
EXPECT_NEAR(plugA.asMAngle().as(MAngle::kRadians), plugB.asMAngle().as(MAngle::kRadians), 1e-5f);
break;
case MFnUnitAttribute::kDistance:
EXPECT_NEAR(plugA.asMDistance().as(MDistance::kFeet), plugB.asMDistance().as(MDistance::kFeet), 1e-5f);
break;
case MFnUnitAttribute::kTime:
EXPECT_NEAR(plugA.asMTime().as(MTime::kSeconds), plugB.asMTime().as(MTime::kSeconds), 1e-5f);
break;
default:
std::cout << ("Unknown unit attribute type \"") << plugA.name().asChar() << "\" " << std::endl;
break;
}
}
break;
case MFn::kGenericAttribute:
case MFn::kMessageAttribute:
{
}
break;
case MFn::kMatrixAttribute:
case MFn::kFloatMatrixAttribute:
{
MFnMatrixData fnA(plugA.asMObject());
MFnMatrixData fnB(plugB.asMObject());
MMatrix vA = fnA.matrix();
MMatrix vB = fnB.matrix();
for(int i = 0; i < 4; ++i)
{
for(int j = 0; j < 4; ++j)
{
EXPECT_NEAR(vA[i][j], vB[i][j], 1e-5f);
}
}
}
break;
case MFn::kEnumAttribute:
EXPECT_EQ(plugA.asShort(), plugB.asShort());
break;
case MFn::kTimeAttribute:
EXPECT_NEAR(plugA.asMTime().as(MTime::kSeconds), plugB.asMTime().as(MTime::kSeconds), 1e-5f);
break;
case MFn::kFloatAngleAttribute:
case MFn::kDoubleAngleAttribute:
EXPECT_NEAR(plugA.asMAngle().as(MAngle::kRadians), plugB.asMAngle().as(MAngle::kRadians), 1e-5f);
break;
case MFn::kFloatLinearAttribute:
case MFn::kDoubleLinearAttribute:
EXPECT_NEAR(plugA.asMDistance().as(MDistance::kFeet), plugB.asMDistance().as(MDistance::kFeet), 1e-5f);
break;
default:
std::cout << ("Unknown attribute type \"") << plugA.name().asChar() << "\" " << plugA.attribute().apiTypeStr() << std::endl;
break;
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void compareNodes(const MObject& nodeA, const MObject& nodeB, bool includeDefaultAttrs, bool includeDynamicAttrs, bool usdTesting)
{
MFnDependencyNode fnA(nodeA);
MFnDependencyNode fnB(nodeB);
for(uint32_t i = 0; i < fnA.attributeCount(); ++i)
{
MPlug plugA(nodeA, fnA.attribute(i)), plugB;
// we only want to process high level attributes, e.g. translate, and not it's kids translateX, translateY, translateZ
if(plugA.isChild())
{
continue;
}
if(plugA.isDynamic())
{
if(!includeDynamicAttrs)
continue;
}
else
{
if(!includeDefaultAttrs)
continue;
}
// can we find the attribute on the second node?
MStatus status;
plugB = fnB.findPlug(plugA.partialName(false, true, true, true, true, true), true, &status);
EXPECT_EQ(MStatus(MS::kSuccess), status);
// compare the plug values to be ensure they match
comparePlugs(plugA, plugB, usdTesting);
}
}
//----------------------------------------------------------------------------------------------------------------------
void compareNodes(const MObject& nodeA, const MObject& nodeB, const char* const attributes[], uint32_t attributeCount, bool usdTesting)
{
MFnDependencyNode fnA(nodeA);
MFnDependencyNode fnB(nodeB);
for(uint32_t i = 0; i < attributeCount; ++i)
{
MPlug plugA = fnA.findPlug(attributes[i]);
MPlug plugB = fnB.findPlug(attributes[i]);
// compare the plug values to be ensure they match
comparePlugs(plugA, plugB, usdTesting);
}
}
//----------------------------------------------------------------------------------------------------------------------
void randomPlug(MPlug plug)
{
// make sure the unit types match
if(plug.isArray())
{
if(plug.attribute().apiType() == MFn::kMatrixAttribute ||
plug.attribute().apiType() == MFn::kFloatMatrixAttribute)
{
for(int i = 0; i < 511; ++i)
{
char tempStr[2048];
sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf;",
plug.name().asChar(),
i,
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble(),
randDouble());
MGlobal::executeCommand(tempStr);
}
}
else
{
// for arrays, just make sure the array sizes match, and then compare each of the element plugs
plug.setNumElements(511);
for(uint32_t i = 0; i < plug.numElements(); ++i)
{
randomPlug(plug.elementByLogicalIndex(i));
}
}
}
else
if(plug.isCompound())
{
// for compound attrs, make sure child counts match, and then compare each of the child plugs
for(uint32_t i = 0; i < plug.numChildren(); ++i)
{
randomPlug(plug.child(i));
}
}
else
{
switch(plug.attribute().apiType())
{
case MFn::kTypedAttribute:
{
MFnTypedAttribute fn(plug.attribute());
switch(fn.attrType())
{
case MFnData::kString:
randomString(plug);
break;
default:
std::cout << ("Unknown typed attribute type") << std::endl;
break;
}
}
break;
case MFn::kNumericAttribute:
{
// when we get here, the attributes represent a single value
// make sure the types match, and compare the values to make sure they
// are the same.
MFnNumericAttribute unAttr(plug.attribute());
switch(unAttr.unitType())
{
case MFnNumericData::kBoolean:
randomBool(plug);
break;
case MFnNumericData::kByte:
randomInt8(plug);
break;
case MFnNumericData::kChar:
randomInt8(plug);
break;
case MFnNumericData::kShort:
randomInt16(plug);
break;
case MFnNumericData::k2Short:
randomInt16(plug.child(0));
randomInt16(plug.child(1));
break;
case MFnNumericData::k3Short:
randomInt16(plug.child(0));
randomInt16(plug.child(1));
randomInt16(plug.child(2));
break;
case MFnNumericData::kLong:
randomInt32(plug);
break;
case MFnNumericData::kInt64:
randomInt64(plug);
break;
case MFnNumericData::k2Long:
randomInt32(plug.child(0));
randomInt32(plug.child(1));
break;
case MFnNumericData::k3Long:
randomInt32(plug.child(0));
randomInt32(plug.child(1));
randomInt32(plug.child(2));
break;
case MFnNumericData::kFloat:
randomFloat(plug);
break;
case MFnNumericData::k2Float:
randomFloat(plug.child(0));
randomFloat(plug.child(1));
break;
case MFnNumericData::k3Float:
randomFloat(plug.child(0));
randomFloat(plug.child(1));
randomFloat(plug.child(2));
break;
case MFnNumericData::kDouble:
randomDouble(plug);
break;
case MFnNumericData::k2Double:
randomDouble(plug.child(0));
randomDouble(plug.child(1));
break;
case MFnNumericData::k3Double:
randomDouble(plug.child(0));
randomDouble(plug.child(1));
randomDouble(plug.child(2));
break;
case MFnNumericData::k4Double:
randomDouble(plug.child(0));
randomDouble(plug.child(1));
randomDouble(plug.child(2));
randomDouble(plug.child(3));
break;
default:
std::cout << ("Unknown numeric attribute type") << std::endl;
break;
}
}
break;
case MFn::kUnitAttribute:
{
MFnUnitAttribute unAttr(plug.attribute());
switch(unAttr.unitType())
{
case MFnUnitAttribute::kAngle:
randomAngle(plug);
break;
case MFnUnitAttribute::kDistance:
randomDistance(plug);
break;
case MFnUnitAttribute::kTime:
randomTime(plug);
break;
default:
std::cout << ("Unknown unit attribute type") << std::endl;
break;
}
}
break;
case MFn::kMatrixAttribute:
case MFn::kFloatMatrixAttribute:
{
}
break;
case MFn::kMessageAttribute:
{
}
break;
case MFn::kEnumAttribute:
{
MFnEnumAttribute unAttr(plug.attribute());
short minVal; unAttr.getMin(minVal);
short maxVal; unAttr.getMax(maxVal);
short random = 0;
MStatus status = MS::kFailure;
while(!status)
{
random = (rand() % (maxVal - minVal + 1)) + minVal;
unAttr.fieldName(random, &status);
}
EXPECT_EQ(MStatus(MS::kSuccess), plug.setShort(random));
}
break;
case MFn::kGenericAttribute:
{
}
break;
case MFn::kTimeAttribute:
randomTime(plug);
break;
case MFn::kFloatAngleAttribute:
case MFn::kDoubleAngleAttribute:
randomAngle(plug);
break;
case MFn::kFloatLinearAttribute:
case MFn::kDoubleLinearAttribute:
randomDistance(plug);
break;
default:
std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " << plug.attribute().apiTypeStr() << std::endl;
break;
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void randomNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount)
{
MFnDependencyNode fn(node);
for(uint32_t i = 0; i < attributeCount; ++i)
{
MStatus status;
MPlug plug = fn.findPlug(attributeNames[i], &status);
EXPECT_EQ(MStatus(MS::kSuccess), status);
randomPlug(plug);
}
}
//----------------------------------------------------------------------------------------------------------------------
void randomAnimatedValue(MPlug plug, double startFrame, double endFrame)
{
MStatus status;
// Create animation curve and set keys for current attribute in time range
MFnAnimCurve fnCurve;
fnCurve.create(plug, NULL, &status);
EXPECT_EQ(MStatus(MS::kSuccess), status);
for(double t = startFrame, e = endFrame + 1e-3f; t < e; t += 1.0)
{
MTime tm(t, MTime::kFilm);
switch (fnCurve.animCurveType())
{
case MFnAnimCurve::kAnimCurveTL:
case MFnAnimCurve::kAnimCurveTA:
case MFnAnimCurve::kAnimCurveTU:
{
double value = randDouble();
fnCurve.addKey(tm, value, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status);
EXPECT_EQ(MStatus(MS::kSuccess), status);
break;
}
default:
{
std::cout << "[DgNodeTranslator::setAngleAnim] Unexpected anim curve type: " << fnCurve.animCurveType() << std::endl;
break;
}
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void randomAnimatedNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount, double startFrame, double endFrame)
{
MStatus status;
MFnDependencyNode fn(node);
for(uint32_t i = 0; i < attributeCount; ++i)
{
MPlug plug = fn.findPlug(attributeNames[i], &status);
EXPECT_EQ(MStatus(MS::kSuccess), status);
// If value is not keyable, set it to be a random value
if (!plug.isKeyable())
{
randomPlug(plug);
continue;
}
switch(plug.attribute().apiType())
{
case MFn::kNumericAttribute:
{
MFnNumericAttribute unAttr(plug.attribute());
switch(unAttr.unitType())
{
case MFnNumericData::kDouble:
case MFnNumericData::kBoolean:
{
randomAnimatedValue(plug, startFrame, endFrame);
break;
}
default:
{
std::cout << ("Unknown numeric attribute type") << std::endl;
break;
}
}
break;
}
case MFn::kFloatLinearAttribute:
case MFn::kDoubleLinearAttribute:
{
randomAnimatedValue(plug, startFrame, endFrame);
break;
}
default:
{
std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " << plug.attribute().apiTypeStr() << std::endl;
break;
}
}
}
}
AL::usdmaya::nodes::ProxyShape* CreateMayaProxyShape(
std::function<UsdStageRefPtr()> buildUsdStage,
const std::string& tempPath,
MObject* shapeParent
)
{
if(buildUsdStage != nullptr)
{
UsdStageRefPtr stage = buildUsdStage();
stage->Export(tempPath, false);
}
MFnDagNode fn;
MObject xform = fn.create("transform");
MObject shape = fn.create("AL_usdmaya_ProxyShape", xform);
if(shapeParent)
*shapeParent = shape;
AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fn.userNode();
proxy->filePathPlug().setString(tempPath.c_str());
return proxy;
}
AL::usdmaya::nodes::ProxyShape* CreateMayaProxyShape(const std::string& rootLayerPath)
{
MFnDagNode fn;
MObject xform = fn.create("transform");
MObject shape = fn.create("AL_usdmaya_ProxyShape", xform);
AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fn.userNode();
proxy->filePathPlug().setString(rootLayerPath.c_str());
return proxy;
}
AL::usdmaya::nodes::ProxyShape* SetupProxyShapeWithMesh()
{
MFileIO::newFile(true);
MGlobal::executeCommand("polySphere");
const MString scene = buildTempPath("AL_USDMayaTests_SceneWithMesh.usda");
MString command;
command.format("file -force -typ \"AL usdmaya export\" -pr -ea \"^1s\"", scene.asChar());
MGlobal::executeCommand(command, true);
//clear scene then create ProxyShape
MFileIO::newFile(true);
AL::usdmaya::nodes::ProxyShape* proxyShape = CreateMayaProxyShape(scene.asChar());
return proxyShape;
}
AL::usdmaya::nodes::ProxyShape* SetupProxyShapeWithMultipleMeshes()
{
MFileIO::newFile(true);
MGlobal::executeCommand("polySphere"); // pSphere1
MGlobal::executeCommand("polySphere"); // pSphere2
MGlobal::executeCommand("polySphere"); // pSphere3
const MString scene = buildTempPath("AL_USDMayaTests_SceneWithMultipleMeshs.usda");
MString command;
command.format("file -force -typ \"AL usdmaya export\" -pr -ea \"^1s\"", scene.asChar());
MGlobal::executeCommand(command, true);
//clear scene then create ProxyShape
MFileIO::newFile(true);
AL::usdmaya::nodes::ProxyShape* proxyShape = CreateMayaProxyShape(scene.asChar());
return proxyShape;
}
| 30.458073 | 140 | 0.579758 | [
"shape",
"transform"
] |
c024f7dd63e183e5f55666de63035a89b09894b0 | 9,757 | cc | C++ | src/map-contained-reads.cc | ebiggers/fragment-string-graph-assembler | d2fb454697e24cf389310b0778f05b56cf2c6271 | [
"BSD-2-Clause"
] | 1 | 2017-04-10T17:42:54.000Z | 2017-04-10T17:42:54.000Z | src/map-contained-reads.cc | ebiggers/fragment-string-graph-assembler | d2fb454697e24cf389310b0778f05b56cf2c6271 | [
"BSD-2-Clause"
] | null | null | null | src/map-contained-reads.cc | ebiggers/fragment-string-graph-assembler | d2fb454697e24cf389310b0778f05b56cf2c6271 | [
"BSD-2-Clause"
] | null | null | null | #include "Overlap.h"
#include "BaseVecVec.h"
#include "AnyStringGraph.h"
#include "util.h"
DEFINE_USAGE(
"Usage: map-contained-reads ORIG_READS_FILE ORIG_OVERLAPS_FILE\n"
" OLD_TO_NEW_INDICES_FILE GRAPH_FILE OUT_GRAPH_FILE\n"
"\n"
"Map contained reads back into a graph.\n"
"\n"
"Input:\n"
" READS_FILE: The set of reads from which the overlaps were found.\n"
" OVERLAPS_FILE: The set of overlaps, computed from the reads in\n"
" READS_FILE.\n"
" OLD_TO_NEW_INDICES_FILE: A map from the old read indices to the new\n"
" read indices.\n"
" GRAPH_FILE: The graph to map the contained reads into.\n"
"\n"
"Output:\n"
" OUT_GRAPH_FILE: The output graph into which the contained reads have.\n"
" been mapped.\n"
);
int main(int argc, char **argv)
{
USAGE_IF(argc != 6);
const char * const orig_reads_file = argv[1];
const char * const orig_overlaps_file = argv[2];
const char * const old_to_new_indices_file = argv[3];
const char * const graph_file = argv[4];
const char * const out_graph_file = argv[5];
info("Loading original reads from \"%s\"", orig_reads_file);
BaseVecVec orig_reads(orig_reads_file);
info("Loading original overlaps from \"%s\"", orig_overlaps_file);
OverlapVecVec orig_overlaps(orig_overlaps_file);
info("Loading map from old to new read indices from \"%s\"", old_to_new_indices_file);
std::vector<size_t> old_to_new_indices;
{
std::ifstream is(old_to_new_indices_file);
boost::archive::binary_iarchive ar(is);
ar >> old_to_new_indices;
}
size_t num_orig_reads = orig_reads.size();
assert(old_to_new_indices.size() == num_orig_reads);
assert(orig_overlaps.size() == num_orig_reads);
// Count the number of contained reads.
size_t num_contained_reads = 0;
for (size_t i = 0; i < num_orig_reads; i++)
if (old_to_new_indices[i] == ~size_t(0))
num_contained_reads++;
// The number of uncontained reads is the number of original reads minus
// the number of contained reads.
size_t num_uncontained_reads = num_orig_reads - num_contained_reads;
info("%zu of %zu original reads were contained (%.2f%%)",
num_contained_reads, num_orig_reads,
TO_PERCENT(num_contained_reads, num_orig_reads));
// Use the old to new indices map to build the reverse map from the new
// to old read indices. At the same time, construct a sequential
// numbering of the contained reads, and build a map from the original
// read indices to contained read indices and a reverse map from the
// contained read indices to the original read indices.
std::vector<size_t> contained_to_old_indices(num_contained_reads, ~size_t(0));
std::vector<size_t> new_to_old_indices(num_uncontained_reads, ~size_t(0));
std::vector<size_t> old_to_contained_indices(num_orig_reads, ~size_t(0));
size_t j = 0;
for (size_t i = 0; i < orig_reads.size(); i++) {
if (old_to_new_indices[i] == ~size_t(0)) {
// The read exists in the original reads but not in the
// new reads, so it is a contained read.
old_to_contained_indices[i] = j;
contained_to_old_indices[j++] = i;
} else {
// The read exists in both the original and new reads,
// so it is not a contained read. It may have been
// renumbered.
assert(old_to_new_indices[i] < num_uncontained_reads);
assert(new_to_old_indices[old_to_new_indices[i]] == ~size_t(0));
new_to_old_indices[old_to_new_indices[i]] = i;
}
}
assert(j == num_contained_reads);
// Find the shortest overhanging overlap for each contained read
info("Finding the shortest overhanging overlap for each contained read");
std::vector<const Overlap *>
shortest_overhang_overlaps(num_contained_reads, NULL);
std::vector<const Overlap *>
shortest_underhang_overlaps(num_contained_reads, NULL);
std::vector<Overlap::read_pos_t>
shortest_overhang_lens(num_contained_reads,
std::numeric_limits<Overlap::read_pos_t>::max());
std::vector<Overlap::read_pos_t>
shortest_underhang_lens(num_contained_reads,
std::numeric_limits<Overlap::read_pos_t>::max());
foreach (const OverlapVecVec::OverlapSet & overlap_set, orig_overlaps) {
foreach(const Overlap & o, overlap_set) {
Overlap::read_idx_t f_idx;
Overlap::read_pos_t f_beg;
Overlap::read_pos_t f_end;
Overlap::read_idx_t g_idx;
Overlap::read_pos_t g_beg;
Overlap::read_pos_t g_end;
bool rc;
Overlap::read_idx_t uncontained_read_orig_idx;
Overlap::read_pos_t uncontained_read_overlap_beg;
Overlap::read_pos_t uncontained_read_overlap_end;
assert_overlap_valid(o, orig_reads, 1, 0);
o.get(f_idx, f_beg, f_end, g_idx, g_beg, g_end, rc);
const BaseVec & f = orig_reads[f_idx];
const BaseVec & g = orig_reads[g_idx];
const BaseVec * uncontained_read;
assert(f_idx < num_orig_reads);
assert(g_idx < num_orig_reads);
size_t contained_read_orig_idx = ~size_t(0);
if (f_beg == 0 && f_end == f.size() - 1) {
// Read f is contained
// ... but only count this overlap if g is NOT
// contained
if (old_to_new_indices[g_idx] != ~size_t(0)) {
contained_read_orig_idx = f_idx;
uncontained_read = &g;
uncontained_read_orig_idx = g_idx;
uncontained_read_overlap_beg = g_beg;
uncontained_read_overlap_end = g_end;
}
} else if (g_beg == 0 && g_end == g.size() - 1) {
// Read g is contained
// ... but only count this overlap is f is NOT
// contained
if (old_to_new_indices[f_idx] != ~size_t(0)) {
contained_read_orig_idx = g_idx;
uncontained_read = &f;
uncontained_read_orig_idx = f_idx;
uncontained_read_overlap_beg = f_beg;
uncontained_read_overlap_end = f_end;
}
}
if (contained_read_orig_idx != ~size_t(0)) {
assert(old_to_new_indices[contained_read_orig_idx] ==
~size_t(0));
assert(old_to_contained_indices[contained_read_orig_idx] !=
~size_t(0));
// This is a containing overlap, and the read
// with original index @contained_read_orig_idx
// is contained. Compute the overhang length.
Overlap::read_pos_t overhang_len;
Overlap::read_pos_t underhang_len;
if (rc) {
//
//
// ---------->
// <------------------------
//
// |overhang|
overhang_len = uncontained_read_overlap_beg;
underhang_len = uncontained_read->length() -
(uncontained_read_overlap_end + 1);
} else {
//
//
// ---------->
// ------------------------>
//
// |overhang|
assert(uncontained_read->length() >=
uncontained_read_overlap_end + 1);
overhang_len = uncontained_read->length() -
(uncontained_read_overlap_end + 1);
underhang_len = uncontained_read_overlap_beg;
}
// Index of this contained read in the
// sequential numbering of the contained reads
size_t contained_idx =
old_to_contained_indices[contained_read_orig_idx];
// Update the shortest overhang if this overhang
// is shorter than the previous shortest one.
if (overhang_len < shortest_overhang_lens[contained_idx]) {
shortest_overhang_overlaps[contained_idx] = &o;
shortest_overhang_lens[contained_idx] = overhang_len;
}
if (underhang_len < shortest_underhang_lens[contained_idx]) {
shortest_underhang_overlaps[contained_idx] = &o;
shortest_underhang_lens[contained_idx] = underhang_len;
}
}
}
}
info("Reading string graph from \"%s\"", graph_file);
AnyStringGraph graph(graph_file);
info("Mapping %zu contained reads into the string graph", num_contained_reads);
// Map the contained reads into the graph, given the overlap to use to
// map each contained read.
for (size_t i = 0; i < num_contained_reads; i++) {
// Original index of this contained read
size_t contained_read_orig_idx;
// The overlap in which the overhang from the end of this
// contained read to its containing read is the shortest
const Overlap *o;
Overlap::read_idx_t f_idx, g_idx;
Overlap::read_idx_t uncontained_read_dir;
Overlap::read_idx_t uncontained_read_new_idx;
// Map the overhang
contained_read_orig_idx = contained_to_old_indices[i];
o = shortest_overhang_overlaps[i];
// Original read index must be valid, the read must be
// contained, and it must have at least 1 overlap with an
// uncontained read.
assert(contained_read_orig_idx < num_orig_reads);
assert(old_to_new_indices[contained_read_orig_idx] == ~size_t(0));
assert(o != NULL);
o->get_indices(f_idx, g_idx);
if (f_idx == contained_read_orig_idx) {
uncontained_read_new_idx = old_to_new_indices[g_idx];
} else {
assert(g_idx == contained_read_orig_idx);
uncontained_read_new_idx = old_to_new_indices[f_idx];
}
assert(uncontained_read_new_idx < num_uncontained_reads);
uncontained_read_dir = (o->is_rc() ? 1 : 0);
graph.map_contained_read(uncontained_read_new_idx,
uncontained_read_dir,
shortest_overhang_lens[i]);
// Map the underhang
o = shortest_underhang_overlaps[i];
assert(o != NULL);
o->get_indices(f_idx, g_idx);
if (f_idx == contained_read_orig_idx) {
uncontained_read_new_idx = old_to_new_indices[g_idx];
} else {
assert(g_idx == contained_read_orig_idx);
uncontained_read_new_idx = old_to_new_indices[f_idx];
}
assert(uncontained_read_new_idx < num_uncontained_reads);
uncontained_read_dir = (o->is_rc() ? 0 : 1);
graph.map_contained_read(uncontained_read_new_idx,
uncontained_read_dir,
shortest_overhang_lens[i]);
}
info("Writing string graph to \"%s\"", out_graph_file);
graph.write(out_graph_file);
return 0;
}
| 35.351449 | 87 | 0.692631 | [
"vector"
] |
c02f56de3ffed5236dcb83c41c4ee815f0fbd154 | 7,809 | hpp | C++ | include/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp | xuebingwu/PKA | 45f8d808cc36879d5da91213bc9902cd45f86b07 | [
"MIT"
] | 9 | 2017-01-26T15:50:52.000Z | 2020-09-01T08:27:00.000Z | include/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp | xuebingwu/PKA | 45f8d808cc36879d5da91213bc9902cd45f86b07 | [
"MIT"
] | 4 | 2017-07-18T21:17:45.000Z | 2020-09-17T02:54:52.000Z | include/boost/geometry/algorithms/detail/buffer/turn_in_piece_visitor.hpp | xuebingwu/PKA | 45f8d808cc36879d5da91213bc9902cd45f86b07 | [
"MIT"
] | 3 | 2017-01-02T14:11:37.000Z | 2019-12-20T13:42:13.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR
#include <boost/range.hpp>
#include <boost/geometry/arithmetic/dot_product.hpp>
#include <boost/geometry/algorithms/equals.hpp>
#include <boost/geometry/algorithms/expand.hpp>
#include <boost/geometry/algorithms/detail/disjoint/point_box.hpp>
#include <boost/geometry/algorithms/detail/overlay/segment_identifier.hpp>
#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>
#include <boost/geometry/policies/compare.hpp>
#include <boost/geometry/strategies/buffer.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/algorithms/comparable_distance.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace buffer
{
struct turn_get_box
{
template <typename Box, typename Turn>
static inline void apply(Box& total, Turn const& turn)
{
geometry::expand(total, turn.robust_point);
}
};
struct turn_ovelaps_box
{
template <typename Box, typename Turn>
static inline bool apply(Box const& box, Turn const& turn)
{
return ! dispatch::disjoint
<
typename Turn::robust_point_type,
Box
>::apply(turn.robust_point, box);
}
};
template <typename Turns, typename Pieces>
class turn_in_piece_visitor
{
Turns& m_turns; // because partition is currently operating on const input only
Pieces const& m_pieces; // to check for piece-type
typedef boost::long_long_type calculation_type;
template <typename Point>
static inline bool projection_on_segment(Point const& subject, Point const& p, Point const& q)
{
typedef Point vector_type;
typedef typename geometry::coordinate_type<Point>::type coordinate_type;
vector_type v = q;
vector_type w = subject;
subtract_point(v, p);
subtract_point(w, p);
coordinate_type const zero = coordinate_type();
coordinate_type const c1 = dot_product(w, v);
if (c1 < zero)
{
return false;
}
coordinate_type const c2 = dot_product(v, v);
if (c2 < c1)
{
return false;
}
return true;
}
template <typename Point, typename Piece>
inline bool on_offsetted(Point const& point, Piece const& piece) const
{
typedef typename strategy::side::services::default_strategy
<
typename cs_tag<Point>::type
>::type side_strategy;
geometry::equal_to<Point> comparator;
for (int i = 1; i < piece.offsetted_count; i++)
{
Point const& previous = piece.robust_ring[i - 1];
Point const& current = piece.robust_ring[i];
// The robust ring contains duplicates, avoid applying side on them (will be 0)
if (! comparator(previous, current))
{
int const side = side_strategy::apply(previous, current, point);
if (side == 0)
{
// Collinear, check if projection falls on it
if (projection_on_segment(point, previous, current))
{
return true;
}
}
}
}
return false;
}
template <typename Point, typename Piece>
static inline
calculation_type comparable_distance_from_offsetted(Point const& point,
Piece const& piece)
{
// TODO: pass subrange to dispatch to avoid making copy
geometry::model::linestring<Point> ls;
std::copy(piece.robust_ring.begin(),
piece.robust_ring.begin() + piece.offsetted_count,
std::back_inserter(ls));
typename default_comparable_distance_result<Point, Point>::type
const comp = geometry::comparable_distance(point, ls);
return static_cast<calculation_type>(comp);
}
public:
inline turn_in_piece_visitor(Turns& turns, Pieces const& pieces)
: m_turns(turns)
, m_pieces(pieces)
{}
template <typename Turn, typename Piece>
inline void apply(Turn const& turn, Piece const& piece, bool first = true)
{
boost::ignore_unused_variable_warning(first);
if (turn.count_within > 0)
{
// Already inside - no need to check again
return;
}
if (piece.type == strategy::buffer::buffered_flat_end
|| piece.type == strategy::buffer::buffered_concave)
{
// Turns cannot be inside a flat end (though they can be on border)
// Neither we need to check if they are inside concave helper pieces
return;
}
bool neighbour = false;
for (int i = 0; i < 2; i++)
{
// Don't compare against one of the two source-pieces
if (turn.operations[i].piece_index == piece.index)
{
return;
}
typename boost::range_value<Pieces>::type const& pc
= m_pieces[turn.operations[i].piece_index];
if (pc.left_index == piece.index
|| pc.right_index == piece.index)
{
if (pc.type == strategy::buffer::buffered_flat_end)
{
// If it is a flat end, don't compare against its neighbor:
// it will always be located on one of the helper segments
return;
}
neighbour = true;
}
}
int geometry_code = detail::within::point_in_geometry(turn.robust_point, piece.robust_ring);
if (geometry_code == -1)
{
return;
}
if (geometry_code == 0 && neighbour)
{
return;
}
Turn& mutable_turn = m_turns[turn.turn_index];
if (geometry_code == 0)
{
// If it is on the border and they are not neighbours, it should be
// on the offsetted ring
if (! on_offsetted(turn.robust_point, piece))
{
// It is on the border but not on the offsetted ring.
// Then it is somewhere on the helper-segments
// Classify it as "within"
geometry_code = 1;
mutable_turn.count_on_helper++; // can still become "near_offsetted"
}
else
{
mutable_turn.count_on_offsetted++; // value is not used anymore
}
}
if (geometry_code == 1)
{
calculation_type const distance
= comparable_distance_from_offsetted(turn.robust_point, piece);
if (distance >= 4)
{
// This is too far from the border, it counts as "really within"
mutable_turn.count_within++;
}
else
{
// Other points count as still "on border" because they might be
// travelled through, but not used as starting point
mutable_turn.count_within_near_offsetted++;
}
}
}
};
}} // namespace detail::buffer
#endif // DOXYGEN_NO_DETAIL
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_TURN_IN_PIECE_VISITOR
| 31.615385 | 100 | 0.592778 | [
"geometry",
"model"
] |
c030d63a3f8868de444a0517e6af063e23178abc | 730 | cxx | C++ | dfsunweighted.cxx | james-n-007/cf | 7bc9d225cfd03f9cb5fd26bf8d061513b7be5b7d | [
"MIT"
] | 8 | 2020-05-08T12:01:42.000Z | 2021-06-11T06:58:18.000Z | dfsunweighted.cxx | CoolDUE69/cf | 8e30070a6920e3845ce1b0ace42d424b0c06af8d | [
"MIT"
] | 9 | 2020-08-03T00:41:42.000Z | 2020-08-11T00:43:13.000Z | dfsunweighted.cxx | CoolDUE69/cf | 8e30070a6920e3845ce1b0ace42d424b0c06af8d | [
"MIT"
] | 9 | 2020-05-20T09:39:51.000Z | 2021-11-14T12:25:08.000Z | #include<bits/stdc++.h>
using namespace std;
void addedge(vector <int > adj[] ,int u ,int v){
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfsutil(int i , vector <int> adj[] ,vector<bool>&vis)
{
vis[i] = true;
cout<<i;
for(auto u = 0;u<adj[i].size();u++){
if(vis[adj[i][u]]==false){
dfsutil(adj[i][u],adj,vis);
}
}
}
void dfs(vector <int > adj[] , int V){
vector<bool>vis(V,false);
for(int i =0 ;i<V;i++){
if(vis[i] == false){
dfsutil(i,adj,vis);
}
}
}
int main(){
int V = 5 ;
vector< int > adj[5] ;
addedge(adj, 0, 1);
addedge(adj, 0, 4);
addedge(adj, 1, 2);
addedge(adj, 1, 3);
addedge(adj, 1, 4);
addedge(adj, 2, 3);
addedge(adj, 3, 4);
dfs(adj,V);
return 0;
}
| 19.210526 | 58 | 0.545205 | [
"vector"
] |
c0325fd348d94dfceab4062da84f7934b97f01c3 | 3,496 | hpp | C++ | libasd/read_binary_as.hpp | anntzer/libasd | 1d116e79cfd552daa0a90aeb4a01403910e563a3 | [
"MIT"
] | 12 | 2018-04-05T04:54:16.000Z | 2022-03-06T07:07:05.000Z | libasd/read_binary_as.hpp | anntzer/libasd | 1d116e79cfd552daa0a90aeb4a01403910e563a3 | [
"MIT"
] | 5 | 2019-12-16T09:07:19.000Z | 2021-12-23T12:53:07.000Z | libasd/read_binary_as.hpp | anntzer/libasd | 1d116e79cfd552daa0a90aeb4a01403910e563a3 | [
"MIT"
] | 5 | 2018-07-19T09:18:40.000Z | 2021-12-21T15:23:45.000Z | #ifndef LIBASD_READ_BINARY_AS_H
#define LIBASD_READ_BINARY_AS_H
#include <istream>
#include <cstring>
#include <libasd/container_dispatcher.hpp>
namespace asd
{
namespace detail
{
template<typename T>
T read_binary_as(const char*& ptr) noexcept
{
T retval;
std::memcpy(std::addressof(retval), ptr, sizeof(T));
ptr += sizeof(T);
return retval;
}
template<typename T>
T read_binary_as(std::istream& is)
{
T retval;
is.read(reinterpret_cast<char*>(std::addressof(retval)), sizeof(T));
return retval;
}
inline void ignore_bytes(const char*& ptr, std::ptrdiff_t pdiff) noexcept
{
ptr += pdiff;
return;
}
inline void ignore_bytes(std::istream& is, std::ptrdiff_t pdiff)
{
is.ignore(pdiff);
return;
}
// read array of value
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(std::istream& is, const std::size_t N, std::true_type)
{
// the traditional C-array form is available. write directory into the ptr.
constexpr std::size_t sz = sizeof(Value);
typename ContainerDispatcher::template rebind<Value>::other retval(N);
is.read(reinterpret_cast<char*>(::asd::container::get_ptr(retval)), sz * N);
return retval;
}
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(std::istream& is, const std::size_t N, std::false_type)
{
// the traditional C-array form is not available, use Iterator.
std::vector<Value> buffer(N);
is.read(reinterpret_cast<char*>(buffer.data()), sizeof(Value) * N);
return typename ContainerDispatcher::template
rebind<Value>::other(buffer.begin(), buffer.end());
}
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(std::istream& is, const std::size_t N)
{
return read_binary_as<Value, ContainerDispatcher>(is, N,
typename container_traits<
typename ContainerDispatcher::template rebind<Value>::other
>::ptr_accessibility{});
}
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(const char*& ptr, const std::size_t N, std::true_type)
{
// the traditional C-array form is available. write directory into the ptr.
typename ContainerDispatcher::template rebind<Value>::other retval(N);
std::memcpy(::asd::container::get_ptr(retval), ptr, sizeof(Value) * N);
ptr += sizeof(Value) * N;
return retval;
}
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(const char*& ptr, const std::size_t N, std::false_type)
{
// the traditional C-array form is not available, use Iterator.
std::vector<Value> buffer(N);
std::memcpy(buffer.data(), ptr, sizeof(Value) * N);
ptr += sizeof(Value) * N;
return typename ContainerDispatcher::template
rebind<Value>::other(buffer.begin(), buffer.end());
}
template<typename Value, typename ContainerDispatcher>
typename ContainerDispatcher::template rebind<Value>::other
read_binary_as(const char*& ptr, const std::size_t N)
{
return read_binary_as<Value, ContainerDispatcher>(ptr, N,
typename container_traits<
typename ContainerDispatcher::template rebind<Value>::other
>::ptr_accessibility{});
}
} // detail
}// asd
#endif// LIBASD_READ_BINARY_AS_H
| 31.781818 | 80 | 0.727689 | [
"vector"
] |
c044e26bcdbef72933b40efe7c50b878785dc797 | 6,452 | hxx | C++ | Modules/Filtering/Mosaic/include/otbStreamingLargeFeatherMosaicFilter.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/Mosaic/include/otbStreamingLargeFeatherMosaicFilter.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/Mosaic/include/otbStreamingLargeFeatherMosaicFilter.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 1999-2011 Insight Software Consortium
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
* Copyright (C) 2016-2019 IRSTEA
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __StreamingLargeFeatherMosaicFilter_hxx
#define __StreamingLargeFeatherMosaicFilter_hxx
#include "otbStreamingLargeFeatherMosaicFilter.h"
namespace otb
{
/**
* Processing
*/
template <class TInputImage, class TOutputImage, class TDistanceImage, class TInternalValueType>
void StreamingLargeFeatherMosaicFilter<TInputImage, TOutputImage, TDistanceImage, TInternalValueType>::ThreadedGenerateData(
const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId)
{
// Debug info
itkDebugMacro(<< "Actually executing thread " << threadId << " in region " << outputRegionForThread);
// Support progress methods/callbacks
itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());
// Get output pointer
OutputImageType* mosaicImage = this->GetOutput();
// Get number of used inputs
const unsigned int nbOfUsedInputImages = Superclass::GetNumberOfUsedInputImages();
// Get number of bands
const unsigned int nBands = Superclass::GetNumberOfBands();
// Iterate through the thread region
IteratorType outputIt(mosaicImage, outputRegionForThread);
// Prepare input pointers, interpolators, and valid regions (input images)
typename std::vector<InputImageType*> currentImage;
typename std::vector<InterpolatorPointerType> interp;
Superclass::PrepareImageAccessors(currentImage, interp);
// Prepare input pointers, interpolators, and valid regions (distances images)
typename std::vector<DistanceImageType*> currentDistanceImage;
typename std::vector<DistanceImageInterpolatorPointer> distanceInterpolator;
Superclass::PrepareDistanceImageAccessors(currentDistanceImage, distanceInterpolator);
// Temporary thread region (from input)
InputImageRegionType threadRegionInCurrentImage;
// Temporary pixels
InternalPixelType interpolatedMathPixel, tempOutputPixel;
interpolatedMathPixel.SetSize(nBands);
tempOutputPixel.SetSize(nBands);
InputImagePixelType interpolatedPixel;
InternalValueType pixelValue, distanceImagePixel, sumDistances;
bool isDataInCurrentOutputPixel;
// Temporary coordinates
OutputImagePointType geoPoint;
unsigned int band, i;
for (outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt)
{
// Current pixel --> Geographical point
mosaicImage->TransformIndexToPhysicalPoint(outputIt.GetIndex(), geoPoint);
// Presence of at least one non-null pixel of the used input images
isDataInCurrentOutputPixel = false;
sumDistances = 0.0;
// Transition pixels
tempOutputPixel.Fill(0.0);
// Loop on used input images
for (i = 0; i < nbOfUsedInputImages; i++)
{
// Check if the point is inside the transformed thread region
// (i.e. the region in the current input image which match the thread
// region)
if (interp[i]->IsInsideBuffer(geoPoint))
{
// Compute the interpolated pixel value
interpolatedPixel = interp[i]->Evaluate(geoPoint);
// Check that interpolated pixel is not empty
if (Superclass::IsPixelNotEmpty(interpolatedPixel))
{
// Get the alpha channel pixel value for this channel
if (distanceInterpolator[i]->IsInsideBuffer(geoPoint))
{
distanceImagePixel = distanceInterpolator[i]->Evaluate(geoPoint);
distanceImagePixel -= Superclass::GetDistanceOffset();
if (distanceImagePixel > 0)
{
// Update the presence of data for this pixel
isDataInCurrentOutputPixel = true;
// sum coef
sumDistances += distanceImagePixel;
/*
* 1. Cast the interpolated pixel into math pixel type
* 2. Multiply by feather coef
* 3. Compute sum
*/
const unsigned int inputImageIndex = Superclass::GetUsedInputImageIndice(i);
for (band = 0; band < nBands; band++)
{
// Cast the interpolated pixel to a internal pixel type
interpolatedMathPixel[band] = static_cast<InternalValueType>(interpolatedPixel[band]);
// Shift-scale the value
if (this->GetShiftScaleInputImages())
{
this->ShiftScaleValue(interpolatedMathPixel[band], inputImageIndex, band);
}
// Multiply by Feather coef
interpolatedMathPixel[band] *= distanceImagePixel;
// Summing
tempOutputPixel[band] += interpolatedMathPixel[band];
} // loop on pixel bands
} // distance > 0
} // Interpolated distance pixel not empty
else
{
itkWarningMacro(<< "Unable to evaluate distance at point " << geoPoint);
}
} // Interpolated pixel is not empty
} // point inside buffer
} // next image
// Prepare output pixel
OutputImagePixelType outputPixel(Superclass::GetNoDataOutputPixel());
if (isDataInCurrentOutputPixel)
{
// Compute output pixel
for (band = 0; band < nBands; band++)
{
// Normalize & cast
pixelValue = tempOutputPixel[band] / sumDistances;
Superclass::NormalizePixelValue(pixelValue);
outputPixel[band] = static_cast<OutputImageInternalPixelType>(pixelValue);
}
} // if data presence
// Update output pixel value
outputIt.Set(outputPixel);
// Update progress
progress.CompletedPixel();
} // next output pixel
}
} // end namespace gtb
#endif
| 34.137566 | 124 | 0.677154 | [
"vector"
] |
c04578ab768d5fe81263adb7b01176c9659919db | 1,904 | hpp | C++ | include/my_async/udp_client/client_base.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | include/my_async/udp_client/client_base.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | include/my_async/udp_client/client_base.hpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | 1 | 2021-03-10T13:02:13.000Z | 2021-03-10T13:02:13.000Z | #ifndef UDP_CLIENT_BASE_SESSION_HPP__
#define UDP_CLIENT_BASE_SESSION_HPP__
#include <boost/asio.hpp>
namespace My_Async{
namespace UDP{
template<typename Derived,
typename InContainer,
typename OutContainer = InContainer,
std::size_t ReadBufferSize = 1024>
class Client_Base{
private:
Derived&
derived()
{
return static_cast<Derived&>(*this);
}
using self_type = Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>;
public:
Client_Base(boost::asio::io_context& ioc, const boost::asio::ip::udp::endpoint& ep);
Client_Base(boost::asio::io_context& ioc);
Client_Base(boost::asio::io_context& ioc, unsigned short port);
~Client_Base(){}
void open(boost::asio::ip::udp::endpoint const& endpoint) noexcept;
void write(OutContainer const data) noexcept;
void write(std::shared_ptr<OutContainer const> data) noexcept;
void close(boost::system::error_code& ec) noexcept;
boost::asio::ip::udp::endpoint endpoint() const;
boost::asio::ip::udp::endpoint local_endpoint() const;
protected:
void do_read() noexcept;
void on_read(boost::system::error_code ec, std::size_t bytes_transfered) noexcept;
void fail(boost::system::error_code ec, char const* what) noexcept;
void writing(std::shared_ptr<OutContainer const> const data) noexcept;
void do_write() noexcept;
void on_write(boost::system::error_code ec, std::size_t) noexcept;
virtual void on_open() noexcept{}
virtual void on_error(boost::system::error_code, char const*) noexcept{}
virtual void on_close(boost::system::error_code) noexcept{}
virtual void read_handler(InContainer data) noexcept = 0;
boost::asio::ip::udp::socket socket_;
boost::asio::ip::udp::endpoint endpoint_;
std::vector<std::shared_ptr<OutContainer const>> queue_;
InContainer buffer_;
};
}//UDP
}//My_Async
#include "impl/client_base_impl.hpp"
#endif /* UDP_CLIENT_BASE_SESSION_HPP__ */
| 28 | 86 | 0.746324 | [
"vector"
] |
c04788dd07694e78a0a51f14b96f75eac4e07879 | 5,465 | cc | C++ | src/tea-napi.cc | nomagick/tea-napi | 1946f8db63ed2c85e59f7a181b0b87e203654c23 | [
"MIT"
] | null | null | null | src/tea-napi.cc | nomagick/tea-napi | 1946f8db63ed2c85e59f7a181b0b87e203654c23 | [
"MIT"
] | null | null | null | src/tea-napi.cc | nomagick/tea-napi | 1946f8db63ed2c85e59f7a181b0b87e203654c23 | [
"MIT"
] | null | null | null | #include <napi.h>
#include <cstdio>
#include <cstdint>
static uint32_t DELTA = 0x9e3779b9;
static size_t TEA_BLOCK_LEN = 8;
static size_t TEA_KEY_LEN = 16;
static void tea_encrypt(uint32_t *v, uint32_t *k, size_t iter) {
uint32_t v0 = v[0], v1 = v[1], sum = 0, i; /* set up */
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
for (i = 0; i < iter; i++) { /* basic cycle start */
sum += DELTA;
v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
} /* end cycle */
v[0] = v0;
v[1] = v1;
}
static void tea_decrypt(uint32_t *v, uint32_t *k, size_t iter) {
uint32_t v0 = v[0], v1 = v[1], sum = DELTA * iter, i; /* set up */
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
for (i = 0; i < iter; i++) { /* basic cycle start */
v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
sum -= DELTA;
} /* end cycle */
v[0] = v0;
v[1] = v1;
}
static Napi::Value TeaDecrypt(const Napi::CallbackInfo &info) {
if (info.Length() != 3) {
Napi::Error::New(info.Env(), "Expected exactly three argument")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[0].IsBuffer()) {
Napi::Error::New(info.Env(), "Expected first param (value) a Buffer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[1].IsBuffer()) {
Napi::Error::New(info.Env(), "Expected second param (key) a Buffer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (info[1].As<Napi::Buffer<uint8_t>>().ByteLength() < TEA_KEY_LEN) {
Napi::Error::New(info.Env(), "Expected second param (key) to be a Buffer at least 16 bytes")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[2].IsNumber() && info[2].As<Napi::Number>().Uint32Value() > 0) {
Napi::Error::New(info.Env(), "Expected third param (iter) an Integer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
Napi::Buffer<uint8_t> valueBuf = info[0].As<Napi::Buffer<uint8_t>>();
Napi::Buffer<uint32_t> keyBuf = info[1].As<Napi::Buffer<uint32_t>>();
size_t iter = info[2].As<Napi::Number>().Uint32Value();
uint32_t tmp[2] = {0};
uint32_t key[4] = {0};
const size_t cnt = valueBuf.ByteLength() / TEA_BLOCK_LEN;
const uint8_t *rawData = valueBuf.Data();
const uint32_t *rawKey = keyBuf.Data();
memcpy((uint32_t *) key, rawKey, TEA_KEY_LEN);
for (size_t i = 0; i < cnt; ++i) {
memcpy((uint8_t *) tmp, rawData + i * TEA_BLOCK_LEN, TEA_BLOCK_LEN);
tea_decrypt(tmp, key, iter);
memcpy((uint8_t *) rawData + (i * TEA_BLOCK_LEN), tmp, TEA_BLOCK_LEN);
}
return valueBuf;
}
static Napi::Value TeaEncrypt(const Napi::CallbackInfo &info) {
if (info.Length() != 3) {
Napi::Error::New(info.Env(), "Expected exactly three argument")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[0].IsBuffer()) {
Napi::Error::New(info.Env(), "Expected first param (value) a Buffer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[1].IsBuffer()) {
Napi::Error::New(info.Env(), "Expected second param (key) a Buffer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (info[1].As<Napi::Buffer<uint8_t>>().ByteLength() < TEA_KEY_LEN) {
Napi::Error::New(info.Env(), "Expected second param (key) to be a Buffer at least 16 bytes")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
if (!info[2].IsNumber() && info[2].As<Napi::Number>().Uint32Value() > 0) {
Napi::Error::New(info.Env(), "Expected third param (iter) an Integer")
.ThrowAsJavaScriptException();
return info.Env().Undefined();
}
Napi::Buffer<uint8_t> valueBuf = info[0].As<Napi::Buffer<uint8_t>>();
Napi::Buffer<uint32_t> keyBuf = info[1].As<Napi::Buffer<uint32_t>>();
size_t iter = info[2].As<Napi::Number>().Uint32Value();
uint32_t tmp[2] = {0};
uint32_t key[4] = {0};
const size_t cnt = valueBuf.ByteLength() / TEA_BLOCK_LEN;
const uint8_t *rawData = valueBuf.Data();
const uint32_t *rawKey = keyBuf.Data();
memcpy((uint32_t *) key, rawKey, TEA_KEY_LEN);
for (size_t i = 0; i < cnt; ++i) {
memcpy((uint8_t *) tmp, rawData + i * TEA_BLOCK_LEN, TEA_BLOCK_LEN);
tea_encrypt(tmp, key, iter);
memcpy((uint8_t *) rawData + (i * TEA_BLOCK_LEN), tmp, TEA_BLOCK_LEN);
}
return valueBuf;
}
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports["teaDecrypt"] = Napi::Function::New(env, TeaDecrypt);
exports["teaEncrypt"] = Napi::Function::New(env, TeaEncrypt);
exports["TEA_BLOCK_LEN"] = Napi::Number::New(env, TEA_BLOCK_LEN);
exports["TEA_KEY_LEN"] = Napi::Number::New(env, TEA_KEY_LEN);
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);
| 37.176871 | 100 | 0.560659 | [
"object"
] |
c0482d5f51bfb82413da7389a9964c86a01a0399 | 5,719 | cpp | C++ | libs/ml/tests/ml/layers/skip_gram.cpp | baykaner/ledger | f45fbd49297a419e3a90a46e9aed0cfa65602109 | [
"Apache-2.0"
] | null | null | null | libs/ml/tests/ml/layers/skip_gram.cpp | baykaner/ledger | f45fbd49297a419e3a90a46e9aed0cfa65602109 | [
"Apache-2.0"
] | null | null | null | libs/ml/tests/ml/layers/skip_gram.cpp | baykaner/ledger | f45fbd49297a419e3a90a46e9aed0cfa65602109 | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "core/serializers/main_serializer.hpp"
#include "ml/layers/skip_gram.hpp"
#include "ml/serializers/ml_types.hpp"
#include "ml/utilities/graph_builder.hpp"
#include "vectorise/fixed_point/fixed_point.hpp"
#include "gtest/gtest.h"
template <typename T>
class SkipGramTest : public ::testing::Test
{
};
using MyTypes = ::testing::Types<fetch::math::Tensor<float>, fetch::math::Tensor<double>,
fetch::math::Tensor<fetch::fixed_point::FixedPoint<32, 32>>,
fetch::math::Tensor<fetch::fixed_point::FixedPoint<16, 16>>>;
TYPED_TEST_CASE(SkipGramTest, MyTypes);
TYPED_TEST(SkipGramTest, saveparams_test)
{
using DataType = typename TypeParam::Type;
using SizeType = typename TypeParam::SizeType;
using LayerType = typename fetch::ml::layers::SkipGram<TypeParam>;
using SPType = typename LayerType::SPType;
SizeType in_size = 1;
SizeType out_size = 1;
SizeType embed_size = 1;
SizeType vocab_size = 10;
SizeType batch_size = 1;
std::string output_name = "SkipGram_Sigmoid";
// create input
TypeParam input({1, batch_size});
TypeParam context({1, batch_size});
TypeParam labels({1, batch_size});
input(0, 0) = static_cast<DataType>(0);
context(0, 0) = static_cast<DataType>(5);
labels(0, 0) = static_cast<DataType>(0);
// Create layer
LayerType layer(in_size, out_size, embed_size, vocab_size);
// add label node
std::string label_name =
layer.template AddNode<fetch::ml::ops::PlaceHolder<TypeParam>>("label", {});
// Add loss function
std::string error_output = layer.template AddNode<fetch::ml::ops::MeanSquareErrorLoss<TypeParam>>(
"num_error", {output_name, label_name});
// set input and ForwardPropagate
layer.SetInput("SkipGram_Input", input);
layer.SetInput("SkipGram_Context", context);
// make initial prediction to set internal buffers which must be correctly set in serialisation
TypeParam prediction0 = layer.Evaluate(output_name, true);
// extract saveparams
auto sp = layer.GetOpSaveableParams();
// downcast to correct type
auto dsp = std::dynamic_pointer_cast<SPType>(sp);
// serialize
fetch::serializers::MsgPackSerializer b;
b << *dsp;
// deserialize
b.seek(0);
auto dsp2 = std::make_shared<SPType>();
b >> *dsp2;
// rebuild
auto layer2 = *(fetch::ml::utilities::BuildLayer<TypeParam, LayerType>(dsp2));
//
// test that deserialized model gives the same forward prediction as the original layer
//
layer.SetInput("SkipGram_Input", input);
layer.SetInput("SkipGram_Context", context);
TypeParam prediction = layer.Evaluate(output_name, true);
// sanity check - serialisation should not affect initial prediction
ASSERT_TRUE(prediction0.AllClose(prediction, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
layer2.SetInput("SkipGram_Input", input);
layer2.SetInput("SkipGram_Context", context);
TypeParam prediction2 = layer2.Evaluate(output_name, true);
ASSERT_TRUE(prediction.AllClose(prediction2, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
// train g
layer.SetInput(label_name, labels);
TypeParam loss = layer.Evaluate(error_output);
layer.BackPropagate(error_output);
layer.ApplyRegularisation();
auto grads = layer.GetGradients();
for (auto &grad : grads)
{
grad *= static_cast<DataType>(-0.1);
}
layer.ApplyGradients(grads);
// train g2
layer2.SetInput(label_name, labels);
TypeParam loss2 = layer2.Evaluate(error_output);
layer2.BackPropagate(error_output);
layer2.ApplyRegularisation();
auto grads2 = layer2.GetGradients();
for (auto &grad : grads2)
{
grad *= static_cast<DataType>(-0.1);
}
layer2.ApplyGradients(grads2);
EXPECT_TRUE(loss.AllClose(loss2, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
//
// test that prediction is different after a back prop and step have been completed
//
layer.SetInput("SkipGram_Input", input); // resets node cache
layer.SetInput("SkipGram_Context", context); // resets node cache
TypeParam prediction3 = layer.Evaluate(output_name);
EXPECT_FALSE(prediction.AllClose(prediction3, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
//
// test that the deserialized model gives the same result as the original layer after training
//
layer2.SetInput("SkipGram_Input", input);
layer2.SetInput("SkipGram_Context", context);
TypeParam prediction5 = layer2.Evaluate(output_name);
EXPECT_TRUE(prediction3.AllClose(prediction5, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
}
| 35.08589 | 100 | 0.678965 | [
"model"
] |
c0498a5e4858c9cc8d03808bd5e4afbade06ff8c | 13,821 | cpp | C++ | src/enji/http.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | 1 | 2018-07-11T01:45:24.000Z | 2018-07-11T01:45:24.000Z | src/enji/http.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | null | null | null | src/enji/http.cpp | aptakhin/enji | 603675cf39f254eb9d888d0442cd085bf0f4e8f6 | [
"MIT"
] | null | null | null | #include "http.h"
#include <fcntl.h>
#include <fstream>
#ifdef _WIN32
# include <io.h>
#endif
namespace enji {
bool stream2stream(std::stringstream& output, std::stringstream&& input);
int cb_http_message_begin(http_parser* parser) {
return 0;
}
int cb_http_url(http_parser* parser, const char* at, size_t len) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_http_url(at, len);
}
int cb_http_status(http_parser* parser, const char* at, size_t len) {
std::cerr << "Got unhandled status: " << String(at, len) << std::endl;
return 0;
}
int cb_http_header_field(http_parser* parser, const char* at, size_t len) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_http_header_field(at, len);
}
int cb_http_header_value(http_parser* parser, const char* at, size_t len) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_http_header_value(at, len);
}
int cb_http_headers_complete(http_parser* parser) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_http_headers_complete();
}
int cb_http_body(http_parser* parser, const char* at, size_t len) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_http_body(at, len);
}
int cb_http_message_complete(http_parser* parser) {
HttpConnection& handler = *reinterpret_cast<HttpConnection*>(parser->data);
return handler.on_message_complete();
}
http_parser_settings& get_http_settings() {
static http_parser_settings http_settings = {};
http_settings.on_message_begin = cb_http_message_begin;
http_settings.on_url = cb_http_url;
http_settings.on_status = cb_http_status;
http_settings.on_header_field = cb_http_header_field;
http_settings.on_header_value = cb_http_header_value;
http_settings.on_headers_complete = cb_http_headers_complete;
http_settings.on_body = cb_http_body;
http_settings.on_message_complete = cb_http_message_complete;
return http_settings;
}
HttpConnection::HttpConnection(HttpServer* parent, size_t id)
: Connection(parent, id),
parent_(parent) {
parser_.reset(new http_parser{});
http_parser_init(parser_.get(), HTTP_REQUEST);
parser_.get()->data = this;
request_.reset(new HttpRequest{});
}
const HttpRequest& HttpConnection::request() const {
return *request_.get();
}
int HttpConnection::on_http_url(const char* at, size_t len) {
request_->url_ += String{at, len};
return 0;
}
int HttpConnection::on_http_header_field(const char* at, size_t len) {
check_header_finished();
read_header_.first += String{at, len};
return 0;
}
int HttpConnection::on_http_header_value(const char* at, size_t len) {
read_header_.second += String{at, len};
return 0;
}
int HttpConnection::on_http_headers_complete() {
check_header_finished();
return 0;
}
int HttpConnection::on_http_body(const char* at, size_t len) {
request_->body_ += String{at, len};
return 0;
}
const String MULTIPART_FORM_DATA = "multipart/form-data; boundary=";
int HttpConnection::on_message_complete() {
message_completed_ = true;
auto expect_iter = request_->headers_.find("Expect");
if (expect_iter != request_->headers_.end()) {
if (expect_iter->second == "100-continue") {
message_completed_ = false;
std::stringstream buf;
buf << "HTTP/1.1 100 Continue\r\n";
write_chunk(buf);
}
}
auto content_type_iter = request_->headers_.find("Content-Type");
if (content_type_iter != request_->headers_.end()) {
String boundary;
auto multipart = content_type_iter->second.find(MULTIPART_FORM_DATA);
if (multipart != String::npos) {
auto boundary_start = multipart + MULTIPART_FORM_DATA.size();
boundary = content_type_iter->second.substr(boundary_start);
}
std::vector<size_t> occurrences;
size_t start = 0;
boundary = "--" + boundary;
while ((start = request_->body_.find(boundary, start)) != String::npos) {
occurrences.push_back(start);
start += boundary.length();
}
const char* body = &request_->body_.front();
for (size_t occurence = 1; occurence < occurrences.size(); ++occurence) {
auto file_content = String{
body + occurrences[occurence - 1] + boundary.length() + 2, // Skip boundary + "\r\n"
body + occurrences[occurence]
};
auto headers_finished = file_content.find("\r\n\r\n");
auto headers = file_content.substr(0, headers_finished);
std::regex regex("Content-Disposition: form-data; name=\"(.+)\"; filename=\"(.+)\"");
std::smatch match_groups;
std::regex_search(headers, match_groups, regex);
File file;
if (!match_groups.empty()) {
file.name_ = match_groups[1].str();
file.filename_ = match_groups[2].str();
}
if (file.name_.empty() && file.filename_.empty()) {
continue;
}
auto file_body = file_content.substr(headers_finished + 4);
file.body_ = std::move(file_body);
request_->files_.emplace_back(std::move(file));
}
}
return 0;
}
void HttpConnection::handle_input(TransferBlock data) {
http_parser_execute(parser_.get(), &get_http_settings(), data.data, data.size);
if (message_completed_) {
request_->method_ = http_method_str(static_cast<http_method>(parser_.get()->method));
tp_parsed_ = std::chrono::high_resolution_clock::now();
parent_->call_handler(*request_.get(), this);
tp_handled_ = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double> elapsed_seconds0 = tp_parsed_ - tp_accepted_;
const std::chrono::duration<double> elapsed_seconds = tp_handled_ - tp_parsed_;
log() << "Times: " << elapsed_seconds0.count() << "s " << elapsed_seconds.count() << "s" << std::endl;
}
}
void HttpConnection::check_header_finished() {
// TODO: Check empty value headers with RFC
if (!read_header_.first.empty() && !read_header_.second.empty()) {
request_->headers_.insert(Header{std::move(read_header_)});
}
}
HttpResponse::HttpResponse(HttpConnection* conn)
: conn_{conn},
response_{std::stringstream::in | std::stringstream::out | std::stringstream::binary},
headers_{std::stringstream::in | std::stringstream::out | std::stringstream::binary},
body_{std::stringstream::in | std::stringstream::out | std::stringstream::binary},
full_response_{std::stringstream::in | std::stringstream::out | std::stringstream::binary} {
}
HttpResponse::~HttpResponse() {
close();
}
HttpResponse& HttpResponse::response(int code) {
code_ = code;
response_ << "HTTP/1.1 " << code << "\r\n";
return *this;
}
HttpResponse& HttpResponse::add_headers(std::vector<std::pair<String, String>> headers) {
for (auto&& h : headers) {
add_header(h.first, h.second);
}
return *this;
}
HttpResponse& HttpResponse::add_header(const String& name, const String& value) {
if (headers_sent_) {
throw std::runtime_error("Can't add headers to response. Headers already sent");
}
headers_ << name << ": " << value << "\r\n";
return *this;
}
bool stream2stream(std::stringstream&& input, std::stringstream& output) {
const size_t alloc_block = 256 * 1024;
char tmp[alloc_block];
bool written_smth = false;
while (input) {
input.read(tmp, sizeof(tmp));
const auto size = input.gcount();
output.write(tmp, size);
if (size) {
written_smth = true;
}
}
return written_smth;
}
void stream2conn(Connection* conn, std::stringstream& buf) {
conn->write_chunk(buf);
}
HttpResponse& HttpResponse::body(const String& value) {
body_ << value;
return *this;
}
HttpResponse& HttpResponse::body(std::stringstream&& buf) {
stream2stream(std::move(buf), body_);
return *this;
}
HttpResponse& HttpResponse::body(const void* data, size_t length) {
body_.write(static_cast<const char*>(data), length);
return *this;
}
void HttpResponse::flush() {
if (!headers_sent_) {
if (!stream2stream(std::move(response_), full_response_)) {
full_response_ << "HTTP/1.1 200\r\n";
}
body_.seekp(0, std::ios::end);
auto body_size = body_.tellp();
std::ostringstream body_size_stream;
body_size_stream << body_size;
add_header("Content-length", body_size_stream.str());
stream2stream(std::move(headers_), full_response_);
headers_sent_ = true;
full_response_ << "\r\n";
}
stream2stream(std::move(body_), full_response_);
stream2conn(conn_, full_response_);
}
void HttpResponse::close() {
flush();
conn_->close();
}
HttpRoute::HttpRoute(const char* path, Handler handler)
: path_{path},
handler_{handler},
path_match_(path) {
}
HttpRoute::HttpRoute(String&& path, Handler handler)
: path_{path},
handler_{handler},
path_match_(path) {
}
HttpRoute::HttpRoute(const char* path, FuncHandler handler)
: path_{path},
handler_{handler},
path_match_(path) {
}
HttpRoute::HttpRoute(String&& path, FuncHandler handler)
: path_{path},
handler_{handler},
path_match_(path) {
}
std::smatch HttpRoute::match(const String& url) const {
std::smatch match_groups;
std::regex_search(url, match_groups, path_match_);
return match_groups;
}
void HttpRoute::call_handler(const HttpRequest& req, HttpResponse& out) {
handler_(req, out);
}
HttpServer::HttpServer()
: Server{} {
create_connection([this]() {
return std::make_shared<HttpConnection>(this, counter_++); });
}
HttpServer::HttpServer(Config& config)
: Server{config} {
create_connection([this]() {
return std::make_shared<HttpConnection>(this, counter_++); });
}
void HttpServer::routes(std::vector<HttpRoute>&& routes) {
routes_ = std::move(routes);
}
void HttpServer::add_route(HttpRoute&& route) {
routes_.emplace_back(route);
}
void HttpServer::call_handler(HttpRequest& request, HttpConnection* bind) {
bool matched = false;
HttpResponse out{bind};
for (auto&& route : routes_) {
auto matches = route.match(request.url());
if (!matches.empty()) {
request.set_match(matches);
route.call_handler(request, out);
matched = true;
}
}
if (!matched) {
out.response(404);
}
bind->log() << request.method() << " " << request.url() << " " << out.code() << std::endl;
}
String match1_filename(const HttpRequest& req) {
return req.match()[1].str();
}
HttpRoute::Handler serve_static(std::function<String(const HttpRequest& req)> request2file, const Config& config) {
#ifdef _MSVC
return HttpRoute::Handler{
[request2file_bind{request2file}, config_bind{config}]
(const HttpRequest& req, HttpResponse& out)
{
static_file(request2file_bind(req), out, config_bind);
}};
#else
return HttpRoute::Handler{
[&]
(const HttpRequest& req, HttpResponse& out) {
static_file(request2file(req), out, config);
}
};
#endif
}
HttpRoute::Handler serve_static(const String& root_dir, std::function<String(const HttpRequest& req)> request2file) {
#ifdef _MSVC
return HttpRoute::Handler{
[root_dir_bind{root_dir}, request2file_bind{request2file}]
(const HttpRequest& req, HttpResponse& out)
{
const auto request_file = request2file_bind(req);
response_file(path_join(root_dir_bind, request_file), out);
}};
#else
return HttpRoute::Handler{
[&]
(const HttpRequest& req, HttpResponse& out)
{
const auto request_file = request2file(req);
response_file(path_join(root_dir, request_file), out);
}};
#endif
}
void static_file(const String& filename, HttpResponse& out, const Config& config) {
response_file(path_join(config["STATIC_ROOT_DIR"].str(), filename), out);
}
void response_file(const String& filename, HttpResponse& out) {
uv_fs_t open_req;
#ifdef _WIN32
int open_mode = _S_IREAD;
#else
int open_mode = S_IRUSR;
#endif
uv_fs_open(nullptr, &open_req, filename.c_str(), O_RDONLY, open_mode, nullptr);
auto open_req_exit = Defer{[&open_req] { uv_fs_req_cleanup(&open_req); }};
const auto fd = static_cast<uv_file>(open_req.result);
if (fd < 0) {
out.response(404);
return;
}
uv_fs_t read_req;
const size_t alloc_block = 64 * 1024;
size_t offset = 0;
char mem[alloc_block];
while (true) {
uv_buf_t buf[] = {uv_buf_init(mem, sizeof(mem))};
int read = uv_fs_read(nullptr, &read_req, fd, buf, 1, offset, nullptr);
auto read_req_exit = Defer{[&read_req] { uv_fs_req_cleanup(&read_req); }};
out.body(buf[0].base, read);
offset += read;
if (static_cast<unsigned int>(read) < buf[0].len) {
break;
}
}
uv_fs_t close_req;
uv_fs_close(nullptr, &close_req, fd, nullptr);
auto close_req_exit = Defer{[&close_req] { uv_fs_req_cleanup(&close_req); }};
}
namespace shortcuts {
void temporary_redirect(const String& redirect_to, HttpResponse& out) {
out.response(307);
out.add_header("Location", redirect_to);
out.close();
}
} // namespace shortcuts
} // namespace enji | 29.915584 | 117 | 0.652485 | [
"vector"
] |
c04b84ad31b767b5151195b6ad786592d8df98b5 | 3,550 | cpp | C++ | autotest/cpp/test_gdal.cpp | mihadyuk/gdal | d4627981715b82ff368547ef00ef26e0b9207048 | [
"MIT"
] | 3 | 2017-01-12T10:18:56.000Z | 2020-03-21T16:42:55.000Z | autotest/cpp/test_gdal.cpp | mihadyuk/gdal | d4627981715b82ff368547ef00ef26e0b9207048 | [
"MIT"
] | null | null | null | autotest/cpp/test_gdal.cpp | mihadyuk/gdal | d4627981715b82ff368547ef00ef26e0b9207048 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// $Id: test_gdal.cpp,v 1.4 2006/12/06 15:39:13 mloskot Exp $
//
// Project: C++ Test Suite for GDAL/OGR
// Purpose: Test general GDAL features.
// Author: Mateusz Loskot <mateusz@loskot.net>
//
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2006, Mateusz Loskot <mateusz@loskot.net>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
//
// $Log: test_gdal.cpp,v $
// Revision 1.4 2006/12/06 15:39:13 mloskot
// Added file header comment and copyright note.
//
//
///////////////////////////////////////////////////////////////////////////////
#include <tut.h>
#include <gdal.h>
#include <gdal_priv.h>
#include <string>
namespace tut
{
// Common fixture with test data
struct test_gdal_data
{
// Expected number of drivers
int drv_count_;
test_gdal_data()
: drv_count_(0)
{
// Windows CE port builds with fixed number of drivers
#ifdef FRMT_aaigrid
drv_count_++;
#endif
#ifdef FRMT_dted
drv_count_++;
#endif
#ifdef FRMT_gtiff
drv_count_++;
#endif
}
};
// Register test group
typedef test_group<test_gdal_data> group;
typedef group::object object;
group test_gdal_group("GDAL");
// Test GDAL driver manager access
template<>
template<>
void object::test<1>()
{
GDALDriverManager* drv_mgr = NULL;
drv_mgr = GetGDALDriverManager();
ensure("GetGDALDriverManager() is NULL", NULL != drv_mgr);
}
// Test number of registered GDAL drivers
template<>
template<>
void object::test<2>()
{
#ifdef WIN32CE
ensure_equals("GDAL registered drivers count doesn't match",
GDALGetDriverCount(), drv_count_);
#endif
}
// Test if AAIGrid driver is registered
template<>
template<>
void object::test<3>()
{
GDALDriverH drv = GDALGetDriverByName("AAIGrid");
#ifdef FRMT_aaigrid
ensure("AAIGrid driver is not registered", NULL != drv);
#else
ensure(true); // Skip
#endif
}
// Test if DTED driver is registered
template<>
template<>
void object::test<4>()
{
GDALDriverH drv = GDALGetDriverByName("DTED");
#ifdef FRMT_dted
ensure("DTED driver is not registered", NULL != drv);
#else
ensure(true); // Skip
#endif
}
// Test if GeoTIFF driver is registered
template<>
template<>
void object::test<5>()
{
GDALDriverH drv = GDALGetDriverByName("GTiff");
#ifdef FRMT_gtiff
ensure("GTiff driver is not registered", NULL != drv);
#else
ensure(true); // Skip
#endif
}
} // namespace tut
| 27.099237 | 79 | 0.587042 | [
"object"
] |
c04f4550e4e222921ad8621b5abfe2c89e615db3 | 8,116 | cpp | C++ | gbe/vram_viewer.cpp | malandrin/gbe | 51822b0723cfdcf42b061862a83c814be553ba16 | [
"MIT"
] | 2 | 2016-02-17T14:24:11.000Z | 2019-12-05T12:36:29.000Z | gbe/vram_viewer.cpp | malandrin/gbe | 51822b0723cfdcf42b061862a83c814be553ba16 | [
"MIT"
] | null | null | null | gbe/vram_viewer.cpp | malandrin/gbe | 51822b0723cfdcf42b061862a83c814be553ba16 | [
"MIT"
] | 1 | 2020-05-18T05:08:47.000Z | 2020-05-18T05:08:47.000Z | #include <imgui.h>
#include <imgui_impl_sdl.h>
#include <SDL_opengl.h>
#include "base.h"
#include "defines.h"
#include "mmu.h"
#include "vram_viewer.h"
static string sRadioButtonsText[5] { "TData 1", "TData 2", "TMap 1", "TMap 2", "OAM" };
static u32 sPalette[4] = { 0xFF000000, 0xFF7F7F7F, 0xFF404040, 0xFFFFFFFF };
//--------------------------------------------
// --
//--------------------------------------------
VRAMViewer::VRAMViewer(const MMU &_mmu) : mMmu(_mmu)
{
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::Init()
{
glGenTextures(1, &mTextureId);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::Render()
{
ImGui::SetNextWindowPos(ImVec2(560, 0));
if (ImGui::Begin("VRAM", nullptr, ImVec2(464, 468), 1.0f, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings))
{
for (int i = 0; i < 5; ++i)
{
ImGui::SameLine();
ImGui::RadioButton(sRadioButtonsText[i].c_str(), &mActiveVRam, i);
}
switch(mActiveVRam)
{
case 0:
case 1:
BuildTileData(mActiveVRam == 0 ? Memory::VRamTileData1StartAddr : Memory::VRamTileData2StartAddr);
ImGui::Image((ImTextureID)mTextureId, ImVec2(384, 384), ImVec2(0.0f, 0.0f), ImVec2(0.5664f, 0.5664f));
break;
case 2:
case 3:
{
ImVec2 screenPos = ImGui::GetCursorScreenPos();
u16 tileData = (mMmu.ReadU8(0xFF40) & 1 << 4) != 0 ? Memory::VRamTileData1StartAddr : Memory::VRamTileData2StartAddr;
BuildTileMap(mActiveVRam == 2 ? Memory::VRamTileMap1StartAddr : Memory::VRamTileMap2StartAddr, tileData);
ImGui::Image((ImTextureID)mTextureId, ImVec2(256, 256), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(0.2265f, 0.2265f, 0.4492f, 1.0f));
// ...
float sx = screenPos.x + 1;
float sy = screenPos.y + 1;
float x = (float)((256 + mMmu.ReadU8(IOReg::SCX)) % 256);
float y = (float)((256 + mMmu.ReadU8(IOReg::SCY)) % 256);
float x2 = (float)(((int)x + Screen::Width) % 256);
float y2 = (float)(((int)y + Screen::Height) % 256);
if (x2 < x)
{
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx, sy + y), ImVec2(sx + x2, sy + y), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y), ImVec2(sx + 256, sy + y), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx, sy + y2), ImVec2(sx + x2, sy + y2), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y2), ImVec2(sx + 256, sy + y2), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
}
else
{
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y), ImVec2(sx + x + Screen::Width, sy + y), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y2), ImVec2(sx + x + Screen::Width, sy + y2), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
}
if (y2 < y)
{
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy), ImVec2(sx + x, sy + y2), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y), ImVec2(sx + x, sy + 256), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x2, sy), ImVec2(sx + x2, sy + y2), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x2, sy + y), ImVec2(sx + x2, sy + 256), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
}
else
{
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x, sy + y), ImVec2(sx + x, sy + y + Screen::Height), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
ImGui::GetWindowDrawList()->AddLine(ImVec2(sx + x2, sy + y), ImVec2(sx + x2, sy + y + Screen::Height), ImColor(ImGui::GetStyle().Colors[ImGuiCol_ButtonActive]));
}
}
break;
case 4:
BuildOAMData();
ImGui::Image((ImTextureID)mTextureId, ImVec2(384, 384), ImVec2(0.0f, 0.0f), ImVec2(0.5664f, 0.53125f));
break;
}
}
ImGui::End();
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::BuildTileMap(u16 _addrMap, u16 _addrTiles)
{
fill_n(mTextureArray, 256 * 256, 0xFF000000);
int r = 0;
int c = 0;
for (int t = 0; t < 1024; ++t)
{
RenderTile(_addrTiles, mMmu.ReadU8(_addrMap + t), c * 8, r * 8);
++c;
if (c == 32)
{
c = 0;
++r;
}
}
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, mTextureArray);
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::BuildOAMData()
{
fill_n(mTextureArray, 256 * 256, 0xFF733A3A);
int r = 0;
int c = 0;
u16 addr = Memory::OAMStartAddr;
u8 objSize = (mMmu.ReadU8(IOReg::LCDC) & (1 << 2)) != 0 ? 16 : 8;
for (int t = 0; t < 40; ++t)
{
addr += 2; // ignore sprite position
u8 sprTile = mMmu.ReadU8(addr++);
u8 sprAttr = mMmu.ReadU8(addr++);
RenderTile(Memory::VRamTileData1StartAddr, sprTile, (c * 8) + c + 1, (r * objSize) + r + 1, objSize, (sprAttr & (1 << 5)) != 0, (sprAttr & (1 << 6)) != 0);
++c;
if (c == 16)
{
c = 0;
++r;
}
}
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, mTextureArray);
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::BuildTileData(u16 _addr)
{
fill_n(mTextureArray, 256 * 256, 0xFF733A3A);
int r = 0;
int c = 0;
for (int t = 0; t < 256; ++t)
{
RenderTile(_addr, t, (c * 8) + c + 1, (r * 8) + r + 1);
++c;
if (c == 16)
{
c = 0;
++r;
}
}
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, mTextureArray);
}
//--------------------------------------------
// --
//--------------------------------------------
void VRAMViewer::RenderTile(u16 _tileDataAddr, u8 _numTile, u8 _x, u8 _y, u8 _h, bool _flipX, bool _flipY)
{
u16 tileAddr;
if (_tileDataAddr == Memory::VRamTileData2StartAddr)
tileAddr = 0x9000 + ((i8)_numTile * 16);
else
tileAddr = _tileDataAddr + (_numTile * 16);
for (int r = 0; r < _h; ++r)
{
u16 rta = tileAddr + ((_flipY ? (_h - r) : r) * 2);
u8 b1 = mMmu.ReadU8(rta);
u8 b2 = mMmu.ReadU8(rta + 1);
for (int b = 7; b >= 0; --b)
{
int rb = _flipX ? (7 - b) : b;
u8 cp = (((b1 >> rb) & 1) << 1) | ((b2 >> rb) & 1);
u32 c = sPalette[cp];
mTextureArray[((_y + r) * 256) + _x + (7 - b)] = c;
}
}
} | 36.558559 | 181 | 0.501109 | [
"render"
] |
c04f4569984fc8d40cf373c8d4200b008216e240 | 2,885 | cpp | C++ | others/Drawing-app/floodfill.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | others/Drawing-app/floodfill.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | others/Drawing-app/floodfill.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include "floodfill.h"
#include <vector>
namespace DrawApp {
struct FillPixelInfo {
int y, xl, xr, dy;
};
#define PUSH(py, pxl, pxr, pdy) \
{ \
struct FillPixelInfo p; \
if (((py) + (pdy) >= 0) && ((py) + (pdy) < image.height())) { \
p.y = (py); \
p.xl = (pxl); \
p.xr = (pxr); \
p.dy = (pdy); \
stack.push_back(p); \
} \
}
#define POP(py, pxl, pxr, pdy) \
{ \
struct FillPixelInfo p = stack.back(); \
stack.pop_back(); \
(py) = p.y + p.dy; \
(pxl) = p.xl; \
(pxr) = p.xr; \
(pdy) = p.dy; \
}
std::vector<QPoint> floodFill(QImage *img, const QPoint &pos,
const QRgb &newColor) {
std::vector<QPoint> res;
QImage image(img->copy());
int x(pos.x());
int y(pos.y());
const QRgb prevColor(image.pixel(x, y));
std::vector<FillPixelInfo> stack;
if ((0 <= x) && (x < image.width()) && (0 <= y) && (y < image.height())) {
if (prevColor == newColor) {
return res;
}
PUSH(y, x, x, 1);
PUSH(y + 1, x, x, -1);
int l, x1, x2, dy;
while (!stack.empty()) {
POP(y, x1, x2, dy);
for (x = x1; (x >= 0) && image.pixel(x, y) == prevColor; --x) {
image.setPixel(x, y, newColor);
res.emplace_back(x, y);
}
if (x >= x1) {
goto skip;
}
l = x + 1;
if (l < x1) {
PUSH(y, l, x1 - 1, -dy);
}
x = x1 + 1;
do {
for (; (x < image.width()) && image.pixel(x, y) == prevColor; ++x) {
image.setPixel(x, y, newColor);
res.emplace_back(x, y);
}
PUSH(y, l, x - 1, dy);
if (x > x2 + 1) {
PUSH(y, x2 + 1, x - 1, -dy);
}
skip:
for (x++; x <= x2 && image.pixel(x, y) != prevColor; ++x) {
}
l = x;
} while (x <= x2);
}
}
return res;
}
} // namespace DrawApp
| 33.941176 | 80 | 0.286308 | [
"vector"
] |
c050b5ba98798f574c52b3c8df8b376187571cb3 | 9,756 | hpp | C++ | Libs/MaterialSystem/RendererCgARB1/TextureMapImpl.hpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | Libs/MaterialSystem/RendererCgARB1/TextureMapImpl.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | Libs/MaterialSystem/RendererCgARB1/TextureMapImpl.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
/**********************************/
/*** Texture Map Implementation ***/
/**********************************/
#ifndef CAFU_MATSYS_TEXTUREMAP_IMPLEMENTATION_HPP_INCLUDED
#define CAFU_MATSYS_TEXTUREMAP_IMPLEMENTATION_HPP_INCLUDED
// Required for #include <GL/gl.h> with MS VC++.
#if defined(_WIN32) && defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <GL/gl.h>
#include "../MapComposition.hpp"
#include "../TextureMap.hpp"
/// This class represents a texture-map.
class TextureMapImplT : public MatSys::TextureMapI
{
public:
// The TextureMapI interface is not repeated here.
/// Returns true if this texture was created from a map composition that was "equivalent" to MC_.
virtual bool IsCreatedFromMapComp(const MapCompositionT& MC_)=0;
/// This function returns an OpenGL object for this texture.
virtual GLuint GetOpenGLObject()=0;
/// Virtual destructor. See the class design diagram and the C++ FAQ 21.05 for more information.
/// (We will delete derived classes via pointers to TextureMapImplT.)
virtual ~TextureMapImplT() {}
};
/// This class represents a 2D texture-map.
class TextureMap2DT : public TextureMapImplT
{
private:
TextureMap2DT(const TextureMap2DT&); // Use of the Copy Constructor is not allowed.
void operator = (const TextureMap2DT&); // Use of the Assignment Operator is not allowed.
enum SourceT { MC, RawPtrExt, RawPtrOwn, BitmapPtrExt, BitmapPtrOwn };
SourceT Source;
MapCompositionT MapComp; ///< Used for Source==MC (and for *ALL* source types for the min/mag filters and wrapping mode).
BitmapT* Bitmap; ///< Used for Source==MC or Source==BitmapPtr*
char* Data; ///< Used for Source==RawPtr*
unsigned long SizeX; ///< Used for Source==RawPtr*
unsigned long SizeY; ///< Used for Source==RawPtr*
char BytesPerPixel; ///< Used for Source==RawPtr*
GLuint OpenGLObject;
unsigned long InitCounter; ///< Do we have to re-upload the Bitmap?
public:
// TextureMapI implementation.
// Needed by some user code for computing the texture s/t-coords.
unsigned int GetSizeX();
unsigned int GetSizeY();
// TextureMapImplT implementation.
bool IsCreatedFromMapComp(const MapCompositionT& MC_);
GLuint GetOpenGLObject();
~TextureMap2DT();
// Internal interface.
// Constructors.
TextureMap2DT(const MapCompositionT& MapComp_);
TextureMap2DT(char* Data_, unsigned long SizeX_, unsigned long SizeY_, char BytesPerPixel_, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
TextureMap2DT(BitmapT* Bitmap_, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
};
/// This class represents a cube texture-map.
class TextureMapCubeT : public TextureMapImplT
{
private:
TextureMapCubeT(const TextureMapCubeT&); // Use of the Copy Constructor is not allowed.
void operator = (const TextureMapCubeT&); // Use of the Assignment Operator is not allowed.
static const GLenum CubeTargets[6];
static const std::string CubeSuffixes[6];
static std::string GetFullCubeMapString(std::string BaseString, unsigned long SuffixNr);
enum SourceT { Files, RawPtrExt, RawPtrOwn, BitmapPtrExt, BitmapPtrOwn };
SourceT Source;
MapCompositionT MapComp; ///< Used for all source types for the min/mag filters and wrapping modes. If Source==Files, MapComp.GetString() is used as the cube map base name (with '#' placeholders).
BitmapT* Bitmap[6]; ///< Used for Source==Files or Source==BitmapPtr*
char* Data[6]; ///< Used for Source==RawPtr*
unsigned long SizeX; ///< Used for Source==RawPtr*
unsigned long SizeY; ///< Used for Source==RawPtr*
char BytesPerPixel; ///< Used for Source==RawPtr*
GLuint OpenGLObject;
unsigned long InitCounter; ///< Do we have to re-upload the Bitmap?
public:
// TextureMapI implementation.
// Needed by some user code for computing the texture s/t-coords.
unsigned int GetSizeX();
unsigned int GetSizeY();
// TextureMapImplT implementation.
bool IsCreatedFromMapComp(const MapCompositionT& MC_);
GLuint GetOpenGLObject();
~TextureMapCubeT();
// Internal implementation.
// Constructors.
TextureMapCubeT(const MapCompositionT& MapComp_);
TextureMapCubeT(char* Data_[6], unsigned long SizeX_, unsigned long SizeY_, char BytesPerPixel_, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
TextureMapCubeT(BitmapT* Bitmap_[6], bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
};
class TextureMapManagerImplT : public MatSys::TextureMapManagerI
{
public:
// TextureMapManagerI implementation.
void SetMaxTextureSize(unsigned long MaxSize);
unsigned long GetMaxTextureSize() const;
MatSys::TextureMapI* GetTextureMap2D(const MapCompositionT& MapComp);
MatSys::TextureMapI* GetTextureMap2D(char* Data, unsigned long SizeX, unsigned long SizeY, char BytesPerPixel, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
MatSys::TextureMapI* GetTextureMap2D(BitmapT* Bitmap, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
void FreeTextureMap(MatSys::TextureMapI* TM);
// Internal implementation.
/// Creates a 2D texture-map by a texture-map composition. The function never fails.
/// Calling this multiple times with the same MapComp will return identical pointers.
TextureMap2DT* GetTextureMap2DInternal(const MapCompositionT& MapComp);
/// Creates a 2D texture-map from a pointer. The function never fails.
/// Calling this multiple times with identical paramaters will each time return a different pointer!
/// If MakePrivateCopy=true, the function makes a private copy of the data pointed to by Data. The caller can then free the original data.
/// If MakePrivateCopy=false, the function relies on the Data being valid and available during the entire lifetime of the returned texture map.
/// SizeX and SizeY MUST be powers of 2, and BytesPerPixel MUST be 3 or 4!
TextureMap2DT* GetTextureMap2DInternal(char* Data, unsigned long SizeX, unsigned long SizeY, char BytesPerPixel, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
/// Creates a 2D texture-map from a BitmapT. The function never fails.
/// Calling this multiple times with identical paramaters will each time return a different pointer!
/// If MakePrivateCopy=true, the function makes a private copy of the data pointed to by Data. The caller can then free the original data.
/// If MakePrivateCopy=false, the function relies on the Bitmap being valid and available during the entire lifetime of the returned texture map.
TextureMap2DT* GetTextureMap2DInternal(BitmapT* Bitmap, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
/// Creates a cube texture-map by a texture-map composition. The function never fails.
/// Calling this multiple times with the same MapComp will return identical pointers.
TextureMapCubeT* GetTextureMapCubeInternal(const MapCompositionT& MapComp);
/// Creates a cube texture-map from a pointer. The function never fails.
/// Calling this multiple times with identical paramaters will each time return a different pointer!
/// If MakePrivateCopy=true, the function makes a private copy of the data pointed to by Data. The caller can then free the original data.
/// If MakePrivateCopy=false, the function relies on the Data being valid and available during the entire lifetime of the returned texture map.
/// SizeX and SizeY MUST be powers of 2, and BytesPerPixel MUST be 3 or 4!
TextureMapCubeT* GetTextureMapCubeInternal(char* Data[6], unsigned long SizeX, unsigned long SizeY, char BytesPerPixel, bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
/// Creates a cube texture-map from a BitmapT. The function never fails.
/// Calling this multiple times with identical paramaters will each time return a different pointer!
/// If MakePrivateCopy=true, the function makes a private copy of the data pointed to by Data. The caller can then free the original data.
/// If MakePrivateCopy=false, the function relies on the Bitmap being valid and available during the entire lifetime of the returned texture map.
TextureMapCubeT* GetTextureMapCubeInternal(BitmapT* Bitmap[6], bool MakePrivateCopy, const MapCompositionT& McForFiltersAndWrapping);
/// Releases the texture map from the texture manager, and all its resources.
void FreeTextureMap(TextureMapImplT* TM);
/// Returns a reference to the texture-map repository.
const ArrayT<TextureMapImplT*>& GetTexMapRepository() const { return TexMapRepository; }
/// Get a pointer/reference to the texture-map manager singleton.
static TextureMapManagerImplT& Get();
private:
TextureMapManagerImplT() : MaxTextureMapSize(4096) { }
TextureMapManagerImplT(const TextureMapManagerImplT&); // Use of the Copy Constructor is not allowed.
void operator = (const TextureMapManagerImplT&); // Use of the Assignment Operator is not allowed.
ArrayT<TextureMapImplT*> TexMapRepository;
ArrayT<unsigned long> TexMapRepositoryCount;
unsigned long MaxTextureMapSize;
};
#endif
| 45.376744 | 207 | 0.723657 | [
"object"
] |
c05314d7a5c6237511c2e4b8addf295c6356bd93 | 1,719 | cpp | C++ | aws-cpp-sdk-frauddetector/source/model/VariableImportanceMetrics.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-frauddetector/source/model/VariableImportanceMetrics.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-frauddetector/source/model/VariableImportanceMetrics.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/frauddetector/model/VariableImportanceMetrics.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FraudDetector
{
namespace Model
{
VariableImportanceMetrics::VariableImportanceMetrics() :
m_logOddsMetricsHasBeenSet(false)
{
}
VariableImportanceMetrics::VariableImportanceMetrics(JsonView jsonValue) :
m_logOddsMetricsHasBeenSet(false)
{
*this = jsonValue;
}
VariableImportanceMetrics& VariableImportanceMetrics::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("logOddsMetrics"))
{
Array<JsonView> logOddsMetricsJsonList = jsonValue.GetArray("logOddsMetrics");
for(unsigned logOddsMetricsIndex = 0; logOddsMetricsIndex < logOddsMetricsJsonList.GetLength(); ++logOddsMetricsIndex)
{
m_logOddsMetrics.push_back(logOddsMetricsJsonList[logOddsMetricsIndex].AsObject());
}
m_logOddsMetricsHasBeenSet = true;
}
return *this;
}
JsonValue VariableImportanceMetrics::Jsonize() const
{
JsonValue payload;
if(m_logOddsMetricsHasBeenSet)
{
Array<JsonValue> logOddsMetricsJsonList(m_logOddsMetrics.size());
for(unsigned logOddsMetricsIndex = 0; logOddsMetricsIndex < logOddsMetricsJsonList.GetLength(); ++logOddsMetricsIndex)
{
logOddsMetricsJsonList[logOddsMetricsIndex].AsObject(m_logOddsMetrics[logOddsMetricsIndex].Jsonize());
}
payload.WithArray("logOddsMetrics", std::move(logOddsMetricsJsonList));
}
return payload;
}
} // namespace Model
} // namespace FraudDetector
} // namespace Aws
| 25.279412 | 122 | 0.770215 | [
"model"
] |
c055afb88a22757a05bf8a1601afd4b003db689e | 6,935 | hh | C++ | DataStreamer/datastreamer.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | DataStreamer/datastreamer.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | DataStreamer/datastreamer.hh | drewnoakes/bold-humanoid | 6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <memory>
#include <queue>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <libwebsockets.h>
#include <opencv2/opencv.hpp>
#include <sigc++/signal.h>
#include "../ImageCodec/JpegCodec/jpegcodec.hh"
#include "../ImageCodec/PngCodec/pngcodec.hh"
#include "../Setting/setting.hh"
#include "../StateObject/stateobject.hh"
#include "../util/assert.hh"
#include "../util/websocketbuffer.hh"
namespace cv
{
class Mat;
}
namespace bold
{
class Camera;
class OptionTree;
enum class ImageEncoding
{
PNG,
JPEG
};
struct CameraSession
{
CameraSession(libwebsocket_context* context, libwebsocket *wsi);
~CameraSession() = default;
void notifyImageAvailable(cv::Mat const& image, ImageEncoding encoding, std::map<uchar, Colour::bgr> const& palette);
int write();
static PngCodec pngCodec;
static JpegCodec jpegCodec;
private:
/** Whether an image is waiting to be encoded. */
bool d_imgWaiting;
/** Whether encoded image data is currently being sent. */
bool d_imgSending;
/** If d_imgSending is true, the encoded JPEG bytes will be here. */
std::unique_ptr<std::vector<uchar>> d_imageBytes;
/** If d_imgSending is true, the number of bytes already sent. */
unsigned d_bytesSent;
std::mutex d_imageMutex;
cv::Mat d_image;
ImageEncoding d_imageEncoding;
std::map<uchar, Colour::bgr> d_palette;
libwebsocket_context* d_context;
libwebsocket* d_wsi;
};
class JsonSession
{
public:
JsonSession(std::string protocolName, libwebsocket* wsi, libwebsocket_context* context);
~JsonSession() = default;
void enqueue(WebSocketBuffer&& buffer, bool suppressLwsNotify = false);
int write();
private:
std::string _protocolName;
libwebsocket* _wsi;
libwebsocket_context* _context;
/** A queue of websocket buffers containing messages to send for this session. */
std::queue<WebSocketBuffer> _queue;
std::mutex _queueMutex;
/** The number of bytes already sent of the front message in the queue. */
int _bytesSent;
unsigned _maxQueueSeen;
std::string _hostName;
std::string _ipAddress;
};
struct LogMessage
{
LogLevel level;
std::string scope;
std::string message;
};
class WebSocketLogAppender : public LogAppender
{
public:
WebSocketLogAppender(libwebsocket_protocols* protocol);
void append(LogLevel level, std::string const& scope, std::string const& message) override;
void writeLogSyncJson(rapidjson::Writer<WebSocketBuffer>& writer);
static void writeJson(rapidjson::Writer<WebSocketBuffer>& writer, LogLevel level, std::string const& scope, std::string const& message);
size_t addSession(JsonSession* session);
size_t removeSession(JsonSession* session);
private:
libwebsocket_protocols* d_protocol;
std::vector<LogMessage> d_criticalMessages;
std::vector<JsonSession*> d_sessions;
std::mutex d_sessionsMutex;
};
class DataStreamer
{
public:
DataStreamer(std::shared_ptr<Camera> camera);
void stop();
/// Emits signal whenever the first client connects to a protocol, or the last disconnects.
sigc::signal<void,std::string,bool> hasClientChanged;
/** Returns true if there is at least one client connected to the camera image protocol. */
bool hasCameraClients() const { return d_cameraSessions.size() != 0; }
/** Enqueues an image to be sent to connected clients. */
void streamImage(cv::Mat const& img, ImageEncoding imageEncoding, std::map<uchar, Colour::bgr> const& palette);
void setOptionTree(std::shared_ptr<OptionTree> optionTree) { d_optionTree = optionTree; }
private:
void writeSettingUpdateJson(SettingBase const* setting, rapidjson::Writer<WebSocketBuffer>& writer);
void run();
void processCommand(std::string json, JsonSession* jsonSession);
void writeControlSyncJson(rapidjson::Writer<WebSocketBuffer>& writer);
const int d_port;
const std::shared_ptr<Camera> d_camera;
libwebsocket_context* d_context;
libwebsocket_protocols* d_protocols;
libwebsocket_protocols* d_controlProtocol;
std::vector<CameraSession*> d_cameraSessions;
std::mutex d_cameraSessionsMutex;
std::vector<JsonSession*> d_controlSessions;
std::mutex d_controlSessionsMutex;
std::shared_ptr<WebSocketLogAppender> d_logAppender;
std::multimap<std::string, JsonSession*> d_stateSessions;
std::mutex d_stateSessionsMutex;
bool d_isStopRequested;
std::thread d_thread;
std::shared_ptr<OptionTree> d_optionTree;
//
// libwebsocket callbacks
//
int callback_http (libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len);
int callback_camera (libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len);
int callback_control(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len);
int callback_log (libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len);
int callback_state (libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len);
static int _callback_camera(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len)
{
return static_cast<DataStreamer*>(libwebsocket_context_user(context))->callback_camera(context, wsi, reason, user, in, len);
}
static int _callback_http(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len)
{
return static_cast<DataStreamer*>(libwebsocket_context_user(context))->callback_http(context, wsi, reason, user, in, len);
}
static int _callback_control(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len)
{
return static_cast<DataStreamer*>(libwebsocket_context_user(context))->callback_control(context, wsi, reason, user, in, len);
}
static int _callback_log(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len)
{
return static_cast<DataStreamer*>(libwebsocket_context_user(context))->callback_log(context, wsi, reason, user, in, len);
}
static int _callback_state(libwebsocket_context* context, libwebsocket* wsi, libwebsocket_callback_reasons reason, void* user, void* in, size_t len)
{
return static_cast<DataStreamer*>(libwebsocket_context_user(context))->callback_state(context, wsi, reason, user, in, len);
}
};
}
| 33.341346 | 154 | 0.731074 | [
"vector"
] |
c0581a6caba0570fdb622a2b7c50407233cc9bbb | 23,469 | cc | C++ | tool/SecVerilog-1.0/SecVerilog/t-dll-proc.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | 1 | 2019-01-28T21:23:37.000Z | 2019-01-28T21:23:37.000Z | tool/SecVerilog-1.0/SecVerilog/t-dll-proc.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | null | null | null | tool/SecVerilog-1.0/SecVerilog/t-dll-proc.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2000-2010 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.will need a Picture Elements Binary Software
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "config.h"
# include <iostream>
# include <cstring>
# include "target.h"
# include "ivl_target.h"
# include "compiler.h"
# include "t-dll.h"
# include <cstdlib>
bool dll_target::process(const NetProcTop*net)
{
bool rc_flag = true;
ivl_process_t obj = (struct ivl_process_s*)
calloc(1, sizeof(struct ivl_process_s));
obj->type_ = net->type();
obj->analog_flag = 0;
FILE_NAME(obj, net);
/* Save the scope of the process. */
obj->scope_ = lookup_scope_(net->scope());
obj->nattr = net->attr_cnt();
obj->attr = fill_in_attributes(net);
/* This little bit causes the process to be completely
generated so that it can be passed to the DLL. The
stmt_cur_ member is used to hold a pointer to the current
statement in progress, and the emit_proc() method fills in
that object.
We know a few things about the current statement: we are
not in the middle of one, and when we are done, we have our
statement back. The asserts check these conditions. */
assert(stmt_cur_ == 0);
stmt_cur_ = (struct ivl_statement_s*)calloc(1, sizeof*stmt_cur_);
assert(stmt_cur_);
rc_flag = net->statement()->emit_proc(this) && rc_flag;
assert(stmt_cur_);
obj->stmt_ = stmt_cur_;
stmt_cur_ = 0;
/* Save the process in the design. */
obj->next_ = des_.threads_;
des_.threads_ = obj;
return rc_flag;
}
void dll_target::task_def(const NetScope*net)
{
ivl_scope_t scop = lookup_scope_(net);
const NetTaskDef*def = net->task_def();
assert(stmt_cur_ == 0);
stmt_cur_ = (struct ivl_statement_s*)calloc(1, sizeof*stmt_cur_);
assert(stmt_cur_);
def->proc()->emit_proc(this);
assert(stmt_cur_);
scop->def = stmt_cur_;
stmt_cur_ = 0;
}
bool dll_target::func_def(const NetScope*net)
{
ivl_scope_t scop = lookup_scope_(net);
const NetFuncDef*def = net->func_def();
assert(stmt_cur_ == 0);
stmt_cur_ = (struct ivl_statement_s*)calloc(1, sizeof*stmt_cur_);
assert(stmt_cur_);
def->proc()->emit_proc(this);
assert(stmt_cur_);
scop->def = stmt_cur_;
stmt_cur_ = 0;
scop->ports = def->port_count() + 1;
if (scop->ports > 0) {
scop->port = new ivl_signal_t[scop->ports];
for (unsigned idx = 1 ; idx < scop->ports ; idx += 1)
scop->port[idx] = find_signal(des_, def->port(idx-1));
}
/* FIXME: the ivl_target API expects port-0 to be the output
port. This assumes that the return value is a signal, which
is *not* correct. Someday, I'm going to have to change
this, but that will break code generators that use this
result. */
if (const NetNet*ret_sig = def->return_sig()) {
scop->port[0] = find_signal(des_, ret_sig);
return true;
}
cerr << "?:0" << ": internal error: "
<< "Function " << net->basename() << " has a return type"
<< " that I do not understand." << endl;
return false;
}
/*
* This private function makes the assignment lvals for the various
* kinds of assignment statements.
*/
void dll_target::make_assign_lvals_(const NetAssignBase*net)
{
assert(stmt_cur_);
unsigned cnt = net->l_val_count();
stmt_cur_->u_.assign_.lvals_ = cnt;
stmt_cur_->u_.assign_.lval_ = new struct ivl_lval_s[cnt];
stmt_cur_->u_.assign_.delay = 0;
for (unsigned idx = 0 ; idx < cnt ; idx += 1) {
struct ivl_lval_s*cur = stmt_cur_->u_.assign_.lval_ + idx;
const NetAssign_*asn = net->l_val(idx);
const NetExpr*loff = asn->get_base();
if (loff == 0) {
cur->loff = 0;
} else {
loff->expr_scan(this);
cur->loff = expr_;
expr_ = 0;
}
cur->width_ = asn->lwidth();
if (asn->sig()) {
cur->type_ = IVL_LVAL_REG;
cur->n.sig = find_signal(des_, asn->sig());
cur->idx = 0;
// If there is a word select expression, it is
// really an array index. Note that the word index
// expression is already converted to canonical
// form by elaboration.
if (asn->word()) {
assert(expr_ == 0);
asn->word()->expr_scan(this);
cur->type_ = IVL_LVAL_ARR;
cur->idx = expr_;
expr_ = 0;
}
} else {
assert(0);
}
}
}
void dll_target::proc_alloc(const NetAlloc*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_ALLOC;
stmt_cur_->u_.alloc_.scope = lookup_scope_(net->scope());
}
/*
*/
bool dll_target::proc_assign(const NetAssign*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
stmt_cur_->type_ = IVL_ST_ASSIGN;
FILE_NAME(stmt_cur_, net);
stmt_cur_->u_.assign_.delay = 0;
/* Make the lval fields. */
make_assign_lvals_(net);
assert(expr_ == 0);
net->rval()->expr_scan(this);
stmt_cur_->u_.assign_.rval_ = expr_;
expr_ = 0;
const NetExpr*del = net->get_delay();
if (del) {
del->expr_scan(this);
stmt_cur_->u_.assign_.delay = expr_;
expr_ = 0;
}
return true;
}
void dll_target::proc_assign_nb(const NetAssignNB*net)
{
const NetExpr* delay_exp = net->get_delay();
const NetExpr* cnt_exp = net->get_count();
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
stmt_cur_->type_ = IVL_ST_ASSIGN_NB;
FILE_NAME(stmt_cur_, net);
stmt_cur_->u_.assign_.delay = 0;
stmt_cur_->u_.assign_.count = 0;
stmt_cur_->u_.assign_.nevent = 0;
/* Make the lval fields. */
make_assign_lvals_(net);
/* Make the rval field. */
assert(expr_ == 0);
net->rval()->expr_scan(this);
stmt_cur_->u_.assign_.rval_ = expr_;
expr_ = 0;
/* Process a delay if it exists. */
if (const NetEConst*delay_num = dynamic_cast<const NetEConst*>(delay_exp)) {
verinum val = delay_num->value();
ivl_expr_t de = new struct ivl_expr_s;
de->type_ = IVL_EX_DELAY;
de->width_ = 8 * sizeof(uint64_t);
de->signed_ = 0;
de->u_.delay_.value = val.as_ulong64();
stmt_cur_->u_.assign_.delay = de;
} else if (delay_exp != 0) {
delay_exp->expr_scan(this);
stmt_cur_->u_.assign_.delay = expr_;
expr_ = 0;
}
/* Process a count if it exists. */
if (const NetEConst*cnt_num = dynamic_cast<const NetEConst*>(cnt_exp)) {
verinum val = cnt_num->value();
ivl_expr_t cnt = new struct ivl_expr_s;
cnt->type_ = IVL_EX_ULONG;
cnt->width_ = 8 * sizeof(unsigned long);
cnt->signed_ = 0;
cnt->u_.ulong_.value = val.as_ulong();
stmt_cur_->u_.assign_.count = cnt;
} else if (cnt_exp != 0) {
cnt_exp->expr_scan(this);
stmt_cur_->u_.assign_.count = expr_;
expr_ = 0;
}
/* Process the events if they exist. This is a copy of code
* from NetEvWait below. */
if (net->nevents() > 0) {
stmt_cur_->u_.assign_.nevent = net->nevents();
if (net->nevents() > 1) {
stmt_cur_->u_.assign_.events = (ivl_event_t*)
calloc(net->nevents(), sizeof(ivl_event_t*));
}
for (unsigned edx = 0 ; edx < net->nevents() ; edx += 1) {
/* Locate the event by name. Save the ivl_event_t in the
statement so that the generator can find it easily. */
const NetEvent*ev = net->event(edx);
ivl_scope_t ev_scope = lookup_scope_(ev->scope());
ivl_event_t ev_tmp=0;
assert(ev_scope);
assert(ev_scope->nevent_ > 0);
for (unsigned idx = 0; idx < ev_scope->nevent_; idx += 1) {
const char*ename =
ivl_event_basename(ev_scope->event_[idx]);
if (strcmp(ev->name(), ename) == 0) {
ev_tmp = ev_scope->event_[idx];
break;
}
}
// XXX should we assert(ev_tmp)?
if (net->nevents() == 1)
stmt_cur_->u_.assign_.event = ev_tmp;
else
stmt_cur_->u_.assign_.events[edx] = ev_tmp;
/* If this is an event with a probe, then connect up the
pins. This wasn't done during the ::event method because
the signals weren't scanned yet. */
if (ev->nprobe() >= 1) {
unsigned iany = 0;
unsigned ineg = ev_tmp->nany;
unsigned ipos = ineg + ev_tmp->nneg;
for (unsigned idx = 0; idx < ev->nprobe(); idx += 1) {
const NetEvProbe*pr = ev->probe(idx);
unsigned base = 0;
switch (pr->edge()) {
case NetEvProbe::ANYEDGE:
base = iany;
iany += pr->pin_count();
break;
case NetEvProbe::NEGEDGE:
base = ineg;
ineg += pr->pin_count();
break;
case NetEvProbe::POSEDGE:
base = ipos;
ipos += pr->pin_count();
break;
}
for (unsigned bit = 0; bit < pr->pin_count();
bit += 1) {
ivl_nexus_t nex = (ivl_nexus_t)
pr->pin(bit).nexus()->t_cookie();
assert(nex);
ev_tmp->pins[base+bit] = nex;
}
}
}
}
}
}
bool dll_target::proc_block(const NetBlock*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
/* First, count the statements in the block. */
unsigned count = 0;
for (const NetProc*cur = net->proc_first()
; cur ; cur = net->proc_next(cur))
count += 1;
/* If the block has no statements, then turn it into a no-op */
if (count == 0) {
stmt_cur_->type_ = IVL_ST_NOOP;
return true;
}
/* If there is exactly one statement, there is no need for the
block wrapper, generate the contained statement instead. */
if ((count == 1) && (net->subscope() == 0)) {
return net->proc_first()->emit_proc(this);
}
/* Handle the general case. The block has some statements in
it, so fill in the block fields of the existing statement,
and generate the contents for the statement array. */
stmt_cur_->type_ = (net->type() == NetBlock::SEQU)
? IVL_ST_BLOCK
: IVL_ST_FORK;
stmt_cur_->u_.block_.nstmt_ = count;
stmt_cur_->u_.block_.stmt_ = (struct ivl_statement_s*)
calloc(count, sizeof(struct ivl_statement_s));
if (net->subscope())
stmt_cur_->u_.block_.scope = lookup_scope_(net->subscope());
else
stmt_cur_->u_.block_.scope = 0;
struct ivl_statement_s*save_cur_ = stmt_cur_;
unsigned idx = 0;
bool flag = true;
for (const NetProc*cur = net->proc_first()
; cur ; cur = net->proc_next(cur), idx += 1) {
assert(idx < count);
stmt_cur_ = save_cur_->u_.block_.stmt_ + idx;
bool rc = cur->emit_proc(this);
flag = flag && rc;
}
assert(idx == count);
stmt_cur_ = save_cur_;
return flag;
}
/*
* A case statement is in turn an array of statements with gate
* expressions. This builds arrays of the right size and builds the
* ivl_expr_t and ivl_statement_s arrays for the substatements.
*/
void dll_target::proc_case(const NetCase*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
switch (net->type()) {
case NetCase::EQ:
stmt_cur_->type_ = IVL_ST_CASE;
break;
case NetCase::EQX:
stmt_cur_->type_ = IVL_ST_CASEX;
break;
case NetCase::EQZ:
stmt_cur_->type_ = IVL_ST_CASEZ;
break;
}
assert(stmt_cur_->type_ != IVL_ST_NONE);
assert(expr_ == 0);
assert(net->expr());
net->expr()->expr_scan(this);
stmt_cur_->u_.case_.cond = expr_;
expr_ = 0;
/* If the condition expression is a real valued expression,
then change the case statement to a CASER statement. */
if (stmt_cur_->u_.case_.cond->value_ == IVL_VT_REAL)
stmt_cur_->type_ = IVL_ST_CASER;
unsigned ncase = net->nitems();
stmt_cur_->u_.case_.ncase = ncase;
stmt_cur_->u_.case_.case_ex = new ivl_expr_t[ncase];
stmt_cur_->u_.case_.case_st = new struct ivl_statement_s[ncase];
ivl_statement_t save_cur = stmt_cur_;
for (unsigned idx = 0 ; idx < ncase ; idx += 1) {
const NetExpr*ex = net->expr(idx);
if (ex) {
ex->expr_scan(this);
save_cur->u_.case_.case_ex[idx] = expr_;
expr_ = 0;
} else {
save_cur->u_.case_.case_ex[idx] = 0;
}
stmt_cur_ = save_cur->u_.case_.case_st + idx;
stmt_cur_->type_ = IVL_ST_NONE;
if (net->stat(idx) == 0) {
stmt_cur_->type_ = IVL_ST_NOOP;
} else {
net->stat(idx)->emit_proc(this);
}
}
stmt_cur_ = save_cur;
}
bool dll_target::proc_cassign(const NetCAssign*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_CASSIGN;
/* Make the l-value fields. */
make_assign_lvals_(net);
assert(expr_ == 0);
net->rval()->expr_scan(this);
stmt_cur_->u_.assign_.rval_ = expr_;
expr_ = 0;
return true;
}
bool dll_target::proc_condit(const NetCondit*net)
{
bool rc_flag = true;
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_CONDIT;
stmt_cur_->u_.condit_.stmt_ = (struct ivl_statement_s*)
calloc(2, sizeof(struct ivl_statement_s));
assert(expr_ == 0);
net->expr()->expr_scan(this);
stmt_cur_->u_.condit_.cond_ = expr_;
if (expr_ == 0)
rc_flag = false;
expr_ = 0;
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = save_cur_->u_.condit_.stmt_+0;
rc_flag = net->emit_recurse_if(this) && rc_flag;
stmt_cur_ = save_cur_->u_.condit_.stmt_+1;
rc_flag = net->emit_recurse_else(this) && rc_flag;
stmt_cur_ = save_cur_;
return rc_flag;
}
bool dll_target::proc_deassign(const NetDeassign*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_DEASSIGN;
/* Make the l-value fields. */
make_assign_lvals_(net);
return true;
}
bool dll_target::proc_delay(const NetPDelay*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
ivl_statement_t tmp = (struct ivl_statement_s*)
calloc(1, sizeof(struct ivl_statement_s));
if (const NetExpr*expr = net->expr()) {
stmt_cur_->type_ = IVL_ST_DELAYX;
assert(expr_ == 0);
expr->expr_scan(this);
stmt_cur_->u_.delayx_.expr = expr_;
expr_ = 0;
stmt_cur_->u_.delayx_.stmt_ = tmp;
} else {
stmt_cur_->type_ = IVL_ST_DELAY;
stmt_cur_->u_.delay_.stmt_ = tmp;
stmt_cur_->u_.delay_.value = net->delay();
}
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = tmp;
bool flag = net->emit_proc_recurse(this);
/* If the recurse doesn't turn this new item into something,
then either it failed or there is no statement
there. Either way, draw a no-op into the statement. */
if (stmt_cur_->type_ == IVL_ST_NONE) {
stmt_cur_->type_ = IVL_ST_NOOP;
}
stmt_cur_ = save_cur_;
return flag;
}
bool dll_target::proc_disable(const NetDisable*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_DISABLE;
stmt_cur_->u_.disable_.scope = lookup_scope_(net->target());
return true;
}
bool dll_target::proc_force(const NetForce*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
stmt_cur_->type_ = IVL_ST_FORCE;
/* Make the l-value fields. */
make_assign_lvals_(net);
assert(expr_ == 0);
net->rval()->expr_scan(this);
stmt_cur_->u_.assign_.rval_ = expr_;
expr_ = 0;
return true;
}
void dll_target::proc_forever(const NetForever*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_FOREVER;
ivl_statement_t tmp = (struct ivl_statement_s*)
calloc(1, sizeof(struct ivl_statement_s));
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = tmp;
net->emit_recurse(this);
save_cur_->u_.forever_.stmt_ = stmt_cur_;
stmt_cur_ = save_cur_;
}
void dll_target::proc_free(const NetFree*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_FREE;
stmt_cur_->u_.free_.scope = lookup_scope_(net->scope());
}
bool dll_target::proc_release(const NetRelease*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_RELEASE;
/* Make the l-value fields. */
make_assign_lvals_(net);
return true;
}
void dll_target::proc_repeat(const NetRepeat*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_REPEAT;
assert(expr_ == 0);
net->expr()->expr_scan(this);
stmt_cur_->u_.while_.cond_ = expr_;
expr_ = 0;
ivl_statement_t tmp = (struct ivl_statement_s*)
calloc(1, sizeof(struct ivl_statement_s));
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = tmp;
net->emit_recurse(this);
save_cur_->u_.while_.stmt_ = stmt_cur_;
stmt_cur_ = save_cur_;
}
void dll_target::proc_stask(const NetSTask*net)
{
unsigned nparms = net->nparms();
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_STASK;
/* System task names are lex_strings strings. */
stmt_cur_->u_.stask_.name_ = net->name();
stmt_cur_->u_.stask_.nparm_= nparms;
stmt_cur_->u_.stask_.parms_= (ivl_expr_t*)
calloc(nparms, sizeof(ivl_expr_t));
for (unsigned idx = 0 ; idx < nparms ; idx += 1) {
if (net->parm(idx))
net->parm(idx)->expr_scan(this);
stmt_cur_->u_.stask_.parms_[idx] = expr_;
expr_ = 0;
}
}
bool dll_target::proc_trigger(const NetEvTrig*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_TRIGGER;
stmt_cur_->u_.wait_.nevent = 1;
/* Locate the event by name. Save the ivl_event_t in the
statement so that the generator can find it easily. */
const NetEvent*ev = net->event();
ivl_scope_t ev_scope = lookup_scope_(ev->scope());
for (unsigned idx = 0 ; idx < ev_scope->nevent_ ; idx += 1) {
const char*ename = ivl_event_basename(ev_scope->event_[idx]);
if (strcmp(ev->name(), ename) == 0) {
stmt_cur_->u_.wait_.event = ev_scope->event_[idx];
break;
}
}
return true;
}
void dll_target::proc_utask(const NetUTask*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_UTASK;
stmt_cur_->u_.utask_.def = lookup_scope_(net->task());
}
bool dll_target::proc_wait(const NetEvWait*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_WAIT;
stmt_cur_->u_.wait_.stmt_ = (struct ivl_statement_s*)
calloc(1, sizeof(struct ivl_statement_s));
// This event processing code is also in the NB assign above.
stmt_cur_->u_.wait_.nevent = net->nevents();
if (net->nevents() > 1) {
stmt_cur_->u_.wait_.events = (ivl_event_t*)
calloc(net->nevents(), sizeof(ivl_event_t*));
}
for (unsigned edx = 0 ; edx < net->nevents() ; edx += 1) {
/* Locate the event by name. Save the ivl_event_t in the
statement so that the generator can find it easily. */
const NetEvent*ev = net->event(edx);
ivl_scope_t ev_scope = lookup_scope_(ev->scope());
ivl_event_t ev_tmp=0;
assert(ev_scope);
assert(ev_scope->nevent_ > 0);
for (unsigned idx = 0 ; idx < ev_scope->nevent_ ; idx += 1) {
const char*ename = ivl_event_basename(ev_scope->event_[idx]);
if (strcmp(ev->name(), ename) == 0) {
ev_tmp = ev_scope->event_[idx];
break;
}
}
// XXX should we assert(ev_tmp)?
if (net->nevents() == 1)
stmt_cur_->u_.wait_.event = ev_tmp;
else
stmt_cur_->u_.wait_.events[edx] = ev_tmp;
/* If this is an event with a probe, then connect up the
pins. This wasn't done during the ::event method because
the signals weren't scanned yet. */
if (ev->nprobe() >= 1) {
unsigned iany = 0;
unsigned ineg = ev_tmp->nany;
unsigned ipos = ineg + ev_tmp->nneg;
for (unsigned idx = 0 ; idx < ev->nprobe() ; idx += 1) {
const NetEvProbe*pr = ev->probe(idx);
unsigned base = 0;
switch (pr->edge()) {
case NetEvProbe::ANYEDGE:
base = iany;
iany += pr->pin_count();
break;
case NetEvProbe::NEGEDGE:
base = ineg;
ineg += pr->pin_count();
break;
case NetEvProbe::POSEDGE:
base = ipos;
ipos += pr->pin_count();
break;
}
for (unsigned bit = 0
; bit < pr->pin_count()
; bit += 1) {
ivl_nexus_t nex = (ivl_nexus_t)
pr->pin(bit).nexus()->t_cookie();
assert(nex);
ev_tmp->pins[base+bit] = nex;
}
}
}
}
/* The ivl_statement_t for the wait statement is not complete
until we calculate the sub-statement. */
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = stmt_cur_->u_.wait_.stmt_;
bool flag = net->emit_recurse(this);
if (flag && (stmt_cur_->type_ == IVL_ST_NONE))
stmt_cur_->type_ = IVL_ST_NOOP;
stmt_cur_ = save_cur_;
return flag;
}
void dll_target::proc_while(const NetWhile*net)
{
assert(stmt_cur_);
assert(stmt_cur_->type_ == IVL_ST_NONE);
FILE_NAME(stmt_cur_, net);
stmt_cur_->type_ = IVL_ST_WHILE;
stmt_cur_->u_.while_.stmt_ = (struct ivl_statement_s*)
calloc(1, sizeof(struct ivl_statement_s));
assert(expr_ == 0);
net->expr()->expr_scan(this);
stmt_cur_->u_.while_.cond_ = expr_;
expr_ = 0;
/* Now generate the statement of the while loop. We know it is
a single statement, and we know that the
emit_proc_recurse() will call emit_proc() for it. */
ivl_statement_t save_cur_ = stmt_cur_;
stmt_cur_ = save_cur_->u_.while_.stmt_;
net->emit_proc_recurse(this);
stmt_cur_ = save_cur_;
}
| 27.321304 | 82 | 0.619668 | [
"object"
] |
c059808f6088eb271b16d388716e4670ba8322ce | 656 | cpp | C++ | problems/leet/77-combinations/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/leet/77-combinations/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/leet/77-combinations/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// *****
class Solution {
void dive(vector<vector<int>> &answers, vector<int> &included, int n, int m,
int k) const {
assert(m + k <= n + 1);
if (k == 0) {
answers.push_back(included);
return;
}
for (int i = m; i + k <= n + 1; ++i) {
included.push_back(i);
dive(answers, included, n, i + 1, k - 1);
included.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> answers;
vector<int> included;
dive(answers, included, n, 1, k);
return answers;
}
};
// *****
int main() {
return 0;
}
| 18.222222 | 78 | 0.532012 | [
"vector"
] |
c05ab1f7548171e4f82a702c845c66043ad696c2 | 3,298 | cpp | C++ | src/ae_denoising_rbm.cpp | wichtounet/word_spotting | 7e25513acc684d79f5c6b622d1d2e55fc40d3192 | [
"MIT"
] | 4 | 2017-11-07T02:36:30.000Z | 2022-01-20T17:46:06.000Z | src/ae_denoising_rbm.cpp | wichtounet/word_spotting | 7e25513acc684d79f5c6b622d1d2e55fc40d3192 | [
"MIT"
] | null | null | null | src/ae_denoising_rbm.cpp | wichtounet/word_spotting | 7e25513acc684d79f5c6b622d1d2e55fc40d3192 | [
"MIT"
] | 1 | 2019-12-11T11:03:25.000Z | 2019-12-11T11:03:25.000Z | //=======================================================================
// Copyright Baptiste Wicht 2015-2017.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef SPOTTER_NO_AE
#include "dll/rbm/rbm.hpp"
#include "dll/dbn.hpp"
#include "ae_config.hpp" // Must be first
#include "ae_rbm.hpp"
#include "ae_evaluation.hpp"
namespace {
template<size_t Noise>
void denoising_rbm_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& clean, float learning_rate, size_t epochs) {
using network_t = typename dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<
patch_height * patch_width, 50,
dll::batch_size<batch_size>,
dll::weight_decay<dll::decay_type::L2>,
dll::momentum
>::layer_t
>, dll::noise<Noise>>::dbn_t;
auto net = std::make_unique<network_t>();
net->display();
// Configure the network
net->template layer_get<0>().learning_rate = learning_rate;
net->template layer_get<0>().initial_momentum = 0.9;
net->template layer_get<0>().momentum = 0.9;
// Train as RBM
net->pretrain_denoising(clean, epochs);
auto folder = spot::evaluate_patches_ae<0, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params);
std::cout << "AE-Result: Denoising-RBM(" << Noise << "):" << folder << std::endl;
}
} // end of anonymous namespace
void denoising_rbm_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& clean){
if (conf.denoising && conf.rbm) {
auto lr = 1e-3;
denoising_rbm_evaluate<0>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<5>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<15>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<20>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<25>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<30>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<35>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<40>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<45>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
denoising_rbm_evaluate<50>(dataset, set, conf, train_word_names, test_image_names, params, clean, lr, epochs);
}
}
#endif // SPOTTER_NO_AE
| 47.114286 | 239 | 0.674955 | [
"vector"
] |
c065db8aaf7da4777771bdcfa4765f131ae9e602 | 24,182 | cxx | C++ | Modules/Visualization/MonteverdiGui/src/mvdImageViewManipulator.cxx | orfeotoolbox/OTB | 7782dd7f07e8a7fb713837d2f1d6d92def41f742 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Visualization/MonteverdiGui/src/mvdImageViewManipulator.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Visualization/MonteverdiGui/src/mvdImageViewManipulator.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mvdImageViewManipulator.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdGui.h"
#include "mvdImageViewRenderer.h"
namespace mvd
{
/*
TRANSLATOR mvd::ImageViewManipulator
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
const int ImageViewManipulator::DEFAULT_GRANULARITY = 1;
const int ImageViewManipulator::DEFAULT_ALPHA_GRANULARITY = 10;
const double ImageViewManipulator::DEFAULT_DYNAMICS_SHIFT_GRANULARITY = 0.01;
const int ImageViewManipulator::DEFAULT_SCROLL_GRANULARITY = 4;
const int ImageViewManipulator::DEFAULT_ZOOM_GRANULARITY = 2;
const double ImageViewManipulator::DEFAULT_DELTA = 0.1;
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*****************************************************************************/
#if USE_VIEW_SETTINGS_SIDE_EFFECT
ImageViewManipulator::ImageViewManipulator(const otb::ViewSettings::Pointer& viewSettings, QObject* p)
: AbstractImageViewManipulator(p),
m_MousePressPosition(),
m_ViewSettings(viewSettings),
m_Timer(NULL),
m_NativeSpacing(),
m_MousePressOrigin(),
m_RenderMode(AbstractImageViewRenderer::RenderingContext::RENDER_MODE_FULL),
m_ZoomFactor(1.0),
m_AlphaGranularity(ImageViewManipulator::DEFAULT_ALPHA_GRANULARITY),
m_DynamicsShiftGranularity(ImageViewManipulator::DEFAULT_DYNAMICS_SHIFT_GRANULARITY),
m_ScrollGranularity(ImageViewManipulator::DEFAULT_SCROLL_GRANULARITY),
m_ZoomGranularity(ImageViewManipulator::DEFAULT_ZOOM_GRANULARITY),
m_IsMouseDragging(false)
{
m_NativeSpacing.Fill(1.0);
}
#else // USE_VIEW_SETTINGS_SIDE_EFFECT
ImageViewManipulator::ImageViewManipulator(QObject* p)
: AbstractImageViewManipulator(p),
m_MousePressPosition(),
m_ViewSettings(otb::ViewSettings::New()),
m_Timer(NULL),
m_NativeSpacing(),
m_MousePressOrigin(),
m_RenderMode(AbstractImageViewRenderer::RenderingContext::RENDER_MODE_FULL),
m_ZoomFactor(1.0),
m_AlphaGranularity(ImageViewManipulator::DEFAULT_ALPHA_GRANULARITY),
m_DynamicsShiftGranularity(ImageViewManipulator::DEFAULT_DYNAMICS_GRANULARITY),
m_ScrollGranularity(ImageViewManipulator::DEFAULT_SCROLL_GRANULARITY),
m_ZoomGranularity(ImageViewManipulator::DEFAULT_ZOOM_GRANULARITY),
m_IsMouseDragging(false)
{
m_NativeSpacing.Fill(1.0);
}
#endif // USE_VIEW_SETTINGS_SIDE_EFFECT
/*****************************************************************************/
ImageViewManipulator::~ImageViewManipulator()
{
}
/******************************************************************************/
void ImageViewManipulator::SetViewportSize(int width, int height)
{
SizeType size;
size[0] = width;
size[1] = height;
assert(!m_ViewSettings.IsNull());
m_ViewSettings->SetViewportSize(size);
}
/******************************************************************************/
SizeType ImageViewManipulator::GetViewportSize() const
{
assert(!m_ViewSettings.IsNull());
return m_ViewSettings->GetViewportSize();
}
/******************************************************************************/
void ImageViewManipulator::SetOrigin(const PointType& origin)
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->SetOrigin(origin);
}
/******************************************************************************/
PointType ImageViewManipulator::GetOrigin() const
{
assert(!m_ViewSettings.IsNull());
return m_ViewSettings->GetOrigin();
}
/******************************************************************************/
void ImageViewManipulator::SetSpacing(const SpacingType& spacing)
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->SetSpacing(spacing);
}
/******************************************************************************/
SpacingType ImageViewManipulator::GetSpacing() const
{
assert(!m_ViewSettings.IsNull());
return m_ViewSettings->GetSpacing();
}
/******************************************************************************/
void ImageViewManipulator::SetNativeSpacing(const SpacingType& spacing)
{
m_NativeSpacing = spacing;
}
/******************************************************************************/
void ImageViewManipulator::SetWkt(const std::string& wkt)
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->SetWkt(wkt);
}
/******************************************************************************/
void ImageViewManipulator::SetImd(const otb::ImageMetadata *imd)
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->SetImageMetadata(imd);
}
/******************************************************************************/
PointType ImageViewManipulator::GetCenter() const
{
assert(!m_ViewSettings.IsNull());
return m_ViewSettings->GetViewportCenter();
}
/******************************************************************************/
void ImageViewManipulator::SetupRenderingContext(AbstractImageViewRenderer::RenderingContext* const c) const
{
assert(c == dynamic_cast<ImageViewRenderer::RenderingContext const*>(c));
ImageViewRenderer::RenderingContext* const context = dynamic_cast<ImageViewRenderer::RenderingContext* const>(c);
// Coverity-19840
// {
assert(context != NULL);
// }
context->m_RenderMode = m_IsMouseDragging ? AbstractImageViewRenderer::RenderingContext::RENDER_MODE_LIGHT : m_RenderMode;
#if USE_VIEW_SETTINGS_SIDE_EFFECT
#else // USE_VIEW_SETTINGS_SIDE_EFFECT
context->m_ViewSettings->SetOrigin(m_ViewSettings->GetOrigin());
context->m_ViewSettings->SetSpacing(m_ViewSettings->GetSpacing());
context->m_ViewSettings->SetViewportSize(m_ViewSettings->GetViewportSize());
context->m_ViewSettings->SetWkt(m_ViewSettings->GetWkt());
context->m_ViewSettings->SetImageMetadata(m_ViewSettings->GetImageMetadata());
context->m_ViewSettings->SetUseProjection(m_ViewSettings->GetUseProjection());
context->m_ViewSettings->SetGeometryChanged(m_ViewSettings->GetGeometryChanged());
#endif // USE_VIEW_SETTINGS_SIDE_EFFECT
}
/******************************************************************************/
void ImageViewManipulator::CenterOn(const PointType& point)
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->Center(point);
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), point);
}
/******************************************************************************/
void ImageViewManipulator::ZoomTo(double scale)
{
// qDebug() << this << "::ZoomTo(" << scale << ")";
assert(scale != 0.0);
assert(!m_ViewSettings.IsNull());
// Remember center of viewport.
otb::ViewSettings::PointType center(m_ViewSettings->GetViewportCenter());
// Calculate spacing based on scale.
#if 0
otb::ViewSettings::SpacingType spacing( m_ViewSettings->GetSpacing() );
spacing[ 0 ] = ( spacing[ 0 ]>0.0 ? 1.0 : -1.0 ) / scale;
spacing[ 1 ] = ( spacing[ 1 ]>0.0 ? 1.0 : -1.0 ) / scale;
#else
otb::ViewSettings::SpacingType spacing(m_NativeSpacing);
// Here, zoom to arbitrary scale-factor relative to
// viewport spacing.
//
// If viewport spacing has previously been set to
// image-spacing, it zooms to arbitrary scale-factor.
//
// This is especially useful to set user-arbitrary scale level
// such as when editing scale-level in status-bar.
spacing[0] /= scale;
spacing[1] /= scale;
#endif
// Change spacing and center.
m_ViewSettings->SetSpacing(spacing);
m_ViewSettings->Center(center);
// Emit ROI changed.
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), center);
// Q_EMIT RenderingContextChanged(center,GetSpacing()[0]);
}
/******************************************************************************/
void ImageViewManipulator::ZoomIn()
{
otb::ViewSettings::SizeType size(GetViewportSize());
PointType point;
Scale(QPoint(size[0] / 2, size[1] / 2), m_ZoomGranularity * MOUSE_WHEEL_STEP_DEGREES, &point);
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), point);
}
/******************************************************************************/
void ImageViewManipulator::ZoomOut()
{
otb::ViewSettings::SizeType size(GetViewportSize());
PointType point;
Scale(QPoint(size[0] / 2, size[1] / 2), -m_ZoomGranularity * MOUSE_WHEEL_STEP_DEGREES, &point);
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), point);
}
/******************************************************************************/
const PointType& ImageViewManipulator::Transform(PointType& viewport, const QPoint& screen) const
{
assert(!m_ViewSettings.IsNull());
m_ViewSettings->ScreenToViewPortTransform(static_cast<double>(screen.x()), static_cast<double>(screen.y()), viewport[0], viewport[1]);
return viewport;
}
/******************************************************************************/
void ImageViewManipulator::ResetViewport()
{
assert(!m_ViewSettings.IsNull());
otb::ViewSettings::SizeType size(m_ViewSettings->GetViewportSize());
m_ViewSettings->Reset();
m_ViewSettings->SetViewportSize(size);
m_NativeSpacing.Fill(1.0);
m_ZoomFactor = 1.0;
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), m_ViewSettings->GetViewportCenter());
}
/******************************************************************************/
void ImageViewManipulator::MousePressEvent(QMouseEvent* e)
{
// qDebug() << this << "::MousePressEvent(" << e << ")";
assert(e != NULL);
switch (e->button())
{
case Qt::NoButton:
break;
case Qt::LeftButton:
m_MousePressPosition = e->pos();
m_MousePressOrigin = m_ViewSettings->GetOrigin();
m_IsMouseDragging = true;
break;
case Qt::RightButton:
Q_EMIT ToggleLayerVisibilityRequested(false);
break;
case Qt::MidButton:
break;
case Qt::XButton1:
break;
case Qt::XButton2:
break;
default:
assert(false && "Unhandled Qt::MouseButton.");
break;
}
/*
Qt::NoModifier 0x00000000 No modifier key is pressed.
Qt::ShiftModifier 0x02000000 A Shift key on the keyboard is pressed.
Qt::ControlModifier 0x04000000 A Ctrl key on the keyboard is pressed.
Qt::AltModifier 0x08000000 An Alt key on the keyboard is pressed.
Qt::MetaModifier 0x10000000 A Meta key on the keyboard is pressed.
Qt::KeypadModifier 0x20000000 A keypad button is pressed.
Qt::GroupSwitchModifier
*/
}
/******************************************************************************/
void ImageViewManipulator::MouseMoveEvent(QMouseEvent* e)
{
// qDebug() << this << "::MouseMoveEvent(" << e << ")";
assert(e != NULL);
/*
qDebug() << "------------------------------------------------";
qDebug() << this << ":" << e;
*/
Qt::MouseButtons buttons = e->buttons();
Qt::KeyboardModifiers modifiers = e->modifiers();
if (buttons == Qt::LeftButton && (modifiers == Qt::NoModifier || modifiers == Qt::ControlModifier))
{
// Cursor moves from press position to current position;
// Image moves the same direction, so apply the negative translation.
Translate(m_MousePressPosition - e->pos());
m_MousePressPosition = e->pos();
Q_EMIT RefreshViewRequested();
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), m_ViewSettings->GetViewportCenter());
}
}
/******************************************************************************/
void ImageViewManipulator::MouseReleaseEvent(QMouseEvent* e)
{
// qDebug() << this << "::MouseReleaseEvent(" << e << ")";
assert(e != NULL);
/*
qDebug() << this << ":" << e;
*/
/*
Qt::MouseButtons buttons = e->buttons();
Qt::KeyboardModifiers modifiers = e->modifiers();
*/
// PointType center;
switch (e->button())
{
case Qt::NoButton:
break;
case Qt::LeftButton:
m_MousePressPosition = QPoint();
m_MousePressOrigin = PointType();
m_IsMouseDragging = false;
Q_EMIT RefreshViewRequested();
break;
case Qt::RightButton:
Q_EMIT ToggleLayerVisibilityRequested(true);
break;
case Qt::MidButton:
break;
case Qt::XButton1:
break;
case Qt::XButton2:
break;
default:
assert(false && "Unhandled Qt::MouseButton.");
break;
}
}
/******************************************************************************/
void ImageViewManipulator::MouseDoubleClickEvent(QMouseEvent* e)
{
// qDebug() << this << "::MouseDoubleClickEvent(" << e << ")";
assert(e != NULL);
if (e->button() == Qt::LeftButton && e->modifiers() == Qt::NoModifier)
{
PointType center;
assert(!m_ViewSettings.IsNull());
const QPoint& p = e->pos();
m_ViewSettings->ScreenToViewPortTransform(p.x(), p.y(), center[0], center[1]);
CenterOn(center);
}
}
/******************************************************************************/
void ImageViewManipulator
#if USE_VIEW_SETTINGS_SIDE_EFFECT
::ResizeEvent(QResizeEvent*)
#else // USE_VIEW_SETTINGS_SIDE_EFFECT
::ResizeEvent(QResizeEvent* e)
#endif // USE_VIEW_SETTINGS_SIDE_EFFECT
{
// assert( e!=NULL );
// qDebug() << this << "::ResizeEvent(" << e << ")";
/*
qDebug() << m_ViewSettings.GetPointer();
otb::ViewSettings::SizeType size( m_ViewSettings->GetViewportSize() );
qDebug() << size[ 0 ] << "," << size[ 1 ] << "\t" << e->size();
*/
#if USE_VIEW_SETTINGS_SIDE_EFFECT
#else // USE_VIEW_SETTINGS_SIDE_EFFECT
assert(e != NULL);
SetViewportSize(e->size().width(), e->size().height());
#endif // USE_VIEW_SETTINGS_SIDE_EFFECT
}
/******************************************************************************/
void ImageViewManipulator::WheelEvent(QWheelEvent* e)
{
assert(e != NULL);
Qt::MouseButtons buttons = e->buttons();
Qt::KeyboardModifiers modifiers = e->modifiers();
if (buttons != Qt::NoButton)
return;
// Delta is rotation distance in number of 8th of degrees (see
// http://qt-project.org/doc/qt-4.8/qwheelevent.html#delta).
assert(e->delta() != 0);
int degrees = e->delta() / MOUSE_WHEEL_STEP_FACTOR;
if (modifiers == Qt::ControlModifier)
Q_EMIT RotateLayersRequested(e->delta() / (MOUSE_WHEEL_STEP_FACTOR * MOUSE_WHEEL_STEP_DEGREES));
//
else if (modifiers == Qt::MetaModifier)
{
// qDebug() << "META+Wheel" << e->delta();
Q_EMIT ShiftAlphaRequested(static_cast<double>(m_AlphaGranularity * e->delta() / (MOUSE_WHEEL_STEP_FACTOR * MOUSE_WHEEL_STEP_DEGREES)) / 100.0);
}
else if (modifiers == (Qt::MetaModifier | Qt::ShiftModifier))
{
// qDebug() << "META+SHIFT+Wheel" << e->delta();
Q_EMIT UpdateGammaRequested(ImageViewManipulator::Factor(degrees, MOUSE_WHEEL_STEP_DEGREES));
}
//
else if (modifiers == Qt::AltModifier)
{
// qDebug() << "ALT+Wheel" << e->delta();
Q_EMIT ResizeShaderRequested(ImageViewManipulator::Factor(degrees, MOUSE_WHEEL_STEP_DEGREES));
}
else if (modifiers == (Qt::AltModifier | Qt::ShiftModifier))
{
// qDebug() << "ALT+SHIFT+Wheel" << e->delta();
Q_EMIT ReparamShaderRequested(ImageViewManipulator::Factor(degrees, MOUSE_WHEEL_STEP_DEGREES));
}
//
else if (modifiers == (Qt::ControlModifier | Qt::AltModifier))
{
// qDebug() << "CTRL+ALT+Wheel" << e->delta();
Q_EMIT ShiftDynamicsRequested(m_DynamicsShiftGranularity * static_cast<double>(e->delta() / (MOUSE_WHEEL_STEP_FACTOR * MOUSE_WHEEL_STEP_DEGREES)));
}
else if (modifiers == (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))
{
// qDebug() << "CTRL+ALT+SHIFT+Wheel" << e->delta();
Q_EMIT ScaleDynamicsRequested(ImageViewManipulator::Factor(degrees, MOUSE_WHEEL_STEP_DEGREES));
}
//
else if (modifiers == Qt::NoModifier)
{
if (m_Timer == NULL)
{
m_Timer = new QTimer();
QObject::connect(m_Timer, SIGNAL(timeout()),
// to:
this, SLOT(OnTimeout()));
}
m_Timer->start(500);
SetFastRenderMode(true);
PointType point;
Scale(e->pos(), degrees, &point);
Q_EMIT RefreshViewRequested();
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), point);
}
}
/******************************************************************************/
void ImageViewManipulator::KeyPressEvent(QKeyEvent* e)
{
assert(e != NULL);
// qDebug() << this << "::KeyPressEvent(" << e << ")";
QPoint vector(0, 0);
int steps = 0;
int key = e->key();
Qt::KeyboardModifiers modifiers = e->modifiers();
switch (key)
{
case Qt::Key_Up:
vector.setY(-1);
break;
case Qt::Key_Down:
vector.setY(+1);
break;
case Qt::Key_Left:
vector.setX(-1);
break;
case Qt::Key_Right:
vector.setX(+1);
break;
case Qt::Key_Plus:
steps = m_ZoomGranularity;
break;
case Qt::Key_Minus:
steps = -m_ZoomGranularity;
break;
case Qt::Key_PageUp:
if (e->modifiers() == Qt::ShiftModifier)
Q_EMIT LayerToTopRequested();
else
Q_EMIT RaiseLayerRequested();
break;
case Qt::Key_PageDown:
if (e->modifiers() == Qt::ShiftModifier)
Q_EMIT LayerToBottomRequested();
else
Q_EMIT LowerLayerRequested();
break;
case Qt::Key_Home:
if (e->modifiers() == Qt::ShiftModifier)
Q_EMIT SelectFirstLayerRequested();
else
Q_EMIT SelectPreviousLayerRequested();
break;
case Qt::Key_End:
if (e->modifiers() == Qt::ShiftModifier)
Q_EMIT SelectLastLayerRequested();
else
Q_EMIT SelectNextLayerRequested();
break;
case Qt::Key_Delete:
if (modifiers.testFlag(Qt::ShiftModifier))
Q_EMIT DeleteAllRequested();
else
Q_EMIT DeleteSelectedRequested();
break;
case Qt::Key_1:
Q_EMIT ZoomToFullResolutionRequested();
break;
case Qt::Key_2:
Q_EMIT ZoomToLayerExtentRequested();
break;
case Qt::Key_3:
Q_EMIT ZoomToFullExtentRequested();
break;
case Qt::Key_A:
Q_EMIT ApplyAllRequested();
break;
case Qt::Key_C:
Q_EMIT ShaderEffectRequested(EFFECT_CHESSBOARD);
break;
case Qt::Key_G:
Q_EMIT ShaderEffectRequested(EFFECT_GRADIENT);
break;
case Qt::Key_D:
Q_EMIT ShaderEffectRequested(EFFECT_LOCAL_CONTRAST);
break;
case Qt::Key_H:
Q_EMIT ShaderEffectRequested(EFFECT_SWIPE_H);
break;
case Qt::Key_N:
Q_EMIT ShaderEffectRequested(EFFECT_NORMAL);
break;
case Qt::Key_P:
if (modifiers.testFlag(Qt::ControlModifier))
Q_EMIT TakeScreenshotRequested(modifiers.testFlag(Qt::ShiftModifier));
else
Q_EMIT SetReferenceRequested();
break;
case Qt::Key_Q:
Q_EMIT ResetQuantilesRequested(modifiers.testFlag(Qt::ShiftModifier));
break;
case Qt::Key_S:
Q_EMIT ShaderEffectRequested(EFFECT_SPECTRAL_ANGLE);
break;
case Qt::Key_T:
Q_EMIT ShaderEffectRequested(EFFECT_LOCAL_TRANSLUCENCY);
break;
case Qt::Key_V:
Q_EMIT ShaderEffectRequested(EFFECT_SWIPE_V);
break;
default:
break;
}
assert(!m_ViewSettings.IsNull());
bool needsRefresh = false;
//
// Translate
if (!vector.isNull())
{
otb::ViewSettings::SizeType size(m_ViewSettings->GetViewportSize());
if (modifiers == Qt::NoModifier)
{
size[0] /= m_ScrollGranularity;
size[1] /= m_ScrollGranularity;
}
else if (modifiers == Qt::ControlModifier)
{
size[0] /= m_ScrollGranularity * 2;
size[1] /= m_ScrollGranularity * 2;
}
vector.rx() *= size[0];
vector.ry() *= size[1];
Translate(vector);
needsRefresh = true;
}
//
// Scale
if (steps != 0)
{
// Qt::ControlModifier doest not work with keypard Qt::Key_Plus/Minus keys.
otb::ViewSettings::SizeType size(m_ViewSettings->GetViewportSize());
Scale(QPoint(size[0] / 2.0, size[1] / 2.0), steps * MOUSE_WHEEL_STEP_DEGREES);
needsRefresh = true;
}
//
// Refresh
if (needsRefresh)
{
Q_EMIT RefreshViewRequested();
Q_EMIT RoiChanged(GetOrigin(), GetViewportSize(), GetSpacing(), m_ViewSettings->GetViewportCenter());
}
}
/******************************************************************************/
void ImageViewManipulator::KeyReleaseEvent(QKeyEvent*)
{
// assert( e!=NULL );
// qDebug() << this << "::KeyPressEvent(" << e << ")";
}
/******************************************************************************/
void ImageViewManipulator::Translate(const QPoint& vector)
{
// qDebug() << this << "::Translate(" << vector << ")";
m_ViewSettings->SetOrigin(ImageViewManipulator::Translate(vector, m_ViewSettings->GetOrigin(), m_ViewSettings->GetSpacing()));
}
/******************************************************************************/
PointType ImageViewManipulator::Translate(const QPoint& vector, const PointType& origin, const SpacingType& spacing)
{
// qDebug() << this << "::Translate(...)";
otb::ViewSettings::PointType origin2(origin);
origin2[0] += static_cast<double>(vector.x()) * spacing[0];
origin2[1] += static_cast<double>(vector.y()) * spacing[1];
/*
qDebug()
<< "(" << m_MousePressOrigin[ 0 ] << "," << m_MousePressOrigin[ 1 ] << ")"
<< "(" << spacing[ 0 ] << "," << spacing[ 1 ] << ")"
<< "(" << origin[ 0 ] << "," << origin[ 1 ] << ")";
*/
return origin2;
}
/******************************************************************************/
void ImageViewManipulator::Scale(const QPoint& center, int degrees, PointType* centerPoint)
{
assert(degrees != 0);
if (degrees == 0)
return;
otb::ViewSettings::PointType point;
Transform(point, center);
if (centerPoint != NULL)
*centerPoint = point;
// See http://qt-project.org/doc/qt-4.8/qwheelevent.html#delta .
assert(m_ZoomGranularity != 0);
int granularity = m_ZoomGranularity;
if (granularity == 0)
granularity = 1;
double factor = pow(2.0, -static_cast<double>(degrees) / static_cast<double>(granularity * MOUSE_WHEEL_STEP_DEGREES));
m_ZoomFactor *= factor;
/*
qDebug()
<< "(" << point[ 0 ] << "," << point[ 1 ] << ")"
<< "g:" << granularity
<< "d:" << degrees
<< "s:" << (static_cast< double >( degrees ) / 15.0)
<< "f:" << factor
<< "z:" << m_ZoomFactor;
*/
m_ViewSettings->Zoom(point, factor);
}
/*****************************************************************************/
ZoomType ImageViewManipulator::GetFixedZoomType() const
{
return ZOOM_TYPE_NONE;
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
void ImageViewManipulator::OnTimeout()
{
assert(m_Timer != NULL);
SetFastRenderMode(false);
Q_EMIT RefreshViewRequested();
delete m_Timer;
m_Timer = NULL;
}
} // end namespace 'mvd'
| 27.510808 | 151 | 0.596394 | [
"vector",
"transform"
] |
c0667ba684037f9873106ec34a3c850dda6af0ea | 16,434 | hpp | C++ | include/nix/valid/checks.hpp | gicmo/nix | 17a5b90e6c12a22e921c181b79eb2a3db1bf61af | [
"BSD-3-Clause"
] | 1 | 2019-08-17T21:19:13.000Z | 2019-08-17T21:19:13.000Z | include/nix/valid/checks.hpp | tapaswenipathak/nix | 4565c2d7b363f27cac88932b35c085ee8fe975a1 | [
"BSD-3-Clause"
] | 2 | 2017-05-30T21:35:54.000Z | 2017-06-01T10:53:23.000Z | include/nix/valid/checks.hpp | gicmo/nix | 17a5b90e6c12a22e921c181b79eb2a3db1bf61af | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_CHECKS_H
#define NIX_CHECKS_H
#include <nix/util/util.hpp>
#include <nix/valid/helper.hpp>
#include <nix/base/IDimensions.hpp>
#include <nix/types.hpp>
#include <boost/optional.hpp>
#include <boost/any.hpp>
namespace nix {
namespace valid {
/**
* @brief Check if later given not greater than initally defined value.
*
* One Check struct that checks whether the given value is not greater
* than the initially given other value, both of which have to be
* convertible to double.
*/
struct notGreater {
const double value;
template<typename T>
notGreater(T value) : value(static_cast<double>(value)) {}
template<typename T2>
bool operator()(const T2 &val) const {
return !(static_cast<double>(val) > value);
}
};
/**
* @brief Check if later given greater than initally defined value.
*
* One Check struct that checks whether the given value is greater than
* the initially given other value, both of which have to be
* convertible to double.
*/
struct isGreater {
const double value;
template<typename T>
isGreater(T value) : value(static_cast<double>(value)) {}
template<typename T2>
bool operator()(const T2 &val) const {
return static_cast<double>(val) > value;
}
};
/**
* @brief Check if later given not smaller than initally defined value.
*
* One Check struct that checks whether the given value is not smaller
* than the initially given other value, both of which have to be
* convertible to double.
*/
struct notSmaller {
const double value;
template<typename T>
notSmaller(T value) : value(static_cast<double>(value)) {}
template<typename T2>
bool operator()(const T2 &val) const {
return !(static_cast<double>(val) < value);
}
};
/**
* @brief Check if later given smaller than initally defined value.
*
* One Check struct that checks whether the given value is smaller than
* the initially given other value, both of which have to be
* convertible to double.
*/
struct isSmaller {
const double value;
template<typename T>
isSmaller(T value) : value(static_cast<double>(value)) {}
template<typename T2>
bool operator()(const T2 &val) const {
return static_cast<double>(val) < value;
}
};
/**
* @brief Check for un-equality of initally defined and later given value.
*
* One Check struct that checks whether the given value is not equal
* to the initially given other value.
*/
template<typename T>
struct notEqual {
const T value;
notEqual(T value) : value(value) {}
template<typename T2>
bool operator()(const T2 &val) const {
return value != val;
}
};
/**
* @brief Check for equality of initally defined and later given value.
*
* One Check struct that checks whether the given value is equal to
* the initially given other value.
*/
template<typename T>
struct isEqual {
const T value;
isEqual(T value) : value(value) {}
template<typename T2>
bool operator()(const T2 &val) const {
return value == val;
}
};
// needed because: for bizarre reasons bool converts to int when compared to boost::optional
template<>
struct isEqual<bool> {
const bool value;
isEqual(bool value) : value(value) {}
template<typename T2>
bool operator()(const T2 &val) const {
return value ? !!val : !val;
}
};
/**
* @brief Check if given value casts to boolean true
*
* One Check struct that checks whether the given value casts to true
* or to false.
* T can be: boost::optional, boost::none, nix-entity
* and any basic type.
*/
struct notFalse {
// WARNING: enum will convert via int, which means 0 = false !
template<typename T>
bool operator()(const T &val) const {
return !!val;
}
};
/**
* @brief Check if given value casts to boolean false
*
* One Check struct that checks whether the given value casts to false
* or to true.
* T can be: boost::optional, boost::none, nix-entity
* and any basic type.
*/
struct isFalse {
// WARNING: enum will convert via int, which means 0 = false !
template<typename T>
bool operator()(const T &val) const {
return !val;
}
};
/**
* @brief Check if given class/struct returns "empty() == false"
*
* One Check struct that checks whether the given value is not empty
* or is empty.
* T can be: any STL container.
*/
struct notEmpty {
template<typename T>
bool operator()(const T &val) const {
return !(val.empty());
}
};
/**
* @brief Check if given class/struct returns "empty() == true"
*
* One Check struct that checks whether the given value is empty or
* not.
* T can be: any STL container.
*/
struct isEmpty {
template<typename T>
bool operator()(const T &val) const {
return val.empty();
}
};
/**
* @brief Check if given class represents valid SI unit string(s)
*
* Base struct to be inherited by the {@link isValidUnit}, {@link
* isAtomicUnit}, {@link isCompoundUnit}. Not viable on its own!
*/
struct isUnit {
typedef std::function<bool(std::string)> TPRED;
virtual bool operator()(const std::string &u) const = 0;
bool operator()(const boost::optional<std::string> &u) const {
// note: relying on short-curcuiting here
return u && (*this)(*u);
}
bool operator()(const std::vector<std::string> &u, TPRED obj) const {
// if test succeeds find_if_not will not find anything & return it == end
return std::find_if_not(u.begin(), u.end(), obj) == u.end();
}
virtual ~isUnit() { }
};
/**
* @brief Check if given class represents valid SI unit string(s)
*
* One Check struct that checks whether the given string(s) represent(s)
* a valid atomic or compound SI unit.
* Parameter can be of type boost optional (containing nothing or
* string) or of type string or a vector of strings.
*/
struct isValidUnit : public isUnit {
bool operator()(const std::string &u) const {
return (util::isSIUnit(u) || util::isCompoundSIUnit(u));
}
bool operator()(const boost::optional<std::string> &u) const {
return isUnit::operator()(u);
}
bool operator()(const std::vector<std::string> &u) const {
return isUnit::operator()(u, *this);
}
};
/**
* @brief Check if given class represents valid atomic SI unit string(s)
*
* One Check struct that checks whether the given string(s) represent(s)
* a valid atomic SI unit.
* Parameter can be of type boost optional (containing nothing or
* string) or of type string or a vector of strings.
*/
struct isAtomicUnit : public isUnit {
bool operator()(const std::string &u) const {
return util::isSIUnit(u);
}
bool operator()(const boost::optional<std::string> &u) const {
return isUnit::operator()(u);
}
bool operator()(const std::vector<std::string> &u) const {
return isUnit::operator()(u, *this);
}
};
/**
* @brief Check if given class represents valid compound SI unit string(s)
*
* One Check struct that checks whether the given string(s) represent(s)
* a valid compound SI unit.
* Parameter can be of type boost optional (containing nothing or
* string) or of type string or a vector of strings.
*/
struct isCompoundUnit : public isUnit {
bool operator()(const std::string &u) const {
return util::isCompoundSIUnit(u);
}
bool operator()(const boost::optional<std::string> &u) const {
return isUnit::operator()(u);
}
bool operator()(const std::vector<std::string> &u) const {
return isUnit::operator()(u, *this);
}
};
/**
* @brief Check if given value can be regarded as being set
*
* One Check struct that checks whether the given value can be
* considered set, by applying {@link notFalse} and {@link notEmpty}
* checks. Value thus is set if: STL cotnainer not empty OR
* bool is true OR boost optional is set OR number is not 0.
* Parameter can be of above types or even boost none_t.
* NOTE: use this if you don't know wheter a type has and "empty"
* method.
*/
struct isSet {
template<typename T>
bool operator()(const T &val) const {
typedef typename std::conditional<hasEmpty<T>::value, notEmpty, notFalse>::type subCheck;
return subCheck(val);
}
};
/**
* @brief Check if given container is sorted using std::is_sorted
*
* One Check struct that checks whether the given container is sorted
* according to std::is_sorted. Thus supports types that are
* supported by std::is_sorted.
*/
struct isSorted {
template<typename T>
bool operator()(const T &container) const {
return std::is_sorted(container.begin(), container.end());
}
};
/**
* @brief Check if given DataArray has given dimensionality
*
* One Check struct that checks whether the given DataArray entity
* has a dimensionality of the given uint value by getting its'
* NDSize class via the "dataExtent" method and checking its' size
* via "size" the method.
*/
struct NIXAPI dimEquals {
size_t value;
dimEquals(const size_t &value) : value(value) {}
bool operator()(const DataArray &array) const;
};
/**
* @brief Check if given DataArrays' dimensions all have units where given units vector has
*
* One Check struct that checks whether the given referenced
* DataArrays' dimensions all have units defined where the tag has.
* (where the tag has means at the same index in the tag's units
* vector as the dimension index in the referenced DataArray)
* Therefore it takes all non-SetDimension dimensions of all given
* references and checks whether the dimension has a unit set if the
* tag has. If a dimension is a SetDimension the test counts as
* passed. Thus in the end the test counts as passed if all non-
* SetDimension dimensions have units set where the tag has and
* have no units set where the tag has not. It counts as failed
* immediately if number of dimensions differs from number of units
* in given unit vector.
*/
struct NIXAPI tagRefsHaveUnits {
std::vector<std::string> units;
tagRefsHaveUnits(const std::vector<std::string> &units) : units(units) {}
bool operator()(const std::vector<DataArray> &references) const;
};
/**
* @brief Check if given units match given referenced DataArrays' units
*
* One Check struct that checks whether the given units (vector of
* strings) match the given referenced DataArrays' (vector of
* DataArray references) units. Therefore it takes all non-
* SetDimension dimensions of all given references and checks
* whether the dimension has a unit convertible to the unit with the
* same index in the given units vector. If a dimension is a
* SetDimension the test counts as passed. Thus in the end the test
* counts as passed if all non-SetDimension dimensions have units
* set that are convertible where the units vector has a unit set
* and all dims have no unit set where the units vector has not.
* The test counts as failed immediately if the number of dimensions
* in a DataArray differs the number of units in the units vector.
*/
struct NIXAPI tagUnitsMatchRefsUnits {
std::vector<std::string> units;
tagUnitsMatchRefsUnits(const std::vector<std::string> &units) : units(units) {}
bool operator()(const std::vector<DataArray> &references) const;
};
/**
* @brief Check if given number of positions and extents matches
*
* One Check struct that checks whether the given number of
* positions matches the given number of extents. It is irrelevant
* which gets passed at construction time and which via operator().
*/
struct NIXAPI extentsMatchPositions {
boost::any extents;
extentsMatchPositions(const DataArray &extents) : extents(extents) {}
extentsMatchPositions(const std::vector<double> &extents) : extents(extents) {}
bool operator()(const DataArray &positions) const;
bool operator()(const std::vector<double> &positions) const;
};
/**
* @brief Check if number of extents (along 2nd dim) match number of references' data dims
*
* One Check struct that checks whether the given number of
* extents (if DataArray: size along 2nd dimensions of extents
* DataArray; if vector: size of vector) matches the data's
* dimensionality in each of the given referenced DataArrays.
*/
struct NIXAPI extentsMatchRefs {
std::vector<DataArray> refs;
extentsMatchRefs(const std::vector<DataArray> &refs) : refs(refs) {}
bool operator()(const DataArray &extents) const;
bool operator()(const std::vector<double> &extents) const;
};
/**
* @brief Check if number of positions (along 2nd dim) match number of references' data dims
*
* One Check struct that checks whether the given number of
* positions (if DataArray: size along 2nd dimensions of positions
* DataArray; if vector: size of vector) matches the data's
* dimensionality in each of the given referenced DataArrays.
* Note: this is just an alias for extentsMatchRefs wich does the
* same thing.
*/
struct NIXAPI positionsMatchRefs {
std::vector<DataArray> refs;
positionsMatchRefs(const std::vector<DataArray> &refs) : refs(refs) {}
bool operator()(const DataArray &positions) const;
bool operator()(const std::vector<double> &positions) const;
};
/**
* @brief Check if range dimension specifics ticks match data
*
* One Check struct that checks whether the dimensions of type
* "Range" in the given dimensions vector have ticks that match
* the given DataArray's data: number of ticks == number of entries
* along the corresponding dimension in the data.
*/
struct NIXAPI dimTicksMatchData {
const DataArray &data;
dimTicksMatchData(const DataArray &data) : data(data) {}
bool operator()(const std::vector<Dimension> &dims) const;
};
/**
* @brief Check if set dimension specifics labels match data
*
* One Check struct that checks whether the dimensions of type
* "Set" in the given dimensions vector have labels that match
* the given DataArray's data: number of labels == number of entries
* along the corresponding dimension in the data.
*/
struct NIXAPI dimLabelsMatchData {
const DataArray &data;
dimLabelsMatchData(const DataArray &data) : data(data) {}
bool operator()(const std::vector<Dimension> &dims) const;
};
} // namespace valid
} // namespace nix
#endif // NIX_CHECKS_H
| 34.2375 | 101 | 0.617074 | [
"vector"
] |
c06b3e26b1065951ed2423c85cc0b1bc464a8541 | 10,740 | cpp | C++ | test/maybe.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | test/maybe.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | test/maybe.cpp | josephwinston/hana | a8586ec1812e14e43dfd6867209412aa1d254e1a | [
"BSL-1.0"
] | null | null | null | /*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/maybe.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/functional/always.hpp>
#include <boost/hana/functional/compose.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <test/auto/applicative.hpp>
#include <test/auto/base.hpp>
#include <test/auto/comparable.hpp>
#include <test/auto/foldable.hpp>
#include <test/auto/functor.hpp>
#include <test/auto/monad.hpp>
#include <test/auto/monad_plus.hpp>
#include <test/auto/orderable.hpp>
#include <test/auto/searchable.hpp>
#include <test/auto/traversable.hpp>
#include <test/cnumeric.hpp>
#include <test/identity.hpp>
#include <test/injection.hpp>
#include <type_traits>
using namespace boost::hana;
template <int i>
constexpr auto ord = test::cnumeric<int, i>;
namespace boost { namespace hana { namespace test {
template <>
auto instances<Maybe> = make<Tuple>(
type<Comparable>,
type<Orderable>,
type<Functor>,
type<Applicative>,
type<Monad>,
type<MonadPlus>,
type<Traversable>,
type<Foldable>,
type<Searchable>
);
template <>
auto objects<Maybe> = make<Tuple>(
nothing,
just(ord<0>),
just(ord<1>),
just(ord<2>)
);
}}}
template <typename ...>
using void_t = void;
template <typename T, typename = void>
struct has_type : std::false_type { };
template <typename T>
struct has_type<T, void_t<typename T::type>>
: std::true_type
{ };
int main() {
test::check_datatype<Maybe>();
constexpr struct { } undefined{};
// Maybe interface
{
auto f = test::injection([]{});
auto x = test::injection([]{})();
auto y = test::injection([]{})();
// Interaction with Type (has a nested ::type)
{
struct T;
static_assert(std::is_same<decltype(just(type<T>))::type, T>{}, "");
static_assert(!has_type<decltype(nothing)>{}, "");
}
// maybe
{
BOOST_HANA_CONSTANT_CHECK(equal(maybe(x, undefined, nothing), x));
BOOST_HANA_CONSTANT_CHECK(equal(maybe(undefined, f, just(x)), f(x)));
}
// is_nothing
{
BOOST_HANA_CONSTANT_CHECK(is_nothing(nothing));
BOOST_HANA_CONSTANT_CHECK(not_(is_nothing(just(undefined))));
}
// is_just
{
BOOST_HANA_CONSTANT_CHECK(is_just(just(undefined)));
BOOST_HANA_CONSTANT_CHECK(not_(is_just(nothing)));
}
// from_just
{
BOOST_HANA_CONSTANT_CHECK(equal(from_just(just(x)), x));
// from_just(nothing);
}
// from_maybe
{
BOOST_HANA_CONSTANT_CHECK(equal(from_maybe(x, nothing), x));
BOOST_HANA_CONSTANT_CHECK(equal(from_maybe(undefined, just(y)), y));
}
// only_when
{
BOOST_HANA_CONSTANT_CHECK(equal(
only_when(always(true_), f, x),
just(f(x))
));
BOOST_HANA_CONSTANT_CHECK(equal(
only_when(always(false_), f, x),
nothing
));
BOOST_HANA_CONSTANT_CHECK(equal(
only_when(always(false_), undefined, x),
nothing
));
}
// sfinae
{
struct invalid { };
auto f = test::injection([]{});
using test::x;
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(f)(),
just(f())
));
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(f)(x<0>),
just(f(x<0>))
));
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(f)(x<0>, x<1>),
just(f(x<0>, x<1>))
));
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(invalid{})(),
nothing
));
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(invalid{})(x<0>),
nothing
));
BOOST_HANA_CONSTANT_CHECK(equal(
sfinae(invalid{})(x<0>, x<1>),
nothing
));
BOOST_HANA_CONSTEXPR_LAMBDA auto incr = sfinae([](auto x) -> decltype(x + 1) {
return x + 1;
});
BOOST_HANA_CONSTEXPR_CHECK(equal(
incr(1), just(2)
));
BOOST_HANA_CONSTANT_CHECK(equal(
incr(invalid{}), nothing
));
BOOST_HANA_CONSTEXPR_CHECK(equal(
bind(just(1), incr), just(2)
));
}
}
// Comparable
{
// equal
{
auto x = test::injection([]{})();
auto y = test::injection([]{})();
BOOST_HANA_CONSTANT_CHECK(equal(nothing, nothing));
BOOST_HANA_CONSTANT_CHECK(not_(equal(nothing, just(x))));
BOOST_HANA_CONSTANT_CHECK(not_(equal(just(x), nothing)));
BOOST_HANA_CONSTANT_CHECK(equal(just(x), just(x)));
BOOST_HANA_CONSTANT_CHECK(not_(equal(just(x), just(y))));
}
}
// Orderable
{
// less
{
BOOST_HANA_CONSTANT_CHECK(less(nothing, just(undefined)));
BOOST_HANA_CONSTANT_CHECK(not_(less(just(undefined), nothing)));
BOOST_HANA_CONSTANT_CHECK(not_(less(nothing, nothing)));
BOOST_HANA_CONSTANT_CHECK(less(just(ord<0>), just(ord<1>)));
BOOST_HANA_CONSTANT_CHECK(not_(less(just(ord<0>), just(ord<0>))));
BOOST_HANA_CONSTANT_CHECK(not_(less(just(ord<1>), just(ord<0>))));
}
}
// Functor
{
// transform
{
auto f = test::injection([]{});
auto x = test::injection([]{})();
BOOST_HANA_CONSTANT_CHECK(equal(transform(nothing, f), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(transform(just(x), f), just(f(x))));
}
}
// Applicative
{
auto f = test::injection([]{});
auto x = test::injection([]{})();
// ap
{
BOOST_HANA_CONSTANT_CHECK(equal(ap(nothing, nothing), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(ap(just(f), nothing), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(ap(nothing, just(x)), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(ap(just(f), just(x)), just(f(x))));
}
// lift
{
BOOST_HANA_CONSTANT_CHECK(equal(lift<Maybe>(x), just(x)));
}
}
// Monad
{
// flatten
{
auto x = test::injection([]{})();
BOOST_HANA_CONSTANT_CHECK(equal(flatten(nothing), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(flatten(just(nothing)), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(flatten(just(just(x))), just(x)));
}
}
// MonadPlus
{
using test::x;
// empty
{
BOOST_HANA_CONSTANT_CHECK(equal(empty<Maybe>(), nothing));
}
// concat
{
auto rv_nothing = [] { return nothing; }; // rvalue nothing
BOOST_HANA_CONSTANT_CHECK(equal(concat(rv_nothing(), nothing), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(concat(nothing, rv_nothing()), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(concat(rv_nothing(), rv_nothing()), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(concat(rv_nothing(), just(x<0>)), just(x<0>)));
BOOST_HANA_CONSTANT_CHECK(equal(concat(just(x<0>), rv_nothing()), just(x<0>)));
BOOST_HANA_CONSTANT_CHECK(equal(concat(nothing, nothing), nothing));
BOOST_HANA_CONSTANT_CHECK(equal(concat(nothing, just(x<0>)), just(x<0>)));
BOOST_HANA_CONSTANT_CHECK(equal(concat(just(x<0>), nothing), just(x<0>)));
BOOST_HANA_CONSTANT_CHECK(equal(concat(just(x<0>), just(x<1>)), just(x<0>)));
}
}
// Traversable
{
auto f = test::injection([]{});
auto x = test::injection([]{})();
auto applicative = test::identity;
using A = test::Identity;
// traverse
{
BOOST_HANA_CONSTANT_CHECK(equal(
traverse<A>(just(x), compose(applicative, f)),
applicative(just(f(x)))
));
BOOST_HANA_CONSTANT_CHECK(equal(
traverse<A>(nothing, compose(applicative, f)),
applicative(nothing)
));
}
}
// Searchable
{
auto x = test::injection([]{})();
auto y = test::injection([]{})();
// find_if
{
BOOST_HANA_CONSTANT_CHECK(equal(
find_if(just(x), equal.to(x)),
just(x)
));
BOOST_HANA_CONSTANT_CHECK(equal(
find_if(just(x), equal.to(y)),
nothing
));
BOOST_HANA_CONSTANT_CHECK(equal(
find_if(nothing, equal.to(x)),
nothing
));
// Previously, there was a bug that would make this fail.
auto non_const_nothing = nothing;
BOOST_HANA_CONSTANT_CHECK(equal(
find_if(non_const_nothing, equal.to(x)),
nothing
));
}
// any_of
{
BOOST_HANA_CONSTANT_CHECK(any_of(just(x), equal.to(x)));
BOOST_HANA_CONSTANT_CHECK(not_(any_of(just(x), equal.to(y))));
BOOST_HANA_CONSTANT_CHECK(not_(any_of(nothing, equal.to(x))));
}
}
// Foldable
{
auto x = test::injection([]{})();
auto s = test::injection([]{})();
auto f = test::injection([]{});
// foldl
{
BOOST_HANA_CONSTANT_CHECK(equal(foldl(just(x), s, f), f(s, x)));
BOOST_HANA_CONSTANT_CHECK(equal(foldl(nothing, s, f), s));
}
// foldr
{
BOOST_HANA_CONSTANT_CHECK(equal(foldr(just(x), s, f), f(x, s)));
BOOST_HANA_CONSTANT_CHECK(equal(foldr(nothing, s, f), s));
}
// unpack
{
BOOST_HANA_CONSTANT_CHECK(equal(unpack(nothing, f), f()));
BOOST_HANA_CONSTANT_CHECK(equal(unpack(just(x), f), f(x)));
// Previously, there was a bug that would make this fail.
auto non_const_nothing = nothing;
BOOST_HANA_CONSTANT_CHECK(equal(unpack(non_const_nothing, f), f()));
}
}
}
| 28.716578 | 91 | 0.535475 | [
"transform"
] |
c072d4ba4db4bfbdc60857dfbbf4f4e01ee6256a | 8,838 | cpp | C++ | src/gpio_node.cpp | slaghuis/ground_control | ce8dba7f16c1c03756b78612cc8e23a7bd9ea494 | [
"Apache-2.0"
] | null | null | null | src/gpio_node.cpp | slaghuis/ground_control | ce8dba7f16c1c03756b78612cc8e23a7bd9ea494 | [
"Apache-2.0"
] | null | null | null | src/gpio_node.cpp | slaghuis/ground_control | ce8dba7f16c1c03756b78612cc8e23a7bd9ea494 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 Xeni Robotics
//
// 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.
/* *********************************************************************************
* Published a ground_control/gpio_write service for ground_control::msg::GpioWrite
* messages and sets the the mentioned GPIO Hi or Low as directed by the message
* content. This can be used to run a buzzer or to light a LED connected to the
* respected GPIO port on the Rasbberry PI
*
* Published a ground_control/gpio_read service for ground_control::msg::GpioRead
* messages and returns the mentioned GPIO Hi or Low status.
* This can be used to read the switch status connected to the respected GPIO port
* on the Rasbberry PI
*
* Code adopted from Tiny GPIO Access - https://abyz.me.uk/rpi/pigpio/examples.html
* *********************************************************************************/
#include <memory>
#include <vector> //std::vector
#include <algorithm> //std::find
#include <sys/mman.h> //MAP_FAILED
#include <unistd.h>
#include <stdio.h> // open() to access /dev/gpio*
#include <fcntl.h> // Flow control
#include "rclcpp/rclcpp.hpp"
#include "ground_control/srv/gpio_read.hpp"
#include "ground_control/srv/gpio_write.hpp"
#define GPSET0 7
#define GPSET1 8
#define GPCLR0 10
#define GPCLR1 11
#define GPLEV0 13
#define GPLEV1 14
#define GPPUD 37
#define GPPUDCLK0 38
#define GPPUDCLK1 39
#define PI_BANK (gpio>>5)
#define PI_BIT (1<<(gpio&0x1F))
/* gpio modes. */
#define PI_INPUT 0
#define PI_OUTPUT 1
#define PI_ALT0 4
#define PI_ALT1 5
#define PI_ALT2 6
#define PI_ALT3 7
#define PI_ALT4 3
#define PI_ALT5 2
/* Values for pull-ups/downs off, pull-down and pull-up. */
#define PI_PUD_OFF 0
#define PI_PUD_DOWN 1
#define PI_PUD_UP 2
using namespace std::chrono_literals;
using GPIOWrite = ground_control::srv::GpioWrite;
using GPIORead = ground_control::srv::GpioRead;
class GpioService : public rclcpp::Node
{
public:
GpioService()
: Node("gpio_service")
{
this->declare_parameter("writeable_gpio_pins", std::vector<int64_t>{17, 27, 22}) ;
this->declare_parameter("readable_gpio_pins", std::vector<int64_t>{5, 6}) ;
one_off_timer_ = this->create_wall_timer(
500ms, std::bind(&GpioService::init, this));
}
private:
void init()
{
// Only run this once. Stop the timer that triggered this.
this->one_off_timer_->cancel();
// Initialise GPIO
if (gpio_initialise() < 0) {
// No need for this node if it cannot address my GPIO. Shutdown.
rclcpp::shutdown();
return;
}
RCLCPP_INFO(
this->get_logger(),
"Pi model = %d, Pi revision = %d\n", piModel, piRev);
// Read ROS parameters
rclcpp::Parameter write_pins = this->get_parameter("writeable_gpio_pins");
writeable_pins = write_pins.as_integer_array();
rclcpp::Parameter read_pins = this->get_parameter("readable_gpio_pins");
readable_pins = read_pins.as_integer_array();
// Setup the writeable GPIO pins
for (auto it : writeable_pins) {
gpio_set_mode(it, PI_OUTPUT);
}
// Setup the GPIO pins
for (auto it : readable_pins) {
gpio_set_mode(it, PI_INPUT);
}
// Start the services. Open for business.
write_servcie_ = this->create_service<GPIOWrite>("ground_control/gpio_write",
std::bind(&GpioService::handle_write_service,this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
read_servcie_ = this->create_service<GPIORead>("ground_control/gpio_read",
std::bind(&GpioService::handle_read_service,this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
void handle_write_service(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<GPIOWrite::Request> request,
const std::shared_ptr<GPIOWrite::Response> response)
{
(void)request_header;
if (request->number < (signed char) writeable_pins.size() ) {
RCLCPP_INFO(
this->get_logger(),
"Adjusting GPIO number %i", writeable_pins[request->number]);
if (request->high) {
gpio_write(writeable_pins[request->number],1);
} else {
gpio_write(writeable_pins[request->number],0);
}
response->result = true;
} else {
RCLCPP_ERROR(
this->get_logger(),
"Specified LED %i out of range [0..%i]", request->number, writeable_pins.size()-1 );
response->result = false;
}
}
void handle_read_service(
const std::shared_ptr<rmw_request_id_t> request_header,
const std::shared_ptr<GPIORead::Request> request,
const std::shared_ptr<GPIORead::Response> response)
{
(void)request_header;
if (request->number < (signed char) readable_pins.size() ) {
RCLCPP_INFO(
this->get_logger(),
"Reading GPIO number %i", readable_pins[request->number]);
response->high = (gpio_read(readable_pins[request->number]) == 1);
response->result = true;
} else {
RCLCPP_ERROR(
this->get_logger(),
"Specified SIWTCH %i out of range [0..%i]", request->number, readable_pins.size()-1 );
response->result = false;
}
}
// GPIO SPECIFIC ROUTINES //////////////////////////////////////////////////////////////////////
unsigned gpio_hardware_revision(void)
{
static unsigned rev = 0;
FILE * filp;
char buf[512];
char term;
int chars=4; /* number of chars in revision string */
if (rev) return rev;
piModel = 0;
filp = fopen ("/proc/cpuinfo", "r");
if (filp != NULL)
{
while (fgets(buf, sizeof(buf), filp) != NULL)
{
if (piModel == 0)
{
if (!strncasecmp("model name", buf, 10))
{
if (strstr (buf, "ARMv6") != NULL)
{
piModel = 1;
chars = 4;
}
else if (strstr (buf, "ARMv7") != NULL)
{
piModel = 2;
chars = 6;
}
else if (strstr (buf, "ARMv8") != NULL)
{
piModel = 2;
chars = 6;
}
}
}
if (!strncasecmp("revision", buf, 8))
{
if (sscanf(buf+strlen(buf)-(chars+1),
"%x%c", &rev, &term) == 2)
{
if (term != '\n') rev = 0;
}
}
}
fclose(filp);
}
return rev;
}
int gpio_initialise(void)
{
int fd;
piRev = gpio_hardware_revision(); /* sets piModel and piRev */
fd = open("/dev/gpiomem", O_RDWR | O_SYNC) ;
if (fd < 0)
{
RCLCPP_ERROR(this->get_logger(), "Failed to open /dev/gpiomem");
return -1;
}
gpioReg = (uint32_t *)mmap(NULL, 0xB4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (gpioReg == MAP_FAILED)
{
RCLCPP_ERROR(this->get_logger(), "Bad, mmap failed");
return -1;
}
return 0;
}
void gpio_set_mode(unsigned gpio, unsigned mode)
{
int reg, shift;
reg = gpio/10;
shift = (gpio%10) * 3;
gpioReg[reg] = (gpioReg[reg] & ~(7<<shift)) | (mode<<shift);
}
void gpio_write(unsigned gpio, unsigned level)
{
if (level == 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT;
else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT;
}
int gpio_read(unsigned gpio)
{
if ((*(gpioReg + GPLEV0 + PI_BANK) & PI_BIT) != 0) return 1;
else return 0;
}
// PRIVATE VARIABLES ///////////////////////////////////////////////////////////////////
uint32_t *gpioReg; // = MAP_FAILED
std::vector<int64_t> writeable_pins;
std::vector<int64_t> readable_pins;
rclcpp::Service<GPIOWrite>::SharedPtr write_servcie_;
rclcpp::Service<GPIORead>::SharedPtr read_servcie_;
rclcpp::TimerBase::SharedPtr one_off_timer_;
unsigned piModel;
unsigned piRev;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<GpioService>());
rclcpp::shutdown();
return 0;
}
| 28.326923 | 131 | 0.588255 | [
"vector",
"model"
] |
c0776cd32e209809758c332da5bd9f3f10696b3b | 26,711 | cpp | C++ | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstackprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstackprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstackprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "zstackprocessor.h"
#include "zstack.hxx"
#include "tz_stack_attribute.h"
#include "tz_stack_bwmorph.h"
#include "zspgrowparser.h"
#include "tz_stack_stat.h"
#include "tz_stack_lib.h"
#include "tz_stack_math.h"
#include "tz_utilities.h"
#include "tz_math.h"
#if _QS_LOG_AVAILABLE_
# include "QsLog.h"
#endif
#include "tz_stack.h"
#include "tz_stack_math.h"
ZStackProcessor::ZStackProcessor()
{
}
void ZStackProcessor::distanceTransform(ZStack *stack, bool isSquared,
bool sliceWise)
{
Stack *distanceMap = NULL;
if (sliceWise) {
distanceMap = Stack_Bwdist_L_U16P(stack->c_stack(), NULL, 0);
} else {
distanceMap = Stack_Bwdist_L_U16(stack->c_stack(), NULL, 0);
}
if (!isSquared) {
uint16_t *array16 = (uint16_t*) distanceMap->array;
size_t volume = Stack_Volume(distanceMap);
for (size_t i = 0; i < volume; i++) {
array16[i] = (uint16_t) fmin2(sqrt(array16[i]), 255.0f);
}
}
stack->load(distanceMap, true);
}
void ZStackProcessor::shortestPathFlow(ZStack *stack)
{
Stack *stackData = stack->c_stack();
Stack *tmpdist = Stack_Bwdist_L_U16P(stackData, NULL, 0);
Sp_Grow_Workspace *sgw = New_Sp_Grow_Workspace();
sgw->wf = Stack_Voxel_Weight_I;
size_t max_index;
Stack_Max(tmpdist, &max_index);
Stack *mask = Make_Stack(GREY, Stack_Width(tmpdist), Stack_Height(tmpdist),
Stack_Depth(tmpdist));
Zero_Stack(mask);
size_t nvoxel = Stack_Voxel_Number(stackData);
size_t i;
for (i = 0; i < nvoxel; i++) {
if (stackData->array[i] == 0) {
mask->array[i] = SP_GROW_BARRIER;
}
}
mask->array[max_index] = SP_GROW_SOURCE;
Sp_Grow_Workspace_Set_Mask(sgw, mask->array);
Stack_Sp_Grow(tmpdist, NULL, 0, NULL, 0, sgw);
ZSpGrowParser parser(sgw);
stack->load(parser.createDistanceStack());
Kill_Stack(mask);
Kill_Stack(tmpdist);
}
void ZStackProcessor::mexihatFilter(ZStack *stack, double sigma)
{
Stack *stackData = stack->c_stack();
Filter_3d *filter = Mexihat_Filter_3d(sigma);
Stack *filtered = Filter_Stack(stackData, filter);
Kill_FMatrix(filter);
stack->load(filtered, true);
}
void ZStackProcessor::expandRegion(ZStack *stack, int r)
{
Stack *stackData = stack->c_stack();
Stack *out = Stack_Region_Expand_M(stackData, 8, r, NULL, NULL);
stack->load(out, true);
}
#if defined(_USE_ITK_)
#include <itkMedianImageFilter.h>
#include <itkCannyEdgeDetectionImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkRescaleIntensityImageFilter.h>
#include <itkGradientAnisotropicDiffusionImageFilter.h>
#include <itkCurvatureFlowImageFilter.h>
#include <itkMinMaxCurvatureFlowImageFilter.h>
#include <itkConnectedThresholdImageFilter.h>
#include <itkDiffusionTensor3D.h>
#include <itkMeasurementVectorTraits.h>
#include <itkGaussianRandomSpatialNeighborSubsampler.h>
#undef ASCII
#include <itkPatchBasedDenoisingImageFilter.h>
#define CONVERT_STACK(ImageType, VoxelType, ch) \
ImageType::RegionType region; \
ImageType::SizeType size; \
size[0] = stack->width(); \
size[1] = stack->height(); \
size[2] = stack->depth(); \
region.SetSize(size); \
image->SetRegions(size); \
image->GetPixelContainer()-> \
SetImportPointer((VoxelType*) stack->c_stack(ch)->array, \
Stack_Voxel_Number(stack->c_stack(ch)));
void ZStackProcessor::convertStack(ZStack *stack,
Uint8Image3DType *image)
{
CONVERT_STACK(Uint8Image3DType, uint8, 0);
}
void ZStackProcessor::convertStack(ZStack *stack,
Uint16Image3DType *image)
{
CONVERT_STACK(Uint16Image3DType, uint16, 0);
}
void ZStackProcessor::convertStack(ZStack *stack,
FloatImage3DType *image)
{
CONVERT_STACK(FloatImage3DType, float32, 0);
}
void ZStackProcessor::copyData(Uint8Image3DType *src, ZStack *dst, int ch)
{
uint8 *array = src->GetPixelContainer()->GetImportPointer();
dst->copyValue(array, dst->getByteNumber(ZStack::SINGLE_CHANNEL), ch);
}
void ZStackProcessor::copyData(Uint16Image3DType *src, ZStack *dst, int ch)
{
uint16 *array = src->GetPixelContainer()->GetImportPointer();
dst->copyValue(array, dst->getByteNumber(ZStack::SINGLE_CHANNEL), ch);
}
void ZStackProcessor::copyData(FloatImage3DType *src, ZStack *dst, int ch)
{
float *array = src->GetPixelContainer()->GetImportPointer();
dst->copyValue(array, dst->getByteNumber(ZStack::SINGLE_CHANNEL), ch);
}
void ZStackProcessor::convertStack(const ZStack *stack, int ch, Uint8Image3DType *image)
{
CONVERT_STACK(Uint8Image3DType, uint8, ch);
}
void ZStackProcessor::convertStack(const ZStack *stack, int ch, Uint16Image3DType *image)
{
CONVERT_STACK(Uint16Image3DType, uint16, ch);
}
void ZStackProcessor::convertStack(const ZStack *stack, int ch, FloatImage3DType *image)
{
CONVERT_STACK(FloatImage3DType, float32, ch);
}
void ZStackProcessor::medianFilter(ZStack *stack, int radius)
{
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::MedianImageFilter<Uint8Image3DType, Uint8Image3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
Uint8Image3DType::SizeType indexRadius;
indexRadius[0] = radius; // radius along x
indexRadius[1] = radius; // radius along y
indexRadius[2] = radius;
filter->SetRadius( indexRadius );
filter->SetInput(image);
filter->Update();
Uint8Image3DType::Pointer output = filter->GetOutput();
copyData(output, stack);
//stack->incrStamp();
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::MedianImageFilter<Uint16Image3DType, Uint16Image3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
Uint16Image3DType::SizeType indexRadius;
indexRadius[0] = radius; // radius along x
indexRadius[1] = radius; // radius along y
indexRadius[2] = radius;
filter->SetRadius( indexRadius );
filter->SetInput(image);
filter->Update();
Uint16Image3DType::Pointer output = filter->GetOutput();
copyData(output, stack);
//stack->incrStamp();
}
break;
default:
break;
}
}
}
void ZStackProcessor::cannyEdge(ZStack *stack, double variance, double low,
double high)
{
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::CastImageFilter<Uint8Image3DType, DoubleImage3DType>
CastToRealFilterType;
typedef itk::RescaleIntensityImageFilter<DoubleImage3DType, Uint8Image3DType>
RescaleFilter;
CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
RescaleFilter::Pointer rescale = RescaleFilter::New();
toReal->SetInput(image);
typedef itk::CannyEdgeDetectionImageFilter<DoubleImage3DType, DoubleImage3DType> FilterType;
FilterType::Pointer canny = FilterType::New();
canny->SetVariance(variance);
canny->SetLowerThreshold(low);
canny->SetUpperThreshold(high);
canny->SetInput(toReal->GetOutput());
rescale->SetInput(canny->GetOutput());
rescale->Update();
Uint8Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
//stack->incrStamp();
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::CastImageFilter<Uint16Image3DType, DoubleImage3DType>
CastToRealFilterType;
typedef itk::RescaleIntensityImageFilter<DoubleImage3DType, Uint16Image3DType>
RescaleFilter;
CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
RescaleFilter::Pointer rescale = RescaleFilter::New();
toReal->SetInput(image);
typedef itk::CannyEdgeDetectionImageFilter<DoubleImage3DType, DoubleImage3DType> FilterType;
FilterType::Pointer canny = FilterType::New();
canny->SetVariance(variance);
canny->SetLowerThreshold(low);
canny->SetUpperThreshold(high);
canny->SetInput(toReal->GetOutput());
rescale->SetInput(canny->GetOutput());
rescale->Update();
Uint16Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
//stack->incrStamp();
}
break;
default:
break;
}
}
}
void ZStackProcessor::anisotropicDiffusion(ZStack *stack, double timeStep,
double conductance, int niter)
{
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::GradientAnisotropicDiffusionImageFilter<Uint8Image3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint8Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
filter->SetConductanceParameter(conductance);
filter->SetTimeStep(timeStep);
filter->SetNumberOfIterations(niter);
filter->SetInput(image);
rescale->SetInput(filter->GetOutput());
rescale->Update();
Uint8Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::GradientAnisotropicDiffusionImageFilter<Uint16Image3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint16Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
filter->SetConductanceParameter(20.0);
filter->SetTimeStep(timeStep);
filter->SetNumberOfIterations(niter);
filter->SetInput(image);
rescale->SetInput(filter->GetOutput());
rescale->Update();
Uint16Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
default:
break;
}
//stack->incrStamp();
}
}
void ZStackProcessor::curvatureFlow(ZStack *stack, double timeStep, int niter)
{
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::CurvatureFlowImageFilter<Uint8Image3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint8Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
filter->SetTimeStep(timeStep);
filter->SetNumberOfIterations(niter);
filter->SetInput(image);
rescale->SetInput(filter->GetOutput());
rescale->Update();
Uint8Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::CurvatureFlowImageFilter<Uint16Image3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint16Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
filter->SetTimeStep(timeStep);
filter->SetNumberOfIterations(niter);
filter->SetInput(image);
rescale->SetInput(filter->GetOutput());
rescale->Update();
Uint16Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
default:
break;
}
//stack->incrStamp();
}
}
void ZStackProcessor::minMaxCurvatureFlow(ZStack *stack, double timeStep,
double radius, int niter)
{
#define MINMAXCURVATUREFLOW(ImageType) \
{ \
ImageType::Pointer image = ImageType::New(); \
convertStack(stack, image); \
typedef itk::MinMaxCurvatureFlowImageFilter<ImageType, FloatImage3DType> FilterType; \
FilterType::Pointer filter = FilterType::New(); \
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, ImageType> RescaleFilter; \
RescaleFilter::Pointer rescale = RescaleFilter::New(); \
filter->SetTimeStep(timeStep); \
filter->SetStencilRadius(radius); \
filter->SetNumberOfIterations(niter); \
filter->SetInput(image); \
rescale->SetInput(filter->GetOutput()); \
rescale->Update(); \
ImageType::Pointer output = rescale->GetOutput(); \
copyData(output, stack); \
}
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
MINMAXCURVATUREFLOW(Uint8Image3DType)
break;
case GREY16:
MINMAXCURVATUREFLOW(Uint16Image3DType)
break;
break;
default:
break;
}
}
}
void ZStackProcessor::connectedThreshold(ZStack *stack, int x, int y, int z,
int lower, int upper)
{
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::ConnectedThresholdImageFilter<Uint8Image3DType, Uint8Image3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
itk::Index<3> index;
index[0] = x;
index[1] = y;
index[2] = z;
filter->SetSeed(index);
filter->SetReplaceValue(1);
filter->SetLower(lower);
filter->SetUpper(upper);
filter->SetInput(image);
filter->Update();
copyData(filter->GetOutput(), stack);
//stack->incrStamp();
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::ConnectedThresholdImageFilter<Uint16Image3DType, Uint16Image3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
itk::Index<3> index;
index[0] = x;
index[1] = y;
index[2] = z;
filter->SetSeed(index);
filter->SetReplaceValue(1);
filter->SetLower(lower);
filter->SetUpper(upper);
filter->SetInput(image);
filter->Update();
copyData(filter->GetOutput(), stack);
//stack->incrStamp();
}
break;
default:
break;
}
//stack->incrStamp();
}
}
void ZStackProcessor::patchBasedDenoising(ZStack *stack, const int numIterations, const int numThreads,
const int numToSample, const float sigmaMultiplicationFactor,
const std::string noiseModel, const float fidelityWeight)
{
#if ITK_VERSION_MAJOR >= 4 && ITK_VERSION_MINOR >= 4
if (!stack->isVirtual()) {
switch (stack->data()->kind) {
case GREY:
{
Uint8Image3DType::Pointer image = Uint8Image3DType::New();
convertStack(stack, image);
typedef itk::RescaleIntensityImageFilter<Uint8Image3DType, FloatImage3DType> RescaleFilter0;
RescaleFilter0::Pointer rescale0 = RescaleFilter0::New();
rescale0->SetOutputMinimum(0.f);
rescale0->SetOutputMaximum(1.f);
typedef itk::PatchBasedDenoisingImageFilter<FloatImage3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint8Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
typedef itk::Statistics::GaussianRandomSpatialNeighborSubsampler<FilterType::PatchSampleType, FloatImage3DType::RegionType> SamplerType;
// patch radius is same for all dimensions of the image
const unsigned int patchRadius = 4;
filter->SetPatchRadius(patchRadius);
// instead of directly setting the weights, could also specify type
filter->UseSmoothDiscPatchWeightsOn();
//filter->UseFastTensorComputationsOn();
// noise model to use
if (noiseModel == "GAUSSIAN")
{
filter->SetNoiseModel(FilterType::GAUSSIAN);
}
else if (noiseModel == "RICIAN")
{
filter->SetNoiseModel(FilterType::RICIAN);
}
else if (noiseModel == "POISSON")
{
filter->SetNoiseModel(FilterType::POISSON);
}
// stepsize or weight for smoothing term
// Large stepsizes may cause instabilities.
filter->SetSmoothingWeight(1);
// stepsize or weight for fidelity term
// use a positive weight to prevent oversmoothing
// (penalizes deviations from noisy data based on a noise model)
filter->SetNoiseModelFidelityWeight(fidelityWeight);
// number of iterations over the image of denoising
filter->SetNumberOfIterations(numIterations);
// number of threads to use in parallel
filter->SetNumberOfThreads(numThreads);
// sampling the image to find similar patches
SamplerType::Pointer sampler = SamplerType::New();
// variance (in physical units) for semi-local Gaussian sampling
sampler->SetVariance(400);
// rectangular window restricting the Gaussian sampling
sampler->SetRadius(50); // 2.5 * standard deviation
// number of random sample "patches" to use for computations
sampler->SetNumberOfResultsRequested(numToSample);
// Sampler can be complete neighborhood sampler, random neighborhood sampler,
// Gaussian sampler, etc.
filter->SetSampler(sampler);
// automatic estimation of the kernel bandwidth
filter->KernelBandwidthEstimationOn();
// update bandwidth every 'n' iterations
filter->SetKernelBandwidthUpdateFrequency(3);
// use 33% of the pixels for the sigma update calculation
filter->SetKernelBandwidthFractionPixelsForEstimation(0.20);
// multiplication factor modifying the automatically-estimated kernel sigma
filter->SetKernelBandwidthMultiplicationFactor(sigmaMultiplicationFactor);
// manually-selected Gaussian kernel sigma
// filter->DoKernelBandwidthEstimationOff();
// typename FilterType::RealArrayType gaussianKernelSigma;
// gaussianKernelSigma.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
// gaussianKernelSigma.Fill(11);
// filter->SetGaussianKernelSigma (gaussianKernelSigma);
rescale0->SetInput(image);
filter->SetInput(rescale0->GetOutput());
rescale->SetInput(filter->GetOutput());
try {
rescale->Update();
}
catch (itk::ExceptionObject & excp)
{
LERROR() << "Caught itk exception" << excp.GetDescription();
return;
}
Uint8Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
case GREY16:
{
Uint16Image3DType::Pointer image = Uint16Image3DType::New();
convertStack(stack, image);
typedef itk::RescaleIntensityImageFilter<Uint16Image3DType, FloatImage3DType> RescaleFilter0;
RescaleFilter0::Pointer rescale0 = RescaleFilter0::New();
rescale0->SetOutputMinimum(0.f);
rescale0->SetOutputMaximum(1.f);
typedef itk::PatchBasedDenoisingImageFilter<FloatImage3DType, FloatImage3DType> FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::RescaleIntensityImageFilter<FloatImage3DType, Uint16Image3DType> RescaleFilter;
RescaleFilter::Pointer rescale = RescaleFilter::New();
typedef itk::Statistics::GaussianRandomSpatialNeighborSubsampler<FilterType::PatchSampleType, FloatImage3DType::RegionType> SamplerType;
// patch radius is same for all dimensions of the image
const unsigned int patchRadius = 4;
filter->SetPatchRadius(patchRadius);
// instead of directly setting the weights, could also specify type
filter->UseSmoothDiscPatchWeightsOn();
//filter->UseFastTensorComputationsOn();
// noise model to use
if (noiseModel == "GAUSSIAN")
{
filter->SetNoiseModel(FilterType::GAUSSIAN);
}
else if (noiseModel == "RICIAN")
{
filter->SetNoiseModel(FilterType::RICIAN);
}
else if (noiseModel == "POISSON")
{
filter->SetNoiseModel(FilterType::POISSON);
}
// stepsize or weight for smoothing term
// Large stepsizes may cause instabilities.
filter->SetSmoothingWeight(1);
// stepsize or weight for fidelity term
// use a positive weight to prevent oversmoothing
// (penalizes deviations from noisy data based on a noise model)
filter->SetNoiseModelFidelityWeight(fidelityWeight);
// number of iterations over the image of denoising
filter->SetNumberOfIterations(numIterations);
// number of threads to use in parallel
filter->SetNumberOfThreads(numThreads);
// sampling the image to find similar patches
SamplerType::Pointer sampler = SamplerType::New();
// variance (in physical units) for semi-local Gaussian sampling
sampler->SetVariance(400);
// rectangular window restricting the Gaussian sampling
sampler->SetRadius(50); // 2.5 * standard deviation
// number of random sample "patches" to use for computations
sampler->SetNumberOfResultsRequested(numToSample);
// Sampler can be complete neighborhood sampler, random neighborhood sampler,
// Gaussian sampler, etc.
filter->SetSampler(sampler);
// automatic estimation of the kernel bandwidth
filter->KernelBandwidthEstimationOn();
// update bandwidth every 'n' iterations
filter->SetKernelBandwidthUpdateFrequency(3);
// use 33% of the pixels for the sigma update calculation
filter->SetKernelBandwidthFractionPixelsForEstimation(0.20);
// multiplication factor modifying the automatically-estimated kernel sigma
filter->SetKernelBandwidthMultiplicationFactor(sigmaMultiplicationFactor);
// manually-selected Gaussian kernel sigma
// filter->DoKernelBandwidthEstimationOff();
// typename FilterType::RealArrayType gaussianKernelSigma;
// gaussianKernelSigma.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
// gaussianKernelSigma.Fill(11);
// filter->SetGaussianKernelSigma (gaussianKernelSigma);
rescale0->SetInput(image);
filter->SetInput(rescale0->GetOutput());
rescale->SetInput(filter->GetOutput());
try {
rescale->Update();
}
catch (itk::ExceptionObject & excp)
{
LERROR() << "Caught itk exception" << excp.GetDescription();
return;
}
Uint16Image3DType::Pointer output = rescale->GetOutput();
copyData(output, stack);
}
break;
default:
break;
}
//stack->incrStamp();
}
#else
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(numIterations);
UNUSED_PARAMETER(numThreads);
UNUSED_PARAMETER(numToSample);
UNUSED_PARAMETER(sigmaMultiplicationFactor);
UNUSED_PARAMETER(noiseModel[0]);
UNUSED_PARAMETER(fidelityWeight);
#endif
}
#else
void ZStackProcessor::medianFilter(ZStack *stack, int radius)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(radius);
}
void ZStackProcessor::anisotropicDiffusion(
ZStack *stack, double timeStep, double conductance, int niter)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(timeStep);
UNUSED_PARAMETER(conductance);
UNUSED_PARAMETER(niter);
}
void ZStackProcessor::cannyEdge(ZStack *stack, double variance,
double low, double high)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(variance);
UNUSED_PARAMETER(low);
UNUSED_PARAMETER(high);
}
void ZStackProcessor::curvatureFlow(ZStack *stack, double timeStep, int niter)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(timeStep);
UNUSED_PARAMETER(niter);
}
void ZStackProcessor::minMaxCurvatureFlow(ZStack *stack, double timeStep,
double radius, int niter)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(timeStep);
UNUSED_PARAMETER(radius);
UNUSED_PARAMETER(niter);
}
void ZStackProcessor::convertStack(ZStack *stack, Uint8Image3DType *image)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(image);
}
void ZStackProcessor::convertStack(ZStack *stack, Uint16Image3DType *image)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(image);
}
void ZStackProcessor::convertStack(ZStack *stack, FloatImage3DType *image)
{
UNUSED_PARAMETER(stack);
UNUSED_PARAMETER(image);
}
void ZStackProcessor::copyData(Uint8Image3DType *src, ZStack *dst, int)
{
UNUSED_PARAMETER(src);
UNUSED_PARAMETER(dst);
}
void ZStackProcessor::copyData(Uint16Image3DType *src, ZStack *dst, int)
{
UNUSED_PARAMETER(src);
UNUSED_PARAMETER(dst);
}
void ZStackProcessor::copyData(FloatImage3DType *src, ZStack *dst, int)
{
UNUSED_PARAMETER(src);
UNUSED_PARAMETER(dst);
}
void ZStackProcessor::convertStack(const ZStack *, int, Uint8Image3DType *)
{
}
void ZStackProcessor::convertStack(const ZStack *, int, Uint16Image3DType *)
{
}
void ZStackProcessor::convertStack(const ZStack *, int, FloatImage3DType *)
{
}
void ZStackProcessor::patchBasedDenoising(ZStack *, const int, const int,
const int, const float,
const std::string, const float)
{
}
#endif
void ZStackProcessor::removeIsolatedObject(ZStack *stack, int r, int dr)
{
Struct_Element *se = Make_Disc_Se(dr);
Stack *out = Stack_Dilate(stack->c_stack(), NULL, se);
Kill_Struct_Element(se);
int minSize = iround(TZ_PI * (r + dr) * (r + dr));
Stack *out2 = Stack_Remove_Small_Object(out, NULL, minSize, 8);
Stack_And(out2, stack->c_stack(), stack->c_stack());
//stack->incrStamp();
Kill_Stack(out);
Kill_Stack(out2);
}
void ZStackProcessor::invert(ZStack *stack)
{
double maxValue = stack->max();
for (int c = 0; c < stack->channelNumber(); ++c) {
Stack_Csub(stack->c_stack(c), maxValue);
}
}
| 32.416262 | 142 | 0.677623 | [
"model"
] |
c078d38fa49fd3b9b3a83c6677bd2b05f2ea3149 | 3,449 | cpp | C++ | Endpoints/src/EndpointAttributeValidation.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,272 | 2017-08-17T04:58:05.000Z | 2022-03-27T03:28:29.000Z | Endpoints/src/EndpointAttributeValidation.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 1,948 | 2017-08-17T03:39:24.000Z | 2022-03-30T15:52:41.000Z | Endpoints/src/EndpointAttributeValidation.cpp | AndersSpringborg/avs-device-sdk | 8e77a64c5be5a0b7b19c53549d91b0c45c37df3a | [
"Apache-2.0"
] | 630 | 2017-08-17T06:35:59.000Z | 2022-03-29T04:04:44.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 "Endpoints/EndpointAttributeValidation.h"
namespace alexaClientSDK {
namespace endpoints {
// Used to calculate the cookies size. Each cookie encoding will have 6 bytes (4x'"', 1x':' 1x',') extra.
constexpr size_t EXTRA_BYTES_PER_COOKIE = 6;
using namespace avsCommon::avs;
using namespace avsCommon::sdkInterfaces::endpoints;
bool isEndpointIdValid(const EndpointIdentifier& identifier) {
auto length = identifier.length();
return (length > 0) && (length <= AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_IDENTIFIER_LENGTH);
}
bool isFriendlyNameValid(const std::string& name) {
auto length = name.length();
return (length > 0) && (length <= AVSDiscoveryEndpointAttributes::MAX_FRIENDLY_NAME_LENGTH);
}
bool isDescriptionValid(const std::string& description) {
auto length = description.length();
return (length > 0) && (length <= AVSDiscoveryEndpointAttributes::MAX_DESCRIPTION_LENGTH);
}
bool isManufacturerNameValid(const std::string& manufacturerName) {
auto length = manufacturerName.length();
return (length > 0) && (length <= AVSDiscoveryEndpointAttributes::MAX_MANUFACTURER_NAME_LENGTH);
}
bool isAdditionalAttributesValid(const AVSDiscoveryEndpointAttributes::AdditionalAttributes& attributes) {
return (
(attributes.manufacturer.length() <=
AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH) &&
(attributes.model.length() <= AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH) &&
(attributes.serialNumber.length() <=
AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH) &&
(attributes.firmwareVersion.length() <=
AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH) &&
(attributes.softwareVersion.length() <=
AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH) &&
(attributes.customIdentifier.length() <=
AVSDiscoveryEndpointAttributes::MAX_ENDPOINT_ADDITIONAL_ATTRIBUTES_LENGTH));
}
bool areConnectionsValid(const std::vector<std::map<std::string, std::string>>& connections) {
for (auto& connection : connections) {
for (auto& keyValuePair : connection) {
if (keyValuePair.second.length() == 0 ||
keyValuePair.second.length() > AVSDiscoveryEndpointAttributes::MAX_CONNECTIONS_VALUE_LENGTH) {
return false;
}
}
}
return true;
}
bool areCookiesValid(const std::map<std::string, std::string>& cookies) {
size_t totalSizeBytes = 0;
for (auto& cookie : cookies) {
totalSizeBytes += cookie.first.size() + cookie.second.size() + EXTRA_BYTES_PER_COOKIE;
}
return totalSizeBytes < AVSDiscoveryEndpointAttributes::MAX_COOKIES_SIZE_BYTES;
}
} // namespace endpoints
} // namespace alexaClientSDK
| 41.059524 | 115 | 0.732096 | [
"vector",
"model"
] |
c07b4ee3677056b373aaa7ef7a145eb1f6bc3b48 | 11,394 | cpp | C++ | GsKit/base/GsApp.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 137 | 2015-01-01T21:04:51.000Z | 2022-03-30T01:41:10.000Z | GsKit/base/GsApp.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 154 | 2015-01-01T16:34:39.000Z | 2022-01-28T14:14:45.000Z | GsKit/base/GsApp.cpp | vogonsorg/Commander-Genius | 456703977d7e574af663fd03d4897728ede10058 | [
"X11"
] | 35 | 2015-03-24T02:20:54.000Z | 2021-05-13T11:44:22.000Z | /*
* GsApp.cpp
*
* Created on: 01.05.2009
* Author: gerstrong
* This Game-engine stripes down the main function
* and provides more dynamic control over the game engine itself
*
* It also manages the load of drivers and main game cycle
*/
#include <string>
#include "GsApp.h"
#include <base/GsTimer.h>
#include <base/GsLogging.h>
#include <base/video/CVideoDriver.h>
#include <base/video/GsEffectController.h>
#include <base/utils/StringUtils.h>
#include <graphics/GsGraphics.h>
#include <widgets/GsMenuController.h>
#include <base/CInput.h>
#include <base/GsArguments.h>
#if __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include <thread>
#include <mutex>
std::string getArgument( int argc, char *argv[], const std::string& text )
{
std::string argument;
for( int i=1 ; i<argc ; i++ )
{
argument = argv[i];
if( argument.find(text) == 0 ) // argument was found!
return argument;
}
return "";
}
bool getBooleanArgument( int argc, char *argv[], const std::string& text )
{
std::string argument;
for( int i=1 ; i<argc ; i++ )
{
argument = argv[i];
if( argument.find(text) == 0 ) // argument was found!
return true;
}
return false;
}
GsApp::GsApp()
{
mpSink.reset(new GsAppEventSink(this));
gEventManager.regSink(mpSink);
}
void GsApp::setName(const std::string &appName)
{
mAppName = appName;
}
std::string GsApp::getName()
{
return mAppName;
}
void GsApp::ignoreLogicCounter()
{
mIgnoreLogicCounterOnce = true;
}
///////////////////////////////
// Cleanup Game Engine here! //
///////////////////////////////
/**
* \brief This function cleans up all the used engines and the singleton
* classes that were used during the program.
* This can happen at the end of the program
* or when an engine may be changed.
*/
void GsApp::cleanup()
{
mpSink = nullptr;
//gInput.shutdown();
}
GsApp::~GsApp()
{
}
//////////////////////////////////
// Initialize Game Engine here! //
//////////////////////////////////
/**
* \brief This is the function where CG beings
*
* \param argc number of arguments
* \param argv pointer to char arrays where
* where the passed arguments are stored
* in the process
* \return If the function could setup
* the game, it will return true, else it
* will be false.
*/
bool GsApp::init(int argc, char *argv[])
{
// Pass all the arguments
gArgs.passArgs(argc, argv);
// Setup the Hardware using the settings we have loaded
gLogging.textOut(FONTCOLORS::GREEN,"Loading hardware settings...<br>");
if(!loadDrivers())
{
gLogging.textOut(FONTCOLORS::RED,"The program cannot start, because you do not meet the hardware requirements.<br>");
return false;
}
return true;
}
void GsApp::deinit()
{
unloadDrivers();
}
void GsApp::pumpEvent(const CEvent *evPtr)
{
if( const SwitchEngineEvent *swEng = dynamic_cast<const SwitchEngineEvent*>(evPtr) )
{
SwitchEngineEvent *swEngVar = const_cast<SwitchEngineEvent*>(swEng);
mpCurEngine.swap( swEngVar->mpEnginePtr );
if(!mpCurEngine->start())
{
gEventManager.add( new GMQuit() );
}
}
else if( dynamic_cast<const GMQuit*>(evPtr) )
{
mpCurEngine.release();
}
else if( const InvokeFunctorEvent *iEv =
dynamic_cast<const InvokeFunctorEvent*>(evPtr) )
{
(*iEv)();
}
else if( const FunctionToEvent *iEv =
dynamic_cast<const FunctionToEvent*>(evPtr) )
{
iEv->runFunction();
}
else // none of the above, let's see if the children have events to be processed
{
mpCurEngine->pumpEvent(evPtr);
gMenuController.pumpEvent(evPtr);
}
}
void GsAppEventSink::pumpEvent(const CEvent *evPtr)
{
mpApp->pumpEvent(evPtr);
}
void GsApp::pollEvents()
{
if( gInput.getExitEvent() )
{
mpCurEngine.release();
return;
}
}
/**
* \brief This function will try to load the hardware
* resources, which are the video driver and the sound.
* Input stuff is only loaded, when CG needs it, what mostly
* happens, when it has started.
*
* \return If the function could load
* the drivers, it will return true, else it
* will be false.
*/
// Load the driver needed to start the game
bool GsApp::loadDrivers()
{
// Init graphics
if (!gVideoDriver.start())
return false;
return true;
}
void GsApp::unloadDrivers()
{
#ifdef USE_VIRTUALPAD
gInput.mpVirtPad = nullptr;
#endif // USE_VIRTUALPAD
gVideoDriver.stop();
}
////
// Process Routine
////
// This function is run every time, the Timer says so, through.
void GsApp::ponder(const float deltaT)
{
gInput.ponder();
pollEvents();
// Process the game control object if no effects are being processed
if(mpCurEngine)
{
mpCurEngine->ponder(deltaT);
}
// Apply graphical effects if any. It does not render, it only prepares for the rendering task.
gEffectController.run(deltaT);
gMenuController.ponder(deltaT);
}
void GsApp::render()
{
gVideoDriver.clearSurfaces();
if(mpCurEngine)
{
mpCurEngine->render();
}
gMenuController.render();
gInput.render();
// Apply graphical effects if any.
gEffectController.render();
// Pass all the surfaces to one. Some special surfaces are used and are collected here
gVideoDriver.collectSurfaces();
// Now you really render the screen
// When enabled, it also applies Filters
gVideoDriver.updateDisplay();
}
void GsApp::setEngine(GsEngine *engPtr)
{
mpCurEngine.reset(engPtr);
}
////////////////////////////
// This is the main cycle //
////////////////////////////
#if __EMSCRIPTEN__
void runMainCycleEmscriptenExtern()
{
gApp.runMainCycleEmscripten();
}
#endif // __EMSCRIPTEN__
void GsApp::runMainCycleNonThreaded()
{
float acc = 0.0f;
float start = 0.0f;
float elapsed = 0.0f;
float total_elapsed = 0.0f;
float curr = 0.0f;
int counter = 0;
while(1)
{
const float logicLatency = gTimer.LogicLatency();
const bool vsyncEnabled = gVideoDriver.isVsync();
curr = timerTicks();
if(gTimer.resetLogicSignal())
start = curr;
if(vsyncEnabled)
{
start = timerTicks();
// Logic cycle
{
// Poll Inputs
gInput.pollEvents();
// Process App Events
gEventManager.processSinks();
// Ponder Game Control
ponder(logicLatency);
}
mIgnoreLogicCounterOnce = false;
// Now we render the whole GameControl Object to the blit surface
render();
elapsed = timerTicks() - start;
total_elapsed += elapsed;
if( mustShutdown() )
break;
}
else
{
const float renderLatency = gTimer.RenderLatency();
elapsed = curr - start;
start = timerTicks();
acc += elapsed;
// Logic cycle
while( acc > logicLatency )
{
// Poll Inputs
gInput.pollEvents();
// Process App Events
gEventManager.processSinks();
// Ponder Game Control
ponder(logicLatency);
acc -= logicLatency;
if(mIgnoreLogicCounterOnce)
{
start = timerTicks();
break;
}
}
mIgnoreLogicCounterOnce = false;
// Now we render the whole GameControl Object to the blit surface
render();
elapsed = timerTicks() - start;
total_elapsed += elapsed;
if( mustShutdown() )
break;
// If renderLatency is zero or less, delays won't happens.
// This means the system renders as much as possible
// with violating the the LPS
auto fWaitTime = -elapsed;
if( renderLatency > 0.0f )
{
fWaitTime = renderLatency+fWaitTime;
}
// wait time remaining in current loop
if( fWaitTime > 0.0f )
{
const auto waitTime = static_cast<Uint32>(fWaitTime);
timerDelay( waitTime );
total_elapsed += static_cast<float>(waitTime);
}
}
// This will refresh the fps display, so it stays readable and calculates an average value.
counter++;
if(counter >= 100)
{
counter = 0;
gTimer.setTimeforLastLoop(total_elapsed/100.0f);
total_elapsed = 0.0f;
}
}
}
/**
* \brief This is the main run cycle of the game,
* no matter what happens in the game logic or
* which engine is chosen, it always get to this point
* Mainly timer and logic processes are performed here.
*/
void GsApp::runMainCycle()
{
// I hope the engine has been set. Otherwise quit the app
if(!mpCurEngine)
{
gLogging << "No Engine set. This should never happen. Please report this issue to the developers";
return ;
}
mpCurEngine->start();
#if __EMSCRIPTEN__
emscripten_set_main_loop(runMainCycleEmscriptenExtern, -1, 1);
#else
runMainCycleNonThreaded();
#endif
cleanup();
}
#if __EMSCRIPTEN__
void GsApp::runMainCycleEmscripten()
{
float acc = 0.0f;
float start = 0.0f;
float elapsed = 0.0f;
float total_elapsed = 0.0f;
float curr = 0.0f;
int counter = 0;
const float logicLatency = gTimer.LogicLatency();
const bool vsyncEnabled = gVideoDriver.isVsync();
curr = timerTicks();
if(gTimer.resetLogicSignal())
start = curr;
{
start = timerTicks();
// Game cycle
{
// Poll Inputs
gInput.pollEvents();
// Process App Events
gEventManager.processSinks();
// Ponder Game Control
ponder(logicLatency);
}
// Now we render the whole GameControl Object to the blit surface
render();
// Apply graphical effects if any.
gEffectController.render();
// Pass all the surfaces to one. Some special surfaces are used and are collected here
gVideoDriver.collectSurfaces();
// Now you really render the screen
// When enabled, it also applies Filters
gVideoDriver.updateDisplay();
elapsed = timerTicks() - start;
total_elapsed += elapsed;
if( mustShutdown() )
return;
}
// This will refresh the fps display, so it stays readable and calculates an average value.
counter++;
if(counter >= 100)
{
counter = 0;
gTimer.setTimeforLastLoop(total_elapsed/100.0f);
total_elapsed = 0.0f;
}
}
#endif // __EMSCRIPTEN__
| 22.473373 | 125 | 0.572055 | [
"render",
"object"
] |
c07ead4397cfe7b763199498f88d359a00073b38 | 4,922 | hpp | C++ | sciplot/specs/plotspecs.hpp | CaeruleusAqua/sciplot | 4470cbd43a08b4caa897631159a47d35d72f5a18 | [
"MIT"
] | null | null | null | sciplot/specs/plotspecs.hpp | CaeruleusAqua/sciplot | 4470cbd43a08b4caa897631159a47d35d72f5a18 | [
"MIT"
] | null | null | null | sciplot/specs/plotspecs.hpp | CaeruleusAqua/sciplot | 4470cbd43a08b4caa897631159a47d35d72f5a18 | [
"MIT"
] | null | null | null | // sciplot - a modern C++ scientific plotting library powered by gnuplot
// https://github.com/sciplot/sciplot
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2018 Allan Leal
//
// 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.
#pragma once
// sciplot includes
#include <limits>
#include <numeric>
#include <sciplot/enums.hpp>
#include <sciplot/specs/linespecs.hpp>
#include <sciplot/util.hpp>
// C++ includes
#include <algorithm>
namespace sciplot
{
/// The class where options for the plot function are specified.
class plotspecs : public linespecs<plotspecs>
{
public:
/// Undefine / ignore column usage value. See use().
static constexpr int USE_AUTO = std::numeric_limits<int>::min();
/// Construct a plotspecs instance.
/// @param what A string representing what to be plot (e.g., "'filename' u 1:2", "sin(x)", etc.)
plotspecs(std::string what) : m_what(what)
{
with(internal::DEFAULT_PLOTSTYLE);
}
/// Convert this plotspecs object into a gnuplot formatted string.
auto repr() const -> std::string
{
std::stringstream ss;
ss << m_what << " ";
ss << gnuplot::optionvaluestr("using", m_using);
ss << gnuplot::optionvaluestr("title", m_title);
ss << gnuplot::optionvaluestr("with", m_with);
ss << linespecs<plotspecs>::repr();
return ss.str();
}
/// Set the title of the plot.
auto title(std::string value) -> plotspecs&
{
m_title = gnuplot::titlestr(value);
return *this;
}
/// Set the format of the plot (lines, points, linespoints).
auto with(plotstyle value) -> plotspecs&
{
m_with = gnuplot::plotstylestr(value);
return *this;
}
/// Set which columns from the data file to use for plot data or tick labels. Resembles the "using" directive for a plot.
/// Pass an USE_AUTO in any of these values to "undefine" that value, e.g. to use column 2 for y, do: plot.use(USE_AUTO, 2);
/// To use strings as tick labels, you can pass them in the corresponding data column in the plot.draw() call.
auto use(int xcol = USE_AUTO, int ycol = USE_AUTO, int zcol = USE_AUTO, int xtic = USE_AUTO, int x2tic = USE_AUTO, int ytic = USE_AUTO, int y2tic = USE_AUTO, int ztic = USE_AUTO) -> plotspecs&
{
std::vector<std::pair<unsigned int, std::string>> values = {
{xcol, std::to_string(xcol)},
{ycol, std::to_string(ycol)},
{zcol, std::to_string(zcol)},
{xtic, "xtic(" + std::to_string(xtic) + ")"},
{x2tic, "x2tic(" + std::to_string(x2tic) + ")"},
{ytic, "ytic(" + std::to_string(ytic) + ")"},
{y2tic, "y2tic(" + std::to_string(y2tic) + ")"},
{ztic, "ztic(" + std::to_string(ztic) + ")"}};
std::vector<std::string> strings;
// filter out all valuzes we don't want to use and put the remaining one int strings
std::for_each(values.begin(), values.end(), [&strings](const std::pair<unsigned int, std::string>& v) { if (v.first != USE_AUTO) { strings.push_back(v.second); } });
// join all remaining values using ":"
m_using = std::accumulate(std::next(strings.begin()), strings.end(), strings[0], [](const std::string& a, const std::string& b) { return a + ":" + b; });
return *this;
}
private:
/// The what to be plotted as a gnuplot formatted string (e.g., "sin(x)").
std::string m_what;
/// The title of the plot as a gnuplot formatted string (e.g., "title 'sin(x)'").
std::string m_title;
/// The style of the plot (lines, points, linespoints) as a gnuplot formatted string (e.g., "with linespoints").
std::string m_with;
/// Select which columns from the data file to use for plot data or tick labels (e.g. "using 1:xtic(2)").
std::string m_using;
};
} // namespace sciplot
| 40.344262 | 196 | 0.655018 | [
"object",
"vector"
] |
c082aba5e81c47c20d2bd054468e5a0151e0e60b | 31,743 | cpp | C++ | src/RHEHpt.cpp | gvita/RHEHpt | f320d8f4e2ef27af19cf62bded85afce8e0de7a7 | [
"MIT"
] | null | null | null | src/RHEHpt.cpp | gvita/RHEHpt | f320d8f4e2ef27af19cf62bded85afce8e0de7a7 | [
"MIT"
] | null | null | null | src/RHEHpt.cpp | gvita/RHEHpt | f320d8f4e2ef27af19cf62bded85afce8e0de7a7 | [
"MIT"
] | null | null | null | #include "RHEHpt.h"
#include "LHAPDF/LHAPDF.h"
#include "Mfinite_HardPart_2.h"
#include "cuba.h"
#include <cmath>
using namespace std::placeholders;
namespace RHEHpt{
RHEHpt::RHEHpt(double CME, const std::string& PDFfile, double MH, double MT, double MB, double MUR, double MUF,
unsigned choice,unsigned channel,bool running_scale, bool verbose):
_PDF(LHAPDF::mkPDF(PDFfile,0)),
Exact_FO_fullmass(CME,0.1,MT,MB,MH,choice),Exact_FO_PL(CME,0.1,MH,MUF,MUR),
_CME(CME), _mH(MH), _mT(MT), _mB(MB), _muR(MUR), _muF(MUF), _choice(choice), _channel(channel),
_running_scale (running_scale), _verbose(verbose), _Lum(_PDF,MUF,5), _Integral_coeff_interpolator(choice)
{
_s = std::pow(CME,2); // GeV^2
_as=_PDF -> alphasQ(_muR);
Exact_FO_fullmass.SetAS(_as);
Exact_FO_PL.SetAS(_as);
std::cout << _s << " " << _as << " " << _mH << " " << _mT << " "<< _mB << " " << _muR << " " << _muF << std::endl;
}
RHEHpt::~RHEHpt(){
std::cout << "deleting RHEHpt" << std::endl;
delete _PDF;
}
/******************************************/
/* RESUMMED DISTRIBUTIONS */
/******************************************/
double RHEHpt::core_hpt_infinite(double N) const{
// const double sigma0 = _as * _as * Gf * std::sqrt(2.) / (576. * M_PI);
const double as_N = _as / N;
// const double M1 = _an_dim(as_N);
// const double M2 = _an_dim(as_N);
const double M1 = N;
const double M2 = M1;
std::cout << "M=" << M1 << std::endl;
const double gamma_factor = tgamma( 1. + M1 ) * tgamma( 1. + M2 ) * tgamma( 2. - M1 - M2 ) / ( tgamma(2.-M1) * tgamma(2.-M2) * tgamma(M1 + M2 ) );
// return R(as_N) * R(as_N) * k * xp_factor * gamma_factor * ( 1 + (2 * M1 * M2)/(1 - M1 - M2));
return SIGMA0() * gamma_factor * ( 1. + (2. * M1 * M2)/(1. - M1 - M2));
}
double RHEHpt::hpt_infinite(double xp,double N) const{
// const double xp = (pt*pt) / (_mH*_mH);
// const double xp_factor = std::pow(xp, 2.*_an_dim(_as/N) - 1. );
const double xp_factor = std::pow(xp, 2.*N - 1. );
return core_hpt_infinite(N)*xp_factor;
}
int _core_hptfinite(const int *ndim, const double x[], const int *ncomp, double res[], void *pars){
res[0] = 0.;
double * p = (double *) pars;
const long double xp = p[0];
const long double yt = p[1];
const long double M = p[2];
const long double x1 = 0.25*x[0];
const long double sqrtx1 = std::sqrt(x1);
const long double r = x[1];
const long double x2 = 1. + x1 + 2.* sqrtx1 *(1.-2.*r);
const long double x2_red = 2.25 - 2.*r; // x2(1/4,r)
long double DF0,F0,F0red;
DF0 = D_F_0( x1, x2, xp, yt, r );
F0 = F_0( x1, x2, xp, yt, r);
F0red = F_0(0.25,x2_red,xp,yt,r);
const long double derivative_term = std::pow(x1*x2,M)/x2 * ( DF0 - (1.-M) * F0* (1.+sqrtx1 - 2.*r)/(sqrtx1*x2) );
const long double surface_term = std::pow(x2_red/4.,M-1)*F0red;
/** P1 Total **/
res[0] = 0.25*(surface_term - derivative_term)/std::sqrt(r*(1.-r));
// and P_2, i.e. the term not integrated by parts
const long double x1p = 0.25/x[0];
const long double x2p = x[1] + x[1]/std::sqrt(x[0]) + x1p;
const long double F_inf = F_Infinitive(x1p,x2p,xp,yt);
res[0] += M * (std::pow( x1p*x2p,M)/(x[0]*x2p)) * (1. + 2.*sqrt(x1p) )*F_inf/std::sqrt(2.*x1p*x2p + 2.*x1p + 2.*x2p - x1p*x1p - x2p*x2p -1.);
return 0;
}
//FIXME aggiungere massa bottom a private classe e cambiare F_costant
double RHEHpt::hpt_finite(double xp, double N) const
{
double M = _an_dim(_as/N);
double p[3] = { xp, get_yt(), M};
double the_integral[1], error[1], prob[1];
double epsrel=1.e-3, epsabs=1.e-15;
int last = 4;
int verbose = 0;
int nregions, neval, fail;
Cuhre(2, 1, _core_hptfinite, &p, 1,
epsrel, epsabs, verbose | last,
0, 500000, 9,
NULL, NULL,
&nregions, &neval, &fail, the_integral, error, prob);
const double F_constant = 4608.*std::pow(M_PI,3.);
std::cout << "hpt_finite integral (" << xp << ") = " << the_integral[0] << " ± " << error[0] << "\tp = " << prob[0] << std::endl;
std::cout << std::endl;
// const double sigma0 = _as * _as * Gf * std::sqrt(2.) / (576. * M_PI);
return SIGMA0() * M * std::pow(xp,2.*M-1.) * F_constant * 2. * the_integral[0];
}
/******************************************/
/* RESUMMED Hpt EXPANSION */
/******************************************/
unsigned int factorial(unsigned int n)
{
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
long double RHEHpt::M(long double x,unsigned i) const{ //inverse mellin of _an_dim^i at x
return std::pow(CA*_as/M_PIl,i)*std::pow(std::log(1./x),i-1)/factorial(i-1);
}
double I_1_2( RHEHpt::_parameters* par);
double I_3( RHEHpt::_parameters* par);
double half_C( RHEHpt::_parameters* par){
return (I_1_2(par) + I_3(par))/(factorial(par->j -1) * factorial(par -> k));
}
double RHEHpt::C(unsigned j, unsigned k,double xp) const
{
const double yt = (_mT*_mT) / (_mH*_mH);
const double yb = (_mB*_mB) / (_mH*_mH);
const double F_constant = 4608.*std::pow(M_PI,3.);
if ( k*j != 0 ) {
_parameters par;
switch (_choice){
case(0): { // total
par.set(j,k,xp,
_parameters::HardF1( std::bind( &F_0_tot, _1, _2, _3, yt, yb, _4)) ,
_parameters::HardF1( std::bind( &D_F_0_tot, _1, _2, _3, yt, yb, _4)) ,
_parameters::HardF2( std::bind( &F_Infinitive_tot, _1, _2, _3, yt, yb))
);
break;
}
case(1): { // only top
par.set(j,k,xp,
_parameters::HardF1( std::bind( &F_0, _1, _2, _3, yt, _4)) ,
_parameters::HardF1( std::bind( &D_F_0, _1, _2, _3, yt, _4)) ,
_parameters::HardF2( std::bind( &F_Infinitive, _1, _2, _3, yt))
);
break;
}
case(2): { // only bottom
par.set(j,k,xp,
_parameters::HardF1( std::bind( &F_0, _1, _2, _3, yb, _4)) ,
_parameters::HardF1( std::bind( &D_F_0, _1, _2, _3, yb, _4)) ,
_parameters::HardF2( std::bind( &F_Infinitive, _1, _2, _3, yb))
);
break;
}
case(3): { // interference
par.set(j,k,xp,
_parameters::HardF1( std::bind( &F_0_inter, _1, _2, _3, yt, yb, _4)) ,
_parameters::HardF1( std::bind( &D_F_0_inter, _1, _2, _3, yt, yb, _4)) ,
_parameters::HardF2( std::bind( &F_Infinitive_inter, _1, _2, _3, yt, yb))
);
break;
}
}
if( j != k ){
double C_j_k = half_C(&par);
par.switch_jk();
double C_k_j = half_C(&par);
return F_constant * (C_j_k + C_k_j);
}
else
return 2. * F_constant * half_C(&par);
}
else if ( k + j > 1.) return 0.;
else switch (_choice){
case(0): {
return M_PI * F_constant * std::norm( A1x_0(xp,yt) + A1x_0(xp,yb) );
break;
}
case(1): {
return M_PI * F_constant * std::norm(A1x_0(xp,yt)); // checked against c0 infinite
break;
}
case(2): {
return M_PI* F_constant * std::norm(A1x_0(xp,yb));
break;
}
case(3): {
return M_PI * F_constant*real(A1x_0(xp,yt)*std::conj(A1x_0(xp,yb))+std::conj(A1x_0(xp,yt))*A1x_0(xp,yb));
break;
}
}
}
std::vector< std::array<unsigned,2> > RHEHpt::partition_of(unsigned n) const
{
/* returns all the couples of int (x,y) s.t. x + y = n and x >= y */
std::vector < std::array<unsigned,2> > result;
const std::size_t max_i = n/2; // deliberate integer division
for(unsigned i = 1; i <= max_i ; ++i)
result.push_back({n-i,i});
return result;
}
std::vector< std::array<unsigned,2> > RHEHpt::symmetric_partition_of(unsigned n) const
{
/* returns all the couples of int (x,y) s.t. x + y = n */
std::vector < std::array<unsigned,2> > result;
const std::size_t max_i = n/2; // deliberate integer division
for(unsigned i = 0; i <= max_i ; ++i){
result.push_back({n-i,i});
if(n-i != i)
result.push_back({i,n-i});
}
return result;
}
double RHEHpt::_Integral_coeff_from_integrals(unsigned i, double xp) const
{
// get couples of int (x,y) s.t. x + y = i and x >= y
std::vector< std::array<unsigned,2> > indices = partition_of(i);
std::vector<double> tmp(indices.size());
std::cout << "number of couples at order " << i << " = " << indices.size() << std::endl;
// compute all coefficients of the i-th order (for i=4 they are c_{1,3} and c_{2,2}), store result in tmp
std::transform(indices.cbegin(),indices.cend(),tmp.begin(),[&](const std::array<unsigned,2>& index_pair){
std::cout << "computing C(" << index_pair[0] << "," << index_pair[1] << ",xp)" << std::endl;
return C(index_pair[0],index_pair[1],xp);
});
return 2.*std::accumulate(tmp.cbegin(),tmp.cend(),0.); // sum of the partial coefficients. 2 comes from M1=M2 symm
}
double RHEHpt::_Integral_coeff_from_file(unsigned order,double xp) const
{
if (order > 3) return _Integral_coeff_from_integrals(order,xp); // N3LO and beyond not precomputed
else if(order > 1) return _Integral_coeff_interpolator(order,xp);
else if (order == 1) return C(1,0,xp);
else return 0;
}
std::vector<double> RHEHpt::Integral_coeffs(unsigned order, double xp, bool HQ, bool singleM) const
{
if(order < 1 ) return std::vector<double>(1,0.);
std::vector<double> coeff_list( order + 1, 0. );
coeff_list[0] = 0; // as^2
if ( HQ ){
coeff_list[1] = 2.-static_cast<int>(singleM); // as^3
if (order == 1) return coeff_list;
coeff_list[2] = 0.; // as^4
if (order == 2) return coeff_list;
coeff_list[3] = 2.*(1. - static_cast<int>(singleM)); // as^5
if (order == 3) return coeff_list;
std::cerr << "N3LO not implemented." << std::endl;
return std::vector<double>(1,0.);
}
/**** finite mass case ****/
coeff_list[1] = C(1,0,xp)/(1.+static_cast<int>(singleM));
if(order > 1 && !singleM){ // C_j_0 = 0 for all j > 1
const double yt = get_yt();
const double yb = get_yb();
/* If yb ~ yb_def and yt ~ yt_def use precomputed coefficients.
We give a 0.5% tolerance in the check, since, experimentally there is about a 1% uncertainty on the quark/higgs mass.*/
if (std::abs(yb - yb_def)/yb_def < 0.005 && std::abs(yt - yt_def)/yt_def < 0.005 ){
// std::cout << "Using precomputed coefficients" << std::endl;
for(unsigned i = 2 ; i < order + 1 ; ++i)
coeff_list[i] = _Integral_coeff_from_file(i,xp);
}
else{
for(unsigned i = 2 ; i < order + 1 ; ++i)
coeff_list[i] = _Integral_coeff_from_integrals(i,xp);
}
}
return coeff_list; // coeff_list[i] should go with M^i
}
std::vector < double > RHEHpt::Xp_prefactor_coeffs(unsigned order, double xp, bool singleM) const
{
// compute the analytic expansion of xp^(2 M-1) up to the n-1-th order (cause the O(M^0) term of Integral_coeffs is 0)
std::vector<double> xp_coeff_list( order +1 ); // this starts at M^0
for(unsigned i = 0 ; i < order+1. ; ++i){
xp_coeff_list[i] = std::pow((2. - static_cast<int>(singleM))*std::log(xp),i)/factorial(i)/xp;
}
return xp_coeff_list;
}
std::vector<double> RHEHpt::pt_distr_series_terms(unsigned order, double xp,double N,bool HQ,bool Nspace) const
{
/*
IMPORTANT NOTE: This is formally correct up to order 4 where you need to expand also R(as_N).
Also at order 4, O(_as) != O(M) since M ~ _as + O(_as^4)
*/
//FIXME need to add R(M)^2
if(order < 1 ) return std::vector<double>(1,0.);
if(_channel == 0) {
std::cerr << "Error: Channel 0 selected in partonic cross section.\n"
<< "Partonic channels are separated and the sum of them has no physical meaning at the partonic level.\n"
<< "Please select a channel or call the hadronic cross section function." << std::endl;
return std::vector<double>(1,0.);
}
// compute the analytic expansion of xp^(2 M-1) up to the n-1-th order (cause the O(M^0) term of Integral_coeffs is 0)
std::vector<double> xp_coeff_list = Xp_prefactor_coeffs(order,xp); // this starts at M^0
// compute the coeff_list for the double integral
// this starts at M^0. This is the longest part of the computation
std::vector<double> integral_coeff_list = Integral_coeffs(order,xp,HQ);
if( _verbose ){
/* print stuff */
std::cout << "integral_coeff_list " << std::endl;
for (auto it : integral_coeff_list){
std::cout << it << " " ;
}
std::cout << std::endl;
std::cout << "xp_coeff_list " << std::endl;
for (auto it : xp_coeff_list){
std::cout << it << " " ;
}
std::cout << std::endl;
}
return pt_distr_series_terms< double >(N,integral_coeff_list,xp_coeff_list,order,Nspace);
}
double RHEHpt::pt_distr_series(unsigned order, double xp,double N, bool HQ, bool Nspace) const
{
std::vector<double> terms = pt_distr_series_terms(order, xp, N, HQ, Nspace);
return SIGMA0() * std::accumulate(terms.cbegin(),terms.cend(),0.);
}
/*************************** I_i integrals definitions ************************/
/************************************* I_1_2 *************************************/
int _core_I_1_2(const int *ndim, const double x[], const int *ncomp, double res[], void *pars){
res[0] = 0.;
if(x[0] < 0.25){
// I_2 calculation
RHEHpt::_parameters * p = (RHEHpt::_parameters *) pars;
const long double xp = p -> xp;
const unsigned j = p -> j;
const unsigned k = p -> k;
RHEHpt::_parameters::HardF1 F_0f = p -> F_0f;
RHEHpt::_parameters::HardF1 D_0f = p -> D_0f;
const long double x1 = x[0];
const long double sqrtx1 = std::sqrt(x1);
const long double r = x[1];
const long double x2 = 1. + x1 + 2.* sqrtx1 *(1.-2.*r);
const long double logjx2 = std::pow(std::log(x2),j-1);
const long double x2_red = 2.25 - 2.*r; // x2(1/4,r)
long double DF0,F0,F0red;
DF0 = D_0f( x1, x2, xp, r );
F0 = F_0f( x1, x2, xp, r);
F0red = F_0f(0.25, x2_red, xp, r);
const long double C1 = (logjx2 / x2) * DF0 ;
//const long double C1=0.0;
long double C2 = logjx2 * F0* (1.+sqrtx1 - 2.*r)/(sqrtx1*x2*x2);
//long double C2=0.0;
if( j > 1 )
C2 -= (j-1.) * std::pow(std::log(x2),j-2) * F0* (1.+sqrtx1 - 2.*r)/(sqrtx1*x2*x2);
// I_1 calculation
const long double I1_numerator = std::pow(std::log(0.25),k)*std::pow(std::log(x2_red),j-1)*F0red/x2_red;
/** Total **/
// 4*I1_numerator because I_1 is an integral on dr, here we are integrating in dr dx
res[0] = (4. * I1_numerator - (C1 - C2 )*std::pow(std::log(x1),k) )/std::sqrt(r*(1.-r));
/*if (res[0]!=res[0]){
std::cout << res[0] << " YES " << x[0]<< " " << x[1] << " " << x2 << " " << x2_red<< " " << DF0<< std::endl;
}*/
}
return 0;
}
double I_1_2(RHEHpt::_parameters* par){
double the_integral[1], error[1], prob[1];
double epsrel=1.e-3, epsabs=1.e-15;
int last = 4;
int verbose = 0;
int nregions, neval, fail;
Cuhre(2, 1, _core_I_1_2, par, 1,
epsrel, epsabs, verbose | last,
0, 500000, 9,
NULL, NULL,
&nregions, &neval, &fail, the_integral, error, prob);
std::cout << "I_2 integral (" << par -> j << "," << par -> k << "," << par -> xp << ") = " << the_integral[0] << " ± " << error[0] << "\tp = " << prob[0] << std::endl;
std::cout << std::endl;
return the_integral[0];
}
/************************************* I_3 *************************************/
int _core_I_3(const int *ndim, const double x[], const int *ncomp, double res[], void *pars){ // TO DO rescale x1 to 1/4 -> 1 and put this inside _core_I_1_2
res[0] = 0.;
RHEHpt::_parameters * p = (RHEHpt::_parameters *) pars;
const long double xp = p -> xp;
const unsigned j = p -> j;
const unsigned k = p -> k;
RHEHpt::_parameters::HardF2 F_inf = p -> F_inf;
const long double x1 = 0.25/x[0];
const long double x2 = x[1] + x[1]/std::sqrt(x[0]) + x1;
res[0] = k * ( std::pow(std::log(x1),k-1) * std::pow(std::log(x2),j-1)/(x[0] * x2))
*(1. + 2.*sqrt(x1) )*F_inf(x1,x2,xp)/std::sqrt(2.*x1*x2 + 2.*x1 + 2.*x2 - x1*x1 - x2*x2 -1.);
return 0;
}
double I_3(RHEHpt::_parameters* par){
double the_integral[1], error[1], prob[1];
double epsrel=1.e-3, epsabs=1.e-15;
int last = 4;
int verbose = 0;
int nregions, neval, fail;
Cuhre(2, 1, _core_I_3, par, 1,
epsrel, epsabs, verbose | last,
0, 500000, 9,
NULL, NULL,
&nregions, &neval, &fail, the_integral, error, prob);
std::cout << "I_3 integral (" << par -> j << "," << par -> k << "," << par -> xp << ") = " << the_integral[0] << " ± " << error[0] << "\tp = " << prob[0] << std::endl;
std::cout << std::endl;
return the_integral[0];
}
/******************************************/
/* FIXED ORDER DISTRIBUTION */
/******************************************/
//CORE FUNCTION
double NLO_PL_sing_function(double x1,void *p){
RHEHpt::_par_part *pars=(RHEHpt::_par_part *)p;
double ris=0.;
switch (pars->_channel_int){
case(1):{
ris=(pars->_Pointlike_int).NLO_PL_sing_doublediff(pars->_xp_int,x1);
break;
}
case(2):{
ris=(pars->_Pointlike_int).NLO_PL_sing_doublediff_gq(pars->_xp_int,x1);
break;
}
case(3):{
ris=(pars->_Pointlike_int).NLO_PL_sing_doublediff_qqbar(pars->_xp_int,x1);
break;
}
case(4):{
ris=0.;
break;
}
case(5):{
ris=0.;
break;
}
case(6):{
ris=0.;
break;
}
}
return(ris);
}
double NLO_PL_notsing_function(double x1,void *p){
RHEHpt::_par_part *pars=(RHEHpt::_par_part *)p;
double ris=0.;
switch (pars->_channel_int){
case(1):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff(pars->_xp_int,x1);
break;
}
case(2):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff_gq(pars->_xp_int,x1);
break;
}
case(3):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff_qqbar(pars->_xp_int,x1);
break;
}
case(4):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff_qq(pars->_xp_int,x1);
break;
}
case(5):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff_qqbarprime(pars->_xp_int,x1);
break;
}
case(6):{
ris=(pars->_Pointlike_int).NLO_PL_notsing_doublediff_qqprime(pars->_xp_int,x1);
break;
}
}
return(ris);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------
long double RHEHpt::sigma_part(long double CME_part,long double pt, unsigned int order, bool heavyquark){
long double sigma = 0.0;
long double sigma0 = SIGMA0();
if (_channel==0){
std::cout<< "TOT channel is not a partonic channel: switch to gg channel major contribution" << std::endl;
_channel=1;
}
if ( heavyquark == false ){
Exact_FO_fullmass.setchannel(_channel);
Exact_FO_fullmass.SetCME(CME_part);
sigma = sigma0 * Exact_FO_fullmass(get_xp(pt));
}
else {
Exact_FO_PL.setchannel(_channel);
if ( order > 1 ){
std::cout << "Error order must be or 0 (LO) or 1(NLO)" << std::endl;
return 0;
}
if ( order == 0 ){
Exact_FO_PL.SetCME(CME_part);
sigma = sigma0 * Exact_FO_PL.LO_PL(get_xp(pt));
}
if( order == 1 ){
Exact_FO_PL.SetCME(CME_part);
_par_part par(Exact_FO_PL,get_xp(pt),_channel);
double precision = 1e-5;
double NLO_PL_sing_ris = 0.0, NLO_PL_sing_error = 0.0;
gsl_function NLO_PL_sing;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
NLO_PL_sing.function = NLO_PL_sing_function;
NLO_PL_sing.params = ∥
gsl_integration_qags (&NLO_PL_sing, 0.0, 1.0, 0, precision, 100000, w, &NLO_PL_sing_ris, &NLO_PL_sing_error);
gsl_integration_workspace_free (w);
double NLO_PL_notsing_ris = 0.0, NLO_PL_notsing_error = 0.0;
gsl_function NLO_PL_notsing;
w = gsl_integration_workspace_alloc (100000);
NLO_PL_notsing.function = NLO_PL_notsing_function;
NLO_PL_notsing.params = ∥
gsl_integration_qags (&NLO_PL_notsing, 0.0, 1.0, 0, precision, 100000, w, &NLO_PL_notsing_ris, &NLO_PL_notsing_error);
gsl_integration_workspace_free (w);
long double NLO_PL_delta_ris= 0.;
switch(_channel){
case(1):{
NLO_PL_delta_ris=Exact_FO_PL.NLO_PL_delta(get_xp(pt));
break;
}
case(2):{
NLO_PL_delta_ris=Exact_FO_PL.NLO_PL_delta_gq(get_xp(pt));
break;
}
case(3):{
NLO_PL_delta_ris=Exact_FO_PL.NLO_PL_delta_qqbar(get_xp(pt));
break;
}
case(4):{
NLO_PL_delta_ris=0.;
break;
}
case(5):{
NLO_PL_delta_ris=0.;
break;
}
case(6):{
NLO_PL_delta_ris=0.;
break;
}
}
sigma = sigma0*(_as*_as/(4.*M_PIl*M_PIl)*(NLO_PL_delta_ris + NLO_PL_sing_ris + NLO_PL_notsing_ris));
//sigma=(NLO_PL_delta_ris + NLO_PL_sing_ris + NLO_PL_notsing_ris);
std::cout << "Sigma_part_NLO( "<< CME_part << " , " << pt << ")= " << sigma << " +- " << sigma0*(_as*_as/(4.*M_PIl*M_PIl)*( NLO_PL_notsing_error + NLO_PL_sing_error ))<< std::endl;
}
}
return sigma;
}
double rho(double xp){
return std::pow( std::sqrt(1.+xp) + std::sqrt(xp) ,2);
}
double LO_fullmass_function(double z,void *p){
RHEHpt::_par_hadro *pars=(RHEHpt::_par_hadro *)p;
long double tauprime=(pars->_tau_int)* rho(pars -> _xp_int);
unsigned int channel=(pars->_channel_int);
pars->_Finite_int.SetCME( pars -> _mH_int / std::sqrt(z) * std::sqrt( rho(pars -> _xp_int) ) );
long double ris=0.0;
switch (channel){
case(0):{
(pars->_Finite_int).setchannel(1);
ris+= 1./z*pars->_Lumi_int.CLum_gg_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
(pars->_Finite_int).setchannel(2);
ris+= 1./z*pars->_Lumi_int.CLum_gq_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
(pars->_Finite_int).setchannel(3);
ris+= 1./z*pars->_Lumi_int.CLum_qqbar_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
break;
}
case(1):{
(pars->_Finite_int).setchannel(1);
ris+= 1./z*pars->_Lumi_int.CLum_gg_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
break;
}
case(2):{
(pars->_Finite_int).setchannel(2);
ris+= 1./z*pars->_Lumi_int.CLum_gq_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
break;
}
case(3):{
(pars->_Finite_int).setchannel(3);
ris+= 1./z*pars->_Lumi_int.CLum_qqbar_x(tauprime/z)*pars->_Finite_int(pars->_xp_int)/z;
break;
}
}
return (ris);
}
double LO_PL_function(double z,void *p){
RHEHpt::_par_hadro *pars=(RHEHpt::_par_hadro *)p;
long double tauprime = (pars->_tau_int) * rho(pars -> _xp_int);
unsigned int channel=(pars->_channel_int);
pars->_Pointlike_int.SetCME(pars->_mH_int/std::sqrt(z)* std::sqrt( rho(pars -> _xp_int) ) );
long double ris=0.;
switch(channel){
case(0):{
(pars->_Pointlike_int).setchannel(1);
ris+=(1./z) * pars->_Lumi_int.CLum_gg_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
(pars->_Pointlike_int).setchannel(2);
ris+=(1./z) * pars->_Lumi_int.CLum_gq_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
(pars->_Pointlike_int).setchannel(3);
ris+=(1./z) * pars->_Lumi_int.CLum_qqbar_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
break;
}
case(1):{
(pars->_Pointlike_int).setchannel(1);
ris+=(1./z) * pars->_Lumi_int.CLum_gg_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
break;
}
case(2):{
(pars->_Pointlike_int).setchannel(2);
ris+=(1./z) * pars->_Lumi_int.CLum_gq_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
break;
}
case(3):{
(pars->_Pointlike_int).setchannel(3);
ris+=(1./z) * pars->_Lumi_int.CLum_qqbar_x(tauprime/z) * pars->_Pointlike_int.LO_PL(pars->_xp_int)/z;
break;
}
}
return (ris);
}
int _core_NLO_PL_notsing(const int *ndim, const double x[], const int *ncomp, double res[], void *pars){
res[0] = 0.;
RHEHpt::_par_hadro *p = (RHEHpt::_par_hadro *) pars;
long double tauprime = ( p -> _tau_int ) * rho(p -> _xp_int);
//Setting integration limit
long double z = tauprime+(1.-tauprime)*x[0];
p->_Pointlike_int.SetCME(p->_mH_int/std::sqrt(z)* std::sqrt( rho(p -> _xp_int) ) );
res[0]+=( (1./z) * p->_Lumi_int.CLum_gg_x(tauprime/z) * p->_Pointlike_int.NLO_PL_notsing_doublediff(p->_xp_int,x[1]) / z );
return 0;
}
int _core_NLO_PL_sing(const int *ndim, const double x[], const int *ncomp, double res[], void *pars){
res[0] = 0.;
RHEHpt::_par_hadro *p = (RHEHpt::_par_hadro *) pars;
long double tauprime = (p->_tau_int) * rho(p -> _xp_int) ;
//Setting integration limit
long double z = tauprime+(1.-tauprime)*x[0];
p->_Pointlike_int.SetCME(p->_mH_int/std::sqrt(z)* std::sqrt( rho(p -> _xp_int) ) );
res[0] += ( (1./z) * p->_Lumi_int.CLum_gg_x(tauprime/z) * p->_Pointlike_int.NLO_PL_sing_doublediff(p->_xp_int,x[1]) / z );
return 0;
}
double NLO_delta_function(double z,void *p){
RHEHpt::_par_hadro *pars=(RHEHpt::_par_hadro *)p;
long double tauprime = (pars->_tau_int) * rho(pars -> _xp_int) ;
pars->_Pointlike_int.SetCME( pars -> _mH_int / std::sqrt(z) * std::sqrt( rho(pars -> _xp_int) ) );
return (1./z*pars->_Lumi_int.CLum_gg_x(tauprime/z)*pars->_Pointlike_int.NLO_PL_delta(pars->_xp_int)/z);
}
double pt_hadro(double z,void *p){
RHEHpt::_par_expansion *pars=(RHEHpt::_par_expansion *)p;
long double tauprime = (pars->_tau_int) * rho(pars -> _xp_int) ;
return (1./z) * pars -> _Lumi_int.CLum_x(tauprime/z, pars -> channel - 1) * pars -> ds_xp_part( z )/z;
}
long double RHEHpt::sigma_hadro_FO_fullmass(long double pt){
long double sigma = 0.0;
long double sigma_error = 0.0;
std::string name; // A string to identify what has been computed, i.e. a human readable equivalent of order and heavyquark
_par_hadro par(_Lum,Exact_FO_fullmass,Exact_FO_PL, get_xp(pt),get_tau(),_mH,_channel);
long double tauprime=(get_tau()) * rho( get_xp(pt) ) ;
double precision = 1e-6;
double LO_fullmass_ris = 0.0, LO_fullmass_error = 0.0;
gsl_function LO_fullmass;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
LO_fullmass.function = LO_fullmass_function;
LO_fullmass.params = ∥
gsl_integration_qags (&LO_fullmass, tauprime, 1.0, 0, precision, 100000, w, &LO_fullmass_ris, &LO_fullmass_error);
gsl_integration_workspace_free (w);
sigma = LO_fullmass_ris * tauprime * gev2_to_pb;
sigma_error = LO_fullmass_error*tauprime*gev2_to_pb;
name = "Sigma_hadro_LO_fullmass";
sigma *= SIGMA0();
sigma_error *= SIGMA0();
std::cout << name + "( " << _CME << " , " << pt << ")= " << sigma << " ± " << sigma_error << std::endl;
return sigma;
}
std::vector<double> RHEHpt::sigma_hadro_FO_pointlike(std::vector<double>& ptgrid, unsigned int order){
// int gridsize = ptgrid.size();
// std::vector< double > result( gridsize, 0. );
std::vector< double > result;
if (order == 1 ){
for (auto pt : ptgrid){
_par_hadro par(_Lum,Exact_FO_fullmass,Exact_FO_PL, get_xp(pt),get_tau(),_mH,_channel);
long double tauprime=(get_tau()) * rho( get_xp(pt) ) ;
double precision = 1e-6;
double LO_PL_ris = 0.0, LO_PL_error = 0.0;
gsl_function LO_PL;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
LO_PL.function = LO_PL_function;
LO_PL.params = ∥
gsl_integration_qags (&LO_PL, tauprime, 1.0, 0, precision, 100000, w, &LO_PL_ris, &LO_PL_error);
gsl_integration_workspace_free (w);
result.push_back( SIGMA0() * LO_PL_ris * tauprime * gev2_to_pb );
}
return result;
}
// in this way it always returns a vector of size ptgrid. In caso of an error or a choice of order == 0, the vector is all zero.
int gridsize = ptgrid.size();
result.resize( gridsize, 0. );
if ( order == 2){
if (_channel > 4){
std::cout << "Error channel must be or 0 (all channels) or 1 (GG) or 2 (GQ) or 3 (QQ)" << std::endl;
return result;
}
if(_running_scale) std::cerr << "\n*** Attention! ***\nRunning scale is on in RHEHpt, but is not implemented in hqt.\n" << std::endl;
_channel += 1; // channel in hqt starts from 1
std::cout << _channel << std::endl;
double CME = _CME;
double MH = _mH;
int len = ((_PDF -> set()).name()).length();
int hqt_order = order;
const char* pdfsetname = (_PDF -> set()).name().c_str();
int pdfmem = 0;
int channel=_channel;
hqt_( &CME, &MH, &MH, &_muR, &_muF, &hqt_order, pdfsetname, &len, &pdfmem, &ptgrid[0],&result[0],&gridsize, &channel);
for (unsigned int i = 0; i < ptgrid.size(); ++i)
{
result[i]*=_mH*_mH/(2.*ptgrid[i]); // from ptdistr to xpdistr
}
return result;
}
else if ( order > 2 ){
std::cout << "Error order must be or 1 (LO,as^3) or 2 (NLO,as^4)" << std::endl;
return result;
}
return result; //
}
long double RHEHpt::pt_distr_hadro(long double pt, unsigned int order, bool heavyquark){
if (_channel == 0){
long double sigma_tot = 0.;
for (short i = 1; i < 4; ++i){
set_channel(i);
//NOTE: Nice, but can be improved. We don't need to recompute int_coeff, xp_coeff for every channel.'.
sigma_tot += pt_distr_hadro(pt,order,heavyquark);
}
set_channel(0); //reset channel
std::cout << "total hadronic cross section at " << pt << " GeV: " << sigma_tot << " pb" << std::endl;
return sigma_tot;
}
double xp = get_xp(pt);
if(_running_scale)
set_running_scale(xp);
std::cout << "hadronic cross section for channel " << _channel
<< " at " << pt << " GeV: ";
std::vector<double> int_coeff = Integral_coeffs( order, xp, heavyquark);
std::vector<double> xp_coeff = Xp_prefactor_coeffs( order, xp);
_par_expansion::Partonic_Distr ds_xp_part; // the partonic cross section object
if ( _channel == 1){ // the gg partonic cross section (at fixed xp, as a function of x)
ds_xp_part = _par_expansion::Partonic_Distr( [&](double tau){
return pt_distr_series(pt_distr_series_terms(tau, int_coeff, xp_coeff, order, false), order); // false = not N space but x space
});
}
else if ( _channel == 2){ // the qg partonic cross section (at fixed xp, as a function of x)
std::vector<double> int_coeff_single = Integral_coeffs( order, xp, heavyquark, true);
std::vector<double> xp_coeff_single = Xp_prefactor_coeffs( order, xp, true); //expansion of xp^{M-1}
// std::cout << "printing coefflist middle" << std::endl;
// for (auto it: int_coeff_single){
// std::cout << it << " " ;
// }
// std::cout << std::endl ;
ds_xp_part = _par_expansion::Partonic_Distr( [=](double tau){
// std::cout << "printing coefflist after" << std::endl;
// for (auto it: int_coeff_single){
// std::cout << it << " " ;
// }
// std::cout << std::endl ;
double hpt_M1_M2 = pt_distr_series(pt_distr_series_terms<double>(tau, int_coeff, xp_coeff, order, false), order);
double hpt_M1_0 = pt_distr_series(pt_distr_series_terms<double>(tau, int_coeff_single, xp_coeff_single, order, false), order);
return (CF/CA) *(hpt_M1_M2 - hpt_M1_0);
});
}
else if ( _channel == 3){ // the qq partonic cross section (at fixed xp, as a function of x)
std::vector<double> int_coeff_single = Integral_coeffs( order, xp, heavyquark, true);
std::vector<double> xp_coeff_single = Xp_prefactor_coeffs( order, xp, true); //expansion of xp^{M-1}
ds_xp_part = _par_expansion::Partonic_Distr( [=](double tau){
double hpt_M1_M2 = pt_distr_series<double>(pt_distr_series_terms(tau, int_coeff, xp_coeff, order, false), order);
double hpt_M1_0 = pt_distr_series<double>(pt_distr_series_terms(tau, int_coeff_single, xp_coeff_single, order, false), order);
return std::pow(CF/CA,2.) *(hpt_M1_M2 - 2.*hpt_M1_0);
});
}
_par_expansion par( _Lum, ds_xp_part, xp , get_tau(), _mH,_channel);
long double tauprime=(get_tau()) * rho( xp ) ;
double precision = 1e-6;
double ris = 0.0, error = 0.0;
gsl_function f;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
f.function = pt_hadro;
f.params = ∥
gsl_integration_qags (&f, tauprime, 1.0, 0, precision, 100000, w, &ris, &error);
gsl_integration_workspace_free (w);
long double sigma = ris * tauprime * gev2_to_pb;
long double sigma_error = error*tauprime*gev2_to_pb;
std::cout << sigma << " pb\ta_s = " << _as << std::endl;
return sigma;
}
std::vector<double> RHEHpt::pt_distr_hadro(const std::vector< double >& ptgrid, unsigned int order, bool heavyquark){
std::vector< double > result;
for (auto pt : ptgrid)
result.push_back( pt_distr_hadro(pt, order, heavyquark) );
return result;
}
}
| 35.706412 | 183 | 0.628264 | [
"object",
"vector",
"transform"
] |
c0832348a31ef5d23c229d57d93a373305af3d84 | 20,549 | cpp | C++ | Source/OrangeScript.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | 4 | 2020-01-25T04:20:07.000Z | 2022-01-14T02:59:28.000Z | Source/OrangeScript.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | null | null | null | Source/OrangeScript.cpp | nolancs/OrangeMUD | 3db3ddf73855bb76110d7a6a8e67271c36652b04 | [
"MIT"
] | 1 | 2020-04-01T04:36:48.000Z | 2020-04-01T04:36:48.000Z | /******************************************************************************
Author: Matthew Nolan OrangeMUD Codebase
Date: January 2001 [Crossplatform]
License: 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.
Copyright 2000-2019 Matthew Nolan, All Rights Reserved
******************************************************************************/
#include "CommonTypes.h"
#include "Area.h"
#include "Mobile.h"
#include "MobileIndex.h"
#include "MUD.h"
#include "Object.h"
#include "ObjectIndex.h"
#include "OrangeScript.h"
#include "OrangeScriptVariable.h"
#include "Person.h"
#include "RoomIndex.h"
#include "StringMagic.h"
#include "StringUtils.h"
#include "Tables.h"
OrangeScript::OrangeScript()
: mOnThis(NULL)
, mType(0)
, mTrigger(0)
, mFlags(0)
, mID(0)
{
}
OrangeScript::~OrangeScript()
{
for(OScriptVariableIter i = mTextVariables.begin(); i != mTextVariables.end(); ++i)
delete *i;
}
#if 0
//***************************************************************************//
///////////////////////////////////////////////////////////////////////////////
//***************************************************************************//
#pragma mark -
#endif
//Outdated
VREF CvtToVRef(VNUM hOldVnum);
void OrangeScript::Convert()
{
Vector<STRINGCW> nFuncNames;
nFuncNames.Add("get_room");
nFuncNames.Add("create_obj");
nFuncNames.Add("CHAR ");
nFuncNames.Add("OBJ ");
nFuncNames.Add("has_obj");
nFuncNames.Add("mob_in_room");
ULONG i;
for(i = 0; i < nFuncNames.size(); ++i)
{
STRINGCW nOldSource = mSource.c_str();
STRINGCW nNewSource, nOldCall, nNewCall;
LONG nNumFound;
LONG nOldVNum = 0;
VREF nNewVRef;
do
{
CHAR* nFoundFunc;
if((nFoundFunc = strstr(nOldSource, nFuncNames[i])) != NULL)
{
nNewSource.Append(nOldSource, nFoundFunc - *nOldSource);
nOldSource.Erase(0, nFoundFunc - *nOldSource);
if(nFuncNames[i] == "CHAR ")
{
nNewSource += "PERSON ";
nOldSource.Erase(0, strlen(nFuncNames[i]));
}
else
if(nFuncNames[i] == "OBJ ")
{
nNewSource += "OBJECT ";
nOldSource.Erase(0, strlen(nFuncNames[i]));
}
else
{
nFoundFunc = strstr(nOldSource, ")");
ASSERT(nFoundFunc);
nOldCall.Clear();
nOldCall.Append(nOldSource, (nFoundFunc - *nOldSource)+1);
STRINGCW nNewCall;
if(i == 4 || i == 5)
{
printf("%s\n", *nOldCall);
CHAR nOldVarBuf[kMaxStringLen];
STRINGCW nSearchStr = nFuncNames[i] + "(%[^(),+], %ld)";
nNumFound = sscanf(nOldCall, *nSearchStr, nOldVarBuf, &nOldVNum);
if(nNumFound != 2)
{
nSearchStr = nFuncNames[i] + "(%[^(),+],%ld)";
nNumFound = sscanf(nOldCall, *nSearchStr, nOldVarBuf, &nOldVNum);
}
ASSERT(nNumFound == 2);
nNewVRef = CvtToVRef((VNUM)nOldVNum);
STRINGCW nAreaStr = MUD::Get()->GetArea(GetArea(nNewVRef))->mFileName;
nNewCall.SPrintF("%s(%s, \"%s/%d\")", *nFuncNames[i], nOldVarBuf, *nAreaStr, GetVnum(nNewVRef));
}
else
{
STRINGCW nSearchStr = nFuncNames[i] + "(%ld)";
nNumFound = sscanf(nOldCall, *nSearchStr, &nOldVNum);
ASSERT(nNumFound == 1);
nNewVRef = CvtToVRef((VNUM)nOldVNum);
STRINGCW nAreaStr = MUD::Get()->GetArea(GetArea(nNewVRef))->mFileName;
nNewCall.SPrintF("%s(\"%s/%d\")", *nFuncNames[i], *nAreaStr, GetVnum(nNewVRef));
}
printf("conv: %s => %s\n", *nOldCall, *nNewCall);
nNewSource += nNewCall;
nOldSource = nFoundFunc+1;
}
}
else
{
nNewSource += nOldSource;
break;
}
}
while(true);
mSource = *nNewSource;
}
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: OrangeScript::IsRunning
//
// Desc:: Returns true if this script is running currently in the MUD.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool OrangeScript::IsRunning()
{
for(List<MUD::RunningScript*>::iterator i = MUD::Get()->mScripts.begin(); i != MUD::Get()->mScripts.end(); ++i)
if((*i)->mScript == this)
return true;
return false;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: OrangeScript::StatTo
//
// Desc:: Gets the name of what this OrangeScript is attached to.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
STRINGCW OrangeScript::OnName()
{
RoomIndex* nRoom = dynamic_cast<RoomIndex*>(mOnThis);
if(nRoom)
return nRoom->mName;
MobileIndex* nMobile = dynamic_cast<MobileIndex*>(mOnThis);
if(nMobile)
return nMobile->mName;
ObjectIndex* nObject = dynamic_cast<ObjectIndex*>(mOnThis);
if(nObject)
return nObject->mName;
return "#[Unknown]#";
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: OrangeScript::StatTo
//
// Desc:: Sends all the statistics about an OrangeScript to a Person.
//
// Input:: The Person to send the statistics to.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void OrangeScript::StatTo(Person* hTo)
{
CHAR* nTypeNames[] = {"Room", "Object", "Mobile"};
STRINGCW nBuf, nTitleBuf;
nTitleBuf.SPrintF("[ ^T%s Script #%d for %s^x ]", nTypeNames[mType], mID, *OnName());
nTitleBuf.Capitalize(true);
nTitleBuf = OverlayCenterLine(nTitleBuf, kGfxSep);
nBuf.SPrintF(
//////////////////////////////////////////////////////////////////////////////////////////
"%s\n"
" Commands: %-35s Trigger: %s\n"
" Keywords: %-35s Flags: <none>\n"
" Texts: %s\n"
"\n"
"^USource Code... ^x\n"
"%s\n",
//////////////////////////////////////////////////////////////////////////////////////////
*nTitleBuf ,
*mCommands , gTriggerTable[mTrigger].mName ,
*mKeywords ,
"n/a yet" ,
mSource.c_str());
hTo->SendPaged(nBuf);
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: PhraseMatch
//
// Desc:: This is basically like IsNamed(), it takes a list of words and a
// list of keys and returns true if all the words in the word list
// match or partially match keys in the keylist. We don't use
// IsNamed() because we only do partial matches on >= 3 characters.
//
// Input:: hWordList: the word list, example "big troll".
// hKeyList: the key list, example "big smelly green troll".
//
// Output:: True if the match succeeded.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool PhraseMatch(STRINGCW& hWordList, STRINGCW& hKeyList)
{
if(hWordList.Empty() || hKeyList.Empty())
return false;
//** Parse Word List **//
STRINGCW nWord, nKeyword, nTheWords = hWordList, nTheKeys;
while(true)
{
nTheWords = nTheWords.OneArgument(nWord);
if(nWord.Empty())
return true;
//** Parse Keyword List **//
nTheKeys = hKeyList;
while(true)
{
nTheKeys = nTheKeys.OneArgument(nKeyword);
if(nKeyword.Empty())
return false;
if(nWord.Length() < 3)
{
if(!strcmp(nKeyword, nWord))
break;
}else{
if(StrPrefix(nKeyword, nWord))
break;
}
}
}
return true;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: OrangeScript::CheckTrigger
//
// Desc:: Given a command and list of arguments it checks to see if this
// script is triggered by them. This works for all types of scripts.
// The script is run and true is returned when triggered.
//
// Input:: hCmd: the command, example "look".
// hArg: the argument(s), example "east".
// theCh: the character in this scripting instance.
// theMob: the mobile in this scripting instance.
// theObj: the object in this scripting instance.
// theVict: the victim in this scripting instance.
//
// Output:: True if the script was triggered.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool OrangeScript::CheckTrigger(STRINGCW& hCmd, STRINGCW& hArg, Person* theCh, Mobile* theMob, Object* theObj, Person* theVict)
{
RoomIndex* theRoom = theCh->mInRoom;
void* nTarget = NULL;
void* nFound = NULL;
if(mTrigger != kScriptTrig_Phrase || hCmd.Empty())
return false;
if(!PhraseMatch(hCmd, mCommands))
return false;
//** Command Followed By Anything/Nothing **//
if(mKeywords.Empty())
{
MUD::Get()->RunScript(this, theRoom, theCh, theMob, theObj, theVict);
return true;
}
//** Object/Mobile Targeted In Keyword **//
if(mKeywords == "*" && mType != kRoomScript)
{
if(mType == kObjectScript)
{
ObjectHolder nRetrieved;
if(theCh->RetrieveObjectsHere(hArg, nRetrieved, kFromInvWearRoom) && nRetrieved.Size() == 1)
nFound = nRetrieved.Front();
nTarget = theObj;
}
else
if(mType == kMobileScript)
{
PersonHolder nRetrieved;
if(theCh->mInRoom->RetrievePeopleAs(theCh, hArg, nRetrieved) && nRetrieved.Size() == 1)
nFound = nRetrieved.Front();
nTarget = theMob;
}
else
{
return false;
}
if(nFound == nTarget)
{
MUD::Get()->RunScript(this, theRoom, theCh, theMob, theObj, theVict);
return true;
}
}
else
//** Command & Keyword Match **//
if(PhraseMatch(hArg, mKeywords))
{
MUD::Get()->RunScript(this, theRoom, theCh, theMob, theObj, theVict);
return true;
}
return false;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: TrigPhrase
//
// Desc:: Attempts to trigger any script when a Person issues a command.
//
// Input:: hCh: the character issuing the command.
// hCmd: the command, example "look".
// hArg: the argument(s), example "east".
//
// Output:: True if a script was triggered.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool TrigPhrase(Person* hCh, STRINGCW& hCmd, STRINGCW& hArg)
{
ObjectIter nObjectScan;
OScriptIter nScriptScan;
//** Object Scripts (on Person) **//
for(nObjectScan = hCh->ObjectHolder::Begin(); nObjectScan != hCh->ObjectHolder::End(); ++nObjectScan)
{
for(nScriptScan = (*nObjectScan)->mIndex->mScriptMap.begin(); nScriptScan != (*nObjectScan)->mIndex->mScriptMap.end(); ++nScriptScan)
{
if((*nScriptScan).second->CheckTrigger(hCmd, hArg, hCh, NULL, *nObjectScan, NULL))
return true;
}
}
//** Object Scripts (in Room) **//
for(nObjectScan = hCh->mInRoom->ObjectHolder::Begin(); nObjectScan != hCh->mInRoom->ObjectHolder::End(); ++nObjectScan)
{
for(nScriptScan = (*nObjectScan)->mIndex->mScriptMap.begin(); nScriptScan != (*nObjectScan)->mIndex->mScriptMap.end(); ++nScriptScan)
{
if((*nScriptScan).second->CheckTrigger(hCmd, hArg, hCh, NULL, *nObjectScan, NULL))
return true;
}
}
//** Mobile Scripts **//
PersonIter nPersonScan;
for(nPersonScan = hCh->mInRoom->PersonHolder::Begin(); nPersonScan != hCh->mInRoom->PersonHolder::End(); ++nPersonScan)
{
if((*nPersonScan)->isMobile)
{
for(nScriptScan = (*nPersonScan)->isMobile->mIndex->mScriptMap.begin(); nScriptScan != (*nPersonScan)->isMobile->mIndex->mScriptMap.end(); ++nScriptScan)
{
if((*nScriptScan).second->CheckTrigger(hCmd, hArg, hCh, (*nPersonScan)->isMobile, NULL, NULL))
return true;
}
}
}
//** Room Scripts **//
for(nScriptScan = hCh->mInRoom->mScriptMap.begin(); nScriptScan != hCh->mInRoom->mScriptMap.end(); ++nScriptScan)
{
if((*nScriptScan).second->CheckTrigger(hCmd, hArg, hCh, NULL, NULL, NULL))
return true;
}
return false;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Name:: TrigMove
//
// Desc:: Attempts to trigger any script when a Person moves using the two
// movement triggers, enter and leave.
//
// Input:: hCh: the character issuing the command.
// hType: kScriptTrig_Enter or kScriptTrig_Leave.
// hDirName: The direction they're leaving to or entering from.
//
// Output:: True if a script was triggered.
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool TrigMove(Person* hCh, SHORT hType, const STRINGCW& hDirName)
{
OScriptIter nScriptScan;
OrangeScript* nScript;
//** Room Scripts **//
for(nScriptScan = hCh->mInRoom->mScriptMap.begin(); nScriptScan != hCh->mInRoom->mScriptMap.end(); ++nScriptScan)
{
nScript = (*nScriptScan).second;
if(nScript->mTrigger == hType)
if(nScript->mKeywords.Empty() || nScript->mKeywords.IsNamed(hDirName))
{
MUD::Get()->RunScript(nScript, hCh->mInRoom, hCh, NULL, NULL, NULL);
return true;
}
}
//** Mobile Scripts **//
PersonIter nPersonScan;
for(nPersonScan = hCh->mInRoom->PersonHolder::Begin(); nPersonScan != hCh->mInRoom->PersonHolder::End(); ++nPersonScan)
{
if((*nPersonScan)->isMobile)
{
for(nScriptScan = (*nPersonScan)->isMobile->mIndex->mScriptMap.begin(); nScriptScan != (*nPersonScan)->isMobile->mIndex->mScriptMap.end(); ++nScriptScan)
{
nScript = (*nScriptScan).second;
if(nScript->mTrigger == hType)
if(nScript->mKeywords.Empty() || nScript->mKeywords.IsNamed(hDirName))
{
MUD::Get()->RunScript(nScript, hCh->mInRoom, hCh, (*nPersonScan)->isMobile, NULL, NULL);
return true;
}
}
}
}
//** Object Scripts (on Person) **//
ObjectIter nObjectScan;
for(nObjectScan = hCh->ObjectHolder::Begin(); nObjectScan != hCh->ObjectHolder::End(); ++nObjectScan)
{
for(nScriptScan = (*nObjectScan)->mIndex->mScriptMap.begin(); nScriptScan != (*nObjectScan)->mIndex->mScriptMap.end(); ++nScriptScan)
{
nScript = (*nScriptScan).second;
if(nScript->mTrigger == hType)
if(nScript->mKeywords.Empty() || nScript->mKeywords.IsNamed(hDirName))
{
MUD::Get()->RunScript(nScript, hCh->mInRoom, hCh, NULL, *nObjectScan, NULL);
return true;
}
}
}
//** Object Scripts (in Room) **//
for(nObjectScan = hCh->mInRoom->ObjectHolder::Begin(); nObjectScan != hCh->mInRoom->ObjectHolder::End(); ++nObjectScan)
{
for(nScriptScan = (*nObjectScan)->mIndex->mScriptMap.begin(); nScriptScan != (*nObjectScan)->mIndex->mScriptMap.end(); ++nScriptScan)
{
nScript = (*nScriptScan).second;
if(nScript->mTrigger == hType)
if(nScript->mKeywords.Empty() || nScript->mKeywords.IsNamed(hDirName))
{
MUD::Get()->RunScript(nScript, hCh->mInRoom, hCh, NULL, *nObjectScan, NULL);
return true;
}
}
}
return false;
}
#if 0
bool TrigAsk(Person *ch, Person *nMob, char *about)
{
char text[MAX_INPUT_LENGTH], Var[MAX_INPUT_LENGTH];
bool found = false;
Script *sScan;
if(!IS_NPC(nMob))
return false;
//** Sort Text **//
text[0] = '\0';
about = one_argument(about, Var);
for(; Var[0] != '\0'; about = one_argument(about, Var))
{
if(IsExactName(Var, "the"))
continue;
if(IsExactName(Var, "about"))
continue;
SmashChars(Var, "?.!", " ");
strcat(text, Var);
strcat(text, " ");
}
for(sScan = nMob->isMobile->iMob->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == ASK)
if(PhraseMatch(text, sScan->keywords))
{
found = true;
sScan->Run(nMob->inRoom, ch, nMob, NULL, NULL);
}
return found;
}
bool TrigWear(Person *ch, Object *item)
{
Script *sScan;
bool ran = false;
for(sScan = item->iObj->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == WEAR)
{
sScan->Run(ch->inRoom, ch, NULL, item, NULL);
ran = true;
}
return ran;
}
bool TrigRemove(Person *ch, Object *item)
{
Script *sScan;
bool ran = false;
for(sScan = item->iObj->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == REMOVE)
{
sScan->Run(ch->inRoom, ch, NULL, item, NULL);
ran = true;
}
return ran;
}
void TrigAttack(Person *ch, Object *item, Person *victim)
{
Script *sScan;
for(sScan = item->iObj->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == ATTACK)
{
sScan->Run(ch->inRoom, ch, NULL, item, victim);
}
}
bool TrigEat(Person *ch, Object *item)
{
Script *sScan;
bool ran = false;
for(sScan = item->iObj->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == EAT)
{
sScan->Run(ch->inRoom, ch, NULL, item, NULL);
ran = true;
}
return ran;
}
void TrigAssist(Person *ch, Person *victim, Person *checkMob)
{
Script *sScan;
if(!checkMob->isMobile)
return;
for(sScan = checkMob->isMobile->iMob->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == ASSIST)
{
sScan->Run(ch->inRoom, ch, checkMob, NULL, victim);
}
}
void TrigDeath(Person *chKiller, Person *mobVict, Object *corpse)
{
Script *sScan;
if(!mobVict->isMobile)
return;
for(sScan = mobVict->isMobile->iMob->scripts; sScan; sScan = sScan->nextLocal)
if(sScan->trigger == DEATH)
{
sScan->Run(mobVict->inRoom, chKiller, mobVict, corpse, NULL);
}
}
#endif
| 30.219118 | 165 | 0.510925 | [
"object",
"vector"
] |
c087b38dc475898ff10bcebc5fe284b370ee3092 | 12,939 | cc | C++ | DQMServices/Components/plugins/EDMtoMEConverter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DQMServices/Components/plugins/EDMtoMEConverter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DQMServices/Components/plugins/EDMtoMEConverter.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | /** \file EDMtoMEConverter.cc
*
* See header file for description of class
*
* \author M. Strang SUNY-Buffalo
*/
#include <cassert>
#include "DQMServices/Components/plugins/EDMtoMEConverter.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
using namespace lat;
template<typename T>
void EDMtoMEConverter::Tokens<T>::set(const edm::InputTag& runInputTag, const edm::InputTag& lumiInputTag, edm::ConsumesCollector& iC) {
runToken = iC.mayConsume<MEtoEDM<T>, edm::InRun>(runInputTag);
lumiToken = iC.mayConsume<MEtoEDM<T>, edm::InLumi>(lumiInputTag);
}
template<typename T>
void EDMtoMEConverter::Tokens<T>::getData(const edm::Run& iRun, edm::Handle<Product>& handle) const {
iRun.getByToken(runToken, handle);
}
template<typename T>
void EDMtoMEConverter::Tokens<T>::getData(const edm::LuminosityBlock& iLumi, edm::Handle<Product>& handle) const {
iLumi.getByToken(lumiToken, handle);
}
namespace {
// general
template <size_t I, size_t N>
struct ForEachHelper {
template <typename Tuple, typename Func>
static
void call(Tuple&& tpl, Func&& func) {
func(std::get<I-1>(tpl));
ForEachHelper<I+1, N>::call(std::forward<Tuple>(tpl), std::forward<Func>(func));
}
};
// break recursion
template <size_t N>
struct ForEachHelper<N, N> {
template <typename Tuple, typename Func>
static
void call(Tuple&& tpl, Func&& func) {
func(std::get<N-1>(tpl));
}
};
// helper function to provide nice interface
template <typename Tuple, typename Func>
void for_each(Tuple&& tpl, Func&& func) {
constexpr auto size = std::tuple_size<typename std::decay<Tuple>::type>::value;
ForEachHelper<1, size>::call(std::forward<Tuple>(tpl), std::forward<Func>(func));
}
template <typename T> struct HistoTraits;
template <> struct HistoTraits<TH1F> {
static TH1F *get(MonitorElement *me) { return me->getTH1F(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book1D(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH1S> {
static TH1S *get(MonitorElement *me) { return me->getTH1S(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book1S(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH1D> {
static TH1D *get(MonitorElement *me) { return me->getTH1D(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book1DD(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH2F> {
static TH2F *get(MonitorElement *me) { return me->getTH2F(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book2D(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH2S> {
static TH2S *get(MonitorElement *me) { return me->getTH2S(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book2S(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH2D> {
static TH2D *get(MonitorElement *me) { return me->getTH2D(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book2DD(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TH3F> {
static TH3F *get(MonitorElement *me) { return me->getTH3F(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->book3D(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TProfile>{
static TProfile *get(MonitorElement *me) { return me->getTProfile(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->bookProfile(std::forward<Args>(args)...);
}
};
template <> struct HistoTraits<TProfile2D> {
static TProfile2D *get(MonitorElement *me) { return me->getTProfile2D(); }
template <typename ...Args> static MonitorElement *book(DQMStore *dbe, Args&&... args) {
return dbe->bookProfile2D(std::forward<Args>(args)...);
}
};
// Default to histograms and similar, others are specialized
template <typename T>
struct AddMonitorElement {
template <typename MEtoEDMObject_object, typename RunOrLumi>
static
MonitorElement *call(DQMStore *dbe, MEtoEDMObject_object *metoedmobject, const std::string& dir, const std::string& name, const RunOrLumi& runOrLumi) {
MonitorElement *me = dbe->get(dir+"/"+metoedmobject->GetName());
if(me) {
auto histo = HistoTraits<T>::get(me);
if(histo && me->getTH1()->CanExtendAllAxes()) {
TList list;
list.Add(metoedmobject);
if (histo->Merge(&list) == -1)
std::cout << "ERROR EDMtoMEConverter::getData(): merge failed for '"
<< metoedmobject->GetName() << "'" << std::endl;
return me;
}
}
dbe->setCurrentFolder(dir);
return HistoTraits<T>::book(dbe, metoedmobject->GetName(), metoedmobject);
}
};
template <>
struct AddMonitorElement<double> {
template <typename MEtoEDMObject_object, typename RunOrLumi>
static
MonitorElement *call(DQMStore *dbe, MEtoEDMObject_object *metoedmobject, const std::string& dir, const std::string& name, const RunOrLumi& runOrLumi) {
dbe->setCurrentFolder(dir);
MonitorElement *me = dbe->bookFloat(name);
me->Fill(*metoedmobject);
return me;
}
};
// long long and int share some commonalities, which are captured here (we can have only one default template definition)
template <typename T>
struct AddMonitorElementForIntegers {
template <typename MEtoEDMObject_object, typename RunOrLumi>
static
MonitorElement *call(DQMStore *dbe, MEtoEDMObject_object *metoedmobject, const std::string& dir, const std::string& name, const RunOrLumi& runOrLumi) {
dbe->setCurrentFolder(dir);
T ival = getProcessedEvents(dbe, dir, name, runOrLumi);
MonitorElement *me = dbe->bookInt(name);
me->Fill(*metoedmobject + ival);
return me;
}
static
T getProcessedEvents(const DQMStore *dbe, const std::string& dir, const std::string& name, const edm::Run&) {
if(name.find("processedEvents") != std::string::npos) {
if(const MonitorElement *me = dbe->get(dir+"/"+name)) {
return me->getIntValue();
}
}
return 0;
}
static
T getProcessedEvents(const DQMStore *dbe, const std::string& dir, const std::string& name, const edm::LuminosityBlock&) {
return 0;
}
};
template <>
struct AddMonitorElement<long long> {
template <typename ...Args>
static
MonitorElement *call(Args&&... args) {
return AddMonitorElementForIntegers<long long>::call(std::forward<Args>(args)...);
}
};
template <>
struct AddMonitorElement<int> {
template <typename ...Args>
static
MonitorElement *call(Args&&... args) {
return AddMonitorElementForIntegers<int>::call(std::forward<Args>(args)...);
}
};
template <>
struct AddMonitorElement<TString> {
template <typename MEtoEDMObject_object, typename RunOrLumi>
static
MonitorElement *call(DQMStore *dbe, MEtoEDMObject_object *metoedmobject, const std::string& dir, const std::string& name, const RunOrLumi& runOrLumi) {
dbe->setCurrentFolder(dir);
std::string scont = metoedmobject->Data();
return dbe->bookString(name, scont);
}
};
void maybeSetLumiFlag(MonitorElement *me, const edm::Run&) {
}
void maybeSetLumiFlag(MonitorElement *me, const edm::LuminosityBlock&) {
me->setLumiFlag();
}
}
EDMtoMEConverter::EDMtoMEConverter(const edm::ParameterSet & iPSet) :
verbosity(0), frequency(0)
{
const edm::InputTag& runInputTag = iPSet.getParameter<edm::InputTag>("runInputTag");
const edm::InputTag& lumiInputTag = iPSet.getParameter<edm::InputTag>("lumiInputTag");
edm::ConsumesCollector iC = consumesCollector();
for_each(tokens_, [&](auto& tok) {
tok.set(runInputTag, lumiInputTag, iC);
});
constexpr char MsgLoggerCat[] = "EDMtoMEConverter_EDMtoMEConverter";
// get information from parameter set
name = iPSet.getUntrackedParameter<std::string>("Name");
verbosity = iPSet.getUntrackedParameter<int>("Verbosity");
frequency = iPSet.getUntrackedParameter<int>("Frequency");
convertOnEndLumi = iPSet.getUntrackedParameter<bool>("convertOnEndLumi",true);
convertOnEndRun = iPSet.getUntrackedParameter<bool>("convertOnEndRun",true);
// use value of first digit to determine default output level (inclusive)
// 0 is none, 1 is basic, 2 is fill output, 3 is gather output
verbosity %= 10;
// get dqm info
dbe = 0;
dbe = edm::Service<DQMStore>().operator->();
// print out Parameter Set information being used
if (verbosity >= 0) {
edm::LogInfo(MsgLoggerCat)
<< "\n===============================\n"
<< "Initialized as EDAnalyzer with parameter values:\n"
<< " Name = " << name << "\n"
<< " Verbosity = " << verbosity << "\n"
<< " Frequency = " << frequency << "\n"
<< "===============================\n";
}
iCountf = 0;
iCount.clear();
assert(sizeof(int64_t) == sizeof(long long));
} // end constructor
EDMtoMEConverter::~EDMtoMEConverter() {}
void EDMtoMEConverter::beginJob()
{
}
void EDMtoMEConverter::endJob()
{
constexpr char MsgLoggerCat[] = "EDMtoMEConverter_endJob";
if (verbosity >= 0)
edm::LogInfo(MsgLoggerCat)
<< "Terminating having processed " << iCount.size() << " runs across "
<< iCountf << " files.";
return;
}
void EDMtoMEConverter::respondToOpenInputFile(const edm::FileBlock& iFb)
{
++iCountf;
return;
}
void EDMtoMEConverter::beginRun(const edm::Run& iRun, const edm::EventSetup& iSetup)
{
constexpr char MsgLoggerCat[] = "EDMtoMEConverter_beginRun";
int nrun = iRun.run();
// keep track of number of unique runs processed
++iCount[nrun];
if (verbosity > 0) {
edm::LogInfo(MsgLoggerCat)
<< "Processing run " << nrun << " (" << iCount.size() << " runs total)";
} else if (verbosity == 0) {
if (nrun%frequency == 0 || iCount.size() == 1) {
edm::LogInfo(MsgLoggerCat)
<< "Processing run " << nrun << " (" << iCount.size() << " runs total)";
}
}
}
void EDMtoMEConverter::endRun(const edm::Run& iRun, const edm::EventSetup& iSetup)
{
if (convertOnEndRun) {
getData(iRun);
}
}
void EDMtoMEConverter::beginLuminosityBlock(const edm::LuminosityBlock& iLumi, const edm::EventSetup& iSetup)
{
}
void EDMtoMEConverter::endLuminosityBlock(const edm::LuminosityBlock& iLumi, const edm::EventSetup& iSetup)
{
if (convertOnEndLumi) {
getData(iLumi);
}
}
void EDMtoMEConverter::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
{
}
template <class T>
void
EDMtoMEConverter::getData(T& iGetFrom)
{
constexpr char MsgLoggerCat[] = "EDMtoMEConverter_getData";
if (verbosity >= 0)
edm::LogInfo (MsgLoggerCat) << "\nRestoring MonitorElements.";
for_each(tokens_, [&](const auto& tok) {
using Tokens_T = typename std::decay<decltype(tok)>::type;
using METype = typename Tokens_T::type;
using MEtoEDM_T = typename Tokens_T::Product;
edm::Handle<MEtoEDM_T> metoedm;
tok.getData(iGetFrom, metoedm);
if(!metoedm.isValid()) {
//edm::LogWarning(MsgLoggerCat)
// << "MEtoEDM<TH1F> doesn't exist in run";
return;
}
std::vector<typename MEtoEDM_T::MEtoEDMObject> metoedmobject =
metoedm->getMEtoEdmObject();
for (unsigned int i = 0; i < metoedmobject.size(); ++i) {
// get full path of monitor element
const std::string& pathname = metoedmobject[i].name;
if (verbosity > 0) std::cout << pathname << std::endl;
std::string dir;
// deconstruct path from fullpath
StringList fulldir = StringOps::split(pathname,"/");
std::string name = *(fulldir.end() - 1);
for (unsigned j = 0; j < fulldir.size() - 1; ++j) {
dir += fulldir[j];
if (j != fulldir.size() - 2) dir += "/";
}
// define new monitor element
MonitorElement *me = AddMonitorElement<METype>::call(dbe, &metoedmobject[i].object, dir, name, iGetFrom);
maybeSetLumiFlag(me, iGetFrom);
// attach taglist
for(const auto& tag: metoedmobject[i].tags) {
dbe->tag(me->getFullname(), tag);
}
} // end loop thorugh metoedmobject
});
// verify tags stored properly
if (verbosity > 0) {
std::vector<std::string> stags;
dbe->getAllTags(stags);
for (unsigned int i = 0; i < stags.size(); ++i) {
std::cout << "Tags: " << stags[i] << std::endl;
}
}
}
| 33.176923 | 155 | 0.648195 | [
"object",
"vector"
] |
c088b249d4d09de804fec28947aeef4b7b680d53 | 13,198 | cpp | C++ | OpenSim/Simulation/AssemblySolver.cpp | tnamayeshi/opensim-core | acbedd604909980293776da3d54b9611732964bf | [
"Apache-2.0"
] | null | null | null | OpenSim/Simulation/AssemblySolver.cpp | tnamayeshi/opensim-core | acbedd604909980293776da3d54b9611732964bf | [
"Apache-2.0"
] | 1 | 2022-03-19T14:24:11.000Z | 2022-03-19T14:24:11.000Z | OpenSim/Simulation/AssemblySolver.cpp | tnamayeshi/opensim-core | acbedd604909980293776da3d54b9611732964bf | [
"Apache-2.0"
] | null | null | null | /* -------------------------------------------------------------------------- *
* OpenSim: AssemblySolver.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* 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 "AssemblySolver.h"
#include "OpenSim/Simulation/Model/Model.h"
#include <OpenSim/Common/Constant.h>
#include "simbody/internal/AssemblyCondition_QValue.h"
using namespace std;
using namespace SimTK;
namespace OpenSim {
class Coordinate;
class CoordinateSet;
//______________________________________________________________________________
AssemblySolver::AssemblySolver
(const Model &model, const SimTK::Array_<CoordinateReference> &coordinateReferences,
double constraintWeight) : Solver(model),
_coordinateReferencesp(coordinateReferences)
{
setAuthors("Ajay Seth");
_assembler = NULL;
_constraintWeight = constraintWeight;
// default accuracy
_accuracy = 1e-4;
// Get model coordinates
const CoordinateSet& modelCoordSet = getModel().getCoordinateSet();
SimTK::Array_<CoordinateReference>::iterator p;
// Cycle through coordinate references
for(p = _coordinateReferencesp.begin();
p != _coordinateReferencesp.end(); p++)
{
if(p){
//Find if any references that are empty and throw them away
if(p->getName() == "" || p->getName() == "unknown"){
//Get rid of the corresponding reference too
p = _coordinateReferencesp.erase(p);
}
// Otherwise an error if the coordinate does not exist for this model
else if ( !modelCoordSet.contains(p->getName())){
throw(Exception("AssemblySolver: Model does not contain coordinate "+p->getName()+"."));
}
}
}
}
void AssemblySolver::setAccuracy(double accuracy)
{
_accuracy = accuracy;
// Changing the accuracy invalidates the existing SimTK::Assembler
_assembler.reset();
}
/* Internal method to convert the CoordinateReferences into goals of the
assembly solver. Subclasses, override and call base to include other goals
such as point of interest matching (Marker tracking). This method is
automatically called by assemble. */
void AssemblySolver::setupGoals(SimTK::State &s)
{
// wipe-out the previous SimTK::Assembler
_assembler.reset(new SimTK::Assembler(getModel().getMultibodySystem()));
_assembler->setAccuracy(_accuracy);
// Define weights on constraints. Note can be specified SimTK::Infinity to strictly enforce constraint
// otherwise the weighted constraint error becomes a goal.
_assembler->setSystemConstraintsWeight(_constraintWeight);
// clear any old coordinate goals
_coordinateAssemblyConditions.clear();
// Get model coordinates
const CoordinateSet& modelCoordSet = getModel().getCoordinateSet();
// Restrict solution to set range of any of the coordinates that are clamped
for(int i=0; i<modelCoordSet.getSize(); ++i){
const Coordinate& coord = modelCoordSet[i];
if(coord.getClamped(s)){
_assembler->restrictQ(coord.getBodyIndex(),
MobilizerQIndex(coord.getMobilizerQIndex()),
coord.getRangeMin(), coord.getRangeMax());
}
}
SimTK::Array_<CoordinateReference>::iterator p;
// Cycle through coordinate references
for(p = _coordinateReferencesp.begin();
p != _coordinateReferencesp.end(); p++) {
if(p){
CoordinateReference *coordRef = p;
const Coordinate &coord = modelCoordSet.get(coordRef->getName());
if(coord.getLocked(s)){
_assembler->lockQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()));
//No longer need the lock on
coord.setLocked(s, false);
//Get rid of the corresponding reference too
_coordinateReferencesp.erase(p);
p--; //decrement since erase automatically points to next in the list
}
else if(!(coord.get_is_free_to_satisfy_constraints())) {
// Make this reference and its current value a goal of the Assembler
SimTK::QValue *coordGoal = new SimTK::QValue(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()),
coordRef->getValue(s) );
// keep a handle to the goal so we can update
_coordinateAssemblyConditions.push_back(coordGoal);
// Add coordinate matching goal to the ik objective
_assembler->adoptAssemblyGoal(coordGoal, coordRef->getWeight(s));
}
}
}
unsigned int nqrefs = _coordinateReferencesp.size(),
nqgoals = _coordinateAssemblyConditions.size();
//Should have a one-to-one matched arrays
if(nqrefs != nqgoals)
throw Exception("AsemblySolver::setupGoals() has a mismatch between number of references and goals.");
}
/* Once a set of coordinates has been specified its target value can
be updated directly */
void AssemblySolver::updateCoordinateReference(const std::string &coordName, double value, double weight)
{
SimTK::Array_<CoordinateReference>::iterator p;
// Cycle through coordinate references
for(p = _coordinateReferencesp.begin();
p != _coordinateReferencesp.end(); p++) {
if(p->getName() == coordName){
p->setValueFunction(*new Constant(value));
p->setWeight(weight);
return;
}
}
}
/* Internal method to update the time, reference values and/or their
weights that define the goals, based on the passed in state. */
void AssemblySolver::updateGoals(const SimTK::State &s)
{
unsigned int nqrefs = _coordinateReferencesp.size();
for(unsigned int i=0; i<nqrefs; i++){
//update goal values from reference.
_coordinateAssemblyConditions[i]->setValue
((_coordinateReferencesp)[i].getValue(s));
//_assembler->setAssemblyConditionWeight(_coordinateAssemblyConditions[i]->
}
}
//______________________________________________________________________________
/*
* Assemble the model such that it satisfies configuration goals and constraints
* The input state is used to initialize the assembly and then is updated to
* return the resulting assembled configuration.
*/
void AssemblySolver::assemble(SimTK::State &state)
{
// Make a working copy of the state that will be used to set the internal
// state of the solver. This is necessary because we may wish to disable
// redundant constraints, but do not want this to affect the state of
// constraints the user expects
SimTK::State s = state;
// Make sure goals are up-to-date.
setupGoals(s);
// Let assembler perform some internal setup
_assembler->initialize(s);
// Useful to include through debug message/log in the future
log_debug("UNASSEMBLED CONFIGURATION (normerr={}, maxerr={}, cost={})",
_assembler->calcCurrentErrorNorm(),
max(abs(_assembler->getInternalState().getQErr())),
_assembler->calcCurrentGoal());
log_debug("Model numQs: {} Assembler num freeQs: {}",
_assembler->getInternalState().getNQ(), _assembler->getNumFreeQs());
try{
// Now do the assembly and return the updated state.
_assembler->assemble();
// Update the q's in the state passed in
_assembler->updateFromInternalState(s);
state.updQ() = s.getQ();
state.updU() = s.getU();
// Get model coordinates
const CoordinateSet& modelCoordSet = getModel().getCoordinateSet();
// Make sure the locks in original state are restored
for(int i=0; i< modelCoordSet.getSize(); ++i){
bool isLocked = modelCoordSet[i].getLocked(state);
if(isLocked)
modelCoordSet[i].setLocked(state, isLocked);
}
// TODO: Useful to include through debug message/log in the future
log_debug("ASSEMBLED CONFIGURATION (acc={} tol={} normerr={}, maxerr={}, cost={})",
_assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(),
_assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())),
_assembler->calcCurrentGoal());
log_debug("# initializations={}", _assembler->getNumInitializations());
log_debug("# assembly steps: {}", _assembler->getNumAssemblySteps());
log_debug(" evals: goal={} grad={} error={} jac={}",
_assembler->getNumGoalEvals(), _assembler->getNumGoalGradientEvals(),
_assembler->getNumErrorEvals(), _assembler->getNumErrorJacobianEvals());
}
catch (const std::exception& ex)
{
std::string msg = "AssemblySolver::assemble() Failed: ";
msg += ex.what();
throw Exception(msg);
}
}
/* Obtain a model configuration that meets the assembly conditions
(desired values and constraints) given a state that satisfies or
is close to satisfying the constraints. Note there can be no change
in the number of constraints or desired coordinates. Desired
coordinate values can and should be updated between repeated calls
to track a desired trajectory of coordinate values. */
void AssemblySolver::track(SimTK::State &s)
{
// move the target locations or angles, etc... just do not change number of goals
// and their type (constrained vs. weighted)
if(_assembler && _assembler->isInitialized()){
updateGoals(s);
}
else{
throw Exception(
"AssemblySolver::track() failed: assemble() must be called first.");
}
// TODO: Useful to include through debug message/log in the future
log_debug("UNASSEMBLED(track) CONFIGURATION (normerr={}, maxerr={}, cost={})",
_assembler->calcCurrentErrorNorm(),
max(abs(_assembler->getInternalState().getQErr())),
_assembler->calcCurrentGoal() );
log_debug("Model numQs: {} Assembler num freeQs: {}",
_assembler->getInternalState().getNQ(), _assembler->getNumFreeQs());
try{
// Now do the assembly and return the updated state.
_assembler->track(s.getTime());
// update the state from the result of the assembler
_assembler->updateFromInternalState(s);
// TODO: Useful to include through debug message/log in the future
log_debug("Tracking: t= {} (acc={} tol={} normerr={}, maxerr={}, cost={})",
s.getTime(),
_assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(),
_assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())),
_assembler->calcCurrentGoal());
}
catch (const std::exception& ex)
{
log_info( "AssemblySolver::track() attempt Failed: {}", ex.what());
throw Exception("AssemblySolver::track() attempt failed.");
}
}
const SimTK::Assembler& AssemblySolver::getAssembler() const
{
OPENSIM_THROW_IF(!_assembler, Exception,
"AssemblySolver::getAssembler() has no underlying Assembler to return.\n"
"AssemblySolver::setupGoals() must be called first.");
return *_assembler;
}
SimTK::Assembler& AssemblySolver::updAssembler()
{
OPENSIM_THROW_IF(!_assembler, Exception,
"AssemblySolver::updAssembler() has no underlying Assembler to return.\n"
"AssemblySolver::setupGoals() must be called first.");
return *_assembler;
}
} // end of namespace OpenSim
| 42.990228 | 134 | 0.629868 | [
"model"
] |
c08c96f4fbdfdea49fd8b99a3dfea8ddbff6e1b0 | 9,068 | cpp | C++ | test/integration_tests/src/test_prepare_on_all.cpp | kw217/cpp-driver | 58c17d15b7ade2a1e6fdf3ce05d6fbe3d90f1828 | [
"Apache-2.0"
] | 1 | 2019-04-22T04:36:53.000Z | 2019-04-22T04:36:53.000Z | test/integration_tests/src/test_prepare_on_all.cpp | kw217/cpp-driver | 58c17d15b7ade2a1e6fdf3ce05d6fbe3d90f1828 | [
"Apache-2.0"
] | null | null | null | test/integration_tests/src/test_prepare_on_all.cpp | kw217/cpp-driver | 58c17d15b7ade2a1e6fdf3ce05d6fbe3d90f1828 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) DataStax, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <string>
#include <boost/chrono.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/test/debug.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include "cassandra.h"
#include "execute_request.hpp"
#include "statement.hpp"
#include "test_utils.hpp"
#define NUM_LOCAL_NODES 3
/**
* Test harness for prepare on all host functionality.
*/
struct PrepareOnAllTests : public test_utils::SingleSessionTest {
/**
* Create a basic schema (system table queries won't always prepare properly)
* and clear all prepared statements.
*/
PrepareOnAllTests()
: SingleSessionTest(NUM_LOCAL_NODES, 0)
, keyspace(str(boost::format("ks_%s") % test_utils::generate_unique_str(uuid_gen)))
, prepared_query_(str(boost::format("SELECT * FROM %s.test") % keyspace)) {
test_utils::execute_query(
session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT) % keyspace % "1"));
test_utils::execute_query(session, str(boost::format("USE %s") % keyspace));
test_utils::execute_query(session, "CREATE TABLE test (k text PRIMARY KEY, v text)");
// The "system.prepare_statements" table only exists in C* 3.10+
if (version >= "3.10") {
for (int node = 1; node <= NUM_LOCAL_NODES; ++node) {
test_utils::execute_query(session_for_node(node).get(),
"TRUNCATE TABLE system.prepared_statements");
}
}
// Ensure existing prepared statements are not re-prepared when they become
// available again.
cass_cluster_set_prepare_on_up_or_add_host(cluster, cass_false);
}
/**
* Get a session that is only connected to the given node.
*
* @param node The node the session should be connected to
* @return The connected session
*/
const test_utils::CassSessionPtr& session_for_node(int node) {
if (node >= static_cast<int>(sessions.size()) || !sessions[node]) {
sessions.resize(node + 1);
std::stringstream ip_address;
ip_address << ccm->get_ip_prefix() << node;
test_utils::CassClusterPtr cluster(cass_cluster_new());
cass_cluster_set_contact_points(cluster.get(), ip_address.str().c_str());
cass_cluster_set_whitelist_filtering(cluster.get(), ip_address.str().c_str());
sessions[node] = test_utils::create_session(cluster.get());
}
return sessions[node];
}
/**
* Verify that all nodes have empty "system.prepared_statements" tables.
*/
void prepared_statements_is_empty_on_all_nodes() {
for (int node = 1; node <= NUM_LOCAL_NODES; ++node) {
prepared_statements_is_empty(node);
}
}
/**
* Verify that a nodes "system.prepared_statements" table is empty.
*
* @param node The node to check
*/
void prepared_statements_is_empty(int node) {
test_utils::CassResultPtr result;
test_utils::execute_query(session_for_node(node).get(),
"SELECT * FROM system.prepared_statements", &result);
BOOST_REQUIRE_EQUAL(cass_result_row_count(result.get()), 0u);
}
/**
* Check to see if a query has been prepared on a given node.
*
* @param node The node to check
* @param query A query string
* @return true if the query has been prepared on the node, otherwise false
*/
bool prepared_statement_is_present(int node, const std::string& query) {
test_utils::CassResultPtr result;
test_utils::execute_query(session_for_node(node).get(),
"SELECT * FROM system.prepared_statements", &result);
test_utils::CassIteratorPtr iterator(cass_iterator_from_result(result.get()));
while (cass_iterator_next(iterator.get())) {
const CassRow* row = cass_iterator_get_row(iterator.get());
BOOST_REQUIRE(row);
const CassValue* query_column = cass_row_get_column_by_name(row, "query_string");
const char* query_string;
size_t query_string_len;
BOOST_REQUIRE_EQUAL(cass_value_get_string(query_column, &query_string, &query_string_len),
CASS_OK);
if (query == std::string(query_string, query_string_len)) {
return true;
}
}
return false;
}
/**
* Get the count of nodes in the cluster where the provided query is prepared.
*
* @param query A query string
* @return The number of nodes that have the prepared statement
*/
int prepared_statement_is_present_count(const std::string& query) {
int count = 0;
for (int node = 1; node <= NUM_LOCAL_NODES; ++node) {
if (prepared_statement_is_present(node, query)) {
count++;
}
}
return count;
}
/**
* Verify that a given number of nodes contain a prepared statement.
*
* @param count The number of nodes the query should be prepared on
*/
void verify_prepared_statement_count(int count) {
prepared_statements_is_empty_on_all_nodes();
test_utils::CassSessionPtr session(test_utils::create_session(cluster));
test_utils::CassFuturePtr future(cass_session_prepare(session.get(), prepared_query_.c_str()));
BOOST_REQUIRE_EQUAL(cass_future_error_code(future.get()), CASS_OK);
test_utils::CassPreparedPtr prepared(cass_future_get_prepared(future.get()));
BOOST_REQUIRE(prepared);
BOOST_CHECK_EQUAL(prepared_statement_is_present_count(prepared_query_), count);
}
/**
* Wait for a session to reconnect to a node.
*
* @param node The node to wait for
*/
void wait_for_node(int node) {
for (int i = 0; i < 10; ++i) {
test_utils::CassStatementPtr statement(cass_statement_new("SELECT * FROM system.peers", 0));
test_utils::CassFuturePtr future(
cass_session_execute(session_for_node(node).get(), statement.get()));
if (cass_future_error_code(future.get()) == CASS_OK) {
return;
}
boost::this_thread::sleep_for(boost::chrono::seconds(1));
}
BOOST_REQUIRE(false);
}
/**
* A vector of sessions that are only connected to a single host (via the
* whitelist policy).
*/
std::vector<test_utils::CassSessionPtr> sessions;
/**
* The test's keyspace
*/
std::string keyspace;
/**
* The query to be prepared
*/
std::string prepared_query_;
};
BOOST_FIXTURE_TEST_SUITE(prepare_on_all, PrepareOnAllTests)
/**
* Verify that only a single node is prepared when the prepare on all hosts
* setting is disabled.
*
* @since 2.8
* @test_category prepared
*
*/
BOOST_AUTO_TEST_CASE(only_prepares_a_single_node_when_disabled) {
if (!check_version("3.10")) return;
// Prepare on all hosts disabled
cass_cluster_set_prepare_on_all_hosts(cluster, cass_false);
// Only a single host should have the statement prepared
verify_prepared_statement_count(1);
}
/**
* Verify that all nodes are prepared properly when the prepare on all hosts
* setting is enabled.
*
* @since 2.8
* @test_category prepared
*
*/
BOOST_AUTO_TEST_CASE(prepares_on_all_nodes_when_enabled) {
if (!check_version("3.10")) return;
// Prepare on all hosts enabled
cass_cluster_set_prepare_on_all_hosts(cluster, cass_true);
// All hosts should have the statement prepared
verify_prepared_statement_count(3);
}
/**
* Verify that all available nodes are prepared properly when the prepare on
* all hosts setting is enabled and one of the nodes is not available.
*
* The statement should be prepared on all available nodes, but not the node
* that was down.
*
* @since 2.8
* @test_category prepared
*
*/
BOOST_AUTO_TEST_CASE(prepare_on_all_handles_node_outage) {
if (!check_version("3.10")) return;
// Prepare on all hosts enabled
cass_cluster_set_prepare_on_all_hosts(cluster, cass_true);
// Ensure there are no existing prepared statements
prepared_statements_is_empty_on_all_nodes();
ccm->kill_node(2);
{ // Prepare the statement
test_utils::CassSessionPtr session(test_utils::create_session(cluster));
test_utils::CassFuturePtr future(cass_session_prepare(session.get(), prepared_query_.c_str()));
BOOST_REQUIRE_EQUAL(cass_future_error_code(future.get()), CASS_OK);
test_utils::CassPreparedPtr prepared(cass_future_get_prepared(future.get()));
BOOST_REQUIRE(prepared);
}
ccm->start_node(2);
// Wait for the session to reconnect to the node
wait_for_node(2);
// The statement should only be prepared on the previously available nodes
BOOST_CHECK_EQUAL(prepared_statement_is_present_count(prepared_query_), 2);
}
BOOST_AUTO_TEST_SUITE_END()
| 31.486111 | 99 | 0.705117 | [
"vector"
] |
c08cd28c3ebb1914c680ca6c2b74f10852889f10 | 8,023 | cpp | C++ | Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtCollada/v_repExtCollada.cpp | keke02/Fast-reconfiguration-of-robotic-production-systems | 44ffe14b8a4a4798b559eede9b3766acb55f294e | [
"CC0-1.0"
] | null | null | null | Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtCollada/v_repExtCollada.cpp | keke02/Fast-reconfiguration-of-robotic-production-systems | 44ffe14b8a4a4798b559eede9b3766acb55f294e | [
"CC0-1.0"
] | null | null | null | Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtCollada/v_repExtCollada.cpp | keke02/Fast-reconfiguration-of-robotic-production-systems | 44ffe14b8a4a4798b559eede9b3766acb55f294e | [
"CC0-1.0"
] | null | null | null | // This file is part of the COLLADA PLUGIN for V-REP
//
// Copyright 2006-2015 Coppelia Robotics GmbH. All rights reserved.
// marc@coppeliarobotics.com
// www.coppeliarobotics.com
//
// The COLLADA PLUGIN is licensed under the terms of GNU GPL:
//
// -------------------------------------------------------------------
// The COLLADA PLUGIN 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.
//
// THE COLLADA PLUGIN IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL
// AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS,
// DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR
// MISUSING THIS SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the COLLADA PLUGIN. If not, see <http://www.gnu.org/licenses/>.
// -------------------------------------------------------------------
//
// This file was automatically created for V-REP release V3.2.3 rev4 on December 21st 2015
#include "v_repExtCollada.h"
#include "v_repLib.h"
#include <iostream>
#include "colladadialog.h"
#ifdef _WIN32
#include <direct.h>
#endif /* _WIN32 */
#if defined (__linux) || defined (__APPLE__)
#include <string.h>
#define _stricmp(x,y) strcasecmp(x,y)
#endif
#define PLUGIN_VERSION 5 // 5 since 14/12/2015 (headless mode detect), 4 since 14/5/2015, 3 since 26/11/2014, 2 since 10/1/2014 (new lock)
LIBRARY vrepLib;
CColladaDialog* colladaDialog=NULL;
// This is the plugin start routine (called just once, just after the plugin was loaded):
VREP_DLLEXPORT unsigned char v_repStart(void* reservedPointer,int reservedInt)
{
// Dynamically load and bind V-REP functions:
// ******************************************
// 1. Figure out this plugin's directory:
char curDirAndFile[1024];
#ifdef _WIN32
_getcwd(curDirAndFile, sizeof(curDirAndFile));
#elif defined (__linux) || defined (__APPLE__)
getcwd(curDirAndFile, sizeof(curDirAndFile));
#endif
std::string currentDirAndPath(curDirAndFile);
// 2. Append the V-REP library's name:
std::string temp(currentDirAndPath);
#ifdef _WIN32
temp+="/v_rep.dll";
#elif defined (__linux)
temp+="/libv_rep.so";
#elif defined (__APPLE__)
temp+="/libv_rep.dylib";
#endif /* __linux || __APPLE__ */
// 3. Load the V-REP library:
vrepLib=loadVrepLibrary(temp.c_str());
if (vrepLib==NULL)
{
std::cout << "Error, could not find or correctly load the V-REP library. Cannot start 'Collada' plugin.\n";
return(0); // Means error, V-REP will unload this plugin
}
if (getVrepProcAddresses(vrepLib)==0)
{
std::cout << "Error, could not find all required functions in the V-REP library. Cannot start 'Collada' plugin.\n";
unloadVrepLibrary(vrepLib);
return(0); // Means error, V-REP will unload this plugin
}
// ******************************************
// Check the version of V-REP:
// ******************************************
int vrepVer;
simGetIntegerParameter(sim_intparam_program_version,&vrepVer);
if (vrepVer<20604) // if V-REP version is smaller than 2.06.04
{
std::cout << "Sorry, your V-REP copy is somewhat old. Cannot start 'Collada' plugin.\n";
unloadVrepLibrary(vrepLib);
return(0); // Means error, V-REP will unload this plugin
}
// ******************************************
// Check if V-REP runs in headless mode:
// ******************************************
if (simGetBooleanParameter(sim_boolparam_headless)>0)
{
std::cout << "V-REP runs in headless mode. Cannot start 'Collada' plugin.\n";
unloadVrepLibrary(vrepLib);
return(0); // Means error, V-REP will unload this plugin
}
// ******************************************
QWidget* pMainWindow = (QWidget*)simGetMainWindow(1);
colladaDialog=new CColladaDialog(pMainWindow); // The plugin dialog
simAddModuleMenuEntry("",1,&colladaDialog->dialogMenuItemHandle);
simSetModuleMenuItemState(colladaDialog->dialogMenuItemHandle,1,"COLLADA import/export...");
return(PLUGIN_VERSION); // initialization went fine, we return the version number of this plugin (can be queried with simGetModuleName)
}
// This is the plugin end routine (called just once, when V-REP is ending, i.e. releasing this plugin):
VREP_DLLEXPORT void v_repEnd()
{
// Here you could handle various clean-up tasks
delete colladaDialog;
unloadVrepLibrary(vrepLib); // release the library
}
// This is the plugin messaging routine (i.e. V-REP calls this function very often, with various messages):
VREP_DLLEXPORT void* v_repMessage(int message,int* auxiliaryData,void* customData,int* replyData)
{ // This is called quite often. Just watch out for messages/events you want to handle
// Keep following 6 lines at the beginning and unchanged:
static bool refreshDlgFlag=true;
int errorModeSaved;
simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);
void* retVal=NULL;
// Here we can intercept many messages from V-REP (actually callbacks).
// For a complete list of messages that you can intercept/react with, search for "sim_message_eventcallback"-type constants
// in the V-REP user manual.
if (message==sim_message_eventcallback_refreshdialogs)
refreshDlgFlag=true; // V-REP dialogs were refreshed. Maybe a good idea to refresh this plugin's dialog too
if (message==sim_message_eventcallback_menuitemselected)
{ // A custom menu bar entry was selected..
if (auxiliaryData[0]==colladaDialog->dialogMenuItemHandle)
{
colladaDialog->makeVisible(!colladaDialog->getVisible()); // Toggle visibility of the dialog
}
}
if (message==sim_message_eventcallback_colladaplugin)
{
if (auxiliaryData[0]==0)
replyData[0]=PLUGIN_VERSION; // this is the version number of this plugin
if (auxiliaryData[0]==1)
replyData[0]=colladaDialog->importSingleGroupedShape((const char*)customData,(auxiliaryData[1]&1)!=0,float(auxiliaryData[2])/1000.0f);
}
if (message==sim_message_eventcallback_instancepass)
{ // It is important to always correctly react to events in V-REP. This message is the most convenient way to do so:
colladaDialog->handleCommands();
colladaDialog->setSimulationStopped(simGetSimulationState()==sim_simulation_stopped);
int flags=auxiliaryData[0];
bool sceneContentChanged=((flags&(1+2+4+8+16+32+64+256))!=0); // object erased, created, model or scene loaded, und/redo called, instance switched, or object scaled since last sim_message_eventcallback_instancepass message
bool instanceSwitched=((flags&64)!=0);
if (instanceSwitched)
{
// React to an instance switch here!!
}
if (sceneContentChanged)
{
refreshDlgFlag=true;
}
}
if ((message==sim_message_eventcallback_guipass)&&refreshDlgFlag)
{ // handle refresh of the plugin's dialog:
colladaDialog->refresh(); // Refresh the dialog
refreshDlgFlag=false;
}
if (message==sim_message_eventcallback_simulationabouttostart)
{
colladaDialog->simulationAboutToStart();
}
if (message==sim_message_eventcallback_mainscriptabouttobecalled)
{
colladaDialog->mainScriptAboutToBeCalled();
}
if (message==sim_message_eventcallback_beforerendering)
{ // we are still in the main SIM thread!
colladaDialog->renderingPassAboutToBeCalled();
}
if (message==sim_message_eventcallback_simulationended)
{
colladaDialog->simulationEnded();
}
// You can add many more messages to handle here
// Keep following unchanged:
simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings
return(retVal);
}
| 38.946602 | 225 | 0.69388 | [
"object",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.