hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d6b6efad1e77ced176a5bec421e7b66f4fab30fb | 7,692 | cc | C++ | src/developer/build_info/build_info_unittest.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/build_info/build_info_unittest.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/developer/build_info/build_info_unittest.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build_info.h"
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/namespace.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/gtest/test_loop_fixture.h>
#include <lib/sys/cpp/testing/component_context_provider.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/vfs/cpp/pseudo_dir.h>
#include <lib/vfs/cpp/pseudo_file.h>
#include <zircon/status.h>
namespace {
const char kFuchsiaBuildInfoDirectoryPath[] = "/config/build-info";
const char kProductFileName[] = "product";
const char kBoardFileName[] = "board";
const char kVersionFileName[] = "version";
const char kLastCommitDateFileName[] = "latest-commit-date";
const char kSnapshotFileName[] = "snapshot";
} // namespace
class BuildInfoServiceInstance {
public:
explicit BuildInfoServiceInstance(std::unique_ptr<sys::ComponentContext> context) {
context_ = std::move(context);
binding_ = std::make_unique<fidl::Binding<fuchsia::buildinfo::Provider>>(&impl_);
fidl::InterfaceRequestHandler<fuchsia::buildinfo::Provider> handler =
[&](fidl::InterfaceRequest<fuchsia::buildinfo::Provider> request) {
binding_->Bind(std::move(request));
};
context_->outgoing()->AddPublicService(std::move(handler));
}
private:
ProviderImpl impl_;
std::unique_ptr<fidl::Binding<fuchsia::buildinfo::Provider>> binding_;
std::unique_ptr<sys::ComponentContext> context_;
};
class BuildInfoServiceTestFixture : public gtest::TestLoopFixture {
public:
BuildInfoServiceTestFixture() : loop_(&kAsyncLoopConfigNoAttachToCurrentThread){};
void SetUp() override {
TestLoopFixture::SetUp();
build_info_service_instance_.reset(new BuildInfoServiceInstance(provider_.TakeContext()));
loop_.StartThread();
// Create a channel.
zx_handle_t endpoint0;
zx_handle_t endpoint1;
zx_status_t status = zx_channel_create(0, &endpoint0, &endpoint1);
ZX_ASSERT_MSG(status == ZX_OK, "Cannot create channel: %s\n", zx_status_get_string(status));
// Get the process's namespace.
fdio_ns_t *ns;
status = fdio_ns_get_installed(&ns);
ZX_ASSERT_MSG(status == ZX_OK, "Cannot get namespace: %s\n", zx_status_get_string(status));
// Create the /config/build-info path in the namespace.
std::string build_info_directory_path(kFuchsiaBuildInfoDirectoryPath);
status = fdio_ns_bind(ns, build_info_directory_path.c_str(), endpoint0);
ZX_ASSERT_MSG(status == ZX_OK, "Cannot bind %s to namespace: %s\n",
build_info_directory_path.c_str(), zx_status_get_string(status));
// Connect the build-info PseudoDir to the /config/build-info path.
zx::channel channel(endpoint1);
build_info_directory_.Serve(fuchsia::io::OPEN_RIGHT_READABLE | fuchsia::io::OPEN_RIGHT_WRITABLE,
std::move(channel), loop_.dispatcher());
}
// Creates a PsuedoDir named |build_info_filename| in the PsuedoDir "/config/build-info" in
// the component's namespace. The file contains |build_info_filename| followed optionally by
// a trailing newline.
void CreateBuildInfoFile(std::string build_info_filename, bool with_trailing_newline = true) {
std::string file_contents(build_info_filename);
// Some build info files contain a trailing newline which the build info service strips.
// Optionally add a trailing newline to test the trailing whitespace stripping.
if (with_trailing_newline) {
file_contents.append("\n");
}
vfs::PseudoFile::ReadHandler versionFileReadFn = [file_contents](std::vector<uint8_t> *output,
size_t max_file_size) {
output->resize(file_contents.length());
std::copy(file_contents.begin(), file_contents.end(), output->begin());
return ZX_OK;
};
vfs::PseudoFile::WriteHandler versionFileWriteFn;
// Create a PseudoFile.
std::unique_ptr<vfs::PseudoFile> pseudo_file = std::make_unique<vfs::PseudoFile>(
file_contents.length(), std::move(versionFileReadFn), std::move(versionFileWriteFn));
// Add the file to the build-info PseudoDir.
build_info_directory_.AddEntry(std::move(build_info_filename), std::move(pseudo_file));
}
void TearDown() override {
TestLoopFixture::TearDown();
build_info_service_instance_.reset();
DestroyBuildInfoFile();
}
protected:
fuchsia::buildinfo::ProviderPtr GetProxy() {
fuchsia::buildinfo::ProviderPtr provider;
provider_.ConnectToPublicService(provider.NewRequest());
return provider;
}
private:
void DestroyBuildInfoFile() {
fdio_ns_t *ns;
zx_status_t status = fdio_ns_get_installed(&ns);
ZX_ASSERT_MSG(status == ZX_OK, "Cannot retrieve the namespace: %s\n",
zx_status_get_string(status));
std::string build_info_directory_path(kFuchsiaBuildInfoDirectoryPath);
status = fdio_ns_unbind(ns, build_info_directory_path.c_str());
ZX_ASSERT_MSG(status == ZX_OK, "Cannot unbind from a namespace: %s\n",
zx_status_get_string(status));
loop_.Quit();
loop_.JoinThreads();
}
std::unique_ptr<BuildInfoServiceInstance> build_info_service_instance_;
sys::testing::ComponentContextProvider provider_;
vfs::PseudoDir build_info_directory_;
async::Loop loop_;
};
TEST_F(BuildInfoServiceTestFixture, BuildInfo) {
CreateBuildInfoFile(kProductFileName);
CreateBuildInfoFile(kBoardFileName);
CreateBuildInfoFile(kVersionFileName);
CreateBuildInfoFile(kLastCommitDateFileName);
fuchsia::buildinfo::ProviderPtr proxy = GetProxy();
proxy->GetBuildInfo([&](const fuchsia::buildinfo::BuildInfo &response) {
EXPECT_TRUE(response.has_product_config());
EXPECT_EQ(response.product_config(), kProductFileName);
EXPECT_TRUE(response.has_board_config());
EXPECT_EQ(response.board_config(), kBoardFileName);
EXPECT_TRUE(response.has_version());
EXPECT_EQ(response.version(), kVersionFileName);
EXPECT_TRUE(response.has_latest_commit_date());
EXPECT_EQ(response.latest_commit_date(), kLastCommitDateFileName);
});
RunLoopUntilIdle();
}
TEST_F(BuildInfoServiceTestFixture, EmptyBuildInfo) {
CreateBuildInfoFile("");
CreateBuildInfoFile("");
CreateBuildInfoFile("");
CreateBuildInfoFile("");
fuchsia::buildinfo::ProviderPtr proxy = GetProxy();
proxy->GetBuildInfo([&](const fuchsia::buildinfo::BuildInfo &response) {
EXPECT_FALSE(response.has_product_config());
EXPECT_FALSE(response.has_board_config());
EXPECT_FALSE(response.has_version());
EXPECT_FALSE(response.has_latest_commit_date());
});
RunLoopUntilIdle();
}
TEST_F(BuildInfoServiceTestFixture, NonPresentBuildInfo) {
fuchsia::buildinfo::ProviderPtr proxy = GetProxy();
proxy->GetBuildInfo([&](const fuchsia::buildinfo::BuildInfo &response) {
EXPECT_FALSE(response.has_product_config());
EXPECT_FALSE(response.has_board_config());
EXPECT_FALSE(response.has_version());
EXPECT_FALSE(response.has_latest_commit_date());
});
RunLoopUntilIdle();
}
TEST_F(BuildInfoServiceTestFixture, Snapshot) {
CreateBuildInfoFile(kSnapshotFileName, false);
fuchsia::buildinfo::ProviderPtr proxy = GetProxy();
proxy->GetSnapshotInfo([&](zx::vmo response) {
uint64_t size;
response.get_size(&size);
auto buffer = std::make_unique<char[]>(size);
response.read(buffer.get(), 0, size);
std::string response_string{buffer.get()};
EXPECT_EQ(response_string, kSnapshotFileName);
});
RunLoopUntilIdle();
}
| 36.803828 | 100 | 0.727899 | wwjiang007 |
d6b72ff253851c83c2993880e81f78e70d7d0fa2 | 3,323 | hpp | C++ | AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp | edellano/Adenita-SAMSON-Edition-Win- | 6df8d21572ef40fe3fc49165dfaa1d4318352a69 | [
"BSD-3-Clause"
] | 2 | 2020-09-07T20:48:43.000Z | 2021-09-03T05:49:59.000Z | AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp | edellano/Adenita-SAMSON-Edition | 6df8d21572ef40fe3fc49165dfaa1d4318352a69 | [
"BSD-3-Clause"
] | 6 | 2020-04-05T18:39:28.000Z | 2022-01-11T14:28:55.000Z | AdenitaCoreSE/include/SEAdenitaCoreSEAppGUI.hpp | edellano/Adenita-SAMSON-Edition-Win- | 6df8d21572ef40fe3fc49165dfaa1d4318352a69 | [
"BSD-3-Clause"
] | 2 | 2021-07-13T12:58:13.000Z | 2022-01-11T13:52:00.000Z | #pragma once
#include "SBGApp.hpp"
#include "ui_SEAdenitaCoreSEAppGUI.h"
#include <QMessageBox>
#include <QComboBox>
#include <QSpinBox>
#include <QToolButton>
class SEAdenitaCoreSEApp;
/// This class implements the GUI of the app
// SAMSON Element generator pro tip: add GUI functionality in this class. The non-GUI functionality should go in the SEAdenitaCoreSEApp class
class SEAdenitaCoreSEAppGUI : public SBGApp {
Q_OBJECT
public:
/// \name Constructors and destructors
//@{
SEAdenitaCoreSEAppGUI(SEAdenitaCoreSEApp* t); ///< Constructs a GUI for the app
virtual ~SEAdenitaCoreSEAppGUI(); ///< Destructs the GUI of the app
//@}
/// \name App
//@{
SEAdenitaCoreSEApp* getApp() const; ///< Returns a pointer to the app
//@}
/// \name Identity
//@{
virtual SBCContainerUUID getUUID() const; ///< Returns the widget UUID
virtual QString getName() const; ///< Returns the widget name (used as a title for the embedding window)
virtual QPixmap getLogo() const; ///< Returns the widget logo
int getFormat() const; ///< Returns the widget format
virtual QString getCitation() const; ///< Returns the citation information
//@}
virtual void keyPressEvent(QKeyEvent *event);
///\name Settings
//@{
void loadSettings(SBGSettings* settings); ///< Load GUI settings
void saveSettings(SBGSettings* settings); ///< Save GUI settings
//@}
// get selected scaffold
std::string GetScaffoldFilename();
public slots:
void onChangeSelector(int idx);
// Main
void onLoadFile();
void onSaveAll();
void onSaveSelection();
void onExport();
void onSetScaffold();
void onCreateBasePair();
void onGenerateSequence();
void onSettings();
void onSetStart();
void onCalculateBindingProperties();
// Editors
void onBreakEditor();
void onConnectEditor();
void onDeleteEditor();
void onDNATwistEditor();
void onMergePartsEditor();
void onCreateStrandEditor();
void onNanotubeCreatorEditor();
void onLatticeCreatorEditor();
void onWireframeEditor();
void onTaggingEditor();
void onTwisterEditor();
// Debug
void onAddNtThreeP();
void onCenterPart();
void onCatenanes();
void onKinetoplast();
void onTestNeighbors();
void onOxDNAImport();
void onFromDatagraph();
void onHighlightXOs();
void onHighlightPosXOs();
void onExportToCanDo();
void onFixDesigns();
private slots:
void CheckForLoadedParts();
private:
void SetupUI();
std::string IsJsonCadnano(QString filename);
void HighlightEditor(QToolButton* b);
std::vector<QToolButton*> menuButtons_;
std::vector<QToolButton*> editSequencesButtons_;
std::vector<QToolButton*> modelingButtons_;
std::vector<QToolButton*> creatorsButtons_;
std::vector<QPushButton*> debugButtons_;
std::vector<QToolButton*> GetMenuButtons();
std::vector<QToolButton*> GetEditSequencesButtons();
std::vector<QToolButton*> GetModelingButtons();
std::vector<QToolButton*> GetCreatorsButtons();
std::vector<QPushButton*> GetDebugButtons();
Ui::SEAdenitaCoreSEAppGUIClass ui;
QToolButton* highlightedEditor_ = nullptr;
};
| 25.75969 | 141 | 0.676497 | edellano |
d6b7722e541ebf76bffe5916983ea58851b594fb | 934 | cpp | C++ | Examples/MacroEquals/main_macro_equals.cpp | sapphire-devteam/SA-UnitTestHelper | 5413b64f5554036e9fd18e2e0f7784f97aaf3c2f | [
"MIT"
] | null | null | null | Examples/MacroEquals/main_macro_equals.cpp | sapphire-devteam/SA-UnitTestHelper | 5413b64f5554036e9fd18e2e0f7784f97aaf3c2f | [
"MIT"
] | null | null | null | Examples/MacroEquals/main_macro_equals.cpp | sapphire-devteam/SA-UnitTestHelper | 5413b64f5554036e9fd18e2e0f7784f97aaf3c2f | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Sapphire's Suite. All Rights Reserved.. All Rights Reserved.
#include <UnitTestHelper.hpp>
using namespace Sa;
#include <limits>
struct MyClass
{
float myFloat = 0.0f;
std::string ToString() const { return std::to_string(myFloat); }
bool operator==(const MyClass& _rhs) const { return myFloat == _rhs.myFloat; }
};
int main()
{
SA_UTH_INIT();
// Single elem
float i = 4.6f;
float j = 1.25f;
/// elem1, elem2, epsilon.
SA_UTH_EQ(i, i);
SA_UTH_EQ(i, j, std::numeric_limits<float>::epsilon()); // Error
// Tab elems.
int size = 3;
float ftab1[] = { 1.45f, 8.36f, 1.247f };
float ftab2[] = { 1.45f, 8.36f, 945.9f };
/// elem1, elem2, size, epsilon.
SA_UTH_EQ(ftab1, ftab2, 2, std::numeric_limits<float>::epsilon());
SA_UTH_EQ(ftab1, ftab2, size); // Error
// Custom elem
MyClass m1{ 4.56f };
MyClass m2{ 8.15f };
SA_UTH_EQ(m1, m1);
SA_UTH_EQ(m1, m2); // Error
SA_UTH_EXIT();
}
| 18.68 | 82 | 0.647752 | sapphire-devteam |
d6b93ff1997f8e0b9757ff88ebc8c24bf999b815 | 21,359 | cpp | C++ | bLSM.cpp | sears/bLSM | fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c | [
"Apache-2.0"
] | 114 | 2015-03-10T16:07:35.000Z | 2022-01-11T08:36:42.000Z | bLSM.cpp | anqin/bLSM | fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c | [
"Apache-2.0"
] | 1 | 2019-03-16T11:31:59.000Z | 2019-03-16T11:31:59.000Z | bLSM.cpp | anqin/bLSM | fc49c4e0ce1ef69bd9d18b7ed5c83151aee9c91c | [
"Apache-2.0"
] | 36 | 2015-02-17T22:04:17.000Z | 2021-06-06T02:38:18.000Z | /*
* blsm.cpp
*
* Copyright 2009-2012 Yahoo! 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 "bLSM.h"
#include "mergeScheduler.h"
#include <stasis/transactional.h>
#include <stasis/bufferManager.h>
#include <stasis/bufferManager/bufferHash.h>
#include <stasis/logger/logger2.h>
#include <stasis/logger/logHandle.h>
#include <stasis/logger/filePool.h>
#include "mergeStats.h"
// Backpressure reads to avoid merge starvation? Experimental/short-term hack
//#define BACKPRESSURE_READS
static inline double tv_to_double(struct timeval tv)
{
return static_cast<double>(tv.tv_sec) +
(static_cast<double>(tv.tv_usec) / 1000000.0);
}
/////////////////////////////////////////////////////////////////
// LOG TABLE IMPLEMENTATION
/////////////////////////////////////////////////////////////////
bLSM::bLSM(int log_mode, pageid_t max_c0_size, pageid_t internal_region_size, pageid_t datapage_region_size, pageid_t datapage_size)
{
recovering = true;
this->max_c0_size = max_c0_size;
this->mean_c0_run_length = max_c0_size;
this->num_c0_mergers = 0;
r_val = 3.0; // MIN_R
tree_c0 = NULL;
tree_c0_mergeable = NULL;
c0_is_merging = false;
tree_c1_prime = NULL;
tree_c1 = NULL;
tree_c1_mergeable = NULL;
tree_c2 = NULL;
// This bool is purely for external code.
this->accepting_new_requests = true;
this->shutting_down_ = false;
c0_flushing = false;
c1_flushing = false;
current_timestamp = 0;
expiry = 0;
this->merge_mgr = 0;
tmerger = new tupleMerger(&replace_merger);
header_mut = rwlc_initlock();
pthread_mutex_init(&rb_mut, 0);
pthread_cond_init(&c0_needed, 0);
pthread_cond_init(&c0_ready, 0);
pthread_cond_init(&c1_needed, 0);
pthread_cond_init(&c1_ready, 0);
epoch = 0;
this->internal_region_size = internal_region_size;
this->datapage_region_size = datapage_region_size;
this->datapage_size = datapage_size;
this->log_mode = log_mode;
this->batch_size = 0;
log_file = stasis_log_file_pool_open("lsm_log",
stasis_log_file_mode,
stasis_log_file_permissions);
}
bLSM::~bLSM()
{
delete merge_mgr; // shuts down pretty print thread.
if(tree_c1 != NULL)
delete tree_c1;
if(tree_c2 != NULL)
delete tree_c2;
if(tree_c0 != NULL)
{
memTreeComponent::tearDownTree(tree_c0);
}
log_file->close(log_file);
pthread_mutex_destroy(&rb_mut);
rwlc_deletelock(header_mut);
pthread_cond_destroy(&c0_needed);
pthread_cond_destroy(&c0_ready);
pthread_cond_destroy(&c1_needed);
pthread_cond_destroy(&c1_ready);
delete tmerger;
}
void bLSM::init_stasis() {
dataPage::register_stasis_page_impl();
// stasis_buffer_manager_hint_writes_are_sequential = 1;
Tinit();
}
void bLSM::deinit_stasis() { Tdeinit(); }
recordid bLSM::allocTable(int xid)
{
table_rec = Talloc(xid, sizeof(tbl_header));
mergeStats * stats = 0;
//create the big tree
tree_c2 = new diskTreeComponent(xid, internal_region_size, datapage_region_size, datapage_size, stats, 10);
//create the small tree
tree_c1 = new diskTreeComponent(xid, internal_region_size, datapage_region_size, datapage_size, stats, 10);
merge_mgr = new mergeManager(this);
merge_mgr->set_c0_size(max_c0_size);
merge_mgr->new_merge(0);
tree_c0 = new memTreeComponent::rbtree_t;
tbl_header.merge_manager = merge_mgr->talloc(xid);
tbl_header.log_trunc = 0;
update_persistent_header(xid);
return table_rec;
}
void bLSM::openTable(int xid, recordid rid) {
table_rec = rid;
Tread(xid, table_rec, &tbl_header);
tree_c2 = new diskTreeComponent(xid, tbl_header.c2_root, tbl_header.c2_state, tbl_header.c2_dp_state, 0);
tree_c1 = new diskTreeComponent(xid, tbl_header.c1_root, tbl_header.c1_state, tbl_header.c1_dp_state, 0);
tree_c0 = new memTreeComponent::rbtree_t;
merge_mgr = new mergeManager(this, xid, tbl_header.merge_manager);
merge_mgr->set_c0_size(max_c0_size);
merge_mgr->new_merge(0);
}
void bLSM::logUpdate(dataTuple * tup) {
byte * buf = tup->to_bytes();
LogEntry * e = stasis_log_write_update(log_file, 0, INVALID_PAGE, 0/*Page**/, 0/*op*/, buf, tup->byte_length());
log_file->write_entry_done(log_file,e);
free(buf);
}
void bLSM::replayLog() {
lsn_t start = tbl_header.log_trunc;
LogHandle * lh = start ? getLSNHandle(log_file, start) : getLogHandle(log_file);
const LogEntry * e;
while((e = nextInLog(lh))) {
switch(e->type) {
case UPDATELOG: {
dataTuple * tup = dataTuple::from_bytes((byte*)stasis_log_entry_update_args_cptr(e));
insertTuple(tup);
dataTuple::freetuple(tup);
} break;
case INTERNALLOG: { } break;
default: assert(e->type == UPDATELOG); abort();
}
}
freeLogHandle(lh);
recovering = false;
printf("\nLog replay complete.\n");
}
lsn_t bLSM::get_log_offset() {
if(recovering || !log_mode) { return INVALID_LSN; }
return log_file->next_available_lsn(log_file);
}
void bLSM::truncate_log() {
if(recovering) {
printf("Not truncating log until recovery is complete.\n");
} else {
if(tbl_header.log_trunc) {
printf("truncating log to %lld\n", tbl_header.log_trunc);
log_file->truncate(log_file, tbl_header.log_trunc);
}
}
}
void bLSM::update_persistent_header(int xid, lsn_t trunc_lsn) {
tbl_header.c2_root = tree_c2->get_root_rid();
tbl_header.c2_dp_state = tree_c2->get_datapage_allocator_rid();
tbl_header.c2_state = tree_c2->get_internal_node_allocator_rid();
tbl_header.c1_root = tree_c1->get_root_rid();
tbl_header.c1_dp_state = tree_c1->get_datapage_allocator_rid();
tbl_header.c1_state = tree_c1->get_internal_node_allocator_rid();
merge_mgr->marshal(xid, tbl_header.merge_manager);
if(trunc_lsn != INVALID_LSN) {
printf("\nsetting log truncation point to %lld\n", trunc_lsn);
tbl_header.log_trunc = trunc_lsn;
}
Tset(xid, table_rec, &tbl_header);
}
void bLSM::flushTable()
{
struct timeval start_tv, stop_tv;
double start, stop;
static double last_start;
static bool first = 1;
static int merge_count = 0;
gettimeofday(&start_tv,0);
start = tv_to_double(start_tv);
c0_flushing = true;
bool blocked = false;
int expmcount = merge_count;
//this waits for the previous merger of the mem-tree
//hopefullly this wont happen
while(get_c0_is_merging()) {
rwlc_cond_wait(&c0_needed, header_mut);
blocked = true;
if(expmcount != merge_count) {
return;
}
}
set_c0_is_merging(true);
merge_mgr->get_merge_stats(0)->handed_off_tree();
merge_mgr->new_merge(0);
gettimeofday(&stop_tv,0);
stop = tv_to_double(stop_tv);
pthread_cond_signal(&c0_ready);
DEBUG("Signaled c0-c1 merge thread\n");
merge_count ++;
merge_mgr->get_merge_stats(0)->starting_merge();
if(blocked && stop - start > 1.0) {
if(first)
{
printf("\nBlocked writes for %f sec\n", stop-start);
first = 0;
}
else
{
printf("\nBlocked writes for %f sec (serviced writes for %f sec)\n",
stop-start, start-last_start);
}
last_start = stop;
} else {
DEBUG("signaled c0-c1 merge\n");
}
c0_flushing = false;
}
dataTuple * bLSM::findTuple(int xid, const dataTuple::key_t key, size_t keySize)
{
// Apply proportional backpressure to reads as well as writes. This prevents
// starvation of the merge threads on fast boxes.
#ifdef BACKPRESSURE_READS
merge_mgr->tick(merge_mgr->get_merge_stats(0));
#endif
//prepare a search tuple
dataTuple *search_tuple = dataTuple::create(key, keySize);
pthread_mutex_lock(&rb_mut);
dataTuple *ret_tuple=0;
//step 1: look in tree_c0
memTreeComponent::rbtree_t::iterator rbitr = get_tree_c0()->find(search_tuple);
if(rbitr != get_tree_c0()->end())
{
DEBUG("tree_c0 size %d\n", get_tree_c0()->size());
ret_tuple = (*rbitr)->create_copy();
}
pthread_mutex_unlock(&rb_mut);
rwlc_readlock(header_mut); // XXX: FIXME with optimisitic concurrency control. Has to be before rb_mut, or we could merge the tuple with itself due to an intervening merge
bool done = false;
//step: 2 look into first in tree if exists (a first level merge going on)
if(get_tree_c0_mergeable() != 0)
{
DEBUG("old mem tree not null %d\n", (*(mergedata->old_c0))->size());
rbitr = get_tree_c0_mergeable()->find(search_tuple);
if(rbitr != get_tree_c0_mergeable()->end())
{
dataTuple *tuple = *rbitr;
if(tuple->isDelete()) //tuple deleted
done = true; //return ret_tuple
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from current tree
ret_tuple = mtuple; //set return tuple to merge result
}
else //key first found in old mem tree
{
ret_tuple = tuple->create_copy();
}
//we cannot free tuple from old-tree 'cos it is not a copy
}
}
//step 2.5: check new c1 if exists
if(!done && get_tree_c1_prime() != 0)
{
DEBUG("old c1 tree not null\n");
dataTuple *tuple_oc1 = get_tree_c1_prime()->findTuple(xid, key, keySize);
if(tuple_oc1 != NULL)
{
bool use_copy = false;
if(tuple_oc1->isDelete())
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_oc1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_oc1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_oc1); //free tuple from tree old c1
}
}
}
//step 3: check c1
if(!done)
{
dataTuple *tuple_c1 = get_tree_c1()->findTuple(xid, key, keySize);
if(tuple_c1 != NULL)
{
bool use_copy = false;
if(tuple_c1->isDelete()) //tuple deleted
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_c1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_c1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_c1); //free tuple from tree c1
}
}
}
//step 4: check old c1 if exists
if(!done && get_tree_c1_mergeable() != 0)
{
DEBUG("old c1 tree not null\n");
dataTuple *tuple_oc1 = get_tree_c1_mergeable()->findTuple(xid, key, keySize);
if(tuple_oc1 != NULL)
{
bool use_copy = false;
if(tuple_oc1->isDelete())
done = true;
else if(ret_tuple != 0) //merge the two
{
dataTuple *mtuple = tmerger->merge(tuple_oc1, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_oc1;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_oc1); //free tuple from tree old c1
}
}
}
//step 5: check c2
if(!done)
{
DEBUG("Not in old first disk tree\n");
dataTuple *tuple_c2 = get_tree_c2()->findTuple(xid, key, keySize);
if(tuple_c2 != NULL)
{
bool use_copy = false;
if(tuple_c2->isDelete())
done = true;
else if(ret_tuple != 0)
{
dataTuple *mtuple = tmerger->merge(tuple_c2, ret_tuple); //merge the two
dataTuple::freetuple(ret_tuple); //free tuple from before
ret_tuple = mtuple; //set return tuple to merge result
}
else //found for the first time
{
use_copy = true;
ret_tuple = tuple_c2;
}
if(!use_copy)
{
dataTuple::freetuple(tuple_c2); //free tuple from tree c2
}
}
}
rwlc_unlock(header_mut);
dataTuple::freetuple(search_tuple);
if (ret_tuple != NULL && ret_tuple->isDelete()) {
// this is a tombstone. don't return it
dataTuple::freetuple(ret_tuple);
return NULL;
}
return ret_tuple;
}
/*
* returns the first record found with the matching key
* (not to be used together with diffs)
**/
dataTuple * bLSM::findTuple_first(int xid, dataTuple::key_t key, size_t keySize)
{
// Apply proportional backpressure to reads as well as writes. This prevents
// starvation of the merge threads on fast boxes.
#ifdef BACKPRESSURE_READS
merge_mgr->tick(merge_mgr->get_merge_stats(0));
#endif
//prepare a search tuple
dataTuple * search_tuple = dataTuple::create(key, keySize);
dataTuple *ret_tuple=0;
//step 1: look in tree_c0
pthread_mutex_lock(&rb_mut);
memTreeComponent::rbtree_t::iterator rbitr = get_tree_c0()->find(search_tuple);
if(rbitr != get_tree_c0()->end())
{
DEBUG("tree_c0 size %d\n", tree_c0->size());
ret_tuple = (*rbitr)->create_copy();
pthread_mutex_unlock(&rb_mut);
}
else
{
DEBUG("Not in mem tree %d\n", tree_c0->size());
pthread_mutex_unlock(&rb_mut);
rwlc_readlock(header_mut); // XXX FIXME WITH OCC!!
//step: 2 look into first in tree if exists (a first level merge going on)
if(get_tree_c0_mergeable() != NULL)
{
DEBUG("old mem tree not null %d\n", (*(mergedata->old_c0))->size());
rbitr = get_tree_c0_mergeable()->find(search_tuple);
if(rbitr != get_tree_c0_mergeable()->end())
{
ret_tuple = (*rbitr)->create_copy();
}
}
if(ret_tuple == 0)
{
DEBUG("Not in first disk tree\n");
//step 4: check in progress c1 if exists
if( get_tree_c1_prime() != 0)
{
DEBUG("old c1 tree not null\n");
ret_tuple = get_tree_c1_prime()->findTuple(xid, key, keySize);
}
}
if(ret_tuple == 0)
{
DEBUG("Not in old mem tree\n");
//step 3: check c1
ret_tuple = get_tree_c1()->findTuple(xid, key, keySize);
}
if(ret_tuple == 0)
{
DEBUG("Not in first disk tree\n");
//step 4: check old c1 if exists
if( get_tree_c1_mergeable() != 0)
{
DEBUG("old c1 tree not null\n");
ret_tuple = get_tree_c1_mergeable()->findTuple(xid, key, keySize);
}
}
if(ret_tuple == 0)
{
DEBUG("Not in old first disk tree\n");
//step 5: check c2
ret_tuple = get_tree_c2()->findTuple(xid, key, keySize);
}
rwlc_unlock(header_mut);
}
dataTuple::freetuple(search_tuple);
if (ret_tuple != NULL && ret_tuple->isDelete()) {
// this is a tombstone. don't return it
dataTuple::freetuple(ret_tuple);
return NULL;
}
return ret_tuple;
}
dataTuple * bLSM::insertTupleHelper(dataTuple *tuple)
{
bool need_free = false;
if(!tuple->isDelete() && expiry != 0) {
// XXX hack for paper experiment
current_timestamp++;
size_t ts_sz = sizeof(int64_t);
int64_t ts = current_timestamp;
int64_t kl = tuple->strippedkeylen();
byte * newkey = (byte*)malloc(kl + 1 + ts_sz);
memcpy(newkey, tuple->strippedkey(), kl);
newkey[kl] = 0;
memcpy(newkey+kl+1, &ts, ts_sz);
dataTuple * old = tuple;
tuple = dataTuple::create(newkey, kl+ 1+ ts_sz, tuple->data(), tuple->datalen());
assert(tuple->strippedkeylen() == old->strippedkeylen());
assert(!dataTuple::compare_obj(tuple, old));
free(newkey);
need_free = true;
} //find the previous tuple with same key in the memtree if exists
pthread_mutex_lock(&rb_mut);
memTreeComponent::rbtree_t::iterator rbitr = tree_c0->find(tuple);
dataTuple * t = 0;
dataTuple * pre_t = 0;
if(rbitr != tree_c0->end())
{
pre_t = *rbitr;
//do the merging
dataTuple *new_t = tmerger->merge(pre_t, tuple);
merge_mgr->get_merge_stats(0)->merged_tuples(new_t, tuple, pre_t);
t = new_t;
tree_c0->erase(pre_t); //remove the previous tuple
tree_c0->insert(new_t); //insert the new tuple
}
else //no tuple with same key exists in mem-tree
{
t = tuple->create_copy();
//insert tuple into the rbtree
tree_c0->insert(t);
}
pthread_mutex_unlock(&rb_mut);
if(need_free) { dataTuple::freetuple(tuple); }
return pre_t;
}
void bLSM::insertManyTuples(dataTuple ** tuples, int tuple_count) {
for(int i = 0; i < tuple_count; i++) {
merge_mgr->read_tuple_from_small_component(0, tuples[i]);
}
if(log_mode && !recovering) {
for(int i = 0; i < tuple_count; i++) {
logUpdate(tuples[i]);
}
batch_size ++;
if(batch_size >= log_mode) {
log_file->force_tail(log_file, LOG_FORCE_COMMIT);
batch_size = 0;
}
}
int num_old_tups = 0;
pageid_t sum_old_tup_lens = 0;
for(int i = 0; i < tuple_count; i++) {
dataTuple * old_tup = insertTupleHelper(tuples[i]);
if(old_tup) {
num_old_tups++;
sum_old_tup_lens += old_tup->byte_length();
dataTuple::freetuple(old_tup);
}
}
merge_mgr->read_tuple_from_large_component(0, num_old_tups, sum_old_tup_lens);
}
void bLSM::insertTuple(dataTuple *tuple)
{
if(log_mode && !recovering) {
logUpdate(tuple);
batch_size++;
if(batch_size >= log_mode) {
log_file->force_tail(log_file, LOG_FORCE_COMMIT);
batch_size = 0;
}
}
// Note, this is where we block for backpressure. Do this without holding
// any locks!
merge_mgr->read_tuple_from_small_component(0, tuple);
dataTuple * pre_t = 0; // this is a pointer to any data tuples that we'll be deleting below. We need to update the merge_mgr statistics with it, but have to do so outside of the rb_mut region.
pre_t = insertTupleHelper(tuple);
if(pre_t) {
// needs to be here; calls update_progress, which sometimes grabs mutexes..
merge_mgr->read_tuple_from_large_component(0, pre_t); // was interspersed with the erase, insert above...
dataTuple::freetuple(pre_t); //free the previous tuple
}
DEBUG("tree size %d tuples %lld bytes.\n", tsize, tree_bytes);
}
bool bLSM::testAndSetTuple(dataTuple *tuple, dataTuple *tuple2)
{
bool succ = false;
static pthread_mutex_t test_and_set_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&test_and_set_mut);
dataTuple * exists = findTuple_first(-1, tuple2 ? tuple2->strippedkey() : tuple->strippedkey(), tuple2 ? tuple2->strippedkeylen() : tuple->strippedkeylen());
if(!tuple2 || tuple2->isDelete()) {
if(!exists || exists->isDelete()) {
succ = true;
} else {
succ = false;
}
} else {
if(tuple2->datalen() == exists->datalen() && !memcmp(tuple2->data(), exists->data(), tuple2->datalen())) {
succ = true;
} else {
succ = false;
}
}
if(exists) dataTuple::freetuple(exists);
if(succ) insertTuple(tuple);
pthread_mutex_unlock(&test_and_set_mut);
return succ;
}
void bLSM::registerIterator(iterator * it) {
its.push_back(it);
}
void bLSM::forgetIterator(iterator * it) {
for(unsigned int i = 0; i < its.size(); i++) {
if(its[i] == it) {
its.erase(its.begin()+i);
break;
}
}
}
void bLSM::bump_epoch() {
epoch++;
for(unsigned int i = 0; i < its.size(); i++) {
its[i]->invalidate();
}
}
| 29.706537 | 197 | 0.607145 | sears |
d6b9f8e0069ac4caae585da9e627391370769674 | 3,832 | cc | C++ | pdns-recursor-4.0.6/ednssubnet.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 7 | 2017-07-16T15:09:26.000Z | 2021-09-01T02:13:15.000Z | pdns-recursor-4.0.6/ednssubnet.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | null | null | null | pdns-recursor-4.0.6/ednssubnet.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 3 | 2017-09-13T09:54:49.000Z | 2019-03-18T01:29:15.000Z | /*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "ednssubnet.hh"
#include "dns.hh"
namespace {
struct EDNSSubnetOptsWire
{
uint16_t family;
uint8_t sourceMask;
uint8_t scopeMask;
} GCCPACKATTRIBUTE; // BRRRRR
}
bool getEDNSSubnetOptsFromString(const string& options, EDNSSubnetOpts* eso)
{
//cerr<<"options.size:"<<options.size()<<endl;
return getEDNSSubnetOptsFromString(options.c_str(), options.length(), eso);
}
bool getEDNSSubnetOptsFromString(const char* options, unsigned int len, EDNSSubnetOpts* eso)
{
EDNSSubnetOptsWire esow;
static_assert (sizeof(esow) == 4, "sizeof(EDNSSubnetOptsWire) must be 4 bytes");
if(len < sizeof(esow))
return false;
memcpy(&esow, options, sizeof(esow));
esow.family = ntohs(esow.family);
//cerr<<"Family when parsing from string: "<<esow.family<<endl;
ComboAddress address;
unsigned int octetsin = esow.sourceMask > 0 ? (((esow.sourceMask - 1)>> 3)+1) : 0;
//cerr<<"octetsin:"<<octetsin<<endl;
if(esow.family == 1) {
if(len != sizeof(esow)+octetsin)
return false;
if(octetsin > sizeof(address.sin4.sin_addr.s_addr))
return false;
memset(&address, 0, sizeof(address));
address.sin4.sin_family = AF_INET;
if(octetsin > 0)
memcpy(&address.sin4.sin_addr.s_addr, options+sizeof(esow), octetsin);
} else if(esow.family == 2) {
if(len != sizeof(esow)+octetsin)
return false;
if(octetsin > sizeof(address.sin6.sin6_addr.s6_addr))
return false;
memset(&address, 0, sizeof(address));
address.sin4.sin_family = AF_INET6;
if(octetsin > 0)
memcpy(&address.sin6.sin6_addr.s6_addr, options+sizeof(esow), octetsin);
}
else
return false;
//cerr<<"Source address: "<<address.toString()<<", mask: "<<(int)esow.sourceMask<<endl;
eso->source = Netmask(address, esow.sourceMask);
/* 'address' has more bits set (potentially) than scopeMask. This leads to odd looking netmasks that promise
more precision than they have. For this reason we truncate the address to scopeMask bits */
address.truncate(esow.scopeMask); // truncate will not throw for odd scopeMasks
eso->scope = Netmask(address, esow.scopeMask);
return true;
}
string makeEDNSSubnetOptsString(const EDNSSubnetOpts& eso)
{
string ret;
EDNSSubnetOptsWire esow;
uint16_t family = htons(eso.source.getNetwork().sin4.sin_family == AF_INET ? 1 : 2);
esow.family = family;
esow.sourceMask = eso.source.getBits();
esow.scopeMask = eso.scope.getBits();
ret.assign((const char*)&esow, sizeof(esow));
int octetsout = ((esow.sourceMask - 1)>> 3)+1;
if(family == htons(1))
ret.append((const char*) &eso.source.getNetwork().sin4.sin_addr.s_addr, octetsout);
else
ret.append((const char*) &eso.source.getNetwork().sin6.sin6_addr.s6_addr, octetsout);
return ret;
}
| 36.495238 | 110 | 0.699635 | hankai17 |
d6be3a6d75ddc19a8644ddffec93b7abf0149286 | 8,720 | cpp | C++ | deps/vision/src/kernel/Vca_VcaProxyFacilitator.cpp | MichaelJCaruso/vxa-node | 4b02a17f48bed6f71f622e0bb743f87d932a2a6f | [
"BSD-3-Clause"
] | 30 | 2016-10-07T15:23:35.000Z | 2020-03-25T20:01:30.000Z | src/kernel/Vca_VcaProxyFacilitator.cpp | MichaelJCaruso/vision-software-src-master | 12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92 | [
"BSD-3-Clause"
] | 30 | 2016-10-31T19:48:08.000Z | 2021-04-28T01:31:53.000Z | software/src/master/src/kernel/Vca_VcaProxyFacilitator.cpp | c-kuhlman/vision | 46b25f7c0da703c059acc8f0a2eac1d5badf9f6d | [
"BSD-3-Clause"
] | 15 | 2016-10-07T16:44:13.000Z | 2021-06-21T18:47:55.000Z | /***** VcaProxyFacilitator Implementation *****/
/************************
************************
***** Interfaces *****
************************
************************/
/********************
***** System *****
********************/
#include "Vk.h"
/******************
***** Self *****
******************/
#include "Vca_VcaProxyFacilitator.h"
/************************
***** Supporting *****
************************/
#include "Vca_CompilerHappyPill.h"
#include "VReceiver.h"
#include "Vca_IPeer.h"
#include "Vca_VcaPeer.h"
/**************************
**************************
***** Construction *****
**************************
**************************/
Vca::VcaProxyFacilitator::VcaProxyFacilitator (
VcaPeer *pSourcePeer, VcaPeer *pTargetPeer
) : m_pSourcePeer (pSourcePeer), m_pTargetPeer (pTargetPeer) {
startup ();
}
Vca::VcaProxyFacilitator::VcaProxyFacilitator (
VcaPeer *pSourcePeer, VcaPeer *pTargetPeer,
IPeer *pSourcePeerReflection, IPeer *pTargetPeerReflection
) : m_pSourcePeer (pSourcePeer)
, m_pTargetPeer (pTargetPeer)
, m_pSourcePeerReflection (pSourcePeerReflection)
, m_pTargetPeerReflection (pTargetPeerReflection) {
}
/*************************
*************************
***** Destruction *****
*************************
*************************/
Vca::VcaProxyFacilitator::~VcaProxyFacilitator () {
}
/********************
********************
***** Update *****
********************
********************/
void Vca::VcaProxyFacilitator::setSourcePeerReflection (IPeer *pPeer) {
m_pSourcePeerReflection.setTo (pPeer);
}
void Vca::VcaProxyFacilitator::setTargetPeerReflection (IPeer *pPeer) {
m_pTargetPeerReflection.setTo (pPeer);
}
/*****************
*****************
***** Use *****
*****************
*****************/
/****************************************************************************
* Routine: startup
* Operation:
* This method does the intial startup process, for a
* VcaFacilitator object to be used. It sends messages to both the source
* as well as the target peer, with the information about each other,
* also requests local interfaces for the images created by them.
****************************************************************************/
void Vca::VcaProxyFacilitator::startup () {
if (!reflectionsAreValid ()) {
VReference<IPeerReceiver> pReceiver1 (
new IPeerReceiver (this, &ThisClass::onTargetPeerReflection)
);
VReference<IPeerReceiver> pReceiver2 (
new IPeerReceiver (this, &ThisClass::onSourcePeerReflection)
);
traceInfo ("\nSending Peers for exchanging");
m_pSourcePeer->getRemoteLocalInterfaceFor (m_pTargetPeer, pReceiver1);
m_pTargetPeer->getRemoteLocalInterfaceFor (m_pSourcePeer, pReceiver2);
}
}
/****************************************************************************
* Routine: onSourcePeerReflection
* Operation:
* On getting the request for constructing an image for source peer, the
* target peer creates a source peer image and returns a local interface
* pointer by calling this routine. This method checks to see whether the other
* reflection has also arrived if so triggers the exchange of the
* reflections obtained
* Precondition: pIPeer, the reflection returned is a valid non-null pointer
****************************************************************************/
void Vca::VcaProxyFacilitator::onSourcePeerReflection (
IPeerReceiver *pReceiver, IPeer *pIPeer
) {
m_pSourcePeerReflection.setTo (pIPeer);
if (reflectionsAreValid ())
onBothReflections ();
}
void Vca::VcaProxyFacilitator::onTargetPeerReflection (
IPeerReceiver *pReceiver, IPeer *pIPeer
) {
m_pTargetPeerReflection.setTo (pIPeer);
if (reflectionsAreValid ())
onBothReflections ();
}
/****************************************************************************
* Routine: onBothReflections
* Operation:
* Once both reflections are obtained, by this facilitator it needs to
* send messages to both the source and target peer indicating their reflections
* at the other end. This method completes the phase of creating a virtual
* plumbing between the source and the target peer by the facilitator object.
* Now it can start the facilitations.
****************************************************************************/
void Vca::VcaProxyFacilitator::onBothReflections () {
traceInfo ("\nExchanging Reflections");
m_pSourcePeer->setRemoteRemoteReflectionFor (m_pTargetPeer, m_pSourcePeerReflection);
m_pTargetPeer->setRemoteRemoteReflectionFor (m_pSourcePeer, m_pTargetPeerReflection);
delegateReflections ();
delegatePendingProxies ();
}
/****************************************************************************
* Routine: delegateReflections
* Operation:
* This method delegates the reflections obtained from the source and the
* target peer. The reflections are being referenced from this facilitator
* object. So they wont be facilitated automatically as there is an internal
* usage. But to relieve this intermediary peer from serving as intermediary
* for the reflections we delegate the reflections also as part of the
* startup process.
* Out of the two reflections, the TargetPeer reflection can be facilitated
* by the current facilitator, but the SourcePeer reflection has to be
* facilitated by creating a new facilitator object which facilitates
* proxies going from the Target peer to the Source peer.
****************************************************************************/
void Vca::VcaProxyFacilitator::delegateReflections () {
traceInfo ("\nDelegating Reflection1");
delegateProxy (m_pTargetPeerReflection->oidr ());
traceInfo ("\nDelegating Reflection2");
VcaProxyFacilitator *pFacilitator;
pFacilitator = m_pTargetPeer->createProxyFacilitatorFor (
m_pSourcePeer, m_pTargetPeerReflection, m_pSourcePeerReflection
);
pFacilitator->processProxy (m_pSourcePeerReflection->oidr ());
}
void Vca::VcaProxyFacilitator::delegatePendingProxies () {
if (!reflectionsAreValid ())
return;
Iterator iterator (m_iPendingProxySet);
while (iterator.isNotAtEnd ()) {
VcaOIDR *pOIDR = *iterator;
// remove from pending list and then delegate...
iterator.Delete ();
pOIDR->deleteFacilitationTo (m_pTargetPeer);
delegateProxy (pOIDR);
}
}
/****************************************************************************
* Routine: processProxy
* Operation:
* When a proxy is being requested to be processed, first a check is made
* to determine whether the reflection are valid. If so then the proxy is
* directly delegated, else it is inserted into the pending proxy set.
****************************************************************************/
void Vca::VcaProxyFacilitator::processProxy (VcaOIDR *pOIDR) {
if (reflectionsAreValid ())
delegateProxy (pOIDR);
else
queueProxy (pOIDR);
}
void Vca::VcaProxyFacilitator::queueProxy (VcaOIDR *pOIDR) {
m_iPendingProxySet.Insert (pOIDR);
pOIDR->addFacilitationPeers (m_pTargetPeer, m_pSourcePeer);
}
/****************************************************************************
* Routine: delegateProxy
* Operation:
* This method performs the work of eliminating this process as a middle man
* in an import/export relationship between two adjacent peers. This method
* operates by manipulating the peer models of its neighbors. It is called
* after this facilitator has constructed appropriate models of the one-hop
* removed peers at those neighbors and performs its work in three steps:
* .
* 1. Send a "Fake Export" message to the upstream object exporter
* requesting that it 'export' the object to the downstream importer.
* 2. Send a "Fake Import" message to the downstream object importer
* requesting that it 'import' the object from the upstream exporter.
* 3. Send a "ReleaseImport" message to the downstream importer requesting
* that it stop importing the object from this process. This message,
* when processed by the downstream peer, will eventually result in a
* ReleaseExport message from the downstream peer absolving this process
* of the export responsibilities it is trying to free itself of.
*
****************************************************************************/
void Vca::VcaProxyFacilitator::delegateProxy (VcaOIDR *pOIDR) {
traceInfo ("\nDelegating Proxy. Calling FakeExport, FakeImport,deleteRemoteImport");
m_pSourcePeer->fakeRemoteExportTo (pOIDR, m_pTargetPeer);
m_pTargetPeer->fakeRemoteImportFrom (pOIDR, m_pSourcePeer);
m_pTargetPeer->deleteRemoteImportOf (pOIDR);
}
| 35.737705 | 89 | 0.613532 | MichaelJCaruso |
d6c0d342360774357947dd6c476b50068613d00b | 514 | cpp | C++ | Algorithms/0397.Integer_Replacement.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0397.Integer_Replacement.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0397.Integer_Replacement.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
unsigned int n;
map<unsigned int,int> dp;
int f(unsigned int x) {
if(x == 1)
return 0;
map<unsigned int,int>::iterator it = dp.find(x);
if(it != dp.end())
return it->second;
int res;
if(x % 2 == 0)
res = dp[x] = f(x/2)+1;
else
res = dp[x] = min(f(x+1),f(x-1))+1;
return res;
}
int integerReplacement(int n) {
this->n = n;
return f(this->n);
}
}; | 23.363636 | 56 | 0.441634 | metehkaya |
d6c104fa17fa520526bfcf9bb738caf35463c9d0 | 2,379 | cpp | C++ | Graph/SmartTravelAgent_mst.cpp | Satyabrat35/Programming | 841ead1bf847b567d8e21963673413cbd65277f4 | [
"Apache-2.0"
] | null | null | null | Graph/SmartTravelAgent_mst.cpp | Satyabrat35/Programming | 841ead1bf847b567d8e21963673413cbd65277f4 | [
"Apache-2.0"
] | null | null | null | Graph/SmartTravelAgent_mst.cpp | Satyabrat35/Programming | 841ead1bf847b567d8e21963673413cbd65277f4 | [
"Apache-2.0"
] | null | null | null | /**************erik****************/
#include<bits/stdc++.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
//map<ll,ll> mp1;
//set<int> s1;
//set<int>::iterator it;
#define maxm(a,b,c) max(a,max(c,b))
#define minm(a,b,c) min(a,min(c,b))
#define f(i,n) for(int i=1;i<n;i++)
#define rf(i,n) for(int i=n-1;i>=0;i--)
const int MAX = 10005;
int arr[MAX];
int val[MAX][MAX];
int parent[MAX];
pair<int,pair<int,int>> p[MAX];
pair<int,int> sp[MAX];
vector<int> vec[MAX];
bool vis[MAX];
queue<int> q;
int n,m,start,dest,value,ct=0;
void initialize(int n){
for(int i=1;i<=n;i++){
arr[i]=i;
}
}
void dfs(int x){
vis[x]=1;
for(int i=0;i<vec[x].size();i++){
if(vis[vec[x][i]]==0){
parent[vec[x][i]]=x;
dfs(vec[x][i]);
}
}
}
void par_chk(int source,int dest){
if(parent[dest]!=source){
int zz = parent[dest];
sp[ct] = make_pair(zz,val[zz][dest]);
ct++;
par_chk(source,zz);
}
}
int root(int x){
while(arr[x] != x){
arr[x] = arr[arr[x]];
x = arr[x];
}
return x;
}
bool find(int x,int y){
if(root(x)==root(y))
return true;
else
return false;
}
void uniwg(int x,int y){
int root_x = root(x);
int root_y = root(y);
arr[root_x] = arr[root_y];
}
void kruskal(){
int x,y;
for(int i=0;i<m;i++){
x = p[i].second.first;
y = p[i].second.second;
if(root(x)!=root(y)){
vec[x].push_back(y);
vec[y].push_back(x);
val[x][y] = p[i].first;
val[y][x] = p[i].first;
uniwg(x,y);
}
}
}
int main() {
cin>>n>>m;
initialize(n);
memset(vis,0,sizeof(vis));
for(int i=0;i<m;i++){
int x,y,wgt;
cin>>x>>y>>wgt;
p[i] = make_pair(wgt,make_pair(x,y));
}
sort(p,p+m);
reverse(p,p+m);
kruskal();
cin>>start>>dest>>value;
vis[start]=0;
dfs(start);
par_chk(start,dest);
int mn = 1e9;
cout<<start<<" ";
for(int i=ct-1;i>=0;i--){
int stop1 = sp[i].first;
int valz = sp[i].second;
mn = min(valz,mn);
cout<<stop1<<" ";
}
cout<<dest<<endl;
mn--;
float qz = (float)value / (float)mn;
cout<<ceil(qz);
return 0;
} | 21.432432 | 45 | 0.497268 | Satyabrat35 |
d6c1056bfef3fed68dadf7c849e6745cab5b1819 | 1,001 | cpp | C++ | opencl/test/unit_test/mocks/ult_cl_device_factory.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | 1 | 2020-09-03T17:10:38.000Z | 2020-09-03T17:10:38.000Z | opencl/test/unit_test/mocks/ult_cl_device_factory.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | opencl/test/unit_test/mocks/ult_cl_device_factory.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/test/unit_test/mocks/ult_cl_device_factory.h"
#include "shared/test/unit_test/mocks/ult_device_factory.h"
#include "opencl/test/unit_test/mocks/mock_cl_device.h"
using namespace NEO;
UltClDeviceFactory::UltClDeviceFactory(uint32_t rootDevicesCount, uint32_t subDevicesCount) {
auto executionEnvironment = new ClExecutionEnvironment();
pUltDeviceFactory = std::make_unique<UltDeviceFactory>(rootDevicesCount, subDevicesCount, *executionEnvironment);
for (auto &pRootDevice : pUltDeviceFactory->rootDevices) {
auto pRootClDevice = new MockClDevice{pRootDevice};
for (auto &pClSubDevice : pRootClDevice->subDevices) {
subDevices.push_back(pClSubDevice.get());
}
rootDevices.push_back(pRootClDevice);
}
}
UltClDeviceFactory::~UltClDeviceFactory() {
for (auto &pClDevice : rootDevices) {
pClDevice->decRefInternal();
}
}
| 29.441176 | 117 | 0.733267 | 8tab |
d6cc54b5038fd2b46509fb1f732378ab4a3a6cb1 | 6,704 | cpp | C++ | export/windows/obj/src/haxe/Utf8.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/haxe/Utf8.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | null | null | null | export/windows/obj/src/haxe/Utf8.cpp | arturspon/zombie-killer | 07848c5006916e9079537a3d703ffe3740afaa5a | [
"MIT"
] | 1 | 2021-07-16T22:57:01.000Z | 2021-07-16T22:57:01.000Z | // Generated by Haxe 4.0.0-rc.2+77068e10c
#include <hxcpp.h>
#ifndef INCLUDED_haxe_Utf8
#include <haxe/Utf8.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_31_new,"haxe.Utf8","new",0x67cc940b,"haxe.Utf8.new","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",31,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_38_addChar,"haxe.Utf8","addChar",0x9a1816c2,"haxe.Utf8.addChar","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",38,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_42_toString,"haxe.Utf8","toString",0xb459e121,"haxe.Utf8.toString","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",42,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_66_charCodeAt,"haxe.Utf8","charCodeAt",0xce7cbeab,"haxe.Utf8.charCodeAt","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",66,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_74_length,"haxe.Utf8","length",0x88322e1b,"haxe.Utf8.length","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",74,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_78_compare,"haxe.Utf8","compare",0x9f848dd0,"haxe.Utf8.compare","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",78,0xf320feca)
HX_LOCAL_STACK_FRAME(_hx_pos_37807d8ab8df9b7c_82_sub,"haxe.Utf8","sub",0x67d06d2b,"haxe.Utf8.sub","C:\\HaxeToolkit\\haxe\\std/cpp/_std/haxe/Utf8.hx",82,0xf320feca)
namespace haxe{
void Utf8_obj::__construct( ::Dynamic size){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_31_new)
HXLINE( 32) this->__s = ::Array_obj< int >::__new();
HXLINE( 33) bool _hx_tmp;
HXDLIN( 33) if (hx::IsNotNull( size )) {
HXLINE( 33) _hx_tmp = hx::IsGreater( size,0 );
}
else {
HXLINE( 33) _hx_tmp = false;
}
HXDLIN( 33) if (_hx_tmp) {
HXLINE( 34) this->__s->reserve(( (int)(size) ));
}
}
Dynamic Utf8_obj::__CreateEmpty() { return new Utf8_obj; }
void *Utf8_obj::_hx_vtable = 0;
Dynamic Utf8_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< Utf8_obj > _hx_result = new Utf8_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool Utf8_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x11cee8b7;
}
void Utf8_obj::addChar(int c){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_38_addChar)
HXDLIN( 38) this->__s->push(c);
}
HX_DEFINE_DYNAMIC_FUNC1(Utf8_obj,addChar,(void))
::String Utf8_obj::toString(){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_42_toString)
HXDLIN( 42) return ::__hxcpp_char_array_to_utf8_string(this->__s);
}
HX_DEFINE_DYNAMIC_FUNC0(Utf8_obj,toString,return )
int Utf8_obj::charCodeAt(::String s,int index){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_66_charCodeAt)
HXDLIN( 66) return _hx_utf8_char_code_at(s,index);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Utf8_obj,charCodeAt,return )
int Utf8_obj::length(::String s){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_74_length)
HXDLIN( 74) return _hx_utf8_length(s);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Utf8_obj,length,return )
int Utf8_obj::compare(::String a,::String b){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_78_compare)
HXDLIN( 78) return _hx_string_compare(a,b);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Utf8_obj,compare,return )
::String Utf8_obj::sub(::String s,int pos,int len){
HX_STACKFRAME(&_hx_pos_37807d8ab8df9b7c_82_sub)
HXDLIN( 82) return _hx_utf8_sub(s,pos,len);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(Utf8_obj,sub,return )
Utf8_obj::Utf8_obj()
{
}
void Utf8_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Utf8);
HX_MARK_MEMBER_NAME(__s,"__s");
HX_MARK_END_CLASS();
}
void Utf8_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(__s,"__s");
}
hx::Val Utf8_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__s") ) { return hx::Val( __s ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"addChar") ) { return hx::Val( addChar_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
bool Utf8_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"sub") ) { outValue = sub_dyn(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"length") ) { outValue = length_dyn(); return true; }
break;
case 7:
if (HX_FIELD_EQ(inName,"compare") ) { outValue = compare_dyn(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"charCodeAt") ) { outValue = charCodeAt_dyn(); return true; }
}
return false;
}
hx::Val Utf8_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"__s") ) { __s=inValue.Cast< ::Array< int > >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Utf8_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("__s",53,69,48,00));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static hx::StorageInfo Utf8_obj_sMemberStorageInfo[] = {
{hx::fsObject /* ::Array< int > */ ,(int)offsetof(Utf8_obj,__s),HX_("__s",53,69,48,00)},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *Utf8_obj_sStaticStorageInfo = 0;
#endif
static ::String Utf8_obj_sMemberFields[] = {
HX_("__s",53,69,48,00),
HX_("addChar",97,a1,fc,7d),
HX_("toString",ac,d0,6e,38),
::String(null()) };
hx::Class Utf8_obj::__mClass;
static ::String Utf8_obj_sStaticFields[] = {
HX_("charCodeAt",f6,e6,54,35),
HX_("length",e6,94,07,9f),
HX_("compare",a5,18,69,83),
HX_("sub",80,a9,57,00),
::String(null())
};
void Utf8_obj::__register()
{
Utf8_obj _hx_dummy;
Utf8_obj::_hx_vtable = *(void **)&_hx_dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_("haxe.Utf8",99,32,41,f3);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Utf8_obj::__GetStatic;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mStatics = hx::Class_obj::dupFunctions(Utf8_obj_sStaticFields);
__mClass->mMembers = hx::Class_obj::dupFunctions(Utf8_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< Utf8_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Utf8_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Utf8_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace haxe
| 32.230769 | 184 | 0.717482 | arturspon |
d6ce0baedf06b54df8f51de1a3ba69492bc3413c | 4,481 | cpp | C++ | source/projectionView.cpp | ixsiid/VST_Sample | 88d12dcf2cde163e9577c23545b3f8f436125197 | [
"MIT"
] | null | null | null | source/projectionView.cpp | ixsiid/VST_Sample | 88d12dcf2cde163e9577c23545b3f8f436125197 | [
"MIT"
] | null | null | null | source/projectionView.cpp | ixsiid/VST_Sample | 88d12dcf2cde163e9577c23545b3f8f436125197 | [
"MIT"
] | null | null | null | #include "../include/projectionView.h"
#include "../include/dft.h"
#include "../include/log.h"
namespace Steinberg {
namespace HelloWorld {
using namespace VSTGUI;
ProjectionView::ProjectionView(const CRect& rect, Projection * proj) : CControl(rect) {
this->proj = proj;
top = rect.top;
left = rect.left;
_points = new CPoint[32];
count = proj->getPointList(_points);
sortPoints();
m = CPoint(256, 256);
showMousePointer = false;
drag = false;
}
CMouseEventResult ProjectionView::onMouseDown(CPoint& pos, const CButtonState& buttons) {
if (buttons.isDoubleClick() && buttons.isLeftButton()) {
if (count < 32) {
_points[count] = pos;
_points[count].x -= left;
_points[count].y -= top;
count++;
sortPoints();
}
return CMouseEventResult::kMouseEventHandled;
} else if (active >= 0 && buttons.isLeftButton()) {
drag = true;
return CMouseEventResult::kMouseEventHandled;
} else if (active >= 2 && buttons.isRightButton()) {
for (int i = active; i < count - 1; i++) {
_points[i] = _points[i + 1];
}
active = -1;
count--;
sortPoints();
return CMouseEventResult::kMouseEventHandled;
}
return CMouseEventResult::kMouseEventNotHandled;
}
CMouseEventResult ProjectionView::onMouseUp(CPoint& where, const CButtonState& buttons) {
drag = false;
return CMouseEventResult::kMouseEventHandled;
}
CMouseEventResult ProjectionView::onMouseMoved(CPoint& pos, const CButtonState& buttons) {
m = pos;
m.x -= left;
m.y -= top;
if (drag) {
if (active == 0) m.x = 0.0;
if (active == 1) m.x = 512.0;
if (m.y < 0.0) m.y = 0.0;
else if (m.y > 512.0) m.y = 512.0;
if (m.x < 0.0) m.x = 0.0;
else if (m.x > 512.0) m.x = 512.0;
_points[active] = m;
sortPoints();
return CMouseEventResult::kMouseEventHandled;
}
active = -1;
for (int i = 0; i < count; i++) {
CCoord dx = m.x - _points[i].x;
CCoord dy = m.y - _points[i].y;
CCoord d = dx * dx + dy * dy;
if (d < 64) {
active = i;
break;
}
}
return CMouseEventResult::kMouseEventHandled;
}
CMouseEventResult ProjectionView::onMouseEntered(CPoint& where, const CButtonState& buttons) {
showMousePointer = true;
return CMouseEventResult::kMouseEventNotHandled;
}
CMouseEventResult ProjectionView::onMouseExited(CPoint& where, const CButtonState& buttons) {
showMousePointer = false;
drag = false;
return CMouseEventResult::kMouseEventNotHandled;
}
void ProjectionView::draw(CDrawContext* context) {
context->setDrawMode(CDrawMode(CDrawModeFlags::kAntiAliasing));
CDrawContext::Transform transform(*context, CGraphicsTransform().translate(getViewSize().getTopLeft()));
const auto width = getWidth();
const auto height = getHeight();
const double borderWidth = 2.0;
const double halfBorderWidth = borderWidth / 2.0;
context->setLineWidth(1.0);
context->setLineStyle(lineStyle);
context->setFrameColor(CColor(19, 193, 54, 255));
context->drawPolygon(points);
for (int i = 0; i < count; i++) {
context->drawEllipse(CRect(_points[i].x - 3, _points[i].y - 3, _points[i].x + 3, _points[i].y + 3), CDrawStyle::kDrawStroked);
}
int r = 5;
if (active >= 0) {
context->setFillColor(CColor(180, 180, 180, 255));
CPoint* p = &_points[active];
context->drawEllipse(CRect(p->x - r, p->y - r, p->x + r, p->y + r), CDrawStyle::kDrawFilled);
context->drawLine(CPoint(0, p->y), CPoint(512, p->y));
context->drawLine(CPoint(p->x, 0), CPoint(p->x, 512));
} else if (showMousePointer) {
context->setFillColor(CColor(180, 180, 180, 255));
context->drawEllipse(CRect(m.x - r, m.y - r, m.x + r, m.y + r), CDrawStyle::kDrawFilled);
}
context->setFrameColor(CColor(19, 19, 254, 255));
CPoint s = {proj->latest.x, 0.0};
CPoint c = {proj->latest.x, proj->latest.y};
CPoint f = {512.0 + 80, proj->latest.y};
context->drawLine(s, c);
context->drawLine(c, f);
setDirty(false);
}
void ProjectionView::sortPoints() {
points.resize(count);
int index[32];
for (int i = 0; i < count - 2; i++) index[i] = i + 2;
for (int i = 0; i < count - 3; i++) {
for (int k = i; k < count - 2; k++) {
if (_points[index[i]].x > _points[index[k]].x) {
int t = index[k];
index[k] = index[i];
index[i] = t;
}
}
}
points[0] = _points[0];
points[count - 1] = _points[1];
for (int i = 1; i < count - 1; i++) {
points[i] = _points[index[i - 1]];
}
proj->setPointList(&points);
}
void ProjectionView::update() { invalid(); }
} // namespace HelloWorld
} // namespace Steinberg | 25.752874 | 128 | 0.649409 | ixsiid |
d6d4077878bdf7b27ae363f9c09f59580f36cbb2 | 4,753 | hpp | C++ | include/cppdevtk/base/posix_signals_watcher_unx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/posix_signals_watcher_unx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | include/cppdevtk/base/posix_signals_watcher_unx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
#define CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
#include "config.hpp"
#if (!CPPDEVTK_PLATFORM_UNIX)
# error "This file is Unix specific!!!"
#endif
#include "socket_pair.hpp"
#include "singletons.hpp"
#include <QtCore/QObject>
#include <QtCore/QSocketNotifier>
#include <QtCore/QString>
#include <csignal>
// non-std extension
#ifndef SIGNULL
#define SIGNULL 0
#else
#if (SIGNULL != 0)
# error "SIGNULL != 0"
#endif
#endif
namespace cppdevtk {
namespace base {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Templates explicit instantiation.
class PosixSignalsWatcher;
#if (!defined(CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_CPP) || CPPDEVTK_COMPILER_CLANG)
CPPDEVTK_BASE_TMPL_EXPL_INST
#endif
template class CPPDEVTK_BASE_API MeyersSingleton<PosixSignalsWatcher>;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \sa <a href="http://doc.qt.io/qt-5/unix-signals.html">Calling Qt Functions From Unix Signal Handlers</a>
/// \attention A signal argument can not be SIGNULL, SIGKILL or SIGSTOP
class CPPDEVTK_BASE_API PosixSignalsWatcher: public QObject, public MeyersSingleton<PosixSignalsWatcher> {
friend class MeyersSingleton<PosixSignalsWatcher>;
Q_OBJECT
Q_SIGNALS:
void Raised(int sig);
// Convenience signals (corresponding Raised() will be also emitted)
// Termination signals
void SigTerm();
void SigInt();
// Daemon signals
void SigHUp();
void SigChld();
void SigTStp();
void SigTtOu();
void SigTtIn();
// TODO: if needed add other convenience signals here
public Q_SLOTS:
/// \pre \a sig is not watched
/// \note By default no signal is watched.
bool Watch(int sig);
/// \pre \a sig is not watched
/// \remark Restores old signal action
bool Unwatch(int sig);
public:
bool IsWatched(int sig);
private Q_SLOTS:
void QtSignalHandler(int socket);
void Dispatch(int sig);
private:
PosixSignalsWatcher();
~PosixSignalsWatcher();
static bool MakeWriteSocketNonBlocking(int sig);
static bool CloseSocketPair(int sig);
static void PosixSignalHandler(int sig); // nothrow guarantee
static QString GetPosixSignalName(int sig);
// - NSIG is non standard extension but present on all platforms we support
// Please see NSIG on: https://www.gnu.org/software/libc/manual/html_node/Standard-Signals.html#Standard-Signals
static const int kNumSigs_ = NSIG - 1;
// - glibc guarantees that the signal numbers are allocated consecutively (this is not required by std).
// Please see Standard Signals: https://www.gnu.org/software/libc/manual/html_node/Standard-Signals.html#Standard-Signals
// This is why we use arrays.
// - sigaction() prevent the signal from being received from within its own signal handler (unless SA_NODEFER is used).
// But a different signal can interrupt current signal handler if it is not blocked by the signal mask.
// This is why we use a socket pair and a socket notifier for each signal.
static socket_t socketPairs_[kNumSigs_][2]; // socketPairs_[x][0] read, socketPairs_[x][1] write
static QSocketNotifier* socketNotifiers_[kNumSigs_];
static struct sigaction oldSigActions_[kNumSigs_];
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline functions.
} // namespace base
} // namespace cppdevtk
#endif // CPPDEVTK_BASE_POSIX_SIGNALS_WATCHER_UNX_HPP_INCLUDED_
| 35.470149 | 126 | 0.637492 | CoSoSys |
d6d474fa9f74a5839fb55c4fb4a80b55b004b937 | 3,072 | cpp | C++ | infer/tests/codetoanalyze/cpp/performance/array.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 14,499 | 2015-06-11T16:00:28.000Z | 2022-03-31T23:43:54.000Z | infer/tests/codetoanalyze/cpp/performance/array.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 1,529 | 2015-06-11T16:55:30.000Z | 2022-03-27T15:59:46.000Z | infer/tests/codetoanalyze/cpp/performance/array.cpp | sujin0529/infer | f08a09d6896ac2a22081ead4830eb86c64af8813 | [
"MIT"
] | 2,225 | 2015-06-11T16:36:10.000Z | 2022-03-31T05:16:59.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <iostream>
#include <iterator>
void array_access_constant() {
float radii[8];
for (int i = 0; i < 4; ++i) {
radii[i * 2] = radii[i];
radii[i * 2 + 1] = radii[i] + 1;
}
}
void array_access_overrun_constant() {
float radii[8];
for (int i = 0; i < 4; ++i) {
radii[i * 2] = radii[i];
radii[i * 2 + 2] = radii[i] + 1;
}
}
void array_access_weird_linear(long (&optionNumerators)[], size_t length) {
for (int j = 0; j < length; ++j) {
if (10 < optionNumerators[j] + 1) {
}
}
}
bool binary_search_log_FN(std::string (&arr)[], size_t length) {
return std::binary_search(arr, arr + length, "x");
}
void fill_linear_FN(std::string (&arr)[], size_t length) {
std::fill(arr, arr + length, "x");
}
void copy_linear_FN(std::string (&arr1)[],
std::string (&arr2)[],
size_t arr1_length) {
std::copy(arr1, arr1 + arr1_length, arr2);
}
void copy_for_linear(std::string (&arr1)[],
std::string (&arr2)[],
size_t arr1_length) {
for (int i = 0; i < arr1_length; ++i) {
arr2[i] = arr1[i];
}
}
// sort_array_template does not exist in the cost-issues file.
// Clang frontend only creates procedures
// when the template is instantiated.
template <size_t N>
void sort_array_template_nlogn(const int (&arr1)[N]) {
std::sort(std::begin(arr1), std::end(arr1));
}
void sort_array_inst_constant() {
int arr1[300];
std::sort(std::begin(arr1), std::end(arr1));
}
void sort_array_nlogn_FN(size_t length) {
std::string arr1[length];
std::sort(arr1, arr1 + length);
}
// expected: O(N)
void array_loop_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
}
// expected: O(N)
void array_loop_while_while_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
int j = 0;
while (j < sizeof(*N) / sizeof(N[0])) {
j++;
}
}
// expected: O(N+M)
void array_loop_while_for_linear_FN(int (&N)[], int (&M)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
i++;
}
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
}
// expected: O(N*M)
void array_nested_loop_while_for_FN(int (&N)[], int (&M)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
i++;
}
}
int size = 10;
void loop_global_var_size_constant() {
int M[size];
for (int j = 0; j < sizeof(*M) / sizeof(M[0]); j++) {
}
}
// expected: O(N)
void array_nested_loop_while_for_linear_FN(int (&N)[]) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
loop_global_var_size_constant();
i++;
}
}
// expected: O(N*M)
void array_nested_loop_for_FN(int (&N)[], int m) {
int i = 0;
while (i < sizeof(*N) / sizeof(N[0])) {
for (int j = 0; j < m; j++) {
}
i++;
}
}
| 21.942857 | 75 | 0.57194 | sujin0529 |
d6d7d99503a87163132fb0ff83f209a325e291b2 | 155 | cpp | C++ | tests/action/test_path_explorer.cpp | regisf/r-backup | 480f69c166266be9d853cbcbf1df4dd12abcffc6 | [
"BSD-3-Clause"
] | null | null | null | tests/action/test_path_explorer.cpp | regisf/r-backup | 480f69c166266be9d853cbcbf1df4dd12abcffc6 | [
"BSD-3-Clause"
] | null | null | null | tests/action/test_path_explorer.cpp | regisf/r-backup | 480f69c166266be9d853cbcbf1df4dd12abcffc6 | [
"BSD-3-Clause"
] | null | null | null | // #include "../../src/action/path_explorer.hpp"
// #include <gtest/gtest.h>
// TEST(test_path_explorer, test_should_be_skipped)
// {
// FAIL();
// } | 19.375 | 51 | 0.632258 | regisf |
d6da8c6b211848a0fd427c0bf6717da1d518aa0f | 21,683 | cpp | C++ | Engine/Source/Developer/GameplayDebugger/Private/GameplayDebuggerTypes.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Developer/GameplayDebugger/Private/GameplayDebuggerTypes.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Developer/GameplayDebugger/Private/GameplayDebuggerTypes.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "GameplayDebuggerTypes.h"
#include "InputCoreTypes.h"
#include "Serialization/MemoryWriter.h"
#include "Serialization/MemoryReader.h"
#include "GameplayDebuggerConfig.h"
#include "DrawDebugHelpers.h"
#include "CanvasItem.h"
#include "Engine/Canvas.h"
DEFINE_LOG_CATEGORY(LogGameplayDebug);
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerShape
FGameplayDebuggerShape FGameplayDebuggerShape::MakePoint(const FVector& Location, const float Radius, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(Location);
NewElement.ShapeData.Add(FVector(Radius, 0, 0));
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Point;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeSegment(const FVector& StartLocation, const FVector& EndLocation, const float Thickness, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(StartLocation);
NewElement.ShapeData.Add(EndLocation);
NewElement.ShapeData.Add(FVector(Thickness, 0, 0));
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Segment;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeSegment(const FVector& StartLocation, const FVector& EndLocation, const FColor& Color, const FString& Description)
{
return MakeSegment(StartLocation, EndLocation, 1.0f, Color, Description);
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeBox(const FVector& Center, const FVector& Extent, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(Center);
NewElement.ShapeData.Add(Extent);
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Box;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeCone(const FVector& Location, const FVector& Direction, const float Length, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(Location);
NewElement.ShapeData.Add(Direction);
NewElement.ShapeData.Add(FVector(Length, 0, 0));
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Cone;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeCylinder(const FVector& Center, const float Radius, const float HalfHeight, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(Center);
NewElement.ShapeData.Add(FVector(Radius, 0, HalfHeight));
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Cylinder;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakeCapsule(const FVector& Center, const float Radius, const float HalfHeight, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData.Add(Center);
NewElement.ShapeData.Add(FVector(Radius, 0, HalfHeight));
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Capsule;
return NewElement;
}
FGameplayDebuggerShape FGameplayDebuggerShape::MakePolygon(const TArray<FVector>& Verts, const FColor& Color, const FString& Description)
{
FGameplayDebuggerShape NewElement;
NewElement.ShapeData = Verts;
NewElement.Color = Color;
NewElement.Description = Description;
NewElement.Type = EGameplayDebuggerShape::Polygon;
return NewElement;
}
void FGameplayDebuggerShape::Draw(UWorld* World, FGameplayDebuggerCanvasContext& Context)
{
FVector DescLocation;
switch (Type)
{
case EGameplayDebuggerShape::Point:
if (ShapeData.Num() == 2 && ShapeData[1].X > 0)
{
DrawDebugSphere(World, ShapeData[0], ShapeData[1].X, 16, Color);
DescLocation = ShapeData[0];
}
break;
case EGameplayDebuggerShape::Segment:
if (ShapeData.Num() == 3 && ShapeData[2].X > 0)
{
DrawDebugLine(World, ShapeData[0], ShapeData[1], Color, false, -1.0f, 0, ShapeData[2].X);
DescLocation = (ShapeData[0] + ShapeData[1]) * 0.5f;
}
break;
case EGameplayDebuggerShape::Box:
if (ShapeData.Num() == 2)
{
DrawDebugBox(World, ShapeData[0], ShapeData[1], Color);
DescLocation = ShapeData[0];
}
break;
case EGameplayDebuggerShape::Cone:
if (ShapeData.Num() == 3 && ShapeData[2].X > 0)
{
DrawDebugCone(World, ShapeData[0], ShapeData[1], ShapeData[2].X, PI * 0.5f, PI * 0.5f, 16, Color);
DescLocation = ShapeData[0];
}
break;
case EGameplayDebuggerShape::Cylinder:
if (ShapeData.Num() == 2)
{
DrawDebugCylinder(World, ShapeData[0] - FVector(0, 0, ShapeData[1].Z), ShapeData[0] + FVector(0, 0, ShapeData[1].Z), ShapeData[1].X, 16, Color);
DescLocation = ShapeData[0];
}
break;
case EGameplayDebuggerShape::Capsule:
if (ShapeData.Num() == 2)
{
DrawDebugCapsule(World, ShapeData[0], ShapeData[1].Z, ShapeData[1].X, FQuat::Identity, Color);
DescLocation = ShapeData[0];
}
break;
case EGameplayDebuggerShape::Polygon:
if (ShapeData.Num() > 0)
{
FVector MidPoint = FVector::ZeroVector;
TArray<int32> Indices;
for (int32 Idx = 0; Idx < ShapeData.Num(); Idx++)
{
Indices.Add(Idx);
MidPoint += ShapeData[Idx];
}
DrawDebugMesh(World, ShapeData, Indices, Color);
DescLocation = MidPoint / ShapeData.Num();
}
break;
default:
break;
}
if (Description.Len() && Context.IsLocationVisible(DescLocation))
{
const FVector2D ScreenLoc = Context.ProjectLocation(DescLocation);
Context.PrintAt(ScreenLoc.X, ScreenLoc.Y, Color, Description);
}
}
FArchive& operator<<(FArchive& Ar, FGameplayDebuggerShape& Shape)
{
Ar << Shape.ShapeData;
Ar << Shape.Description;
Ar << Shape.Color;
uint8 TypeNum = static_cast<uint8>(Shape.Type);
Ar << TypeNum;
Shape.Type = static_cast<EGameplayDebuggerShape>(TypeNum);
return Ar;
}
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerCanvasContext
enum class EStringParserToken : uint8
{
OpenTag,
CloseTag,
NewLine,
EndOfString,
RegularChar,
Tab,
};
class FTaggedStringParser
{
public:
struct FNode
{
FString String;
FColor Color;
bool bNewLine;
FNode() : Color(FColor::White), bNewLine(false) {}
FNode(const FColor& InColor) : Color(InColor), bNewLine(false) {}
};
TArray<FNode> NodeList;
FTaggedStringParser(const FColor& InDefaultColor) : DefaultColor(InDefaultColor) {}
void ParseString(const FString& StringToParse)
{
DataIndex = 0;
DataString = StringToParse;
if (DataIndex >= DataString.Len())
{
return;
}
const FString TabString(TEXT(" "));
FColor TagColor;
FNode CurrentNode(DefaultColor);
for (EStringParserToken Token = ReadToken(); Token != EStringParserToken::EndOfString; Token = ReadToken())
{
switch (Token)
{
case EStringParserToken::RegularChar:
CurrentNode.String.AppendChar(DataString[DataIndex]);
break;
case EStringParserToken::NewLine:
NodeList.Add(CurrentNode);
CurrentNode = FNode(NodeList.Last().Color);
CurrentNode.bNewLine = true;
break;
case EStringParserToken::Tab:
CurrentNode.String.Append(TabString);
break;
case EStringParserToken::OpenTag:
if (ParseTag(TagColor))
{
NodeList.Add(CurrentNode);
CurrentNode = FNode(TagColor);
}
break;
}
DataIndex++;
}
NodeList.Add(CurrentNode);
}
private:
int32 DataIndex;
FString DataString;
FColor DefaultColor;
EStringParserToken ReadToken() const
{
EStringParserToken OutToken = EStringParserToken::RegularChar;
const TCHAR Char = DataIndex < DataString.Len() ? DataString[DataIndex] : TEXT('\0');
switch (Char)
{
case TEXT('\0'):
OutToken = EStringParserToken::EndOfString;
break;
case TEXT('{'):
OutToken = EStringParserToken::OpenTag;
break;
case TEXT('}'):
OutToken = EStringParserToken::CloseTag;
break;
case TEXT('\n'):
OutToken = EStringParserToken::NewLine;
break;
case TEXT('\t'):
OutToken = EStringParserToken::Tab;
break;
default:
break;
}
return OutToken;
}
bool ParseTag(FColor& OutColor)
{
FString TagString;
EStringParserToken Token = ReadToken();
for (; Token != EStringParserToken::EndOfString && Token != EStringParserToken::CloseTag; Token = ReadToken())
{
if (Token == EStringParserToken::RegularChar)
{
TagString.AppendChar(DataString[DataIndex]);
}
DataIndex++;
}
bool bResult = false;
if (Token == EStringParserToken::CloseTag)
{
const FString TagColorLower = TagString.ToLower();
const bool bIsColorName = GColorList.IsValidColorName(*TagColorLower);
if (bIsColorName)
{
OutColor = GColorList.GetFColorByName(*TagColorLower);
bResult = true;
}
else
{
bResult = OutColor.InitFromString(TagString);
}
}
return bResult;
}
};
FGameplayDebuggerCanvasContext::FGameplayDebuggerCanvasContext(UCanvas* InCanvas, UFont* InFont)
{
if (InCanvas)
{
Canvas = InCanvas;
Font = InFont;
CursorX = DefaultX = InCanvas->SafeZonePadX;
CursorY = DefaultY = InCanvas->SafeZonePadY;
}
else
{
CursorX = DefaultX = 0.0f;
CursorY = DefaultY = 0.0f;
}
}
void FGameplayDebuggerCanvasContext::Print(const FString& String)
{
Print(FColor::White, String);
}
void FGameplayDebuggerCanvasContext::Print(const FColor& Color, const FString& String)
{
FTaggedStringParser Parser(Color);
Parser.ParseString(String);
const float LineHeight = GetLineHeight();
for (int32 NodeIdx = 0; NodeIdx < Parser.NodeList.Num(); NodeIdx++)
{
const FTaggedStringParser::FNode& NodeData = Parser.NodeList[NodeIdx];
if (NodeData.bNewLine)
{
if (Canvas.IsValid() && (CursorY + LineHeight) > Canvas->ClipY)
{
DefaultX += Canvas->ClipX / 2;
CursorY = 0.0f;
}
CursorX = DefaultX;
CursorY += LineHeight;
}
if (NodeData.String.Len() > 0)
{
float SizeX = 0.0f, SizeY = 0.0f;
MeasureString(NodeData.String, SizeX, SizeY);
FCanvasTextItem TextItem(FVector2D::ZeroVector, FText::FromString(NodeData.String), Font.Get(), FLinearColor(NodeData.Color));
if (FontRenderInfo.bEnableShadow)
{
TextItem.EnableShadow(FColor::Black, FVector2D(1, 1));
}
DrawItem(TextItem, CursorX, CursorY);
CursorX += SizeX;
}
}
MoveToNewLine();
}
void FGameplayDebuggerCanvasContext::PrintAt(float PosX, float PosY, const FString& String)
{
const float SavedPosX = CursorX;
const float SavedPosY = CursorY;
const float SavedDefX = DefaultX;
DefaultX = CursorX = PosX;
DefaultY = CursorY = PosY;
Print(FColor::White, String);
CursorX = SavedPosX;
CursorY = SavedPosY;
DefaultX = SavedDefX;
}
void FGameplayDebuggerCanvasContext::PrintAt(float PosX, float PosY, const FColor& Color, const FString& String)
{
const float SavedPosX = CursorX;
const float SavedPosY = CursorY;
const float SavedDefX = DefaultX;
DefaultX = CursorX = PosX;
DefaultY = CursorY = PosY;
Print(Color, String);
CursorX = SavedPosX;
CursorY = SavedPosY;
DefaultX = SavedDefX;
}
// copied from Core/Private/Misc/VarargsHeler.h
#define GROWABLE_PRINTF(PrintFunc) \
int32 BufferSize = 1024; \
TCHAR* Buffer = NULL; \
int32 Result = -1; \
/* allocate some stack space to use on the first pass, which matches most strings */ \
TCHAR StackBuffer[512]; \
TCHAR* AllocatedBuffer = NULL; \
\
/* first, try using the stack buffer */ \
Buffer = StackBuffer; \
GET_VARARGS_RESULT( Buffer, ARRAY_COUNT(StackBuffer), ARRAY_COUNT(StackBuffer) - 1, Fmt, Fmt, Result ); \
\
/* if that fails, then use heap allocation to make enough space */ \
while(Result == -1) \
{ \
FMemory::SystemFree(AllocatedBuffer); \
/* We need to use malloc here directly as GMalloc might not be safe. */ \
Buffer = AllocatedBuffer = (TCHAR*) FMemory::SystemMalloc( BufferSize * sizeof(TCHAR) ); \
GET_VARARGS_RESULT( Buffer, BufferSize, BufferSize-1, Fmt, Fmt, Result ); \
BufferSize *= 2; \
}; \
Buffer[Result] = 0; \
; \
\
PrintFunc; \
FMemory::SystemFree(AllocatedBuffer);
VARARG_BODY(void, FGameplayDebuggerCanvasContext::Printf, const TCHAR*, VARARG_NONE)
{
GROWABLE_PRINTF(Print(Buffer));
}
VARARG_BODY(void, FGameplayDebuggerCanvasContext::Printf, const TCHAR*, VARARG_EXTRA(const FColor& Color))
{
GROWABLE_PRINTF(Print(Color, Buffer));
}
VARARG_BODY(void, FGameplayDebuggerCanvasContext::PrintfAt, const TCHAR*, VARARG_EXTRA(float PosX) VARARG_EXTRA(float PosY))
{
GROWABLE_PRINTF(PrintAt(PosX, PosY, Buffer));
}
VARARG_BODY(void, FGameplayDebuggerCanvasContext::PrintfAt, const TCHAR*, VARARG_EXTRA(float PosX) VARARG_EXTRA(float PosY) VARARG_EXTRA(const FColor& Color))
{
GROWABLE_PRINTF(PrintAt(PosX, PosY, Color, Buffer));
}
void FGameplayDebuggerCanvasContext::MoveToNewLine()
{
const float LineHeight = GetLineHeight();
CursorY += LineHeight;
CursorX = DefaultX;
}
void FGameplayDebuggerCanvasContext::MeasureString(const FString& String, float& OutSizeX, float& OutSizeY) const
{
OutSizeX = OutSizeY = 0.0f;
UCanvas* CanvasOb = Canvas.Get();
if (CanvasOb)
{
FString StringWithoutFormatting = String;
int32 BracketStart = INDEX_NONE;
while (StringWithoutFormatting.FindChar(TEXT('{'), BracketStart))
{
int32 BracketEnd = INDEX_NONE;
if (StringWithoutFormatting.FindChar(TEXT('}'), BracketEnd))
{
if (BracketEnd > BracketStart)
{
StringWithoutFormatting.RemoveAt(BracketStart, BracketEnd - BracketStart + 1, false);
}
}
}
TArray<FString> Lines;
StringWithoutFormatting.ParseIntoArrayLines(Lines);
UFont* FontOb = Font.Get();
for (int32 Idx = 0; Idx < Lines.Num(); Idx++)
{
float LineSizeX = 0.0f, LineSizeY = 0.0f;
CanvasOb->StrLen(FontOb, Lines[Idx], LineSizeX, LineSizeY);
OutSizeX = FMath::Max(OutSizeX, LineSizeX);
OutSizeY += LineSizeY;
}
}
}
float FGameplayDebuggerCanvasContext::GetLineHeight() const
{
UFont* FontOb = Font.Get();
return FontOb ? FontOb->GetMaxCharHeight() : 0.0f;
}
FVector2D FGameplayDebuggerCanvasContext::ProjectLocation(const FVector& Location) const
{
UCanvas* CanvasOb = Canvas.Get();
return CanvasOb ? FVector2D(CanvasOb->Project(Location)) : FVector2D::ZeroVector;
}
bool FGameplayDebuggerCanvasContext::IsLocationVisible(const FVector& Location) const
{
return Canvas.IsValid() && Canvas->SceneView && Canvas->SceneView->ViewFrustum.IntersectSphere(Location, 1.0f);
}
void FGameplayDebuggerCanvasContext::DrawItem(FCanvasItem& Item, float PosX, float PosY)
{
UCanvas* CanvasOb = Canvas.Get();
if (CanvasOb)
{
CanvasOb->DrawItem(Item, PosX, PosY);
}
}
void FGameplayDebuggerCanvasContext::DrawIcon(const FColor& Color, const FCanvasIcon& Icon, float PosX, float PosY, float Scale)
{
UCanvas* CanvasOb = Canvas.Get();
if (CanvasOb)
{
CanvasOb->SetDrawColor(Color);
CanvasOb->DrawIcon(Icon, PosX, PosY, Scale);
}
}
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerDataPack
int32 FGameplayDebuggerDataPack::PacketSize = 512;
bool FGameplayDebuggerDataPack::CheckDirtyAndUpdate()
{
TArray<uint8> UncompressedBuffer;
FMemoryWriter ArWriter(UncompressedBuffer);
SerializeDelegate.Execute(ArWriter);
const uint32 NewDataCRC = FCrc::MemCrc32(UncompressedBuffer.GetData(), UncompressedBuffer.Num());
if ((NewDataCRC == DataCRC) && !bIsDirty)
{
return false;
}
DataCRC = NewDataCRC;
return true;
}
bool FGameplayDebuggerDataPack::RequestReplication(int16 SyncCounter)
{
if (bNeedsConfirmation && !bReceived)
{
return false;
}
TArray<uint8> UncompressedBuffer;
FMemoryWriter ArWriter(UncompressedBuffer);
SerializeDelegate.Execute(ArWriter);
const uint32 NewDataCRC = FCrc::MemCrc32(UncompressedBuffer.GetData(), UncompressedBuffer.Num());
if ((NewDataCRC == DataCRC) && !bIsDirty)
{
return false;
}
const int32 MaxUncompressedDataSize = PacketSize;
Header.bIsCompressed = (UncompressedBuffer.Num() > MaxUncompressedDataSize);
if (Header.bIsCompressed)
{
const int32 UncompressedSize = UncompressedBuffer.Num();
int32 CompressionHeader = UncompressedSize;
const int32 CompressionHeaderSize = sizeof(CompressionHeader);
int32 CompressedSize = FMath::TruncToInt(1.1f * UncompressedSize);
Data.SetNum(CompressionHeaderSize + CompressedSize);
uint8* CompressedBuffer = Data.GetData();
FMemory::Memcpy(CompressedBuffer, &CompressionHeader, CompressionHeaderSize);
CompressedBuffer += CompressionHeaderSize;
FCompression::CompressMemory((ECompressionFlags)(COMPRESS_ZLIB | COMPRESS_BiasMemory),
CompressedBuffer, CompressedSize, UncompressedBuffer.GetData(), UncompressedSize);
Data.SetNum(CompressionHeaderSize + CompressedSize);
}
else
{
Data = UncompressedBuffer;
}
bNeedsConfirmation = IsMultiPacket(Data.Num());
bReceived = false;
bIsDirty = false;
DataCRC = NewDataCRC;
Header.DataOffset = 0;
Header.DataSize = Data.Num();
Header.SyncCounter = SyncCounter;
Header.DataVersion++;
return true;
}
void FGameplayDebuggerDataPack::OnReplicated()
{
if (Header.DataSize == 0)
{
ResetDelegate.Execute();
return;
}
if (Header.bIsCompressed)
{
uint8* CompressedBuffer = Data.GetData();
int32 CompressionHeader = 0;
const int32 CompressionHeaderSize = sizeof(CompressionHeader);
FMemory::Memcpy(&CompressionHeader, CompressedBuffer, CompressionHeaderSize);
CompressedBuffer += CompressionHeaderSize;
const int32 CompressedSize = Data.Num() - CompressionHeaderSize;
const int32 UncompressedSize = CompressionHeader;
TArray<uint8> UncompressedBuffer;
UncompressedBuffer.AddUninitialized(UncompressedSize);
FCompression::UncompressMemory((ECompressionFlags)(COMPRESS_ZLIB | COMPRESS_BiasMemory),
UncompressedBuffer.GetData(), UncompressedSize, CompressedBuffer, CompressedSize);
FMemoryReader ArReader(UncompressedBuffer);
SerializeDelegate.Execute(ArReader);
}
else
{
FMemoryReader ArReader(Data);
SerializeDelegate.Execute(ArReader);
}
Header.DataOffset = Header.DataSize;
}
void FGameplayDebuggerDataPack::OnPacketRequest(int16 DataVersion, int32 DataOffset)
{
// client should confirm with the same version and offset that server currently replicates
if (DataVersion == Header.DataVersion && DataOffset == Header.DataOffset)
{
Header.DataOffset = FMath::Min(DataOffset + FGameplayDebuggerDataPack::PacketSize, Header.DataSize);
bReceived = (Header.DataOffset == Header.DataSize);
}
// if for some reason it requests previous data version, rollback to first packet
else if (DataVersion < Header.DataVersion)
{
Header.DataOffset = 0;
}
// it may also request a previous packet from the same version, rollback and send next one
else if (DataVersion == Header.DataVersion && DataOffset < Header.DataOffset)
{
Header.DataOffset = FMath::Max(0, DataOffset + FGameplayDebuggerDataPack::PacketSize);
}
}
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerInputModifier
FGameplayDebuggerInputModifier FGameplayDebuggerInputModifier::Shift(true, false, false, false);
FGameplayDebuggerInputModifier FGameplayDebuggerInputModifier::Ctrl(false, true, false, false);
FGameplayDebuggerInputModifier FGameplayDebuggerInputModifier::Alt(false, false, true, false);
FGameplayDebuggerInputModifier FGameplayDebuggerInputModifier::Cmd(false, false, false, true);
FGameplayDebuggerInputModifier FGameplayDebuggerInputModifier::None;
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerInputHandler
bool FGameplayDebuggerInputHandler::IsValid() const
{
return FKey(KeyName).IsValid();
}
FString FGameplayDebuggerInputHandler::ToString() const
{
FString KeyDesc = KeyName.ToString();
if (Modifier.bShift)
{
KeyDesc = FString(TEXT("Shift+")) + KeyDesc;
}
if (Modifier.bAlt)
{
KeyDesc = FString(TEXT("Alt+")) + KeyDesc;
}
if (Modifier.bCtrl)
{
KeyDesc = FString(TEXT("Ctrl+")) + KeyDesc;
}
if (Modifier.bCmd)
{
KeyDesc = FString(TEXT("Cmd+")) + KeyDesc;
}
return KeyDesc;
}
//////////////////////////////////////////////////////////////////////////
// FGameplayDebuggerInputHandlerConfig
FName FGameplayDebuggerInputHandlerConfig::CurrentCategoryName;
FName FGameplayDebuggerInputHandlerConfig::CurrentExtensionName;
FGameplayDebuggerInputHandlerConfig::FGameplayDebuggerInputHandlerConfig(const FName ConfigName, const FName DefaultKeyName)
{
KeyName = DefaultKeyName;
UpdateConfig(ConfigName);
}
FGameplayDebuggerInputHandlerConfig::FGameplayDebuggerInputHandlerConfig(const FName ConfigName, const FName DefaultKeyName, const FGameplayDebuggerInputModifier& DefaultModifier)
{
KeyName = DefaultKeyName;
Modifier = DefaultModifier;
UpdateConfig(ConfigName);
}
void FGameplayDebuggerInputHandlerConfig::UpdateConfig(const FName ConfigName)
{
if (FGameplayDebuggerInputHandlerConfig::CurrentCategoryName != NAME_None)
{
UGameplayDebuggerConfig* MutableToolConfig = UGameplayDebuggerConfig::StaticClass()->GetDefaultObject<UGameplayDebuggerConfig>();
MutableToolConfig->UpdateCategoryInputConfig(FGameplayDebuggerInputHandlerConfig::CurrentCategoryName, ConfigName, KeyName, Modifier);
}
else if (FGameplayDebuggerInputHandlerConfig::CurrentExtensionName != NAME_None)
{
UGameplayDebuggerConfig* MutableToolConfig = UGameplayDebuggerConfig::StaticClass()->GetDefaultObject<UGameplayDebuggerConfig>();
MutableToolConfig->UpdateExtensionInputConfig(FGameplayDebuggerInputHandlerConfig::CurrentExtensionName, ConfigName, KeyName, Modifier);
}
}
| 28.014212 | 188 | 0.733662 | windystrife |
d6dbe2b458bb202daf066b4258ca621ef81265e3 | 5,335 | cpp | C++ | Source/DialogSystemEditor/Private/DialogSystemEditor.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | Source/DialogSystemEditor/Private/DialogSystemEditor.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | Source/DialogSystemEditor/Private/DialogSystemEditor.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | #include "DialogSystemEditor.h"
#include "Developer/AssetTools/Public/AssetTypeCategories.h"
#include "Editor/PropertyEditor/Public/PropertyEditorModule.h"
#include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructure.h"
#include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructureModule.h"
#include "ISettingsModule.h"
#include "ThumbnailRendering/ThumbnailManager.h"
#include "QaDSEditor/BrushSet.h"
#include "Dialog/DialogAssetEditor.h"
#include "Quest/QuestAssetEditor.h"
#include "AssetToolsModule.h"
#include "Dialog/DialogAssetTypeActions.h"
#include "Quest/QuestAssetTypeActions.h"
#include "TypeEditorCustomization/PhraseNodeCustomization.h"
#include "TypeEditorCustomization/DialogPhraseEventCustomization.h"
#include "TypeEditorCustomization/QuestStageCustomization.h"
#include "TypeEditorCustomization/QuestStageEventCustomization.h"
#include "QaDSSettings.h"
#include "Quest/QuestEditorNodeFactory.h"
#include "EdGraphUtilities.h"
#include "StoryKey/StoryKeyWindow.h"
DEFINE_LOG_CATEGORY(DialogModuleLog)
#define LOCTEXT_NAMESPACE "FDialogSystemModule"
void FDialogSystemEditorModule::StartupModule()
{
FBrushSet::Register();
FDialogCommands::Register();
FQuestCommands::Register();
auto& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetCategory = AssetTools.RegisterAdvancedAssetCategory(FName(TEXT("Gameplay")), LOCTEXT("GameplayAssetCategory", "Gameplay"));
AssetTools.RegisterAssetTypeActions(MakeShareable(new FDialogAssetTypeActions(AssetCategory)));
AssetTools.RegisterAssetTypeActions(MakeShareable(new FQuestAssetTypeActions(AssetCategory)));
auto& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.RegisterCustomClassLayout("DialogPhraseEdGraphNode", FOnGetDetailCustomizationInstance::CreateStatic(&FPhraseNodeDetails::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("DialogPhraseEvent", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogPhraseEventCustomization::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("DialogPhraseCondition", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FDialogPhraseEventCustomization::MakeInstance));
PropertyModule.RegisterCustomClassLayout("QuestStageEdGraphNode", FOnGetDetailCustomizationInstance::CreateStatic(&FQuestStageDetails::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("QuestStageEvent", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FQuestStageEventCustomization::MakeInstance));
PropertyModule.RegisterCustomPropertyTypeLayout("QuestStageCondition", FOnGetPropertyTypeCustomizationInstance::CreateStatic(&FQuestStageEventCustomization::MakeInstance));
auto& SettingsModule = FModuleManager::LoadModuleChecked<ISettingsModule>("Settings");
SettingsModule.RegisterSettings("Project", "Plugins", "Dialog",
LOCTEXT("RuntimeSettingsName", "Dialog Editor"),
LOCTEXT("RuntimeSettingsDescription", "Dialog editor settings"),
UQaDSSettings::StaticClass()->GetDefaultObject()
);
FEdGraphUtilities::RegisterVisualNodeFactory(MakeShareable(new FQuestEditorNodeFactory));
FEdGraphUtilities::RegisterVisualNodeFactory(MakeShareable(new FDialogEditorNodeFactory));
auto& MenuStructure = WorkspaceMenu::GetMenuStructure();
auto developerCategory = MenuStructure.GetDeveloperToolsMiscCategory();
auto& SpawnerEntry = FGlobalTabmanager::Get()->RegisterNomadTabSpawner("StoryKeyWindow", FOnSpawnTab::CreateRaw(this, &FDialogSystemEditorModule::SpawnStoryKeyTab))
.SetDisplayName(LOCTEXT("StoryKey", "Story Key"))
.SetIcon(FSlateIcon("DialogSystem", "DialogSystem.StoryKeyIcon_16"));
SpawnerEntry.SetGroup(developerCategory);
}
void FDialogSystemEditorModule::ShutdownModule()
{
FDialogCommands::Unregister();
FBrushSet::Unregister();
if (FModuleManager::Get().IsModuleLoaded("Settings"))
{
auto& SettingsModule = FModuleManager::LoadModuleChecked<ISettingsModule>("Settings");
SettingsModule.UnregisterSettings("Project", "Plugins", "Dialog");
}
if (FModuleManager::Get().IsModuleLoaded("PropertyEditor"))
{
auto& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.UnregisterCustomClassLayout("DialogPhraseNode");
PropertyModule.UnregisterCustomPropertyTypeLayout("DialogPhraseEvent");
PropertyModule.UnregisterCustomPropertyTypeLayout("DialogPhraseCondition");
PropertyModule.UnregisterCustomClassLayout("QuestStageEdGraphNode");
PropertyModule.UnregisterCustomPropertyTypeLayout("QuestStageEvent");
PropertyModule.UnregisterCustomPropertyTypeLayout("QuestStageCondition");
}
if (FModuleManager::Get().IsModuleLoaded("AssetTools"))
{
auto& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetTools.UnregisterAssetTypeActions(MakeShareable(new FDialogAssetTypeActions(AssetCategory)));
AssetTools.UnregisterAssetTypeActions(MakeShareable(new FQuestAssetTypeActions(AssetCategory)));
}
}
TSharedRef<SDockTab> FDialogSystemEditorModule::SpawnStoryKeyTab(const FSpawnTabArgs&)
{
TSharedRef<SDockTab> tab = SNew(SDockTab)
.TabRole(ETabRole::NomadTab);
tab->SetContent(SNew(SStoryKeyWindow));
return tab;
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDialogSystemEditorModule, DialogSystemEditor) | 48.063063 | 177 | 0.837863 | n3td0g |
d6e120a0bfa0ea8773815e18dc1282910dbd1a6c | 1,061 | cpp | C++ | i2c/BMP180/src/main.cpp | mc-b/IoTKitV3 | 87d7a66a1730f71bc69110a214b1b2a18f22edcb | [
"Apache-2.0"
] | 2 | 2019-01-24T19:53:40.000Z | 2020-01-08T07:41:35.000Z | i2c/BMP180/src/main.cpp | mc-b/IoTKitV3 | 87d7a66a1730f71bc69110a214b1b2a18f22edcb | [
"Apache-2.0"
] | null | null | null | i2c/BMP180/src/main.cpp | mc-b/IoTKitV3 | 87d7a66a1730f71bc69110a214b1b2a18f22edcb | [
"Apache-2.0"
] | 5 | 2019-01-12T04:48:11.000Z | 2020-12-16T09:36:43.000Z | /**
* Bosch BMP180 Digital Pressure Sensor
*
* Der Sensor liefert keinen Wert fuer Luftfeuchtigkeit, deshalb wird der Luftdruck in kPa geliefert.
*/
#include "mbed.h"
#include <BMP180Wrapper.h>
#include "OLEDDisplay.h"
// UI
OLEDDisplay oled( MBED_CONF_IOTKIT_OLED_RST, MBED_CONF_IOTKIT_OLED_SDA, MBED_CONF_IOTKIT_OLED_SCL );
static DevI2C devI2c( MBED_CONF_IOTKIT_I2C_SDA, MBED_CONF_IOTKIT_I2C_SCL );
static BMP180Wrapper hum_temp(&devI2c);
int main()
{
uint8_t id;
float value1, value2;
oled.clear();
oled.printf( "Temp/Pressure Sensor\n" );
/* Init all sensors with default params */
hum_temp.init(NULL);
hum_temp.enable();
hum_temp.read_id(&id);
printf("humidity & air pressure = 0x%X\r\n", id);
while (true)
{
hum_temp.get_temperature(&value1);
hum_temp.get_humidity(&value2);
printf("BMP180: [temp] %.2f C, [kPa] %.2f%%\r\n", value1, value2);
oled.cursor( 1, 0 );
oled.printf( "temp: %3.2f\nkPa : %3.2f", value1, value2 );
wait( 1.0f );
}
}
| 25.261905 | 101 | 0.655985 | mc-b |
d6e1d1b1639cad42a803f7393044fb8a46502eb5 | 20 | cpp | C++ | tutorials/cplusplus.com#1.0#1/basicsofcpp/basicinputoutput/cin/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | tutorials/cplusplus.com#1.0#1/basicsofcpp/basicinputoutput/cin/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | tutorials/cplusplus.com#1.0#1/basicsofcpp/basicinputoutput/cin/source1.cpp | officialrafsan/CppDroid | 5fb2cc7750fea53b1ea6ff47b5094da6e95e9224 | [
"MIT"
] | null | null | null | int age;
cin >> age; | 10 | 11 | 0.6 | officialrafsan |
d6e39e70fae327912f6873c30dbdedebf5e06f51 | 21,363 | cpp | C++ | src/prod/src/Common/NamingUri.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 1 | 2018-03-15T02:09:21.000Z | 2018-03-15T02:09:21.000Z | src/prod/src/Common/NamingUri.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | src/prod/src/Common/NamingUri.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
namespace Common
{
GlobalWString NamingUri::NameUriScheme = make_global<std::wstring>(L"fabric");
GlobalWString NamingUri::RootAuthority = make_global<std::wstring>(L"");
GlobalWString NamingUri::RootNamingUriString = make_global<std::wstring>(L"fabric:");
GlobalWString NamingUri::InvalidRootNamingUriString = make_global<std::wstring>(L"fabric://");
GlobalWString NamingUri::NamingUriConcatenationReservedTokenDelimiter = make_global<std::wstring>(L"+");
// All reserved token delimiters should be listed here.
GlobalWString NamingUri::ReservedTokenDelimiters = make_global<std::wstring>(L"$+|~");
Global<NamingUri> NamingUri::RootNamingUri = make_global<NamingUri>(L"");
GlobalWString NamingUri::SegmentDelimiter = make_global<std::wstring>(L"/");
GlobalWString NamingUri::HierarchicalNameDelimiter = make_global<std::wstring>(L"~");
NamingUri::NamingUri(
std::wstring const & scheme,
std::wstring const & authority,
std::wstring const & path,
std::wstring const & query,
std::wstring const & fragment)
: Uri(scheme, authority, path, query, fragment)
{
ASSERT_IFNOT(IsNamingUri(*this), "Invalid naming uri");
}
NamingUri NamingUri::GetAuthorityName() const
{
return Segments.empty() ? NamingUri() : NamingUri(Segments[0]);
}
NamingUri NamingUri::GetParentName() const
{
if (Path.empty())
{
return NamingUri::RootNamingUri;
}
size_t index = Path.find_last_of(L"/");
ASSERT_IF(index == wstring::npos, "No / in path?");
wstring truncPath = Path.substr(0, index);
return NamingUri(truncPath);
}
NamingUri NamingUri::GetTrimQueryAndFragmentName() const
{
if (this->Query.empty() && this->Fragment.empty())
{
return *this;
}
else
{
return NamingUri(this->Path);
}
}
size_t NamingUri::GetHash() const
{
return StringUtility::GetHash(this->ToString());
}
size_t NamingUri::GetTrimQueryAndFragmentHash() const
{
return StringUtility::GetHash(this->GetTrimQueryAndFragment().ToString());
}
bool NamingUri::IsPrefixOf(NamingUri const & other) const
{
return Uri::IsPrefixOf(other);
}
bool NamingUri::TryParse(std::wstring const & input, __out NamingUri & output)
{
if (StringUtility::StartsWith<std::wstring>(input, InvalidRootNamingUriString))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: authorities are not supported.",
input);
return false;
}
NamingUri uri;
if (Uri::TryParse(input, uri) && IsNamingUri(uri))
{
output = std::move(uri);
return true;
}
return false;
}
bool NamingUri::TryParse(FABRIC_URI name, __out NamingUri & output)
{
if (name == NULL)
{
Trace.WriteWarning(Uri::TraceCategory, "Invalid NULL parameter: FABRIC_URI.");
return false;
}
std::wstring tempName(name);
return NamingUri::TryParse(tempName, /*out*/output);
}
HRESULT NamingUri::TryParse(
FABRIC_URI name,
std::wstring const & traceId,
__out NamingUri & nameUri)
{
// Validate and parse the input name pointer
if (name == NULL)
{
Trace.WriteWarning(Uri::TraceCategory, traceId, "Invalid NULL parameter: name.");
return E_POINTER;
}
auto error = ParameterValidator::IsValid(
name,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
Trace.WriteWarning(
Uri::TraceCategory,
traceId,
"Input uri doesn't respect parameter size limits ({0}-{1}).",
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
return error.ToHResult();
}
std::wstring tempName(name);
if (!NamingUri::TryParse(tempName, /*out*/nameUri))
{
Trace.WriteWarning(Uri::TraceCategory, traceId, "{0}: Input uri is not a valid naming uri.", tempName);
return FABRIC_E_INVALID_NAME_URI;
}
return S_OK;
}
ErrorCode NamingUri::TryParse(
FABRIC_URI name,
StringLiteral const & parameterName,
__inout NamingUri & nameUri)
{
// Validate and parse the input name pointer
if (name == NULL)
{
ErrorCode innerError(ErrorCodeValue::ArgumentNull, wformatString("{0} {1}.", GET_COMMON_RC(Invalid_Null_Pointer), parameterName));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
auto error = ParameterValidator::IsValid(
name,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
ErrorCode innerError(
ErrorCodeValue::InvalidArgument,
wformatString("{0} {1}, {2}, {3}.", GET_COMMON_RC(Invalid_LPCWSTR_Length), parameterName, ParameterValidator::MinStringSize, CommonConfig::GetConfig().MaxNamingUriLength));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
std::wstring tempName(name);
if (!NamingUri::TryParse(tempName, /*out*/nameUri))
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString("{0} {1}.", GET_NAMING_RC(Invalid_Uri), tempName));
Trace.WriteWarning(Uri::TraceCategory, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
return ErrorCode::Success();
}
ErrorCode NamingUri::TryParse(
std::wstring const & nameText,
std::wstring const & traceId,
__out NamingUri & nameUri)
{
auto error = ParameterValidator::IsValid(
nameText.c_str(),
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength);
if (!error.IsSuccess())
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString(
"{0} {1} {2}, {3}.",
GET_COMMON_RC(Invalid_LPCWSTR_Length),
nameText,
ParameterValidator::MinStringSize,
CommonConfig::GetConfig().MaxNamingUriLength));
Trace.WriteInfo(Uri::TraceCategory, traceId, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
if (!TryParse(nameText, nameUri))
{
ErrorCode innerError(ErrorCodeValue::InvalidNameUri, wformatString("{0} {1}.", GET_NAMING_RC(Invalid_Uri), nameText));
Trace.WriteWarning(Uri::TraceCategory, traceId, "NamingUri::TryParse: {0}: {1}", innerError, innerError.Message);
return innerError;
}
return ErrorCode::Success();
}
bool NamingUri::IsNamingUri(Uri const & question)
{
if (question.Scheme != NameUriScheme)
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' has invalid scheme: supported scheme is 'fabric:'.",
question);
return false;
}
if ((question.Type != UriType::Absolute) && (question.Type != UriType::Empty))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: 'fabric:' scheme requires absolute path.",
question);
return false;
}
// Disallow empty segments
if (StringUtility::Contains<wstring>(question.Path, L"//"))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: empty segments in path are not supported.",
question);
return false;
}
// List of reserved characters
for (auto delimiterIt = ReservedTokenDelimiters->begin(); delimiterIt != ReservedTokenDelimiters->end(); ++delimiterIt)
{
wstring delimiter = wformatString("{0}", *delimiterIt);
if (StringUtility::Contains<wstring>(question.Path, delimiter))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: '{1}' is a reserved character.",
question,
delimiter);
return false;
}
}
// Disallow trailing slash
if ((question.Path.size() > 0) && (question.Path[question.Path.size() - 1] == L'/'))
{
Trace.WriteWarning(
Uri::TraceCategory,
"NamingUri '{0}' is invalid: trailing '/' is not supported.",
question);
return false;
}
return true;
}
bool NamingUri::TryCombine(std::wstring const & path, __out NamingUri & result) const
{
wstring temp(this->ToString());
if (!path.empty())
{
temp.append(L"/");
temp.append(path);
}
NamingUri uri;
if (TryParse(temp, uri))
{
result = move(uri);
return true;
}
return false;
}
NamingUri NamingUri::Combine(NamingUri const & name, wstring const & path)
{
NamingUri result;
if (!name.TryCombine(path, result))
{
Assert::CodingError("could not combine {0} and {1} into a Naming Uri", name, path);
}
return result;
}
ErrorCode NamingUri::FabricNameToId(std::wstring const & name, __inout std::wstring &escapedId)
{
std::wstring temp = name;
StringUtility::TrimLeading<std::wstring>(temp, NamingUri::RootNamingUriString);
StringUtility::TrimLeading<std::wstring>(temp, NamingUri::SegmentDelimiter);
return EscapeString(temp, escapedId);
}
ErrorCode NamingUri::FabricNameToId(std::wstring const & name, bool useDelimiter, __inout std::wstring &escapedId)
{
std::wstring temp = name;
std::wstring tempId;
NamingUri::FabricNameToId(temp, tempId);
if (useDelimiter)
{
StringUtility::Replace<std::wstring>(tempId, NamingUri::SegmentDelimiter, NamingUri::HierarchicalNameDelimiter);
}
return EscapeString(tempId, escapedId);
}
ErrorCode NamingUri::IdToFabricName(std::wstring const& scheme, std::wstring const& id, __inout std::wstring &name)
{
ASSERT_IF(scheme.empty(), "IdToFabricName - scheme cannot be empty");
std::wstring escapedId;
auto error = UnescapeString(id, escapedId);
if (!error.IsSuccess())
{
return error;
}
StringUtility::Replace<std::wstring>(escapedId, NamingUri::HierarchicalNameDelimiter, NamingUri::SegmentDelimiter);
name = wformatString("{0}{1}{2}", scheme, *NamingUri::SegmentDelimiter, escapedId);
return ErrorCode::Success();
}
void NamingUri::ParseHost(std::wstring & input, std::wstring & host, std::wstring & remain)
{
input = input.substr(1, std::string::npos);
std::size_t nextFound = remain.find(L"/");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"?");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"#");
if (nextFound == std::string::npos)
{
nextFound = input.length();
}
}
}
host = L"/";
host = host + input.substr(0, nextFound);
remain = input.substr(nextFound, std::string::npos);
}
void NamingUri::ParsePath(std::wstring & input, std::wstring & path, std::wstring & remain)
{
std::size_t nextFound = remain.find(L"?");
if (nextFound == std::string::npos)
{
nextFound = remain.find(L"#");
if (nextFound == std::string::npos)
{
nextFound = input.length();
}
}
path = input.substr(0, nextFound);
remain = input.substr(nextFound, std::string::npos);
}
ErrorCode NamingUri::ParseUnsafeUri(std::wstring const & input, std::wstring & protocol, std::wstring & host, std::wstring & path, std::wstring & queryFragment)
{
std::size_t protocolFound = input.find(L":/");
std::wstring remain;
if (protocolFound != std::string::npos)
{
protocol = input.substr(0, protocolFound + 2);
remain = input.substr(protocolFound + 2, std::string::npos);
}
else
{
remain = input;
}
// Has host
if (remain.length() > 0 && *(remain.begin()) == '/')
{
ParseHost(remain, host, remain);
}
ParsePath(remain, path, remain);
queryFragment = remain;
return ErrorCodeValue::Success;
}
ErrorCode NamingUri::EscapeString(std::wstring const & input, __inout std::wstring &output)
{
#if defined(PLATFORM_UNIX)
std::wstring protocol;
std::wstring host;
std::wstring path;
std::wstring queryFragment;
ErrorCode result = ParseUnsafeUri(input, protocol, host, path, queryFragment);
std::string pathString;
StringUtility::Utf16ToUtf8(path, pathString);
static const char lookup[] = "0123456789ABCDEF";
std::ostringstream out;
for (std::string::size_type i = 0; i < pathString.length(); i++) {
const char& c = pathString.at(i);
if (c == '[' ||
c == ']' ||
c == '&' ||
c == '^' ||
c == '`' ||
c == '{' ||
c == '}' ||
c == '|' ||
c == '"' ||
c == '<' ||
c == '>' ||
c == '\\' ||
c == ' ')
{
out << '%';
out << lookup[(c & 0xF0) >> 4];
out << lookup[(c & 0x0F)];
}
else
{
out << c;
}
}
std::wstring pathEscape;
StringUtility::Utf8ToUtf16(out.str(), pathEscape);
output = protocol + host + pathEscape + queryFragment;
#else
DWORD size = 1;
std::vector<WCHAR> buffer;
buffer.resize(size);
HRESULT hr = UrlEscape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_ESCAPE_AS_UTF8);
if (FAILED(hr) && hr == E_POINTER)
{
buffer.resize(size);
hr = UrlEscape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_ESCAPE_AS_UTF8);
if (FAILED(hr))
{
return ErrorCode::FromHResult(hr);
}
output = buffer.data();
}
else
{
return ErrorCode::FromHResult(hr);
}
#endif
return ErrorCodeValue::Success;
}
ErrorCode NamingUri::UnescapeString(std::wstring const& input, __inout std::wstring& output)
{
#if defined(PLATFORM_UNIX)
std::wstring protocol;
std::wstring host;
std::wstring path;
std::wstring queryFragment;
ErrorCode result = ParseUnsafeUri(input, protocol, host, path, queryFragment);
std::ostringstream out;
std::string pathString;
StringUtility::Utf16ToUtf8(path, pathString);
for (std::string::size_type i = 0; i < pathString.length(); i++) {
if (pathString.at(i) == '%') {
std::string temp(pathString.substr(i + 1, 2));
std::istringstream in(temp);
short c = 0;
in >> std::hex >> c;
out << static_cast<unsigned char>(c);
i += 2;
}
else {
out << pathString.at(i);
}
}
std::wstring pathUnescape;
StringUtility::Utf8ToUtf16(out.str(), pathUnescape);
output = protocol + host + pathUnescape + queryFragment;
#else
DWORD size = 1;
std::vector<WCHAR> buffer;
buffer.resize(size);
HRESULT hr = UrlUnescape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_UNESCAPE_AS_UTF8);
if (FAILED(hr) && hr == E_POINTER)
{
buffer.resize(size);
hr = UrlUnescape(const_cast<WCHAR*>(input.data()), buffer.data(), &size, URL_UNESCAPE_AS_UTF8);
if (FAILED(hr))
{
return ErrorCodeValue::InvalidNameUri;
}
output = buffer.data();
}
else
{
return ErrorCodeValue::InvalidNameUri;
}
#endif
return ErrorCode::Success();
}
ErrorCode NamingUri::UrlEscapeString(std::wstring const & input, std::wstring & output)
{
// Clear the output because we are appending to it.
output.clear();
wstring basicEncodedStr;
// First call escape string
auto error = NamingUri::EscapeString(input, basicEncodedStr);
// If escape returns an error, then return that error
if (!error.IsSuccess())
{
return error;
}
// Replace chars with their encodings by appending
// either the original char or its replacement to the output string
// comma(",")
// colon(":")
// dollar("$")
// plus sign("+")
// semi - colon(";")
// equals("=")
// 'At' symbol("@")
//
// ampersand ("&")
// forward slash("/")
// question mark("?")
// pound("#")
// less than and greater than("<>")
// open and close brackets("[]")
// open and close braces("{}")
// pipe("|")
// backslash("\")
// caret("^")
// space(" ")
// percent ("%") is not encoded here because it cannot be encoded twice.
for (wchar_t c : basicEncodedStr)
{
if (c == L',') // ,
{
output += L"%2C";
}
else if (c == L':') // :
{
output += L"%3A";
}
else if (c == L'$') // $
{
output += L"%24";
}
else if (c == L'+') // +
{
output += L"%2B";
}
else if (c == L';') // ;
{
output += L"%3B";
}
else if (c == L'=') // =
{
output += L"%3D";
}
else if (c == L'@') // @
{
output += L"%40";
} // The following may never be called since EscapeString may have already taken care of them (OS dependent)
else if (c == L'&') // &
{
output += L"%26";
}
else if (c == L'/') // / (forward slash)
{
output += L"%2F";
}
else if (c == L'\\') // back slash
{
output += L"%5C";
}
else if (c == L'?') // ?
{
output += L"%3F";
}
else if (c == L'#') // #
{
output += L"%23";
}
else if (c == L'<') // <
{
output += L"%3C";
}
else if (c == L'>') // >
{
output += L"%3E";
}
else if (c == L'[') // [
{
output += L"%5B";
}
else if (c == L']') // ]
{
output += L"%5D";
}
else if (c == L'{') // {
{
output += L"%7B";
}
else if (c == L'}') // }
{
output += L"%7D";
}
else if (c == L'|') // |
{
output += L"%7C";
}
else if (c == L'^') // ^
{
output += L"%5E";
}
else if (c == L' ') // space
{
output += L"%20";
}
else
{
output += c;
}
}
return ErrorCode::Success();
}
}
| 32.368182 | 188 | 0.509011 | AnthonyM |
d6e4c6fbaf3b25abe73d2ba982b61b08b5df586c | 9,425 | cpp | C++ | PanelSwCustomActions/RegistryKey.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | PanelSwCustomActions/RegistryKey.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | PanelSwCustomActions/RegistryKey.cpp | jozefizso/PanelSwWixExtension | 08f1c9a803d94911d06f5d24d8dc43423b13aaa6 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "RegistryKey.h"
#include <strutil.h>
#include "..\CaCommon\SummaryStream.h"
#pragma comment( lib, "CaCommon.lib")
CRegistryKey::CRegistryKey(void)
: _hKey( NULL)
, _hRootKey( NULL)
, _area( RegArea::Default)
, _samAccess( RegAccess::All)
{
Close();
}
CRegistryKey::~CRegistryKey(void)
{
Close();
}
HRESULT CRegistryKey::Close()
{
HRESULT hr = S_OK;
_hRootKey = NULL;
::memset( _keyName, 0, sizeof( WCHAR) * MAX_PATH);
return hr;
}
HRESULT CRegistryKey::Create( RegRoot root, WCHAR* key, RegArea area, RegAccess access)
{
HRESULT hr = S_OK;
HKEY hKey = NULL, hParentKey = NULL;
LONG lRes;
hr = Close();
BreakExitOnFailure( hr, "Failed to close registry key");
BreakExitOnNull( key, hr, E_FILENOTFOUND, "key is NULL");
BreakExitOnNull( *key, hr, E_FILENOTFOUND, "key points to NULL");
WcaLog( LOGLEVEL::LOGMSG_STANDARD, "Attempting to create registry key %ls", key);
hParentKey = Root2Handle( root);
BreakExitOnNull( hParentKey, hr, E_FILENOTFOUND, "key is NULL");
_samAccess = access;
_area = area;
if( _area == RegArea::Default)
{
hr = GetDefaultArea( &_area);
BreakExitOnFailure( hr, "Failed to get default registry area");
}
lRes = ::RegCreateKeyExW( hParentKey, key, 0, NULL, 0, _samAccess | _area, NULL, &hKey, NULL);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to create registry key");
_hKey = hKey;
_hRootKey = hParentKey;
wcscpy_s<MAX_PATH>( _keyName, key);
LExit:
return hr;
}
HRESULT CRegistryKey::Open( RegRoot root, WCHAR* key, RegArea area, RegAccess access)
{
HRESULT hr = S_OK;
HKEY hKey = NULL, hParentKey = NULL;
LONG lRes;
BreakExitOnNull( key, hr, E_INVALIDARG, "key is NULL");
hr = Close();
BreakExitOnFailure( hr, "Failed to close registry key");
hParentKey = Root2Handle( root);
BreakExitOnNull( hParentKey, hr, E_INVALIDARG, "Parent key is NULL");
WcaLog( LOGLEVEL::LOGMSG_STANDARD, "Attempting to open registry key %ls", key);
_samAccess = access;
_area = area;
if( _area == RegArea::Default)
{
hr = GetDefaultArea( &_area);
BreakExitOnFailure( hr, "Failed to get default registry area");
}
lRes = ::RegOpenKeyExW( hParentKey, key, 0, _samAccess | _area, &hKey);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to open registry key");
_hKey = hKey;
_hRootKey = hParentKey;
wcscpy_s<MAX_PATH>( _keyName, key);
LExit:
return hr;
}
HRESULT CRegistryKey::Delete()
{
HRESULT hr = S_OK;
LONG lRes = ERROR_SUCCESS;
WCHAR keyName[ MAX_PATH];
BreakExitOnNull( _hKey, hr, E_FILENOTFOUND, "_hKey is NULL");
// Copy info
HKEY rootKey = _hRootKey;
wcscpy_s<MAX_PATH>( keyName, _keyName);
// Close held handle.
Close();
// Delete key
lRes = ::RegDeleteKeyExW( rootKey, keyName, _area, 0);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to delete registry key");
LExit:
return hr;
}
HRESULT CRegistryKey::GetValue( WCHAR* name, BYTE** pData, RegValueType* pType, DWORD* pDataSize)
{
LONG lRes = ERROR_SUCCESS;
HRESULT hr = S_OK;
BreakExitOnNull( pData, hr, E_INVALIDARG, "pData is NULL");
BreakExitOnNull( pType, hr, E_INVALIDARG, "pType is NULL");
BreakExitOnNull( pDataSize, hr, E_INVALIDARG, "pDataSize is NULL");
(*pDataSize) = 0;
lRes = ::RegQueryValueEx( _hKey, name, 0, (LPDWORD)pType, NULL, pDataSize);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to query registry value");
BreakExitOnNull( (*pDataSize), hr, E_FILENOTFOUND, "Registry value's size is 0.");
(*pData) = new BYTE[ (*pDataSize) + 1];
BreakExitOnNull( (*pData), hr, E_NOT_SUFFICIENT_BUFFER, "Can't allocate buffer");
lRes = ::RegQueryValueEx( _hKey, name, 0, (LPDWORD)pType, (*pData), pDataSize);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to get registry value");
(*pData)[ (*pDataSize)] = NULL; // Just to make sure.
LExit:
return hr;
}
HRESULT CRegistryKey::SetValue( WCHAR* name, RegValueType type, BYTE* value, DWORD valueSize)
{
HRESULT hr = S_OK;
LONG lRes = ERROR_SUCCESS;
BreakExitOnNull( _hKey, hr, E_FILENOTFOUND, "_hKey is NULL");
lRes = ::RegSetValueEx( _hKey, name, 0, type, value, valueSize);
hr = HRESULT_FROM_WIN32( lRes);
BreakExitOnFailure( hr, "Failed to set registry value");
LExit:
return hr;
}
HRESULT CRegistryKey::SetValueString( WCHAR* name, WCHAR* value)
{
HRESULT hr = S_OK;
BreakExitOnNull( name, hr, E_FILENOTFOUND, "name is NULL");
BreakExitOnNull( value, hr, E_FILENOTFOUND, "value is NULL");
DWORD dwSize = ((wcslen( value) + 1) * sizeof( WCHAR));
hr = SetValue(
name
, RegValueType::String
, (BYTE*)value
, dwSize
);
LExit:
return hr;
}
HRESULT CRegistryKey::DeleteValue( WCHAR* name)
{
HRESULT hr = S_OK;
LONG lRes = ERROR_SUCCESS;
BreakExitOnNull( _hKey, hr, E_FILENOTFOUND, "_hKey is NULL");
RegDeleteValue( _hKey, name);
LExit:
return hr;
}
HKEY CRegistryKey::Root2Handle( RegRoot root)
{
switch( root)
{
case RegRoot::ClassesRoot:
return HKEY_CLASSES_ROOT;
case RegRoot::LocalMachine:
return HKEY_LOCAL_MACHINE;
case RegRoot::CurrentUser:
return HKEY_CURRENT_USER;
case RegRoot::CurrentConfig:
return HKEY_CURRENT_CONFIG;
case RegRoot::PerformanceData:
return HKEY_PERFORMANCE_DATA;
case RegRoot::Users:
return HKEY_USERS;
}
return NULL;
}
HRESULT CRegistryKey::ParseRoot( LPCWSTR pRootString, RegRoot* peRoot)
{
HRESULT hr = S_OK;
BreakExitOnNull( peRoot, hr, E_INVALIDARG, "Invalid root pointer");
if(( pRootString == NULL) || ( wcslen( pRootString) == 0))
{
(*peRoot) = RegRoot::CurrentUser;
ExitFunction();
}
if(( _wcsicmp( pRootString, L"HKLM") == 0)
|| ( _wcsicmp( pRootString, L"HKEY_LOCAL_MACHINE") == 0))
{
(*peRoot) = RegRoot::LocalMachine;
}
else if(( _wcsicmp( pRootString, L"HKCR") == 0)
|| ( _wcsicmp( pRootString, L"HKEY_CLASSES_ROOT") == 0))
{
(*peRoot) = RegRoot::ClassesRoot;
}
else if(( _wcsicmp( pRootString, L"HKCC") == 0)
|| ( _wcsicmp( pRootString, L"HKEY_CURRENT_CONFIG") == 0))
{
(*peRoot) = RegRoot::CurrentConfig;
}
else if(( _wcsicmp( pRootString, L"HKCU") == 0)
|| ( _wcsicmp( pRootString, L"HKEY_CURRENT_USER") == 0))
{
(*peRoot) = RegRoot::CurrentUser;
}
else if(( _wcsicmp( pRootString, L"HKU") == 0)
|| ( _wcsicmp( pRootString, L"HKEY_USERS") == 0))
{
(*peRoot) = RegRoot::Users;
}
else
{
hr = E_INVALIDARG;
BreakExitOnFailure( hr, "Invalid root name");
}
LExit:
return hr;
}
HRESULT CRegistryKey::ParseArea( LPCWSTR pAreaString, RegArea* peArea)
{
HRESULT hr = S_OK;
BreakExitOnNull( peArea, hr, E_INVALIDARG, "Invalid area pointer");
if(( pAreaString == NULL) || ((*pAreaString) == NULL) || ( _wcsicmp( pAreaString, L"default") == 0))
{
hr = GetDefaultArea( peArea);
BreakExitOnFailure( hr, "Failed to get default registry area");
ExitFunction();
}
else if( _wcsicmp( pAreaString, L"x86") == 0)
{
(*peArea) = RegArea::X86;
}
else if( _wcsicmp( pAreaString, L"x64") == 0)
{
(*peArea) = RegArea::X64;
}
else
{
hr = E_INVALIDARG;
BreakExitOnFailure( hr, "Invalid area name");
}
LExit:
return hr;
}
HRESULT CRegistryKey::ParseValueType(LPCWSTR pTypeString, RegValueType* peType)
{
HRESULT hr = S_OK;
BreakExitOnNull(peType, hr, E_INVALIDARG, "Invalid type pointer");
if ((pTypeString == NULL) || (wcslen(pTypeString) == 0))
{
(*peType) = RegValueType::String;
ExitFunction();
}
if ((_wcsicmp(pTypeString, L"REG_SZ") == 0)
|| (_wcsicmp(pTypeString, L"String") == 0)
|| (_wcsicmp(pTypeString, L"1") == 0))
{
(*peType) = RegValueType::String;
}
else if ((_wcsicmp(pTypeString, L"REG_BINARY") == 0)
|| (_wcsicmp(pTypeString, L"Binary") == 0)
|| (_wcsicmp(pTypeString, L"3") == 0))
{
(*peType) = RegValueType::Binary;
}
else if ((_wcsicmp(pTypeString, L"REG_DWORD") == 0)
|| (_wcsicmp(pTypeString, L"DWord") == 0)
|| (_wcsicmp(pTypeString, L"4") == 0))
{
(*peType) = RegValueType::DWord;
}
else if ((_wcsicmp(pTypeString, L"REG_EXPAND_SZ") == 0)
|| (_wcsicmp(pTypeString, L"Expandable") == 0)
|| (_wcsicmp(pTypeString, L"2") == 0))
{
(*peType) = RegValueType::Expandable;
}
else if ((_wcsicmp(pTypeString, L"REG_MULTI_SZ") == 0)
|| (_wcsicmp(pTypeString, L"MultiString") == 0)
|| (_wcsicmp(pTypeString, L"7") == 0))
{
(*peType) = RegValueType::MultiString;
}
else if ((_wcsicmp(pTypeString, L"REG_QWORD") == 0)
|| (_wcsicmp(pTypeString, L"QWord") == 0)
|| (_wcsicmp(pTypeString, L"11") == 0))
{
(*peType) = RegValueType::QWord;
}
else
{
hr = E_INVALIDARG;
BreakExitOnFailure(hr, "Invalid area name");
}
LExit:
return hr;
}
HRESULT CRegistryKey::GetDefaultArea( CRegistryKey::RegArea* pArea)
{
HRESULT hr = S_OK;
DWORD dwRes = ERROR_SUCCESS;
bool bIsX64 = false;
::MessageBox( NULL, L"MsiBreak", L"MsiBreak", MB_OK);
BreakExitOnNull( pArea, hr, E_INVALIDARG, "pArea is NULL");
(*pArea) = RegArea::Default;
hr = CSummaryStream::GetInstance()->IsPackageX64( &bIsX64);
BreakExitOnFailure( hr, "Failed determining package bitness");
(*pArea) = bIsX64 ? RegArea::X64 : RegArea::X86;
LExit:
return hr;
}
| 24.737533 | 102 | 0.655491 | jozefizso |
d6e55864a45b653f2c47e24a7b36362958ed11dd | 53,607 | cpp | C++ | src/mame/drivers/gameplan.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/gameplan.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/gameplan.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Chris Moore
/***************************************************************************
GAME PLAN driver
driver by Chris Moore
Killer Comet memory map
MAIN CPU:
Address Dir Data Name Description
---------------- --- -------- --------- -----------------------
00000-xxxxxxxxxx R/W xxxxxxxx RAM can be either 256 bytes (2x2101) or 1kB (2x2114)
00001----------- n.c.
00010----------- n.c.
00011----------- n.c.
00100-------xxxx R/W xxxxxxxx VIA 1 6522 for video interface
00101-------xxxx R/W xxxxxxxx VIA 2 6522 for I/O interface
00110-------xxxx R/W xxxxxxxx VIA 3 6522 for interface with audio CPU
00111----------- n.c.
01-------------- n.c.
10-------------- n.c.
11000xxxxxxxxxxx R xxxxxxxx ROM E2 program ROM
11001xxxxxxxxxxx R xxxxxxxx ROM F2 program ROM
11010xxxxxxxxxxx R xxxxxxxx ROM G2 program ROM
11011xxxxxxxxxxx R xxxxxxxx ROM J2 program ROM
11100xxxxxxxxxxx R xxxxxxxx ROM J1 program ROM
11101xxxxxxxxxxx R xxxxxxxx ROM G1 program ROM
11110xxxxxxxxxxx R xxxxxxxx ROM F1 program ROM
11111xxxxxxxxxxx R xxxxxxxx ROM E1 program ROM
SOUND CPU:
Address Dir Data Name Description
---------------- --- -------- --------- -----------------------
000-0----xxxxxxx R/W xxxxxxxx VIA 5 6532 internal RAM
000-1------xxxxx R/W xxxxxxxx VIA 5 6532 for interface with main CPU
001------------- n.c.
010------------- n.c.
011------------- n.c.
100------------- n.c.
101-----------xx R/W xxxxxxxx PSG 1 AY-3-8910
110------------- n.c.
111--xxxxxxxxxxx R xxxxxxxx ROM E1
Notes:
- There are two dip switch banks connected to the 8910 ports. They are only
used for testing.
- Megatack's test mode reports the same fire buttons as Killer Comet, but this
is wrong: there is only one fire button, not three.
- Megatack's actual name which displays proudly on the cover and everywhere in
the manual as "MEGATTACK"
- Checked and verified DIPs from manuals and service mode for:
Challenger
Kaos
Killer Comet
Megattack
Pot Of Gold (Leprechaun)
TODO:
- The board has, instead of a watchdog, a timed reset that has to be disabled
on startup. The disable line is tied to CA2 of VIA2, but I don't see writes
to that pin in the log. Missing support in machine/6522via.cpp?
- Kaos needs a kludge to avoid a deadlock (see the via_irq() function below).
I don't know if this is a shortcoming of the driver or of 6522via.cpp.
- Investigate and document the 8910 dip switches
- Fix the input ports of Kaos
****************************************************************************/
#include "emu.h"
#include "includes/gameplan.h"
#include "cpu/m6502/m6502.h"
#include "sound/ay8910.h"
#include "speaker.h"
/*************************************
*
* VIA 2 - I/O
*
*************************************/
void gameplan_state::io_select_w(uint8_t data)
{
switch (data)
{
case 0x01: m_current_port = 0; break;
case 0x02: m_current_port = 1; break;
case 0x04: m_current_port = 2; break;
case 0x08: m_current_port = 3; break;
case 0x80: m_current_port = 4; break;
case 0x40: m_current_port = 5; break;
}
}
uint8_t gameplan_state::io_port_r()
{
static const char *const portnames[] = { "IN0", "IN1", "IN2", "IN3", "DSW0", "DSW1" };
return ioport(portnames[m_current_port])->read();
}
WRITE_LINE_MEMBER(gameplan_state::coin_w)
{
machine().bookkeeping().coin_counter_w(0, ~state & 1);
}
/*************************************
*
* VIA 3 - audio
*
*************************************/
WRITE_LINE_MEMBER(gameplan_state::audio_reset_w)
{
m_audiocpu->set_input_line(INPUT_LINE_RESET, state ? CLEAR_LINE : ASSERT_LINE);
if (state == 0)
{
m_riot->reset();
machine().scheduler().boost_interleave(attotime::zero, attotime::from_usec(10));
}
}
void gameplan_state::audio_cmd_w(uint8_t data)
{
m_riot->porta_in_set(data, 0x7f);
}
WRITE_LINE_MEMBER(gameplan_state::audio_trigger_w)
{
m_riot->porta_in_set(state << 7, 0x80);
}
/*************************************
*
* RIOT - audio
*
*************************************/
WRITE_LINE_MEMBER(gameplan_state::r6532_irq)
{
m_audiocpu->set_input_line(0, state);
if (state == ASSERT_LINE)
machine().scheduler().boost_interleave(attotime::zero, attotime::from_usec(10));
}
/*************************************
*
* Main CPU memory handlers
*
*************************************/
void gameplan_state::gameplan_main_map(address_map &map)
{
map(0x0000, 0x03ff).mirror(0x1c00).ram();
map(0x2000, 0x200f).mirror(0x07f0).m(m_via_0, FUNC(via6522_device::map)); /* VIA 1 */
map(0x2800, 0x280f).mirror(0x07f0).m(m_via_1, FUNC(via6522_device::map)); /* VIA 2 */
map(0x3000, 0x300f).mirror(0x07f0).m(m_via_2, FUNC(via6522_device::map)); /* VIA 3 */
map(0x8000, 0xffff).rom();
}
/*************************************
*
* Audio CPU memory handlers
*
*************************************/
void gameplan_state::gameplan_audio_map(address_map &map)
{
map(0x0000, 0x007f).mirror(0x1780).ram(); /* 6532 internal RAM */
map(0x0800, 0x081f).mirror(0x17e0).rw(m_riot, FUNC(riot6532_device::read), FUNC(riot6532_device::write));
map(0xa000, 0xa000).mirror(0x1ffc).w("aysnd", FUNC(ay8910_device::address_w));
map(0xa001, 0xa001).mirror(0x1ffc).r("aysnd", FUNC(ay8910_device::data_r));
map(0xa002, 0xa002).mirror(0x1ffc).w("aysnd", FUNC(ay8910_device::data_w));
map(0xe000, 0xe7ff).mirror(0x1800).rom();
}
/* same as Gameplan, but larger ROM */
void gameplan_state::leprechn_audio_map(address_map &map)
{
map(0x0000, 0x007f).mirror(0x1780).ram(); /* 6532 internal RAM */
map(0x0800, 0x081f).mirror(0x17e0).rw(m_riot, FUNC(riot6532_device::read), FUNC(riot6532_device::write));
map(0xa000, 0xa000).mirror(0x1ffc).w("aysnd", FUNC(ay8910_device::address_w));
map(0xa001, 0xa001).mirror(0x1ffc).r("aysnd", FUNC(ay8910_device::data_r));
map(0xa002, 0xa002).mirror(0x1ffc).w("aysnd", FUNC(ay8910_device::data_w));
map(0xe000, 0xefff).mirror(0x1000).rom();
}
/*************************************
*
* Input ports
*
*************************************/
static INPUT_PORTS_START( killcom )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_COIN3 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_COCKTAIL
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_COCKTAIL
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_COCKTAIL
PORT_START("DSW0") /* DSW A - from "TEST NO.6 - dip switch A" */
PORT_DIPNAME( 0x03, 0x03, "Coinage P1/P2" ) PORT_DIPLOCATION("SW1:1,2")
PORT_DIPSETTING( 0x03, "1 Credit/2 Credits" )
PORT_DIPSETTING( 0x02, "2 Credits/3 Credits" )
PORT_DIPSETTING( 0x01, "2 Credits/4 Credits" )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unused ) ) PORT_DIPLOCATION("SW1:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x00, "4" )
PORT_DIPSETTING( 0x08, "5" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW1:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW1:6" )
PORT_DIPNAME( 0xc0, 0xc0, "Reaction" ) PORT_DIPLOCATION("SW1:7,8")
PORT_DIPSETTING( 0xc0, "Slowest" )
PORT_DIPSETTING( 0x80, "Slow" )
PORT_DIPSETTING( 0x40, "Fast" )
PORT_DIPSETTING( 0x00, "Fastest" )
PORT_START("DSW1") /* DSW B - from "TEST NO.6 - dip switch B" */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW2:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW2:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW2:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW2:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW2:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW2:6" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW2:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:8")
PORT_DIPSETTING( 0x80, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW3:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW3:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW3:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW3:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW3:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW3:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW3:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW3:8" )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW4:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW4:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW4:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW4:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW4:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW4:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW4:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW4:8" )
INPUT_PORTS_END
static INPUT_PORTS_START( megatack )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_COIN3 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("DSW0") /* DSW A - from "TEST NO.6 - dip switch A" */
PORT_DIPNAME( 0x03, 0x03, "Coinage P1/P2" ) PORT_DIPLOCATION("SW1:1,2")
PORT_DIPSETTING( 0x03, "1 Credit/2 Credits" )
PORT_DIPSETTING( 0x02, "2 Credits/3 Credits" )
PORT_DIPSETTING( 0x01, "2 Credits/4 Credits" )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW1:3" )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:4")
PORT_DIPSETTING( 0x08, "3" )
PORT_DIPSETTING( 0x00, "4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW1:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW1:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW1:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW1:8" )
PORT_START("DSW1") /* DSW B - from "TEST NO.6 - dip switch B" */
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:1,2,3")
PORT_DIPSETTING( 0x07, "20000" )
PORT_DIPSETTING( 0x06, "30000" )
PORT_DIPSETTING( 0x05, "40000" )
PORT_DIPSETTING( 0x04, "50000" )
PORT_DIPSETTING( 0x03, "60000" )
PORT_DIPSETTING( 0x02, "70000" )
PORT_DIPSETTING( 0x01, "80000" )
PORT_DIPSETTING( 0x00, "90000" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW2:4" )
PORT_DIPNAME( 0x10, 0x10, "Monitor View" ) PORT_DIPLOCATION("SW2:5")
PORT_DIPSETTING( 0x10, "Direct" )
PORT_DIPSETTING( 0x00, "Mirror" )
PORT_DIPNAME( 0x20, 0x20, "Monitor Orientation" ) PORT_DIPLOCATION("SW2:6")
PORT_DIPSETTING( 0x20, "Horizontal" )
PORT_DIPSETTING( 0x00, "Vertical" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW2:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:8")
PORT_DIPSETTING( 0x80, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPNAME( 0x01, 0x00, "Sound Test A 0" ) PORT_DIPLOCATION("SW3:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, "Sound Test A 1" ) PORT_DIPLOCATION("SW3:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x00, "Sound Test A 2" ) PORT_DIPLOCATION("SW3:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x00, "Sound Test A 3" ) PORT_DIPLOCATION("SW3:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, "Sound Test A 4" ) PORT_DIPLOCATION("SW3:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x00, "Sound Test A 5" ) PORT_DIPLOCATION("SW3:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x00, "Sound Test A 6" ) PORT_DIPLOCATION("SW3:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, "Sound Test Enable" ) PORT_DIPLOCATION("SW3:8")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPNAME( 0x01, 0x00, "Sound Test B 0" ) PORT_DIPLOCATION("SW4:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, "Sound Test B 1" ) PORT_DIPLOCATION("SW4:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x00, "Sound Test B 2" ) PORT_DIPLOCATION("SW4:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x00, "Sound Test B 3" ) PORT_DIPLOCATION("SW4:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, "Sound Test B 4" ) PORT_DIPLOCATION("SW4:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x00, "Sound Test B 5" ) PORT_DIPLOCATION("SW4:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x00, "Sound Test B 6" ) PORT_DIPLOCATION("SW4:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x00, "Sound Test B 7" ) PORT_DIPLOCATION("SW4:8")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
static INPUT_PORTS_START( challeng )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_COCKTAIL
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("DSW0") /* DSW A - from "TEST NO.6 - dip switch A" */
PORT_DIPNAME( 0x03, 0x03, "Coinage P1/P2" ) PORT_DIPLOCATION("SW1:1,2")
PORT_DIPSETTING( 0x03, "1 Credit/2 Credits" )
PORT_DIPSETTING( 0x02, "2 Credits/3 Credits" )
PORT_DIPSETTING( 0x01, "2 Credits/4 Credits" )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW1:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW1:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW1:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW1:6" )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:7,8")
PORT_DIPSETTING( 0xc0, "3" )
PORT_DIPSETTING( 0x80, "4" )
PORT_DIPSETTING( 0x40, "5" )
PORT_DIPSETTING( 0x00, "6" )
// Manual states information which differs from actual settings for DSW1
// Switches 4 & 5 are factory settings and remain in the OFF position.
// Switches 6 & 7 are factory settings which remain in the ON position.
PORT_START("DSW1") /* DSW B - from "TEST NO.6 - dip switch B" */
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:1,2,3")
PORT_DIPSETTING( 0x01, "20000" )
PORT_DIPSETTING( 0x00, "30000" )
PORT_DIPSETTING( 0x07, "40000" )
PORT_DIPSETTING( 0x06, "50000" )
PORT_DIPSETTING( 0x05, "60000" )
PORT_DIPSETTING( 0x04, "70000" )
PORT_DIPSETTING( 0x03, "80000" )
PORT_DIPSETTING( 0x02, "90000" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW2:4" )
PORT_DIPNAME( 0x10, 0x10, "Monitor View" ) PORT_DIPLOCATION("SW2:5")
PORT_DIPSETTING( 0x10, "Direct" )
PORT_DIPSETTING( 0x00, "Mirror" )
PORT_DIPNAME( 0x20, 0x20, "Monitor Orientation" ) PORT_DIPLOCATION("SW2:6")
PORT_DIPSETTING( 0x20, "Horizontal" )
PORT_DIPSETTING( 0x00, "Vertical" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW2:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:8")
PORT_DIPSETTING( 0x80, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPNAME( 0x01, 0x00, "Sound Test A 0" ) PORT_DIPLOCATION("SW3:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, "Sound Test A 1" ) PORT_DIPLOCATION("SW3:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x00, "Sound Test A 2" ) PORT_DIPLOCATION("SW3:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x00, "Sound Test A 3" ) PORT_DIPLOCATION("SW3:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, "Sound Test A 4" ) PORT_DIPLOCATION("SW3:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x00, "Sound Test A 5" ) PORT_DIPLOCATION("SW3:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x00, "Sound Test A 6" ) PORT_DIPLOCATION("SW3:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, "Sound Test Enable" ) PORT_DIPLOCATION("SW3:8")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPNAME( 0x01, 0x00, "Sound Test B 0" ) PORT_DIPLOCATION("SW4:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x00, "Sound Test B 1" ) PORT_DIPLOCATION("SW4:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x04, 0x00, "Sound Test B 2" ) PORT_DIPLOCATION("SW4:3")
PORT_DIPSETTING( 0x04, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x08, 0x00, "Sound Test B 3" ) PORT_DIPLOCATION("SW4:4")
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, "Sound Test B 4" ) PORT_DIPLOCATION("SW4:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x20, 0x00, "Sound Test B 5" ) PORT_DIPLOCATION("SW4:6")
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x00, "Sound Test B 6" ) PORT_DIPLOCATION("SW4:7")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x00, "Sound Test B 7" ) PORT_DIPLOCATION("SW4:8")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
INPUT_PORTS_END
static INPUT_PORTS_START( kaos )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_COIN3 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_COCKTAIL
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("DSW0")
PORT_DIPNAME( 0x0f, 0x0e, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW1:1,2,3,4")
PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x0d, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x0b, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x09, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_7C ) )
PORT_DIPSETTING( 0x07, DEF_STR( 1C_8C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 1C_9C ) )
PORT_DIPSETTING( 0x05, "1 Coin/10 Credits" )
PORT_DIPSETTING( 0x04, "1 Coin/11 Credits" )
PORT_DIPSETTING( 0x03, "1 Coin/12 Credits" )
PORT_DIPSETTING( 0x02, "1 Coin/13 Credits" )
PORT_DIPSETTING( 0x01, "1 Coin/14 Credits" )
PORT_DIPSETTING( 0x0f, DEF_STR( 2C_3C ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x60, 0x60, "Max Credits" ) PORT_DIPLOCATION("SW1:6,7")
PORT_DIPSETTING( 0x60, "10" )
PORT_DIPSETTING( 0x40, "20" )
PORT_DIPSETTING( 0x20, "30" )
PORT_DIPSETTING( 0x00, "40" )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Free_Play ) ) PORT_DIPLOCATION("SW1:8")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START("DSW1")
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW2:1")
PORT_DIPSETTING( 0x01, "3" )
PORT_DIPSETTING( 0x00, "4" )
PORT_DIPNAME( 0x02, 0x00, "Speed" ) PORT_DIPLOCATION("SW2:2")
PORT_DIPSETTING( 0x00, "Slow" )
PORT_DIPSETTING( 0x02, "Fast" )
PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:3,4")
PORT_DIPSETTING( 0x0c, "No Bonus" )
PORT_DIPSETTING( 0x08, "10k" )
PORT_DIPSETTING( 0x04, "10k 30k" )
PORT_DIPSETTING( 0x00, "10k 30k 60k" )
PORT_DIPNAME( 0x10, 0x10, "Number of $" ) PORT_DIPLOCATION("SW2:5")
PORT_DIPSETTING( 0x10, "8" )
PORT_DIPSETTING( 0x00, "12" )
PORT_DIPNAME( 0x20, 0x00, "Bonus erg" ) PORT_DIPLOCATION("SW2:6")
PORT_DIPSETTING( 0x20, "Every other screen" )
PORT_DIPSETTING( 0x00, "Every screen" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW2:7" )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:8")
PORT_DIPSETTING( 0x80, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW3:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW3:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW3:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW3:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW3:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW3:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW3:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW3:8" )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW4:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW4:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW4:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW4:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW4:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW4:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW4:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW4:8" )
INPUT_PORTS_END
static INPUT_PORTS_START( leprechn )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_COCKTAIL
PORT_START("DSW0") /* DSW A - from "TEST NO.6 - dip switch A" */
PORT_DIPNAME( 0x09, 0x09, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW1:1,4")
PORT_DIPSETTING( 0x09, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_7C ) )
PORT_DIPNAME( 0x22, 0x22, "Max Credits" ) PORT_DIPLOCATION("SW1:2,6")
PORT_DIPSETTING( 0x22, "10" )
PORT_DIPSETTING( 0x20, "20" )
PORT_DIPSETTING( 0x02, "30" )
PORT_DIPSETTING( 0x00, "40" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW1:3")
PORT_DIPSETTING( 0x04, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Free_Play ) ) PORT_DIPLOCATION("SW1:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW1:7,8")
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_4C ) )
PORT_START("DSW1") /* DSW B - from "TEST NO.6 - dip switch B" */
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW2:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW2:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW2:3" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW2:4")
PORT_DIPSETTING( 0x08, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW2:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW2:6" )
PORT_DIPNAME( 0xc0, 0x40, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:7,8")
PORT_DIPSETTING( 0x40, "30000" )
PORT_DIPSETTING( 0x80, "60000" )
PORT_DIPSETTING( 0x00, "90000" )
PORT_DIPSETTING( 0xc0, DEF_STR( None ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW3:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW3:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW3:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW3:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW3:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW3:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW3:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW3:8" )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW4:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW4:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW4:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW4:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW4:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW4:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW4:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW4:8" )
INPUT_PORTS_END
static INPUT_PORTS_START( potogold )
PORT_INCLUDE(leprechn)
PORT_MODIFY("DSW1")
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW2:4")
PORT_DIPSETTING( 0x08, "3" )
PORT_DIPSETTING( 0x00, "4" )
INPUT_PORTS_END
static INPUT_PORTS_START( piratetr )
PORT_START("IN0") /* COL. A - from "TEST NO.7 - status locator - coin-door" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Do Tests") PORT_CODE(KEYCODE_F1)
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_SERVICE ) PORT_NAME("Select Test") PORT_CODE(KEYCODE_F2)
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_START("IN1") /* COL. B - from "TEST NO.7 - status locator - start sws." */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 )
PORT_START("IN2") /* COL. C - from "TEST NO.8 - status locator - player no.1" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
PORT_START("IN3") /* COL. D - from "TEST NO.8 - status locator - player no.2" */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_COCKTAIL
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_COCKTAIL
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_COCKTAIL
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_COCKTAIL
PORT_START("DSW0") /* DSW A - from "TEST NO.6 - dip switch A" */
PORT_DIPNAME( 0x09, 0x09, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW1:1,4")
PORT_DIPSETTING( 0x09, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_7C ) )
PORT_DIPNAME( 0x22, 0x22, "Max Credits" ) PORT_DIPLOCATION("SW1:2,6")
PORT_DIPSETTING( 0x22, "10" )
PORT_DIPSETTING( 0x20, "20" )
PORT_DIPSETTING( 0x02, "30" )
PORT_DIPSETTING( 0x00, "40" )
PORT_DIPNAME( 0x04, 0x04, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW1:3")
PORT_DIPSETTING( 0x04, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x10, 0x10, DEF_STR( Free_Play ) ) PORT_DIPLOCATION("SW1:5")
PORT_DIPSETTING( 0x10, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW1:7,8")
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_4C ) )
PORT_START("DSW1") /* DSW B - from "TEST NO.6 - dip switch B" */
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW2:1")
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, "Stringing Check" ) PORT_DIPLOCATION("SW2:2")
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW2:3" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW2:4")
PORT_DIPSETTING( 0x08, "3" )
PORT_DIPSETTING( 0x00, "4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW2:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW2:6" )
PORT_DIPNAME( 0xc0, 0x40, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW2:7,8")
PORT_DIPSETTING( 0x40, "30000" )
PORT_DIPSETTING( 0x80, "60000" )
PORT_DIPSETTING( 0x00, "90000" )
PORT_DIPSETTING( 0xc0, DEF_STR( None ) )
PORT_START("DSW2") /* audio board DSW A */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW3:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW3:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW3:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW3:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW3:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW3:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW3:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW3:8" )
PORT_START("DSW3") /* audio board DSW B */
PORT_DIPUNUSED_DIPLOC( 0x01, 0x01, "SW4:1" )
PORT_DIPUNUSED_DIPLOC( 0x02, 0x02, "SW4:2" )
PORT_DIPUNUSED_DIPLOC( 0x04, 0x04, "SW4:3" )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "SW4:4" )
PORT_DIPUNUSED_DIPLOC( 0x10, 0x10, "SW4:5" )
PORT_DIPUNUSED_DIPLOC( 0x20, 0x20, "SW4:6" )
PORT_DIPUNUSED_DIPLOC( 0x40, 0x40, "SW4:7" )
PORT_DIPUNUSED_DIPLOC( 0x80, 0x80, "SW4:8" )
INPUT_PORTS_END
/*************************************
*
* Machine drivers
*
*************************************/
void gameplan_state::machine_start()
{
/* register for save states */
save_item(NAME(m_current_port));
save_item(NAME(m_video_x));
save_item(NAME(m_video_y));
save_item(NAME(m_video_command));
save_item(NAME(m_video_data));
save_item(NAME(m_video_previous));
}
void gameplan_state::machine_reset()
{
m_current_port = 0;
m_video_x = 0;
m_video_y = 0;
m_video_command = 0;
m_video_data = 0;
m_video_previous = 0;
}
void gameplan_state::gameplan(machine_config &config)
{
M6502(config, m_maincpu, GAMEPLAN_MAIN_CPU_CLOCK);
m_maincpu->set_addrmap(AS_PROGRAM, &gameplan_state::gameplan_main_map);
M6502(config, m_audiocpu, GAMEPLAN_AUDIO_CPU_CLOCK);
m_audiocpu->set_addrmap(AS_PROGRAM, &gameplan_state::gameplan_audio_map);
RIOT6532(config, m_riot, GAMEPLAN_AUDIO_CPU_CLOCK);
m_riot->out_pb_callback().set(m_soundlatch, FUNC(generic_latch_8_device::write));
m_riot->irq_callback().set(FUNC(gameplan_state::r6532_irq));
/* video hardware */
gameplan_video(config);
/* audio hardware */
SPEAKER(config, "mono").front_center();
GENERIC_LATCH_8(config, m_soundlatch, 0);
ay8910_device &aysnd(AY8910(config, "aysnd", GAMEPLAN_AY8910_CLOCK));
aysnd.port_a_read_callback().set_ioport("DSW2");
aysnd.port_b_read_callback().set_ioport("DSW3");
aysnd.add_route(ALL_OUTPUTS, "mono", 0.33);
/* via */
MOS6522(config, m_via_0, GAMEPLAN_MAIN_CPU_CLOCK);
m_via_0->writepa_handler().set(FUNC(gameplan_state::video_data_w));
m_via_0->writepb_handler().set(FUNC(gameplan_state::gameplan_video_command_w));
m_via_0->ca2_handler().set(FUNC(gameplan_state::video_command_trigger_w));
m_via_0->irq_handler().set(FUNC(gameplan_state::via_irq));
MOS6522(config, m_via_1, GAMEPLAN_MAIN_CPU_CLOCK);
m_via_1->readpa_handler().set(FUNC(gameplan_state::io_port_r));
m_via_1->writepb_handler().set(FUNC(gameplan_state::io_select_w));
m_via_1->cb2_handler().set(FUNC(gameplan_state::coin_w));
MOS6522(config, m_via_2, GAMEPLAN_MAIN_CPU_CLOCK);
m_via_2->readpb_handler().set(m_soundlatch, FUNC(generic_latch_8_device::read));
m_via_2->writepa_handler().set(FUNC(gameplan_state::audio_cmd_w));
m_via_2->ca2_handler().set(FUNC(gameplan_state::audio_trigger_w));
m_via_2->cb2_handler().set(FUNC(gameplan_state::audio_reset_w));
}
void gameplan_state::leprechn(machine_config &config)
{
gameplan(config);
m_maincpu->set_clock(LEPRECHAUN_MAIN_CPU_CLOCK);
m_via_0->set_clock(LEPRECHAUN_MAIN_CPU_CLOCK);
m_via_1->set_clock(LEPRECHAUN_MAIN_CPU_CLOCK);
m_via_2->set_clock(LEPRECHAUN_MAIN_CPU_CLOCK);
/* basic machine hardware */
m_audiocpu->set_addrmap(AS_PROGRAM, &gameplan_state::leprechn_audio_map);
/* video hardware */
leprechn_video(config);
/* via */
m_via_0->readpb_handler().set(FUNC(gameplan_state::leprechn_videoram_r));
m_via_0->writepb_handler().set(FUNC(gameplan_state::leprechn_video_command_w));
}
/*************************************
*
* ROM defintions
*
*************************************/
ROM_START( killcom )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "killcom.e2", 0xc000, 0x0800, CRC(a01cbb9a) SHA1(a8769243adbdddedfda5f3c8f054e9281a0eca46) )
ROM_LOAD( "killcom.f2", 0xc800, 0x0800, CRC(bb3b4a93) SHA1(a0ea61ac30a4d191db619b7bfb697914e1500036) )
ROM_LOAD( "killcom.g2", 0xd000, 0x0800, CRC(86ec68b2) SHA1(a09238190d61684d943ce0acda25eb901d2580ac) )
ROM_LOAD( "killcom.j2", 0xd800, 0x0800, CRC(28d8c6a1) SHA1(d9003410a651221e608c0dd20d4c9c60c3b0febc) )
ROM_LOAD( "killcom.j1", 0xe000, 0x0800, CRC(33ef5ac5) SHA1(42f839ad295d3df457ced7886a0003eff7e6c4ae) )
ROM_LOAD( "killcom.g1", 0xe800, 0x0800, CRC(49cb13e2) SHA1(635e4665042ddd9b8c0b9f275d4bcc6830dc6a98) )
ROM_LOAD( "killcom.f1", 0xf000, 0x0800, CRC(ef652762) SHA1(414714e5a3f83916bd3ae54afe2cb2271ee9008b) )
ROM_LOAD( "killcom.e1", 0xf800, 0x0800, CRC(bc19dcb7) SHA1(eb983d2df010c12cb3ffb584fceafa54a4e956b3) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "killsnd.e1", 0xe000, 0x0800, CRC(77d4890d) SHA1(a3ed7e11dec5d404f022c521256ff50aa6940d3c) )
ROM_END
ROM_START( megatack )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "megattac.e2", 0xc000, 0x0800, CRC(33fa5104) SHA1(15693eb540563e03502b53ed8a83366e395ca529) )
ROM_LOAD( "megattac.f2", 0xc800, 0x0800, CRC(af5e96b1) SHA1(5f6ab47c12d051f6af446b08f3cd459fbd2c13bf) )
ROM_LOAD( "megattac.g2", 0xd000, 0x0800, CRC(670103ea) SHA1(e11f01e8843ed918c6ea5dda75319dc95105d345) )
ROM_LOAD( "megattac.j2", 0xd800, 0x0800, CRC(4573b798) SHA1(388db11ab114b3575fe26ed65bbf49174021939a) )
ROM_LOAD( "megattac.j1", 0xe000, 0x0800, CRC(3b1d01a1) SHA1(30bbf51885b1e510b8d21cdd82244a455c5dada0) )
ROM_LOAD( "megattac.g1", 0xe800, 0x0800, CRC(eed75ef4) SHA1(7c02337344f2716d2f2771229f7dee7b651eeb95) )
ROM_LOAD( "megattac.f1", 0xf000, 0x0800, CRC(c93a8ed4) SHA1(c87e2f13f2cc00055f4941c272a3126b165a6252) )
ROM_LOAD( "megattac.e1", 0xf800, 0x0800, CRC(d9996b9f) SHA1(e71d65b695000fdfd5fd1ce9ae39c0cb0b61669e) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "megatsnd.e1", 0xe000, 0x0800, CRC(0c186bdb) SHA1(233af9481a3979971f2d5aa75ec8df4333aa5e0d) )
ROM_END
ROM_START( megatacka ) // original Centuri PCB
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "meg-e2.bin", 0xc000, 0x0800, CRC(9664c7b1) SHA1(356e7f5f3b2a9b829fac53e7bf9193278b4de2ed) )
ROM_LOAD( "meg-f2.bin", 0xc800, 0x0800, CRC(67c42523) SHA1(f9fc88cdea05a2d0e89e3ba9b545bf3476b37d2d) )
ROM_LOAD( "meg-g2.bin", 0xd000, 0x0800, CRC(71f36604) SHA1(043988126343b6224e8e1d6c0dbba6b6b08fe493) )
ROM_LOAD( "meg-j2.bin", 0xd800, 0x0800, CRC(4ddcc145) SHA1(3a6d42a58c388eaaf6561351fa98936d98975e0b) )
ROM_LOAD( "meg-j1.bin", 0xe000, 0x0800, CRC(911d5d9a) SHA1(92bfe0f69a6e563363df59ebee745d7b3cfc0141) )
ROM_LOAD( "meg-g1.bin", 0xe800, 0x0800, CRC(22a51c9b) SHA1(556e09216ed85eaf3870f85515c273c7eb1ab13a) )
ROM_LOAD( "meg-f1.bin", 0xf000, 0x0800, CRC(2ffa51ac) SHA1(7c5d8295c5e71a9918a02d203139b024bd3bf8f4) )
ROM_LOAD( "meg-e1.bin", 0xf800, 0x0800, CRC(01dbe4ad) SHA1(af72778ae112f24a92fb3007bb456331c3896b50) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "megatsnd.e1", 0xe000, 0x0800, CRC(0c186bdb) SHA1(233af9481a3979971f2d5aa75ec8df4333aa5e0d) ) // missing for this board, using the one from the parent
ROM_END
ROM_START( challeng )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "chall.6", 0xa000, 0x1000, CRC(b30fe7f5) SHA1(ce93a57d626f90d31ddedbc35135f70758949dfa) )
ROM_LOAD( "chall.5", 0xb000, 0x1000, CRC(34c6a88e) SHA1(250577e2c8eb1d3a78cac679310ec38924ac1fe0) )
ROM_LOAD( "chall.4", 0xc000, 0x1000, CRC(0ddc18ef) SHA1(9f1aa27c71d7e7533bddf7de420c06fb0058cf60) )
ROM_LOAD( "chall.3", 0xd000, 0x1000, CRC(6ce03312) SHA1(69c047f501f327f568fe4ad1274168f9dda1ca70) )
ROM_LOAD( "chall.2", 0xe000, 0x1000, CRC(948912ad) SHA1(e79738ab94501f858f4d5f218787267523611e92) )
ROM_LOAD( "chall.1", 0xf000, 0x1000, CRC(7c71a9dc) SHA1(2530ada6390fb46c44bf7bf2636910ee54786493) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "chall.snd", 0xe000, 0x0800, CRC(1b2bffd2) SHA1(36ceb5abbc92a17576c375019f1c5900320398f9) )
ROM_END
ROM_START( kaos )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "kaosab.g2", 0x9000, 0x0800, CRC(b23d858f) SHA1(e31fa657ace34130211a0b9fc0d115fd89bb20dd) )
ROM_CONTINUE( 0xd000, 0x0800 )
ROM_LOAD( "kaosab.j2", 0x9800, 0x0800, CRC(4861e5dc) SHA1(96ca0b8625af3897bd4a50a45ea964715f9e4973) )
ROM_CONTINUE( 0xd800, 0x0800 )
ROM_LOAD( "kaosab.j1", 0xa000, 0x0800, CRC(e055db3f) SHA1(099176629723c1a9bdc59f440339b2e8c38c3261) )
ROM_CONTINUE( 0xe000, 0x0800 )
ROM_LOAD( "kaosab.g1", 0xa800, 0x0800, CRC(35d7c467) SHA1(6d5bfd29ff7b96fed4b24c899ddd380e47e52bc5) )
ROM_CONTINUE( 0xe800, 0x0800 )
ROM_LOAD( "kaosab.f1", 0xb000, 0x0800, CRC(995b9260) SHA1(580896aa8b6f0618dc532a12d0795b0d03f7cadd) )
ROM_CONTINUE( 0xf000, 0x0800 )
ROM_LOAD( "kaosab.e1", 0xb800, 0x0800, CRC(3da5202a) SHA1(6b5aaf44377415763aa0895c64765a4b82086f25) )
ROM_CONTINUE( 0xf800, 0x0800 )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "kaossnd.e1", 0xe000, 0x0800, CRC(ab23d52a) SHA1(505f3e4a56e78a3913010f5484891f01c9831480) )
ROM_END
ROM_START( leprechn )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "lep1", 0x8000, 0x1000, CRC(2c4a46ca) SHA1(28a157c1514bc9f27cc27baddb83cf1a1887f3d1) )
ROM_LOAD( "lep2", 0x9000, 0x1000, CRC(6ed26b3e) SHA1(4ee5d09200d9e8f94ae29751c8ee838faa268f15) )
ROM_LOAD( "lep3", 0xa000, 0x1000, CRC(a2eaa016) SHA1(be992ee787766137fd800ec59529c98ef2e6991e) )
ROM_LOAD( "lep4", 0xb000, 0x1000, CRC(6c12a065) SHA1(2acae6a5b94cbdcc550cee88a7be9254fdae908c) )
ROM_LOAD( "lep5", 0xc000, 0x1000, CRC(21ddb539) SHA1(b4dd0a1916adc076fa6084c315459fcb2522161e) )
ROM_LOAD( "lep6", 0xd000, 0x1000, CRC(03c34dce) SHA1(6dff202e1a3d0643050f3287f6b5906613d56511) )
ROM_LOAD( "lep7", 0xe000, 0x1000, CRC(7e06d56d) SHA1(5f68f2047969d803b752a4cd02e0e0af916c8358) )
ROM_LOAD( "lep8", 0xf000, 0x1000, CRC(097ede60) SHA1(5509c41167c066fa4e7f4f4bd1ce9cd00773a82c) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "lepsound", 0xe000, 0x1000, CRC(6651e294) SHA1(ce2875fc4df61a30d51d3bf2153864b562601151) )
ROM_END
ROM_START( potogold )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "pog.pg1", 0x8000, 0x1000, CRC(9f1dbda6) SHA1(baf20e9a0793c0f1529396f95a820bd1f9431465) )
ROM_LOAD( "pog.pg2", 0x9000, 0x1000, CRC(a70e3811) SHA1(7ee306dc7d75a7d3fd497870ec92bef9d86535e9) )
ROM_LOAD( "pog.pg3", 0xa000, 0x1000, CRC(81cfb516) SHA1(12732707e2a51ec39563f2d1e898cc567ab688f0) )
ROM_LOAD( "pog.pg4", 0xb000, 0x1000, CRC(d61b1f33) SHA1(da024c0776214b8b5a3e49401c4110e86a1bead1) )
ROM_LOAD( "pog.pg5", 0xc000, 0x1000, CRC(eee7597e) SHA1(9b5cd293580c5d212f8bf39286070280d55e4cb3) )
ROM_LOAD( "pog.pg6", 0xd000, 0x1000, CRC(25e682bc) SHA1(085d2d553ec10f2f830918df3a7fb8e8c1e5d18c) )
ROM_LOAD( "pog.pg7", 0xe000, 0x1000, CRC(84399f54) SHA1(c90ba3e3120adda2785ab5abd309e0a703d39f8b) )
ROM_LOAD( "pog.pg8", 0xf000, 0x1000, CRC(9e995a1a) SHA1(5c525e6c161d9d7d646857b27cecfbf8e0943480) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "pog.snd", 0xe000, 0x1000, CRC(ec61f0a4) SHA1(26944ecc3e7413259928c8b0a74b2260e67d2c4e) )
ROM_END
ROM_START( leprechp )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "lep1", 0x8000, 0x1000, CRC(2c4a46ca) SHA1(28a157c1514bc9f27cc27baddb83cf1a1887f3d1) )
ROM_LOAD( "lep2", 0x9000, 0x1000, CRC(6ed26b3e) SHA1(4ee5d09200d9e8f94ae29751c8ee838faa268f15) )
ROM_LOAD( "3u15.bin", 0xa000, 0x1000, CRC(b5f79fd8) SHA1(271f7b55ecda5bb99f40687264256b82649e2141) )
ROM_LOAD( "lep4", 0xb000, 0x1000, CRC(6c12a065) SHA1(2acae6a5b94cbdcc550cee88a7be9254fdae908c) )
ROM_LOAD( "lep5", 0xc000, 0x1000, CRC(21ddb539) SHA1(b4dd0a1916adc076fa6084c315459fcb2522161e) )
ROM_LOAD( "lep6", 0xd000, 0x1000, CRC(03c34dce) SHA1(6dff202e1a3d0643050f3287f6b5906613d56511) )
ROM_LOAD( "lep7", 0xe000, 0x1000, CRC(7e06d56d) SHA1(5f68f2047969d803b752a4cd02e0e0af916c8358) )
ROM_LOAD( "lep8", 0xf000, 0x1000, CRC(097ede60) SHA1(5509c41167c066fa4e7f4f4bd1ce9cd00773a82c) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "lepsound", 0xe000, 0x1000, CRC(6651e294) SHA1(ce2875fc4df61a30d51d3bf2153864b562601151) )
ROM_END
ROM_START( piratetr )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "1u13.bin", 0x8000, 0x1000, CRC(4433bb61) SHA1(eee0d7f356118f8595dd7533541db744a63a8176) )
ROM_LOAD( "2u14.bin", 0x9000, 0x1000, CRC(9bdc4b77) SHA1(ebaab8b3024efd3d0b76647085d441ca204ad5d5) )
ROM_LOAD( "3u15.bin", 0xa000, 0x1000, CRC(ebced718) SHA1(3a2f4385347f14093360cfa595922254c9badf1a) )
ROM_LOAD( "4u16.bin", 0xb000, 0x1000, CRC(f494e657) SHA1(83a31849de8f4f70d7547199f229079f491ddc61) )
ROM_LOAD( "5u17.bin", 0xc000, 0x1000, CRC(2789d68e) SHA1(af8f334ce4938cd75143b729c97cfbefd68c9e13) )
ROM_LOAD( "6u18.bin", 0xd000, 0x1000, CRC(d91abb3a) SHA1(11170e69686c2a1f2dc31d41516f44b612f99bad) )
ROM_LOAD( "7u19.bin", 0xe000, 0x1000, CRC(6e8808c4) SHA1(d1f76fd37d8f78552a9d53467073cc9a571d96ce) )
ROM_LOAD( "8u20.bin", 0xf000, 0x1000, CRC(2802d626) SHA1(b0db688500076ee73e0001c00089a8d552c6f607) )
ROM_REGION( 0x10000, "audiocpu", 0 )
ROM_LOAD( "su31.bin", 0xe000, 0x1000, CRC(2fe86a11) SHA1(aaafe411b9cb3d0221cc2af73d34ad8bb74f8327) )
ROM_END
/*************************************
*
* Game drivers
*
*************************************/
GAME( 1980, killcom, 0, gameplan, killcom, gameplan_state, empty_init, ROT0, "Game Plan (Centuri license)", "Killer Comet", MACHINE_SUPPORTS_SAVE )
GAME( 1980, megatack, 0, gameplan, megatack, gameplan_state, empty_init, ROT0, "Game Plan (Centuri license)", "Megatack (set 1)", MACHINE_SUPPORTS_SAVE )
GAME( 1980, megatacka, megatack, gameplan, megatack, gameplan_state, empty_init, ROT0, "Game Plan (Centuri license)", "Megatack (set 2)", MACHINE_SUPPORTS_SAVE )
GAME( 1981, challeng, 0, gameplan, challeng, gameplan_state, empty_init, ROT0, "Game Plan (Centuri license)", "Challenger", MACHINE_SUPPORTS_SAVE )
GAME( 1981, kaos, 0, gameplan, kaos, gameplan_state, empty_init, ROT270, "Game Plan", "Kaos", MACHINE_SUPPORTS_SAVE )
GAME( 1982, leprechn, 0, leprechn, leprechn, gameplan_state, empty_init, ROT0, "Tong Electronic", "Leprechaun", MACHINE_SUPPORTS_SAVE )
GAME( 1982, potogold, leprechn, leprechn, potogold, gameplan_state, empty_init, ROT0, "Tong Electronic (Game Plan license)", "Pot of Gold", MACHINE_SUPPORTS_SAVE )
GAME( 1982, leprechp, leprechn, leprechn, potogold, gameplan_state, empty_init, ROT0, "Tong Electronic (Pacific Polytechnical license)", "Leprechaun (Pacific)", MACHINE_SUPPORTS_SAVE )
GAME( 1982, piratetr, 0, leprechn, piratetr, gameplan_state, empty_init, ROT0, "Tong Electronic", "Pirate Treasure", MACHINE_SUPPORTS_SAVE )
| 45.429661 | 187 | 0.704218 | Robbbert |
d6eb8f831c53eadf73c7a302ff50b2fa9423ce2c | 1,385 | cpp | C++ | game/game/definitions/visualfxdefinitions.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 576 | 2019-07-22T19:14:33.000Z | 2022-03-31T22:27:28.000Z | game/game/definitions/visualfxdefinitions.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 208 | 2019-07-22T17:25:30.000Z | 2022-03-14T18:53:06.000Z | game/game/definitions/visualfxdefinitions.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 67 | 2019-10-14T19:39:38.000Z | 2022-01-27T13:58:03.000Z | #include "visualfxdefinitions.h"
#include <Tempest/Log>
#include "graphics/visualfx.h"
#include "gothic.h"
using namespace Tempest;
VisualFxDefinitions::VisualFxDefinitions() {
vm = Gothic::inst().createVm("VisualFx.dat");
}
VisualFxDefinitions::~VisualFxDefinitions() {
vm->clearReferences(Daedalus::IC_Pfx);
}
const VisualFx* VisualFxDefinitions::get(std::string_view name) {
std::string cname = std::string(name);
auto it = vfx.find(cname);
if(it!=vfx.end())
return it->second.get();
Daedalus::GEngineClasses::CFx_Base def;
if(!implGet(cname,def))
return nullptr;
auto ret = vfx.insert(std::make_pair<std::string,std::unique_ptr<VisualFx>>(std::move(cname),nullptr));
ret.first->second.reset(new VisualFx(def,*vm,name));
auto& vfx = *ret.first->second;
vfx.dbgName = name.data();
return &vfx;
}
bool VisualFxDefinitions::implGet(std::string_view name,
Daedalus::GEngineClasses::CFx_Base& ret) {
if(!vm || name.empty())
return false;
char buf[256] = {};
std::snprintf(buf,sizeof(buf),"%.*s",int(name.size()),name.data());
auto id = vm->getDATFile().getSymbolIndexByName(buf);
if(id==size_t(-1)) {
Log::e("invalid visual effect: \"",buf,"\"");
return false;
}
vm->initializeInstance(ret, id, Daedalus::IC_Vfx);
vm->clearReferences(Daedalus::IC_Vfx);
return true;
}
| 25.648148 | 105 | 0.66426 | houkama |
d6eee2708dbb00fd305fc1cc4b9964a38cf58567 | 1,332 | cpp | C++ | code/engine.vc2008/xrCore/DateTime.cpp | icetorch2001/xray-oxygen | 8c210ac2824f794cea69266048fe12d584ee3f04 | [
"Apache-2.0"
] | 1 | 2021-09-14T14:28:56.000Z | 2021-09-14T14:28:56.000Z | code/engine.vc2008/xrCore/DateTime.cpp | icetorch2001/xray-oxygen | 8c210ac2824f794cea69266048fe12d584ee3f04 | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrCore/DateTime.cpp | icetorch2001/xray-oxygen | 8c210ac2824f794cea69266048fe12d584ee3f04 | [
"Apache-2.0"
] | 3 | 2021-11-01T06:21:26.000Z | 2022-01-08T16:13:23.000Z | #include "stdafx.h"
#include "DateTime.hpp"
Time::Time()
{
t = time(nullptr);
aTm = *localtime(&t);
}
Time::Time(time_t InTime)
: t(InTime)
{
aTm = *localtime(&t);
}
int Time::GetSeconds() const
{
return aTm.tm_sec;
}
int Time::GetMinutes() const
{
return aTm.tm_min;
}
int Time::GetHours() const
{
return aTm.tm_hour;
}
int Time::GetDay() const
{
return aTm.tm_mday;
}
int Time::GetMonth() const
{
return aTm.tm_mon + 1;
}
int Time::GetYear() const
{
return aTm.tm_year + 1900;
}
Time::string Time::GetSecondsString() const
{
return (GetSeconds() < 10) ? "0" + xr_string::ToString(GetSeconds()) : xr_string::ToString(GetSeconds());
}
Time::string Time::GetMinutesString() const
{
return (GetMinutes() < 10) ? "0" + xr_string::ToString(GetMinutes()) : xr_string::ToString(GetMinutes());
}
Time::string Time::GetHoursString() const
{
return (GetHours() < 10) ? "0" + xr_string::ToString(GetHours()) : xr_string::ToString(GetHours());
}
Time::string Time::GetDayString() const
{
return (GetDay() < 10) ? "0" + xr_string::ToString(GetDay()) : xr_string::ToString(GetDay());
}
Time::string Time::GetMonthString() const
{
return (GetMonth() < 10) ? "0" + xr_string::ToString(GetMonth()) : xr_string::ToString(GetMonth());
}
Time::string Time::GetYearString() const
{
return xr_string::ToString(GetYear());
} | 18 | 106 | 0.671171 | icetorch2001 |
d6f089d99a397f8a5e7b624930a39dc86f3b8f0a | 3,682 | cpp | C++ | 004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp | Mr-Devin/GraphicAlgorithm | 58877e6a8dba75ab171b0d89260defaffa22d047 | [
"MIT"
] | 1 | 2021-11-16T11:40:04.000Z | 2021-11-16T11:40:04.000Z | 004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp | younha169/GraphicAlgorithm | 93287ae4d4171764e788371887c4fd1549304552 | [
"MIT"
] | null | null | null | 004_Metalights Improved Interleaved Shading/SplitGBufferPass.cpp | younha169/GraphicAlgorithm | 93287ae4d4171764e788371887c4fd1549304552 | [
"MIT"
] | null | null | null | #include "SplitGBufferPass.h"
#include "Interface.h"
#include "Common.h"
#include "Utils.h"
#include "Shader.h"
CSplitGBufferPass::CSplitGBufferPass(const std::string& vPassName, int vExcutionOrder) : IRenderPass(vPassName, vExcutionOrder)
{
}
CSplitGBufferPass::~CSplitGBufferPass()
{
}
void CSplitGBufferPass::initV()
{
auto AlbedoTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("AlbedoTexture");
auto NormalTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("NormalTexture");
auto PositionTexture = ElayGraphics::ResourceManager::getSharedDataByName<std::shared_ptr<ElayGraphics::STexture>>("PositionTexture");
auto TextureConfig4Albedo = std::make_shared<ElayGraphics::STexture>();
auto TextureConfig4Normal = std::make_shared<ElayGraphics::STexture>();
auto TextureConfig4Position = std::make_shared<ElayGraphics::STexture>();
TextureConfig4Albedo->InternalFormat = TextureConfig4Normal->InternalFormat = TextureConfig4Position->InternalFormat = GL_RGBA32F;
TextureConfig4Albedo->ExternalFormat = TextureConfig4Normal->ExternalFormat = TextureConfig4Position->ExternalFormat = GL_RGBA;
TextureConfig4Albedo->DataType = TextureConfig4Normal->DataType = TextureConfig4Position->DataType = GL_FLOAT;
TextureConfig4Albedo->Type4MinFilter = TextureConfig4Normal->Type4MinFilter = TextureConfig4Position->Type4MinFilter = GL_LINEAR;
TextureConfig4Albedo->Type4MagFilter = TextureConfig4Normal->Type4MagFilter = TextureConfig4Position->Type4MagFilter = GL_LINEAR;
TextureConfig4Albedo->ImageBindUnit= 0;
TextureConfig4Normal->ImageBindUnit = 1;
TextureConfig4Position->ImageBindUnit = 2;
genTexture(TextureConfig4Albedo);
genTexture(TextureConfig4Normal);
genTexture(TextureConfig4Position);
m_pShader = std::make_shared<CShader>("SplitGBuffer_CS.glsl");
m_pShader->activeShader();
m_pShader->setTextureUniformValue("u_InputAlbedoTexture", AlbedoTexture);
m_pShader->setTextureUniformValue("u_InputNormalTexture", NormalTexture);
m_pShader->setTextureUniformValue("u_InputPositionTexture", PositionTexture);
m_pShader->setIntUniformValue("u_WindowWidth", ElayGraphics::WINDOW_KEYWORD::getWindowWidth());
m_pShader->setIntUniformValue("u_WindowHeight", ElayGraphics::WINDOW_KEYWORD::getWindowHeight());
m_pShader->setIntUniformValue("u_SubBufferNumX", m_SubBufferNumX);
m_pShader->setIntUniformValue("u_SubBufferNumY", m_SubBufferNumY);
m_pShader->setImageUniformValue(TextureConfig4Albedo);
m_pShader->setImageUniformValue(TextureConfig4Normal);
m_pShader->setImageUniformValue(TextureConfig4Position);
std::vector<int> LocalGroupSize;
m_pShader->InquireLocalGroupSize(LocalGroupSize);
m_GlobalGroupSize.push_back((ElayGraphics::WINDOW_KEYWORD::getWindowWidth() + LocalGroupSize[0] - 1) / LocalGroupSize[0]);
m_GlobalGroupSize.push_back((ElayGraphics::WINDOW_KEYWORD::getWindowHeight() + LocalGroupSize[1] - 1) / LocalGroupSize[1]);
m_GlobalGroupSize.push_back(1);
ElayGraphics::ResourceManager::registerSharedData("SubBufferNumX", m_SubBufferNumX);
ElayGraphics::ResourceManager::registerSharedData("SubBufferNumY", m_SubBufferNumY);
ElayGraphics::ResourceManager::registerSharedData("SplitedAlbedoImage", TextureConfig4Albedo);
ElayGraphics::ResourceManager::registerSharedData("SplitedNormalImage", TextureConfig4Normal);
ElayGraphics::ResourceManager::registerSharedData("SplitedPositionImage", TextureConfig4Position);
}
void CSplitGBufferPass::updateV()
{
m_pShader->activeShader();
glDispatchCompute(m_GlobalGroupSize[0], m_GlobalGroupSize[1], m_GlobalGroupSize[2]);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
} | 54.955224 | 135 | 0.828083 | Mr-Devin |
d6f1d738d10176761223244ddd03d4c2762231f1 | 1,187 | cpp | C++ | src/test/multi/1.cpp | cbosoft/rlp | 21adacbb514f3ff68a77577c2d097fcaaaeffe25 | [
"MIT"
] | 1 | 2020-03-28T15:53:08.000Z | 2020-03-28T15:53:08.000Z | src/test/multi/1.cpp | cbosoft/rlp | 21adacbb514f3ff68a77577c2d097fcaaaeffe25 | [
"MIT"
] | null | null | null | src/test/multi/1.cpp | cbosoft/rlp | 21adacbb514f3ff68a77577c2d097fcaaaeffe25 | [
"MIT"
] | null | null | null | #include "multi.hpp"
MultiInteractionTest::MultiInteractionTest(bool is_quiet)
: TestRunner("Multi particle test", is_quiet)
{
this->input_data = {
Vec3({4.22479, 1.67952, 10.0})
};
this->expected_results = {
Vec3({4.0653970383976529845, 1.3030129329153037343, 0.77670979214002822122})
};
}
void MultiInteractionTest::run(Vec3 point, Vec3 expected_result)
{
// build
PeriodicBox box(10.0, this->is_quiet?-10:0);
Particle *pi = new Particle(1.0, Vec3({4.71171, 0.118055, 10.0}));
box.add_particle(pi);
pi->set_position(Vec3({4.71171, 0.118055, 0.363677}));
Particle *pj = new Particle(1.0, Vec3({3.52381, 1.62458, 10.0}));
box.add_particle(pj);
Particle *pk = new Particle(1.0, Vec3({4.51687, 1.74221, 10.0}));
box.add_particle(pk);
Particle *pl = new Particle(1.0, Vec3({4.05131, 0.775026, 10.0}));
box.add_particle(pl);
Particle *pm = new Particle(1.0, point);
box.add_particle(pm);
Vec3 result = pm->get_position();
if (result == expected_result) {
this->pass();
}
else {
this->fail(Formatter() << "Particle did not settle to expected position. Expected " << expected_result << ", got " << result << ".");
}
}
| 25.255319 | 137 | 0.656276 | cbosoft |
d6f2721ece0f2de78fbe13346552ceae479b4c4a | 373 | cpp | C++ | tests/testcases/unary.cpp | graydon/uint128_t | e7d55400adde4fa13008d6f4778ad3514d41aca7 | [
"MIT"
] | 180 | 2015-02-23T22:18:43.000Z | 2022-03-12T11:46:31.000Z | tests/testcases/unary.cpp | graydon/uint128_t | e7d55400adde4fa13008d6f4778ad3514d41aca7 | [
"MIT"
] | 15 | 2017-06-14T13:09:42.000Z | 2022-01-16T22:25:50.000Z | tests/testcases/unary.cpp | graydon/uint128_t | e7d55400adde4fa13008d6f4778ad3514d41aca7 | [
"MIT"
] | 52 | 2015-04-08T03:44:06.000Z | 2022-03-25T14:04:36.000Z | #include <gtest/gtest.h>
#include "uint128_t.h"
TEST(Arithmetic, unary_plus){
const uint128_t value(0x12345ULL);
EXPECT_EQ(+value, value);
}
TEST(Arithmetic, unary_minus){
const uint128_t val(1);
const uint128_t neg = -val;
EXPECT_EQ(-val, neg);
EXPECT_EQ(-neg, val);
EXPECT_EQ(neg, uint128_t(0xffffffffffffffffULL, 0xffffffffffffffffULL));
} | 23.3125 | 76 | 0.705094 | graydon |
d6f39dfa02feb89ede21cceaec669673a72df4f6 | 763 | cpp | C++ | 0049 - Group Anagrams/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | 5 | 2018-10-18T06:47:19.000Z | 2020-06-19T09:30:03.000Z | 0049 - Group Anagrams/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | 0049 - Group Anagrams/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | //
// main.cpp
// 49 - Group Anagrams
//
// Created by ynfMac on 2019/12/7.
// Copyright © 2019 ynfMac. All rights reserved.
//
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (const string& s : strs) {
string key = s;
sort(key.begin(), key.end());
m[key].push_back(s);
}
vector<vector<string>> res;
for (const auto& p :m) {
res.push_back(p.second);
}
return res;
}
};
int main(int argc, const char * argv[]) {
std::cout << "Hello, World!\n";
return 0;
}
| 20.621622 | 64 | 0.551769 | xiaoswu |
d6f566cc52dacde8c6ea30a0da584fef01856ac7 | 4,710 | cpp | C++ | ouster_viz/src/image.cpp | UTS-CAS/ouster_example | d4572d0ea4d724d0802e1ca789a29bbf365198aa | [
"MIT",
"BSD-3-Clause"
] | null | null | null | ouster_viz/src/image.cpp | UTS-CAS/ouster_example | d4572d0ea4d724d0802e1ca789a29bbf365198aa | [
"MIT",
"BSD-3-Clause"
] | null | null | null | ouster_viz/src/image.cpp | UTS-CAS/ouster_example | d4572d0ea4d724d0802e1ca789a29bbf365198aa | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2020, Ouster, Inc.
* All rights reserved.
*/
#include "image.h"
#include <stdexcept>
#include <vector>
#include "camera.h"
#include "common.h"
#include "glfw.h"
#include "ouster/point_viz.h"
namespace ouster {
namespace viz {
namespace impl {
bool GLImage::initialized = false;
GLuint GLImage::program_id;
GLuint GLImage::vertex_id;
GLuint GLImage::uv_id;
GLuint GLImage::image_id;
GLuint GLImage::mask_id;
GLImage::GLImage() {
if (!GLImage::initialized)
throw std::logic_error("GLCloud not initialized");
glGenBuffers(2, vertexbuffers.data());
// initialize index buffer
GLubyte indices[] = {0, 1, 2, 0, 2, 3};
glGenBuffers(1, &image_index_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, image_index_id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLubyte), indices,
GL_STATIC_DRAW);
GLuint textures[2];
glGenTextures(2, textures);
image_texture_id = textures[0];
mask_texture_id = textures[1];
// initialize textures
GLfloat init[4] = {0, 0, 0, 0};
load_texture(init, 1, 1, image_texture_id, GL_RED, GL_RED);
load_texture(init, 1, 1, mask_texture_id, GL_RGBA, GL_RGBA);
}
GLImage::GLImage(const Image& /*image*/) : GLImage{} {}
GLImage::~GLImage() {
glDeleteBuffers(2, vertexbuffers.data());
glDeleteTextures(1, &image_texture_id);
glDeleteTextures(1, &mask_texture_id);
}
void GLImage::draw(const WindowCtx& ctx, const CameraData&, Image& image) {
// update state
if (image.position_changed_) {
x0 = image.position_[0];
x1 = image.position_[1];
y0 = image.position_[2];
y1 = image.position_[3];
hshift = image.hshift_;
image.position_changed_ = false;
}
glUniform1i(image_id, 0);
glUniform1i(mask_id, 1);
glActiveTexture(GL_TEXTURE0);
if (image.image_changed_) {
load_texture(image.image_data_.data(), image.image_width_,
image.image_height_, image_texture_id, GL_RED, GL_RED);
image.image_changed_ = false;
}
glBindTexture(GL_TEXTURE_2D, image_texture_id);
glActiveTexture(GL_TEXTURE1);
if (image.mask_changed_) {
load_texture(image.mask_data_.data(), image.mask_width_,
image.mask_height_, mask_texture_id, GL_RGBA, GL_RGBA);
image.mask_changed_ = false;
}
glBindTexture(GL_TEXTURE_2D, mask_texture_id);
// draw
double aspect = impl::window_aspect(ctx);
GLfloat x0_scaled = x0 / aspect + hshift;
GLfloat x1_scaled = x1 / aspect + hshift;
const GLfloat vertices[] = {x0_scaled, y0, x0_scaled, y1,
x1_scaled, y1, x1_scaled, y0};
const GLfloat texcoords[] = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0};
glEnableVertexAttribArray(vertex_id);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 4 * 2, vertices,
GL_DYNAMIC_DRAW);
glVertexAttribPointer(vertex_id,
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glEnableVertexAttribArray(uv_id);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffers[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 4 * 2, texcoords,
GL_DYNAMIC_DRAW);
glVertexAttribPointer(uv_id,
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, image_index_id);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, (void*)0);
glDisableVertexAttribArray(vertex_id);
glDisableVertexAttribArray(uv_id);
}
void GLImage::initialize() {
GLImage::program_id =
load_shaders(image_vertex_shader_code, image_fragment_shader_code);
// TODO: handled differently than cloud ids...
GLImage::vertex_id = glGetAttribLocation(GLImage::program_id, "vertex");
GLImage::uv_id = glGetAttribLocation(GLImage::program_id, "vertex_uv");
GLImage::image_id = glGetUniformLocation(GLImage::program_id, "image");
GLImage::mask_id = glGetUniformLocation(GLImage::program_id, "mask");
GLImage::initialized = true;
}
void GLImage::uninitialize() { glDeleteProgram(GLImage::program_id); }
void GLImage::beginDraw() { glUseProgram(GLImage::program_id); }
void GLImage::endDraw() {}
} // namespace impl
} // namespace viz
} // namespace ouster
| 32.040816 | 76 | 0.634607 | UTS-CAS |
d6f7ad1910e4f6b4486444fe307b734c4a62613b | 754 | hxx | C++ | ds/adsi/winnt/cuoi.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/winnt/cuoi.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/winnt/cuoi.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
class CWinNTUserOtherInfo;
class CWinNTUserOtherInfo : INHERIT_TRACKING,
public IADsFSUserOtherInfo
{
friend class CWinNTUser;
public:
/* IUnknown methods */
STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID FAR* ppvObj) ;
DECLARE_STD_REFCOUNTING
DECLARE_IDispatch_METHODS
DECLARE_IADsFSUserOtherInfo_METHODS
CWinNTUserOtherInfo::CWinNTUserOtherInfo();
CWinNTUserOtherInfo::~CWinNTUserOtherInfo();
static
HRESULT
Create(
CCoreADsObject FAR * pCoreADsObject,
CWinNTUserOtherInfo FAR * FAR * ppUserOI
);
protected:
CCoreADsObject * _pCoreADsObject;
CAggregatorDispMgr *_pDispMgr;
};
| 17.952381 | 71 | 0.651194 | npocmaka |
d6f7bcff72dda89ef8880f3cb0501646fa1349f5 | 357 | hpp | C++ | PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 6 | 2019-08-15T09:48:55.000Z | 2021-07-25T14:40:59.000Z | PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 43 | 2019-12-25T14:54:52.000Z | 2022-02-24T17:22:48.000Z | PlanetaMatchMakerServer/source/utilities/asio_stream_compatibility.hpp | InstytutXR/PlanetaMatchMaker | 4bf7503c031aea467c191c3a0d14c6dd58354f99 | [
"MIT"
] | 2 | 2020-05-06T20:14:44.000Z | 2020-06-02T21:21:10.000Z | #pragma once
#include <boost/asio.hpp>
namespace boost {
namespace asio {
std::ostream& operator <<(std::ostream& os, const basic_socket<ip::tcp>::endpoint_type& endpoint);
}
namespace system {
std::ostream& operator <<(std::ostream& os, const error_code& error_code);
std::ostream& operator <<(std::ostream& os, const system_error& error);
}
}
| 25.5 | 100 | 0.703081 | InstytutXR |
d6fb0c289baea16265ec7b05735877e69c88a012 | 2,301 | cpp | C++ | utility/checked_delete.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 47 | 2016-05-20T08:49:47.000Z | 2022-01-03T01:17:07.000Z | utility/checked_delete.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | null | null | null | utility/checked_delete.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 37 | 2016-07-25T04:52:08.000Z | 2022-02-14T03:55:08.000Z | // Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;
#include <boost/checked_delete.hpp>
using namespace boost;
///////////////////////////////////////
class demo_class;
void do_delete(demo_class* p)
//{ delete p;}
{ checked_delete(p);}
///////////////////////////////////////
void case1()
{
auto p1 = new int(10);
checked_delete(p1);
auto p2 = new int[10];
checked_array_delete(p2);
}
///////////////////////////////////////
class demo_class
{
public:
~demo_class()
{ cout << "dtor exec." << endl; }
};
void case2()
{
auto p1 = new demo_class;
//checked_delete(p1);
checked_deleter<demo_class>()(p1);
auto p2 = new demo_class[10];
//checked_array_delete(p2);
checked_array_deleter<demo_class>()(p2);
cout << "try for_each" << endl;
vector<demo_class*> v;
v.push_back(new demo_class);
v.push_back(new demo_class);
for_each(v.begin(),v.end(), checked_deleter<demo_class>());
}
///////////////////////////////////////
struct my_checked_deleter
{
typedef void result_type;
template<class T>
void operator()(T* x) const
{
boost::checked_delete(x);
}
};
void case3()
{
cout << "my_checked_deleter" << endl;
auto p = new int(10);
my_checked_deleter()(p);
vector<int*> v;
v.push_back(new int(10));
for_each(v.begin(), v.end(),
my_checked_deleter());
}
///////////////////////////////////////
void case4()
{
cout << "incomplete type" << endl;
auto p = new demo_class();
//auto p = (demo_class*)(1996);
do_delete(p);
}
///////////////////////////////////////
#include <boost/static_assert.hpp>
template<class Pointer> inline
void my_checked_delete(Pointer p)
{
BOOST_STATIC_ASSERT(is_pointer<Pointer>::value);
typedef typename remove_pointer<Pointer>::type T;
BOOST_STATIC_ASSERT(is_object<T>::value);
BOOST_STATIC_ASSERT(!is_array<T>::value);
BOOST_STATIC_ASSERT(sizeof(T) >0 );
delete p;
}
void case5()
{
//auto p = new int[2][2];
auto p = new int;
my_checked_delete(p);
}
///////////////////////////////////////
int main()
{
std::cout << "hello checked_delete" << std::endl;
case1();
case2();
case3();
case4();
case5();
}
| 17.044444 | 63 | 0.544111 | MaxHonggg |
d6fe59a8c3a1b85861b53530072006152e35cdf8 | 2,768 | cpp | C++ | source/custom/nirfmxinstr_service.custom.cpp | DavidCurtiss/grpc-device | 74f49a0c29dd016c46cf0ca21973a53edda71bac | [
"MIT"
] | null | null | null | source/custom/nirfmxinstr_service.custom.cpp | DavidCurtiss/grpc-device | 74f49a0c29dd016c46cf0ca21973a53edda71bac | [
"MIT"
] | null | null | null | source/custom/nirfmxinstr_service.custom.cpp | DavidCurtiss/grpc-device | 74f49a0c29dd016c46cf0ca21973a53edda71bac | [
"MIT"
] | null | null | null | #include <nirfmxinstr/nirfmxinstr_service.h>
#include <server/converters.h>
#include <sstream>
namespace nirfmxinstr_grpc {
const auto kErrorReadBufferTooSmall = -200229;
const auto kWarningCAPIStringTruncatedToFitBuffer = 200026;
//---------------------------------------------------------------------
//---------------------------------------------------------------------
::grpc::Status NiRFmxInstrService::GetNIRFSASessionArray(::grpc::ServerContext* context, const GetNIRFSASessionArrayRequest* request, GetNIRFSASessionArrayResponse* response)
{
if (context->IsCancelled()) {
return ::grpc::Status::CANCELLED;
}
try {
auto instrument_grpc_session = request->instrument();
auto instrument = session_repository_->access_session(instrument_grpc_session.id(), instrument_grpc_session.name());
auto initiating_session_id = session_repository_->access_session_id(instrument_grpc_session.id(), instrument_grpc_session.name());
auto nirfsa_sessions = std::vector<ViSession>{};
int32 array_size{};
int32 actual_array_size{};
while (true) {
auto status = library_->GetNIRFSASessionArray(instrument, nullptr, 0, &actual_array_size);
if (status < 0) {
response->set_status(status);
return ::grpc::Status::OK;
}
array_size = actual_array_size;
nirfsa_sessions.resize(array_size);
status = library_->GetNIRFSASessionArray(instrument, nirfsa_sessions.data(), array_size, &actual_array_size);
if (status == kErrorReadBufferTooSmall || status == kWarningCAPIStringTruncatedToFitBuffer) {
// buffer is now too small, try again
continue;
}
if (request->session_names_size() != 0 && request->session_names_size() != array_size) {
std::stringstream stream;
stream << "Number of session_names must be zero or match actual array size (" << array_size << ").";
return ::grpc::Status(::grpc::INVALID_ARGUMENT, stream.str());
}
response->set_status(status);
if (status == 0) {
for (auto i = 0; i < array_size; ++i) {
auto init_lambda = [&]() {
return std::make_tuple(0, nirfsa_sessions[i]);
};
uint32_t session_id = 0;
const auto session_name = request->session_names_size() ? request->session_names(i) : "";
int status = vi_session_resource_repository_->add_dependent_session(session_name, init_lambda, initiating_session_id, session_id);
auto session = response->add_nirfsa_sessions();
session->set_id(session_id);
}
}
return ::grpc::Status::OK;
}
}
catch (nidevice_grpc::LibraryLoadException& ex) {
return ::grpc::Status(::grpc::NOT_FOUND, ex.what());
}
}
} // namespace nirfmxinstr_grpc
| 41.939394 | 174 | 0.649566 | DavidCurtiss |
d9010b55ad78ce4d46baa6ae6a686e8932f05969 | 121 | hpp | C++ | src/rolmodl/hpp/forwarddecl/Win.hpp | maximsmol/rolmodl | fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f | [
"MIT"
] | 1 | 2022-02-19T21:34:42.000Z | 2022-02-19T21:34:42.000Z | src/rolmodl/hpp/forwarddecl/Win.hpp | maximsmol/rolmodl | fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f | [
"MIT"
] | null | null | null | src/rolmodl/hpp/forwarddecl/Win.hpp | maximsmol/rolmodl | fb41b7f9f4669eea84ce6f1574cdf1be9b6f072f | [
"MIT"
] | 1 | 2021-12-07T09:33:42.000Z | 2021-12-07T09:33:42.000Z | #pragma once
#include <cstdint>
#include <SDL.h>
namespace rolmodl {
class Win_Base;
class Win;
class Win_SW;
}
| 10.083333 | 19 | 0.68595 | maximsmol |
d902c74f190f2586b6730d9b3dc14bec827c6668 | 7,534 | cpp | C++ | musicplayer/plugins/openmptplugin/openmpt/soundlib/Load_far.cpp | Osmose/moseamp | 8357daf2c93bc903c8041cc82bf3567e8d085a60 | [
"MIT"
] | 6 | 2017-04-19T19:06:03.000Z | 2022-01-11T14:44:14.000Z | plugins/openmptplugin/openmpt/soundlib/Load_far.cpp | sasq64/musicplayer | 372852c2f4e3231a09db2628fc4b7e7c2bfeec67 | [
"MIT"
] | 4 | 2018-04-04T20:27:32.000Z | 2020-04-25T10:46:21.000Z | musicplayer/plugins/openmptplugin/openmpt/soundlib/Load_far.cpp | Osmose/moseamp | 8357daf2c93bc903c8041cc82bf3567e8d085a60 | [
"MIT"
] | 2 | 2018-06-08T15:20:48.000Z | 2020-08-19T14:24:21.000Z | /*
* Load_far.cpp
* ------------
* Purpose: Farandole (FAR) module loader
* Notes : (currently none)
* Authors: OpenMPT Devs (partly inspired by Storlek's FAR loader from Schism Tracker)
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Loaders.h"
OPENMPT_NAMESPACE_BEGIN
// FAR File Header
struct FARFileHeader
{
uint8le magic[4];
char songName[40];
uint8le eof[3];
uint16le headerLength;
uint8le version;
uint8le onOff[16];
uint8le editingState[9]; // Stuff we don't care about
uint8le defaultSpeed;
uint8le chnPanning[16];
uint8le patternState[4]; // More stuff we don't care about
uint16le messageLength;
};
MPT_BINARY_STRUCT(FARFileHeader, 98)
struct FAROrderHeader
{
uint8le orders[256];
uint8le numPatterns; // supposed to be "number of patterns stored in the file"; apparently that's wrong
uint8le numOrders;
uint8le restartPos;
uint16le patternSize[256];
};
MPT_BINARY_STRUCT(FAROrderHeader, 771)
// FAR Sample header
struct FARSampleHeader
{
// Sample flags
enum SampleFlags
{
smp16Bit = 0x01,
smpLoop = 0x08,
};
char name[32];
uint32le length;
uint8le finetune;
uint8le volume;
uint32le loopStart;
uint32le loopEnd;
uint8le type;
uint8le loop;
// Convert sample header to OpenMPT's internal format.
void ConvertToMPT(ModSample &mptSmp) const
{
mptSmp.Initialize();
mptSmp.nLength = length;
mptSmp.nLoopStart = loopStart;
mptSmp.nLoopEnd = loopEnd;
mptSmp.nC5Speed = 8363 * 2;
mptSmp.nVolume = volume * 16;
if(type & smp16Bit)
{
mptSmp.nLength /= 2;
mptSmp.nLoopStart /= 2;
mptSmp.nLoopEnd /= 2;
}
if((loop & 8) && mptSmp.nLoopEnd > mptSmp.nLoopStart)
{
mptSmp.uFlags.set(CHN_LOOP);
}
}
// Retrieve the internal sample format flags for this sample.
SampleIO GetSampleFormat() const
{
return SampleIO(
(type & smp16Bit) ? SampleIO::_16bit : SampleIO::_8bit,
SampleIO::mono,
SampleIO::littleEndian,
SampleIO::signedPCM);
}
};
MPT_BINARY_STRUCT(FARSampleHeader, 48)
static bool ValidateHeader(const FARFileHeader &fileHeader)
{
if(std::memcmp(fileHeader.magic, "FAR\xFE", 4) != 0
|| std::memcmp(fileHeader.eof, "\x0D\x0A\x1A", 3)
)
{
return false;
}
if(fileHeader.headerLength < sizeof(FARFileHeader))
{
return false;
}
return true;
}
static uint64 GetHeaderMinimumAdditionalSize(const FARFileHeader &fileHeader)
{
return fileHeader.headerLength - sizeof(FARFileHeader);
}
CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderFAR(MemoryFileReader file, const uint64 *pfilesize)
{
FARFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return ProbeWantMoreData;
}
if(!ValidateHeader(fileHeader))
{
return ProbeFailure;
}
return ProbeAdditionalSize(file, pfilesize, GetHeaderMinimumAdditionalSize(fileHeader));
}
bool CSoundFile::ReadFAR(FileReader &file, ModLoadingFlags loadFlags)
{
file.Rewind();
FARFileHeader fileHeader;
if(!file.ReadStruct(fileHeader))
{
return false;
}
if(!ValidateHeader(fileHeader))
{
return false;
}
if(!file.CanRead(mpt::saturate_cast<FileReader::off_t>(GetHeaderMinimumAdditionalSize(fileHeader))))
{
return false;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
// Globals
InitializeGlobals(MOD_TYPE_FAR);
m_nChannels = 16;
m_nSamplePreAmp = 32;
m_nDefaultSpeed = fileHeader.defaultSpeed;
m_nDefaultTempo.Set(80);
m_nDefaultGlobalVolume = MAX_GLOBAL_VOLUME;
m_modFormat.formatName = U_("Farandole Composer");
m_modFormat.type = U_("far");
m_modFormat.charset = mpt::CharsetCP437;
mpt::String::Read<mpt::String::maybeNullTerminated>(m_songName, fileHeader.songName);
// Read channel settings
for(CHANNELINDEX chn = 0; chn < 16; chn++)
{
ChnSettings[chn].Reset();
ChnSettings[chn].dwFlags = fileHeader.onOff[chn] ? ChannelFlags(0) : CHN_MUTE;
ChnSettings[chn].nPan = ((fileHeader.chnPanning[chn] & 0x0F) << 4) + 8;
}
// Read song message
if(fileHeader.messageLength != 0)
{
m_songMessage.ReadFixedLineLength(file, fileHeader.messageLength, 132, 0); // 132 characters per line... wow. :)
}
// Read orders
FAROrderHeader orderHeader;
if(!file.ReadStruct(orderHeader))
{
return false;
}
ReadOrderFromArray(Order(), orderHeader.orders, orderHeader.numOrders, 0xFF, 0xFE);
Order().SetRestartPos(orderHeader.restartPos);
file.Seek(fileHeader.headerLength);
// Pattern effect LUT
static const EffectCommand farEffects[] =
{
CMD_NONE,
CMD_PORTAMENTOUP,
CMD_PORTAMENTODOWN,
CMD_TONEPORTAMENTO,
CMD_RETRIG,
CMD_VIBRATO, // depth
CMD_VIBRATO, // speed
CMD_VOLUMESLIDE, // up
CMD_VOLUMESLIDE, // down
CMD_VIBRATO, // sustained (?)
CMD_NONE, // actually slide-to-volume
CMD_S3MCMDEX, // panning
CMD_S3MCMDEX, // note offset => note delay?
CMD_NONE, // fine tempo down
CMD_NONE, // fine tempo up
CMD_SPEED,
};
// Read patterns
for(PATTERNINDEX pat = 0; pat < 256; pat++)
{
if(!orderHeader.patternSize[pat])
{
continue;
}
FileReader patternChunk = file.ReadChunk(orderHeader.patternSize[pat]);
// Calculate pattern length in rows (every event is 4 bytes, and we have 16 channels)
ROWINDEX numRows = (orderHeader.patternSize[pat] - 2) / (16 * 4);
if(!(loadFlags & loadPatternData) || !Patterns.Insert(pat, numRows))
{
continue;
}
// Read break row and unused value (used to be pattern tempo)
ROWINDEX breakRow = patternChunk.ReadUint8();
patternChunk.Skip(1);
if(breakRow > 0 && breakRow < numRows - 2)
{
breakRow++;
} else
{
breakRow = ROWINDEX_INVALID;
}
// Read pattern data
for(ROWINDEX row = 0; row < numRows; row++)
{
PatternRow rowBase = Patterns[pat].GetRow(row);
for(CHANNELINDEX chn = 0; chn < 16; chn++)
{
ModCommand &m = rowBase[chn];
uint8 data[4];
patternChunk.ReadArray(data);
if(data[0] > 0 && data[0] < 85)
{
m.note = data[0] + 35 + NOTE_MIN;
m.instr = data[1] + 1;
}
if(m.note != NOTE_NONE || data[2] > 0)
{
m.volcmd = VOLCMD_VOLUME;
m.vol = (Clamp(data[2], uint8(1), uint8(16)) - 1u) * 4u;
}
m.param = data[3] & 0x0F;
switch(data[3] >> 4)
{
case 0x03: // Porta to note
m.param <<= 2;
break;
case 0x04: // Retrig
m.param = 6 / (1 + (m.param & 0xf)) + 1; // ugh?
break;
case 0x06: // Vibrato speed
case 0x07: // Volume slide up
m.param *= 8;
break;
case 0x0A: // Volume-portamento (what!)
m.volcmd = VOLCMD_VOLUME;
m.vol = (m.param << 2) + 4;
break;
case 0x0B: // Panning
m.param |= 0x80;
break;
case 0x0C: // Note offset
m.param = 6 / (1 + m.param) + 1;
m.param |= 0x0D;
}
m.command = farEffects[data[3] >> 4];
}
}
Patterns[pat].WriteEffect(EffectWriter(CMD_PATTERNBREAK, 0).Row(breakRow).RetryNextRow());
}
if(!(loadFlags & loadSampleData))
{
return true;
}
// Read samples
uint8 sampleMap[8]; // Sample usage bitset
file.ReadArray(sampleMap);
for(SAMPLEINDEX smp = 0; smp < 64; smp++)
{
if(!(sampleMap[smp >> 3] & (1 << (smp & 7))))
{
continue;
}
FARSampleHeader sampleHeader;
if(!file.ReadStruct(sampleHeader))
{
return true;
}
m_nSamples = smp + 1;
ModSample &sample = Samples[m_nSamples];
mpt::String::Read<mpt::String::nullTerminated>(m_szNames[m_nSamples], sampleHeader.name);
sampleHeader.ConvertToMPT(sample);
sampleHeader.GetSampleFormat().ReadSample(sample, file);
}
return true;
}
OPENMPT_NAMESPACE_END
| 22.158824 | 114 | 0.678922 | Osmose |
d9039defe88679682a44ede05e8bdb7ccadcc678 | 273 | cpp | C++ | test/prog_tests/test1/problems/keyboard.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | test/prog_tests/test1/problems/keyboard.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | test/prog_tests/test1/problems/keyboard.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | #include "keyboard.h"
#include "strlib.h"
char arr[] = {'?', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
void getAllEncryption(string digits, Set<string> &words, Lexicon &lex) {
}
| 27.3 | 150 | 0.435897 | Liquidibrium |
d905a9ffc825dde40cd5c10f1e3ea532268ff364 | 3,459 | cpp | C++ | Source/Engine/Engine/GameObject3D.cpp | Syoukei66/Animal-Space-Battle | edb17e2f75fd5b43697889597e1eaac2e9e9cd76 | [
"MIT"
] | null | null | null | Source/Engine/Engine/GameObject3D.cpp | Syoukei66/Animal-Space-Battle | edb17e2f75fd5b43697889597e1eaac2e9e9cd76 | [
"MIT"
] | null | null | null | Source/Engine/Engine/GameObject3D.cpp | Syoukei66/Animal-Space-Battle | edb17e2f75fd5b43697889597e1eaac2e9e9cd76 | [
"MIT"
] | null | null | null | #include "GameObject3D.h"
#include "GameObjectRenderState.h"
// =================================================================
// Constructor / Destructor
// =================================================================
GameObject3D::GameObject3D()
: parent_(nullptr)
, children_()
{
this->transform_ = new Transform3D(this);
this->transform_->Init();
}
GameObject3D::~GameObject3D()
{
delete this->transform_;
}
// =================================================================
// Method
// =================================================================
void GameObject3D::Init()
{
GameObject::Init();
}
void GameObject3D::ManagedPreUpdate()
{
this->PreUpdate();
for (GameObject3D* child : this->children_)
{
child->ManagedPreUpdate();
}
}
void GameObject3D::ManagedUpdate()
{
this->Update();
for (GameObject3D* child : this->children_)
{
child->ManagedUpdate();
}
}
void GameObject3D::ManagedPostUpdate()
{
this->PostUpdate();
for (GameObject3D* child : this->children_)
{
child->ManagedPostUpdate();
}
}
void GameObject3D::AddChild(GameObject3D* child)
{
child->parent_ = this;
this->children_.push_back(child);
child->FireOnPositionChanged(this);
child->FireOnScaleChanged(this);
child->FireOnRotationChanged(this);
}
void GameObject3D::RemoveChild(GameObject3D* child)
{
if (child->parent_ != this)
{
return;
}
child->parent_ = nullptr;
for (std::vector<GameObject3D*>::iterator it = this->children_.begin(); it != this->children_.end(); ++it)
{
if (child == (*it))
{
this->children_.erase(it);
return;
}
}
}
void GameObject3D::RemoveSelf()
{
if (!this->parent_)
{
return;
}
this->parent_->RemoveChild(this);
}
void GameObject3D::ClearChildren()
{
for (GameObject3D* child : this->children_)
{
child->parent_ = nullptr;
}
this->children_.clear();
}
void GameObject3D::Draw(GameObjectRenderState* state)
{
if (!this->IsVisible())
{
return;
}
this->PushMatrixStack(state);
// 自分自身の描画
this->ManagedDraw(state);
// 子の描画
for (GameObject3D* child : this->children_)
{
child->Draw(state);
}
this->PopMatrixStack(state);
}
void GameObject3D::PushMatrixStack(GameObjectRenderState* state)
{
state->PushMatrix(this->transform_->GetMatrix());
//if (this->IsBillboardingRoot())
//{
// state->PushMatrix(state->GetCamera()->GetBillboardingMatrix());
//}
}
void GameObject3D::PopMatrixStack(GameObjectRenderState* state)
{
//if (this->IsBillboardingRoot())
//{
// state->PopMatrix();
//}
state->PopMatrix();
}
// =================================================================
// Events
// =================================================================
void GameObject3D::FireOnPositionChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnPositionChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnPositionChanged(root);
}
}
void GameObject3D::FireOnScaleChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnScaleChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnScaleChanged(root);
}
}
void GameObject3D::FireOnRotationChanged(GameObject* root)
{
this->transform_->OnWorldTransformDirty();
this->OnRotationChanged(root);
for (GameObject3D* child : this->children_)
{
child->FireOnRotationChanged(root);
}
}
| 20.110465 | 108 | 0.596993 | Syoukei66 |
d906207eb9cd47b104e346b5cb69ccdf83e246b2 | 1,516 | cc | C++ | components/autofill/core/browser/suggestion.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | components/autofill/core/browser/suggestion.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/browser/suggestion.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.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 "components/autofill/core/browser/suggestion.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/credit_card.h"
namespace autofill {
SuggestionBackendID::SuggestionBackendID()
: variant(0) {
}
SuggestionBackendID::SuggestionBackendID(const std::string& g, size_t v)
: guid(g),
variant(v) {
}
SuggestionBackendID::~SuggestionBackendID() {
}
bool SuggestionBackendID::operator<(const SuggestionBackendID& other) const {
if (variant != other.variant)
return variant < other.variant;
return guid < other.guid;
}
Suggestion::Suggestion()
: frontend_id(0) {
}
Suggestion::Suggestion(const Suggestion& other)
: backend_id(other.backend_id),
frontend_id(other.frontend_id),
value(other.value),
label(other.label),
icon(other.icon) {
}
Suggestion::Suggestion(const base::string16& v)
: frontend_id(0),
value(v) {
}
Suggestion::Suggestion(const std::string& v,
const std::string& l,
const std::string& i,
int fid)
: frontend_id(fid),
value(base::UTF8ToUTF16(v)),
label(base::UTF8ToUTF16(l)),
icon(base::UTF8ToUTF16(i)) {
}
Suggestion::~Suggestion() {
}
} // namespace autofill
| 24.451613 | 77 | 0.676121 | kjthegod |
d9069f1e1538cf1f8469e29bbc94bbd40f57f2c3 | 12,569 | hxx | C++ | opencascade/AppDef_Variational.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AppDef_Variational.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AppDef_Variational.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1996-05-14
// Created by: Philippe MANGIN / Jeannine PANCIATICI
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AppDef_Variational_HeaderFile
#define _AppDef_Variational_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <AppDef_MultiLine.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <AppParCurves_HArray1OfConstraintCouple.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <Standard_Real.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Boolean.hxx>
#include <AppParCurves_MultiBSpCurve.hxx>
#include <Standard_OStream.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <math_Vector.hxx>
#include <AppParCurves_Constraint.hxx>
class AppDef_SmoothCriterion;
class math_Matrix;
class FEmTool_Curve;
class FEmTool_Assembly;
class PLib_Base;
//! This class is used to smooth N points with constraints
//! by minimization of quadratic criterium but also
//! variational criterium in order to obtain " fair Curve "
//! Computes the approximation of a Multiline by
//! Variational optimization.
class AppDef_Variational
{
public:
DEFINE_STANDARD_ALLOC
//! Constructor.
//! Initialization of the fields.
//! warning : Nc0 : number of PassagePoint consraints
//! Nc2 : number of TangencyPoint constraints
//! Nc3 : number of CurvaturePoint constraints
//! if
//! ((MaxDegree-Continuity)*MaxSegment -Nc0 - 2*Nc1
//! -3*Nc2)
//! is negative
//! The problem is over-constrained.
//!
//! Limitation : The MultiLine from AppDef has to be composed by
//! only one Line ( Dimension 2 or 3).
Standard_EXPORT AppDef_Variational(const AppDef_MultiLine& SSP, const Standard_Integer FirstPoint, const Standard_Integer LastPoint, const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer MaxDegree = 14, const Standard_Integer MaxSegment = 100, const GeomAbs_Shape Continuity = GeomAbs_C2, const Standard_Boolean WithMinMax = Standard_False, const Standard_Boolean WithCutting = Standard_True, const Standard_Real Tolerance = 1.0, const Standard_Integer NbIterations = 2);
//! Makes the approximation with the current fields.
Standard_EXPORT void Approximate();
//! returns True if the creation is done
//! and correspond to the current fields.
Standard_EXPORT Standard_Boolean IsCreated() const;
//! returns True if the approximation is ok
//! and correspond to the current fields.
Standard_EXPORT Standard_Boolean IsDone() const;
//! returns True if the problem is overconstrained
//! in this case, approximation cannot be done.
Standard_EXPORT Standard_Boolean IsOverConstrained() const;
//! returns all the BSpline curves approximating the
//! MultiLine from AppDef SSP after minimization of the parameter.
Standard_EXPORT AppParCurves_MultiBSpCurve Value() const;
//! returns the maximum of the distances between
//! the points of the multiline and the approximation
//! curves.
Standard_EXPORT Standard_Real MaxError() const;
//! returns the index of the MultiPoint of ErrorMax
Standard_EXPORT Standard_Integer MaxErrorIndex() const;
//! returns the quadratic average of the distances between
//! the points of the multiline and the approximation
//! curves.
Standard_EXPORT Standard_Real QuadraticError() const;
//! returns the distances between the points of the
//! multiline and the approximation curves.
Standard_EXPORT void Distance (math_Matrix& mat);
//! returns the average error between
//! the MultiLine from AppDef and the approximation.
Standard_EXPORT Standard_Real AverageError() const;
//! returns the parameters uses to the approximations
Standard_EXPORT const Handle(TColStd_HArray1OfReal)& Parameters() const;
//! returns the knots uses to the approximations
Standard_EXPORT const Handle(TColStd_HArray1OfReal)& Knots() const;
//! returns the values of the quality criterium.
Standard_EXPORT void Criterium (Standard_Real& VFirstOrder, Standard_Real& VSecondOrder, Standard_Real& VThirdOrder) const;
//! returns the Weights (as percent) associed to the criterium used in
//! the optimization.
Standard_EXPORT void CriteriumWeight (Standard_Real& Percent1, Standard_Real& Percent2, Standard_Real& Percent3) const;
//! returns the Maximum Degree used in the approximation
Standard_EXPORT Standard_Integer MaxDegree() const;
//! returns the Maximum of segment used in the approximation
Standard_EXPORT Standard_Integer MaxSegment() const;
//! returns the Continuity used in the approximation
Standard_EXPORT GeomAbs_Shape Continuity() const;
//! returns if the approximation search to minimize the
//! maximum Error or not.
Standard_EXPORT Standard_Boolean WithMinMax() const;
//! returns if the approximation can insert new Knots or not.
Standard_EXPORT Standard_Boolean WithCutting() const;
//! returns the tolerance used in the approximation.
Standard_EXPORT Standard_Real Tolerance() const;
//! returns the number of iterations used in the approximation.
Standard_EXPORT Standard_Integer NbIterations() const;
//! Prints on the stream o information on the current state
//! of the object.
//! MaxError,MaxErrorIndex,AverageError,QuadraticError,Criterium
//! Distances,Degre,Nombre de poles, parametres, noeuds
Standard_EXPORT void Dump (Standard_OStream& o) const;
//! Define the constraints to approximate
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetConstraints (const Handle(AppParCurves_HArray1OfConstraintCouple)& aConstrainst);
//! Defines the parameters used by the approximations.
Standard_EXPORT void SetParameters (const Handle(TColStd_HArray1OfReal)& param);
//! Defines the knots used by the approximations
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetKnots (const Handle(TColStd_HArray1OfReal)& knots);
//! Define the Maximum Degree used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetMaxDegree (const Standard_Integer Degree);
//! Define the maximum number of segments used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetMaxSegment (const Standard_Integer NbSegment);
//! Define the Continuity used in the approximation
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetContinuity (const GeomAbs_Shape C);
//! Define if the approximation search to minimize the
//! maximum Error or not.
Standard_EXPORT void SetWithMinMax (const Standard_Boolean MinMax);
//! Define if the approximation can insert new Knots or not.
//! If this value is incompatible with the others fields
//! this method modify nothing and returns false
Standard_EXPORT Standard_Boolean SetWithCutting (const Standard_Boolean Cutting);
//! define the Weights (as percent) associed to the criterium used in
//! the optimization.
//!
//! if Percent <= 0
Standard_EXPORT void SetCriteriumWeight (const Standard_Real Percent1, const Standard_Real Percent2, const Standard_Real Percent3);
//! define the Weight (as percent) associed to the
//! criterium Order used in the optimization : Others
//! weights are updated.
//! if Percent < 0
//! if Order < 1 or Order > 3
Standard_EXPORT void SetCriteriumWeight (const Standard_Integer Order, const Standard_Real Percent);
//! define the tolerance used in the approximation.
Standard_EXPORT void SetTolerance (const Standard_Real Tol);
//! define the number of iterations used in the approximation.
//! if Iter < 1
Standard_EXPORT void SetNbIterations (const Standard_Integer Iter);
protected:
private:
Standard_EXPORT void TheMotor (Handle(AppDef_SmoothCriterion)& J, const Standard_Real WQuadratic, const Standard_Real WQuality, Handle(FEmTool_Curve)& TheCurve, TColStd_Array1OfReal& Ecarts);
Standard_EXPORT void Adjusting (Handle(AppDef_SmoothCriterion)& J, Standard_Real& WQuadratic, Standard_Real& WQuality, Handle(FEmTool_Curve)& TheCurve, TColStd_Array1OfReal& Ecarts);
Standard_EXPORT void Optimization (Handle(AppDef_SmoothCriterion)& J, FEmTool_Assembly& A, const Standard_Boolean ToAssemble, const Standard_Real EpsDeg, Handle(FEmTool_Curve)& Curve, const TColStd_Array1OfReal& Parameters) const;
Standard_EXPORT void Project (const Handle(FEmTool_Curve)& C, const TColStd_Array1OfReal& Ti, TColStd_Array1OfReal& ProjTi, TColStd_Array1OfReal& Distance, Standard_Integer& NumPoints, Standard_Real& MaxErr, Standard_Real& QuaErr, Standard_Real& AveErr, const Standard_Integer NbIterations = 2) const;
Standard_EXPORT void ACR (Handle(FEmTool_Curve)& Curve, TColStd_Array1OfReal& Ti, const Standard_Integer Decima) const;
Standard_EXPORT void SplitCurve (const Handle(FEmTool_Curve)& InCurve, const TColStd_Array1OfReal& Ti, const Standard_Real CurveTol, Handle(FEmTool_Curve)& OutCurve, Standard_Boolean& iscut) const;
Standard_EXPORT void Init();
Standard_EXPORT void InitSmoothCriterion();
Standard_EXPORT void InitParameters (Standard_Real& Length);
Standard_EXPORT void InitCriterionEstimations (const Standard_Real Length, Standard_Real& J1, Standard_Real& J2, Standard_Real& J3) const;
Standard_EXPORT void EstTangent (const Standard_Integer ipnt, math_Vector& VTang) const;
Standard_EXPORT void EstSecnd (const Standard_Integer ipnt, const math_Vector& VTang1, const math_Vector& VTang2, const Standard_Real Length, math_Vector& VScnd) const;
Standard_EXPORT void InitCutting (const Handle(PLib_Base)& aBase, const Standard_Real CurvTol, Handle(FEmTool_Curve)& aCurve) const;
Standard_EXPORT void AssemblingConstraints (const Handle(FEmTool_Curve)& Curve, const TColStd_Array1OfReal& Parameters, const Standard_Real CBLONG, FEmTool_Assembly& A) const;
Standard_EXPORT Standard_Boolean InitTthetaF (const Standard_Integer ndimen, const AppParCurves_Constraint typcon, const Standard_Integer begin, const Standard_Integer jndex);
AppDef_MultiLine mySSP;
Standard_Integer myNbP3d;
Standard_Integer myNbP2d;
Standard_Integer myDimension;
Standard_Integer myFirstPoint;
Standard_Integer myLastPoint;
Standard_Integer myNbPoints;
Handle(TColStd_HArray1OfReal) myTabPoints;
Handle(AppParCurves_HArray1OfConstraintCouple) myConstraints;
Standard_Integer myNbConstraints;
Handle(TColStd_HArray1OfReal) myTabConstraints;
Standard_Integer myNbPassPoints;
Standard_Integer myNbTangPoints;
Standard_Integer myNbCurvPoints;
Handle(TColStd_HArray1OfInteger) myTypConstraints;
Handle(TColStd_HArray1OfReal) myTtheta;
Handle(TColStd_HArray1OfReal) myTfthet;
Standard_Integer myMaxDegree;
Standard_Integer myMaxSegment;
Standard_Integer myNbIterations;
Standard_Real myTolerance;
GeomAbs_Shape myContinuity;
Standard_Integer myNivCont;
Standard_Boolean myWithMinMax;
Standard_Boolean myWithCutting;
Standard_Real myPercent[3];
Standard_Real myCriterium[4];
Handle(AppDef_SmoothCriterion) mySmoothCriterion;
Handle(TColStd_HArray1OfReal) myParameters;
Handle(TColStd_HArray1OfReal) myKnots;
AppParCurves_MultiBSpCurve myMBSpCurve;
Standard_Real myMaxError;
Standard_Integer myMaxErrorIndex;
Standard_Real myAverageError;
Standard_Boolean myIsCreated;
Standard_Boolean myIsDone;
Standard_Boolean myIsOverConstr;
};
#endif // _AppDef_Variational_HeaderFile
| 41.896667 | 512 | 0.782003 | mgreminger |
d90727825ec09c42fad4533752c89cd24eb0ad1f | 2,607 | cpp | C++ | ChessVisualizer/ChessGame.cpp | nErumin/Interactive_Chess | 8b7769febb5bf94e8099257785dff8997d9c3dec | [
"MIT"
] | 3 | 2019-06-08T09:10:45.000Z | 2019-11-24T03:10:00.000Z | ChessVisualizer/ChessGame.cpp | Jang-Woo-Jin/Interactive_Chess | 8b7769febb5bf94e8099257785dff8997d9c3dec | [
"MIT"
] | 4 | 2019-03-23T14:59:57.000Z | 2019-09-18T04:29:18.000Z | ChessVisualizer/ChessGame.cpp | Jang-Woo-Jin/Interactive_Chess | 8b7769febb5bf94e8099257785dff8997d9c3dec | [
"MIT"
] | null | null | null | #include "ChessGame.h"
#include "Player.h"
#include "Board.h"
#include "PieceColor.h"
#include "PlayerType.h"
#include "NullPiece.h"
#include <memory>
#include "Vector2.h"
#include "MathUtils.h"
ChessGame::ChessGame()
: result{ GameResult::None }
{
}
void ChessGame::initializeGame(std::pair<PieceColor, PieceColor> playerPieceColors)
{
players.push_back(std::make_shared<Player>(PlayerType::Human, playerPieceColors.first));
players.push_back(std::make_shared<Player>(PlayerType::Robot, playerPieceColors.second));
currentTurnPlayerIndex = players.at(0)->getOwningPieceColor() == PieceColor::White ?
0 :
1;
getBoard().initializeBoardCellPieces(playerPieceColors.second, playerPieceColors.first);
}
std::vector<std::shared_ptr<Player>> ChessGame::getPlayers() const
{
std::vector<std::shared_ptr<Player>> returnPlayers(players.size());
for (size_t i = 0; i < players.size(); ++i)
{
returnPlayers[i] = players[i];
}
return returnPlayers;
}
Board& ChessGame::getBoard() noexcept
{
return gameBoard;
}
const Board& ChessGame::getBoard() const noexcept
{
return gameBoard;
}
Player& ChessGame::getCurrentPlayer() noexcept
{
return *players[currentTurnPlayerIndex];
}
const Player& ChessGame::getCurrentPlayer() const noexcept
{
return *players[currentTurnPlayerIndex];
}
Player& ChessGame::getNextPlayer() noexcept
{
size_t nextPlayerIndex = (currentTurnPlayerIndex + 1) % players.size();
return *players[nextPlayerIndex];
}
const Player& ChessGame::getNextPlayer() const noexcept
{
size_t nextPlayerIndex = (currentTurnPlayerIndex + 1) % players.size();
return *players[nextPlayerIndex];
}
void ChessGame::movePiece(const Vector2 pieceLocation, const Vector2 deltaLocation)
{
auto indices = normalizeToIntegerVector(pieceLocation);
auto selectedPieceColor = getBoard().getCell(indices.second, indices.first).getPiece()->getColor();
if (selectedPieceColor != getCurrentPlayer().getOwningPieceColor())
{
throw std::logic_error{ "not your piece" };
}
getBoard().movePiece(pieceLocation, deltaLocation);
}
void ChessGame::setToNextPlayer()
{
Player& changingPlayer = *players[currentTurnPlayerIndex];
currentTurnPlayerIndex = (currentTurnPlayerIndex + 1) % players.size();
notifyToObservers(changingPlayer, *players[currentTurnPlayerIndex]);
}
GameResult ChessGame::getGameResult() const noexcept
{
return result;
}
void ChessGame::setGameResult(GameResult newResult) noexcept
{
result = newResult;
}
ChessGame::~ChessGame()
{
}
| 24.59434 | 103 | 0.721903 | nErumin |
d91133aa2d6e50a954999b734a5f129b200ef21c | 1,308 | cpp | C++ | leetcode/787. Cheapest Flights Within K Stops.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | 1 | 2018-09-13T12:16:42.000Z | 2018-09-13T12:16:42.000Z | leetcode/787. Cheapest Flights Within K Stops.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | leetcode/787. Cheapest Flights Within K Stops.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
vector< vector< pair<int, int> > > adj(n);
for(int i = 0; i < flights.size(); i++) {
int u = flights[i][0];
int v = flights[i][1];
int w = flights[i][2];
adj[u].push_back({v, w});
}
vector< vector<int> > distance(n, vector<int>(K + 2, 1e9));
for(int i = 0; i <= K; i++) {
distance[src][i] = 0;
}
queue< pair<int, int> > q;
q.push({src, 0});
while(!q.empty()) {
pair<int, int> top = q.front();
q.pop();
int u = top.first;
int stops = top.second;
if(stops > K) {
continue;
}
for(auto i : adj[u]) {
int v = i.first;
int w = i.second;
if(distance[v][stops + 1] > distance[u][stops] + w) {
distance[v][stops + 1] = distance[u][stops] + w;
q.push({v, stops + 1});
}
}
}
int minDist = INT_MAX;
for(auto i : distance[dst]) {
minDist = min(minDist, i);
}
return minDist == 1e9 ? -1 : minDist;
}
};
| 31.902439 | 89 | 0.407492 | chamow97 |
d91148dff2f98caf9ebfc8bbd422ef78cc17fad9 | 4,368 | hpp | C++ | src/tools/include/benchmark.hpp | kovdan01/parallel-computing | 878d836e4b05563dc7fe11b6d7ca65fea950b5b7 | [
"Intel"
] | null | null | null | src/tools/include/benchmark.hpp | kovdan01/parallel-computing | 878d836e4b05563dc7fe11b6d7ca65fea950b5b7 | [
"Intel"
] | null | null | null | src/tools/include/benchmark.hpp | kovdan01/parallel-computing | 878d836e4b05563dc7fe11b6d7ca65fea950b5b7 | [
"Intel"
] | null | null | null | #ifndef PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
#define PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
#include <chrono>
// NOTE: gcc 8.2.0 on cHARISMa does not support concepts
// Instead, use horrible std::enable_if
// #include <concepts>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <type_traits>
namespace my
{
template <typename T>
inline __attribute__((always_inline)) void do_not_optimize(T& value)
{
#if defined(__clang__)
asm volatile("" : "+r,m"(value) : : "memory");
#else
asm volatile("" : "+m,r"(value) : : "memory");
#endif
}
inline __attribute__((always_inline)) std::uint64_t ticks()
{
std::uint64_t tsc;
asm volatile("mfence; " // memory barrier
"rdtsc; " // read of tsc
"shl $32,%%rdx; " // shift higher 32 bits stored in rdx up
"or %%rdx,%%rax" // and or onto rax
: "=a"(tsc) // output to tsc
:
: "%rcx", "%rdx", "memory");
return tsc;
}
struct TicksAndNanoseconds
{
double ticks;
double nanoseconds;
};
class NanosecondsTimer
{
public:
NanosecondsTimer(double& result, std::size_t iterations_count = 1)
: m_result(result)
, m_iterations_count(iterations_count)
{
m_time_before = std::chrono::high_resolution_clock::now();
}
~NanosecondsTimer()
{
try
{
using namespace std::chrono;
high_resolution_clock::time_point time_after = high_resolution_clock::now();
m_result = duration_cast<nanoseconds>(time_after - m_time_before).count() / static_cast<double>(m_iterations_count);
}
catch (...)
{
std::exit(EXIT_FAILURE);
}
}
private:
double& m_result;
std::size_t m_iterations_count;
std::chrono::high_resolution_clock::time_point m_time_before;
};
class TicksTimer
{
public:
TicksTimer(double& result, std::size_t iterations_count = 1)
: m_result(result)
, m_iterations_count(iterations_count)
{
m_ticks_before = ticks();
}
~TicksTimer()
{
try
{
std::uint64_t ticks_after = ticks();
m_result = (ticks_after - m_ticks_before) / static_cast<double>(m_iterations_count);
}
catch (...)
{
std::exit(EXIT_FAILURE);
}
}
private:
double& m_result;
std::size_t m_iterations_count;
std::uint64_t m_ticks_before;
};
class Timer : public NanosecondsTimer, public TicksTimer
{
public:
Timer(TicksAndNanoseconds& result, std::size_t iterations_count = 1)
: NanosecondsTimer(result.nanoseconds, iterations_count)
, TicksTimer(result.ticks, iterations_count)
{
}
};
// NOTE: gcc 8.2.0 on cHARISMa does not support concepts
// Instead, use horrible std::enable_if
// template <typename Function>
// concept ReturnsVoid = std::same_as<std::invoke_result_t<Function>, void>;
// template <typename Function>
// concept DoesNotReturnVoid = !ReturnsVoid<Function>;
template <typename Function>
// requires DoesNotReturnVoid<Function>
std::enable_if_t<!std::is_same_v<std::invoke_result_t<Function>, void>, double>
benchmark_function(Function f, std::size_t iterations_count = 1)
{
double nanoseconds;
{
NanosecondsTimer timer(nanoseconds, iterations_count);
for (std::size_t i = 0; i < iterations_count; ++i)
{
auto result = f();
do_not_optimize(result);
}
}
return nanoseconds;
}
template <typename Function>
// requires ReturnsVoid<Function>
std::enable_if_t<std::is_same_v<std::invoke_result_t<Function>, void>, double>
benchmark_function(Function f, std::size_t iterations_count = 1)
{
double nanoseconds;
{
NanosecondsTimer timer(nanoseconds, iterations_count);
for (std::size_t i = 0; i < iterations_count; ++i)
{
f();
}
}
return nanoseconds;
}
inline void print_result(std::string_view label, double result)
{
std::cout << label;
std::cout << std::fixed;
std::cout << std::setprecision(2) << std::setfill(' ') << std::setw(15) << result << std::endl;
std::cout << std::scientific;
}
} // namespace my
#endif // PARALLEL_COMPUTING_TOOLS_BENCHMARK_HPP_
| 25.846154 | 128 | 0.633013 | kovdan01 |
d911b4fcec81fea1c844a18f81a150e5deff5489 | 16,907 | cpp | C++ | OpenTESArena/src/Game/Game.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Game/Game.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Game/Game.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | #include <chrono>
#include <cmath>
#include <cstdint>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include "SDL.h"
#include "Game.h"
#include "Options.h"
#include "PlayerInterface.h"
#include "../Assets/CityDataFile.h"
#include "../Interface/Panel.h"
#include "../Media/FontManager.h"
#include "../Media/MusicFile.h"
#include "../Media/MusicName.h"
#include "../Media/TextureManager.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "../Utilities/Platform.h"
#include "components/debug/Debug.h"
#include "components/utilities/File.h"
#include "components/utilities/String.h"
#include "components/vfs/manager.hpp"
namespace
{
// Size of scratch buffer in bytes, reset each frame.
constexpr int SCRATCH_BUFFER_SIZE = 65536;
}
Game::Game()
{
DebugLog("Initializing (Platform: " + Platform::getPlatform() + ").");
// Get the current working directory. This is most relevant for platforms
// like macOS, where the base path might be in the app's own "Resources" folder.
this->basePath = Platform::getBasePath();
// Get the path to the options folder. This is platform-dependent and points inside
// the "preferences directory" so it's always writable.
this->optionsPath = Platform::getOptionsPath();
// Parse options-default.txt and options-changes.txt (if it exists). Always prefer the
// default file before the "changes" file.
this->initOptions(this->basePath, this->optionsPath);
// Initialize virtual file system using the Arena path in the options file.
const bool arenaPathIsRelative = File::pathIsRelative(this->options.getMisc_ArenaPath().c_str());
VFS::Manager::get().initialize(std::string(
(arenaPathIsRelative ? this->basePath : "") + this->options.getMisc_ArenaPath()));
// Initialize the OpenAL Soft audio manager.
const bool midiPathIsRelative = File::pathIsRelative(this->options.getAudio_MidiConfig().c_str());
const std::string midiPath = (midiPathIsRelative ? this->basePath : "") +
this->options.getAudio_MidiConfig();
this->audioManager.init(this->options.getAudio_MusicVolume(),
this->options.getAudio_SoundVolume(), this->options.getAudio_SoundChannels(),
this->options.getAudio_SoundResampling(), this->options.getAudio_Is3DAudio(), midiPath);
// Initialize the SDL renderer and window with the given settings.
this->renderer.init(this->options.getGraphics_ScreenWidth(),
this->options.getGraphics_ScreenHeight(),
static_cast<Renderer::WindowMode>(this->options.getGraphics_WindowMode()),
this->options.getGraphics_LetterboxMode());
// Initialize the texture manager.
this->textureManager.init();
// Determine which version of the game the Arena path is pointing to.
const bool isFloppyVersion = [this, arenaPathIsRelative]()
{
// Path to the Arena folder.
const std::string fullArenaPath = [this, arenaPathIsRelative]()
{
// Include the base path if the ArenaPath is relative.
const std::string path = (arenaPathIsRelative ? this->basePath : "") +
this->options.getMisc_ArenaPath();
return String::addTrailingSlashIfMissing(path);
}();
// Check for the CD version first.
const std::string &acdExeName = ExeData::CD_VERSION_EXE_FILENAME;
const std::string acdExePath = fullArenaPath + acdExeName;
if (File::exists(acdExePath.c_str()))
{
DebugLog("CD version.");
return false;
}
// If that's not there, check for the floppy disk version.
const std::string &aExeName = ExeData::FLOPPY_VERSION_EXE_FILENAME;
const std::string aExePath = fullArenaPath + aExeName;
if (File::exists(aExePath.c_str()))
{
DebugLog("Floppy disk version.");
return true;
}
// If neither exist, it's not a valid Arena directory.
throw DebugException("\"" + fullArenaPath + "\" does not have an Arena executable.");
}();
// Load various miscellaneous assets.
this->miscAssets.init(isFloppyVersion);
// Load and set window icon.
const Surface icon = [this]()
{
const std::string iconPath = this->basePath + "data/icon.bmp";
Surface surface = Surface::loadBMP(iconPath.c_str(), Renderer::DEFAULT_PIXELFORMAT);
// Treat black as transparent.
const uint32_t black = surface.mapRGBA(0, 0, 0, 255);
SDL_SetColorKey(surface.get(), SDL_TRUE, black);
return surface;
}();
this->renderer.setWindowIcon(icon);
this->scratchAllocator.init(SCRATCH_BUFFER_SIZE);
// Initialize panel and music to default.
this->panel = Panel::defaultPanel(*this);
this->setMusic(MusicName::PercIntro);
// Use a texture as the cursor instead.
SDL_ShowCursor(SDL_FALSE);
// Leave some members null for now. The game data is initialized when the player
// enters the game world, and the "next panel" is a temporary used by the game
// to avoid corruption between panel events which change the panel.
this->gameData = nullptr;
this->nextPanel = nullptr;
this->nextSubPanel = nullptr;
// This keeps the programmer from deleting a sub-panel the same frame it's in use.
// The pop is delayed until the beginning of the next frame.
this->requestedSubPanelPop = false;
}
Panel *Game::getActivePanel() const
{
return (this->subPanels.size() > 0) ?
this->subPanels.back().get() : this->panel.get();
}
AudioManager &Game::getAudioManager()
{
return this->audioManager;
}
InputManager &Game::getInputManager()
{
return this->inputManager;
}
FontManager &Game::getFontManager()
{
return this->fontManager;
}
bool Game::gameDataIsActive() const
{
return this->gameData.get() != nullptr;
}
GameData &Game::getGameData() const
{
// The caller should not request the game data when there is no active session.
DebugAssert(this->gameDataIsActive());
return *this->gameData.get();
}
Options &Game::getOptions()
{
return this->options;
}
Renderer &Game::getRenderer()
{
return this->renderer;
}
TextureManager &Game::getTextureManager()
{
return this->textureManager;
}
MiscAssets &Game::getMiscAssets()
{
return this->miscAssets;
}
ScratchAllocator &Game::getScratchAllocator()
{
return this->scratchAllocator;
}
Profiler &Game::getProfiler()
{
return this->profiler;
}
const FPSCounter &Game::getFPSCounter() const
{
return this->fpsCounter;
}
void Game::setPanel(std::unique_ptr<Panel> nextPanel)
{
this->nextPanel = std::move(nextPanel);
}
void Game::pushSubPanel(std::unique_ptr<Panel> nextSubPanel)
{
this->nextSubPanel = std::move(nextSubPanel);
}
void Game::popSubPanel()
{
// The active sub-panel must not pop more than one sub-panel, because it may
// have unintended side effects for other panels below it.
DebugAssertMsg(!this->requestedSubPanelPop, "Already scheduled to pop sub-panel.");
// If there are no sub-panels, then there is only the main panel, and panels
// should never have any sub-panels to pop.
DebugAssertMsg(this->subPanels.size() > 0, "No sub-panels to pop.");
this->requestedSubPanelPop = true;
}
void Game::setMusic(MusicName musicName, const std::optional<MusicName> &jingleMusicName)
{
if (jingleMusicName.has_value())
{
// Play jingle first and set the main music as the next music.
const std::string &jingleFilename = MusicFile::fromName(*jingleMusicName);
const bool loop = false;
this->audioManager.playMusic(jingleFilename, loop);
std::string nextFilename = MusicFile::fromName(musicName);
this->audioManager.setNextMusic(std::move(nextFilename));
}
else
{
// Play main music immediately.
const std::string &filename = MusicFile::fromName(musicName);
const bool loop = true;
this->audioManager.playMusic(filename, loop);
}
}
void Game::setGameData(std::unique_ptr<GameData> gameData)
{
this->gameData = std::move(gameData);
}
void Game::initOptions(const std::string &basePath, const std::string &optionsPath)
{
// Load the default options first.
const std::string defaultOptionsPath(basePath + "options/" + Options::DEFAULT_FILENAME);
this->options.loadDefaults(defaultOptionsPath);
// Check if the changes options file exists.
const std::string changesOptionsPath(optionsPath + Options::CHANGES_FILENAME);
if (!File::exists(changesOptionsPath.c_str()))
{
// Make one. Since the default options object has no changes, the new file will have
// no key-value pairs.
DebugLog("Creating options file at \"" + changesOptionsPath + "\".");
this->options.saveChanges();
}
else
{
// Read in any key-value pairs in the "changes" options file.
this->options.loadChanges(changesOptionsPath);
}
}
void Game::resizeWindow(int width, int height)
{
// Resize the window, and the 3D renderer if initialized.
const bool fullGameWindow = this->options.getGraphics_ModernInterface();
this->renderer.resize(width, height,
this->options.getGraphics_ResolutionScale(), fullGameWindow);
}
void Game::saveScreenshot(const Surface &surface)
{
// Get the path + filename to use for the new screenshot.
const std::string screenshotPath = []()
{
const std::string screenshotFolder = Platform::getScreenshotPath();
const std::string screenshotPrefix("screenshot");
int imageIndex = 0;
auto getNextAvailablePath = [&screenshotFolder, &screenshotPrefix, &imageIndex]()
{
std::stringstream ss;
ss << std::setw(3) << std::setfill('0') << imageIndex;
imageIndex++;
return screenshotFolder + screenshotPrefix + ss.str() + ".bmp";
};
std::string path = getNextAvailablePath();
while (File::exists(path.c_str()))
{
path = getNextAvailablePath();
}
return path;
}();
const int status = SDL_SaveBMP(surface.get(), screenshotPath.c_str());
if (status == 0)
{
DebugLog("Screenshot saved to \"" + screenshotPath + "\".");
}
else
{
DebugCrash("Failed to save screenshot to \"" + screenshotPath + "\": " +
std::string(SDL_GetError()));
}
}
void Game::handlePanelChanges()
{
// If a sub-panel pop was requested, then pop the top of the sub-panel stack.
if (this->requestedSubPanelPop)
{
this->subPanels.pop_back();
this->requestedSubPanelPop = false;
// Unpause the panel that is now the top-most one.
const bool paused = false;
this->getActivePanel()->onPauseChanged(paused);
}
// If a new sub-panel was requested, then add it to the stack.
if (this->nextSubPanel.get() != nullptr)
{
// Pause the top-most panel.
const bool paused = true;
this->getActivePanel()->onPauseChanged(paused);
this->subPanels.push_back(std::move(this->nextSubPanel));
}
// If a new panel was requested, switch to it. If it will be the active panel
// (i.e., there are no sub-panels), then subsequent events will be sent to it.
if (this->nextPanel.get() != nullptr)
{
this->panel = std::move(this->nextPanel);
}
}
void Game::handleEvents(bool &running)
{
// Handle events for the current game state.
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
// Application events and window resizes are handled here.
bool applicationExit = this->inputManager.applicationExit(e);
bool resized = this->inputManager.windowResized(e);
bool takeScreenshot = this->inputManager.keyPressed(e, SDLK_PRINTSCREEN);
if (applicationExit)
{
running = false;
}
if (resized)
{
int width = e.window.data1;
int height = e.window.data2;
this->resizeWindow(width, height);
// Call each panel's resize method. The panels should not be listening for
// resize events themselves because it's more of an "application event" than
// a panel event.
this->panel->resize(width, height);
for (auto &subPanel : this->subPanels)
{
subPanel->resize(width, height);
}
}
if (takeScreenshot)
{
// Save a screenshot to the local folder.
const auto &renderer = this->getRenderer();
const Surface screenshot = renderer.getScreenshot();
this->saveScreenshot(screenshot);
}
// Panel-specific events are handled by the active panel.
this->getActivePanel()->handleEvent(e);
// See if the event requested any changes in active panels.
this->handlePanelChanges();
}
}
void Game::tick(double dt)
{
// Tick the active panel.
this->getActivePanel()->tick(dt);
// See if the panel tick requested any changes in active panels.
this->handlePanelChanges();
}
void Game::render()
{
// Draw the panel's main content.
this->panel->render(this->renderer);
// Draw any sub-panels back to front.
for (auto &subPanel : this->subPanels)
{
subPanel->render(this->renderer);
}
// Call the active panel's secondary render method. Secondary render items are those
// that are hidden on panels below the active one.
Panel *activePanel = this->getActivePanel();
activePanel->renderSecondary(this->renderer);
// Get the active panel's cursor texture and alignment.
const Panel::CursorData cursor = activePanel->getCurrentCursor();
// Draw cursor if not null. Some panels do not define a cursor (like cinematics),
// so their cursor is always null.
if (cursor.getTexture() != nullptr)
{
// The panel should not be drawing the cursor themselves. It's done here
// just to make sure that the cursor is drawn only once and is always drawn last.
this->renderer.drawCursor(*cursor.getTexture(), cursor.getAlignment(),
this->inputManager.getMousePosition(), this->options.getGraphics_CursorScale());
}
this->renderer.present();
}
void Game::loop()
{
// Nanoseconds per second. Only using this much precision because it's what
// high_resolution_clock gives back. Microseconds would be fine too.
constexpr int64_t timeUnits = 1000000000;
// Longest allowed frame time.
const std::chrono::duration<int64_t, std::nano> maxFrameTime(timeUnits / Options::MIN_FPS);
// On some platforms, thread sleeping takes longer than it should, so include a value to
// help compensate.
std::chrono::nanoseconds sleepBias(0);
auto thisTime = std::chrono::high_resolution_clock::now();
// Primary game loop.
bool running = true;
while (running)
{
const auto lastTime = thisTime;
thisTime = std::chrono::high_resolution_clock::now();
// Shortest allowed frame time.
const std::chrono::duration<int64_t, std::nano> minFrameTime(
timeUnits / this->options.getGraphics_TargetFPS());
// Time since the last frame started.
const auto frameTime = [minFrameTime, &sleepBias, &thisTime, lastTime]()
{
// Delay the current frame if the previous one was too fast.
auto diff = thisTime - lastTime;
if (diff < minFrameTime)
{
const auto sleepTime = minFrameTime - diff + sleepBias;
std::this_thread::sleep_for(sleepTime);
// Compensate for sleeping too long. Thread sleeping has questionable accuracy.
const auto tempTime = std::chrono::high_resolution_clock::now();
const auto unnecessarySleepTime = [thisTime, sleepTime, tempTime]()
{
const auto tempFrameTime = tempTime - thisTime;
return tempFrameTime - sleepTime;
}();
sleepBias = -unnecessarySleepTime;
thisTime = tempTime;
diff = thisTime - lastTime;
}
return diff;
}();
// Two delta times: actual and clamped. Use the clamped delta time for game calculations
// so things don't break at low frame rates.
constexpr double timeUnitsReal = static_cast<double>(timeUnits);
const double dt = static_cast<double>(frameTime.count()) / timeUnitsReal;
const double clampedDt = std::fmin(frameTime.count(), maxFrameTime.count()) / timeUnitsReal;
// Reset scratch allocator for use with this frame.
this->scratchAllocator.clear();
// Update the input manager's state.
this->inputManager.update();
// Update the audio manager listener (if any) and check for finished sounds.
if (this->gameDataIsActive())
{
const AudioManager::ListenerData listenerData = [this]()
{
const Player &player = this->getGameData().getPlayer();
const Double3 &position = player.getPosition();
const Double3 &direction = player.getDirection();
return AudioManager::ListenerData(position, direction);
}();
this->audioManager.update(dt, &listenerData);
}
else
{
this->audioManager.update(dt, nullptr);
}
// Update FPS counter.
this->fpsCounter.updateFrameTime(dt);
// Listen for input events.
try
{
this->handleEvents(running);
}
catch (const std::exception &e)
{
DebugCrash("handleEvents() exception! " + std::string(e.what()));
}
// Animate the current game state by delta time.
try
{
// Multiply delta time by the time scale. I settled on having the effects of this
// be application-wide rather than just in the game world since it's intended to
// simulate lower DOSBox cycles.
const double timeScaledDt = clampedDt * this->options.getMisc_TimeScale();
this->tick(timeScaledDt);
}
catch (const std::exception &e)
{
DebugCrash("tick() exception! " + std::string(e.what()));
}
// Draw to the screen.
try
{
this->render();
}
catch (const std::exception &e)
{
DebugCrash("render() exception! " + std::string(e.what()));
}
}
// At this point, the program has received an exit signal, and is now
// quitting peacefully.
this->options.saveChanges();
}
| 29.250865 | 99 | 0.71497 | Digital-Monk |
d913cf8009db59777cb25dd5b9ffb58230955898 | 856 | hpp | C++ | env/message_list.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 61 | 2015-12-05T19:34:20.000Z | 2021-06-25T09:07:09.000Z | env/message_list.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 9 | 2016-02-19T23:22:20.000Z | 2017-01-03T18:41:04.000Z | env/message_list.hpp | mapsme/travelguide | 26dd50b93f55ef731175c19d12514da5bace9fa4 | [
"Apache-2.0"
] | 35 | 2015-12-17T00:09:14.000Z | 2021-01-27T10:47:11.000Z | #pragma once
#include "strings.hpp"
#include "message_std.hpp"
namespace msg
{
inline string ToString(char const * s) { return s; }
/// Override ToString function for your custom class in it's namespace.
/// Your function will be called according to the ADL lookup.
/// This is the default "last chance" implementation.
template <class T>
inline string ToString(T const & t)
{
return str::ToString(t);
}
inline string MessageList()
{
return string();
}
template <class T1>
inline string MessageList(T1 const & t1)
{
return ToString(t1);
}
template <class T1, class T2>
inline string MessageList(T1 const & t1, T2 const & t2)
{
return ToString(t1) + " " + ToString(t2);
}
template <class T1, class T2, class T3>
inline string MessageList(T1 const & t1, T2 const & t2, T3 const & t3)
{
return MessageList(t1, t2) + " " + ToString(t3);
}
}
| 19.454545 | 71 | 0.696262 | mapsme |
d9148fb579e05a5f56eef4b51b873bc619bf2c09 | 1,645 | cpp | C++ | src/armnn/layers/MemImportLayer.cpp | UberLambda/armnn | ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a | [
"MIT"
] | null | null | null | src/armnn/layers/MemImportLayer.cpp | UberLambda/armnn | ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a | [
"MIT"
] | null | null | null | src/armnn/layers/MemImportLayer.cpp | UberLambda/armnn | ba163f93c8a0e858c9fb1ea85e4ac34c966ef38a | [
"MIT"
] | null | null | null | //
// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "MemImportLayer.hpp"
#include "LayerCloneBase.hpp"
#include <armnn/TypesUtils.hpp>
#include <backendsCommon/WorkloadData.hpp>
#include <backendsCommon/WorkloadFactory.hpp>
#include <backendsCommon/MemImportWorkload.hpp>
namespace armnn
{
MemImportLayer::MemImportLayer(const char* name)
: Layer(1, 1, LayerType::MemImport, name)
{
}
MemImportLayer* MemImportLayer::Clone(Graph& graph) const
{
return CloneBase<MemImportLayer>(graph, GetName());
}
std::unique_ptr<IWorkload> MemImportLayer::CreateWorkload(const IWorkloadFactory& factory) const
{
IgnoreUnused(factory);
MemImportQueueDescriptor descriptor;
//This is different from other workloads. Does not get created by the workload factory.
return std::make_unique<ImportMemGenericWorkload>(descriptor, PrepInfoAndDesc(descriptor));
}
void MemImportLayer::ValidateTensorShapesFromInputs()
{
VerifyLayerConnections(1, CHECK_LOCATION());
const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape();
VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod);
auto inferredShapes = InferOutputShapes({ GetInputSlot(0).GetConnection()->GetTensorInfo().GetShape() });
ARMNN_ASSERT(inferredShapes.size() == 1);
ValidateAndCopyShape(outputShape, inferredShapes[0], m_ShapeInferenceMethod, "MemImportLayer");
}
void MemImportLayer::Accept(ILayerVisitor& visitor) const
{
IgnoreUnused(visitor);
throw armnn::Exception("MemImportLayer should not appear in an input graph");
}
} // namespace armnn
| 28.362069 | 109 | 0.768997 | UberLambda |
d9150cc66db91b2e7def973f1b5f6bcf9b967920 | 667 | hpp | C++ | Murat/src/core/LayerStack.hpp | dilmuratjohn/openglTutorial-cpp | 98b524db0c0f13fa9166a13e252777bee8ec60cd | [
"Apache-2.0"
] | null | null | null | Murat/src/core/LayerStack.hpp | dilmuratjohn/openglTutorial-cpp | 98b524db0c0f13fa9166a13e252777bee8ec60cd | [
"Apache-2.0"
] | null | null | null | Murat/src/core/LayerStack.hpp | dilmuratjohn/openglTutorial-cpp | 98b524db0c0f13fa9166a13e252777bee8ec60cd | [
"Apache-2.0"
] | null | null | null | //
// Created by murat on 2019-08-09.
//
#ifndef M_LAYER_STACK_HPP
#define M_LAYER_STACK_HPP
#include "Layer.hpp"
#include <muratpch.hpp>
namespace Murat {
class LayerStack {
public:
LayerStack();
~LayerStack();
void pushLayer(Layer *layer);
void pushOverlay(Layer *overlay);
void popLayer(Layer *layer);
void popOverlay(Layer *overlay);
std::vector<Layer *>::iterator begin() { return m_Layers.begin(); }
std::vector<Layer *>::iterator end() { return m_Layers.end(); }
private:
std::vector<Layer *> m_Layers;
unsigned int m_LayerInsertIndex = 0;
};
}
#endif | 18.027027 | 75 | 0.611694 | dilmuratjohn |
d91a238a3c440aa54ae9f3d30e36724a5c777042 | 1,971 | cpp | C++ | bezGameEngine/src/bez/Events/MouseEvent.cpp | Gustvo/bezGameEngine | 8d0ac4613d1a1aac65cab51d337b9a77d56f29ec | [
"MIT"
] | null | null | null | bezGameEngine/src/bez/Events/MouseEvent.cpp | Gustvo/bezGameEngine | 8d0ac4613d1a1aac65cab51d337b9a77d56f29ec | [
"MIT"
] | null | null | null | bezGameEngine/src/bez/Events/MouseEvent.cpp | Gustvo/bezGameEngine | 8d0ac4613d1a1aac65cab51d337b9a77d56f29ec | [
"MIT"
] | null | null | null | #include <stdafx.hpp>
#include <bez/Events/MouseEvent.hpp>
namespace bez {
/// Mouse Motion Event
MouseMotionEvent::MouseMotionEvent(float x, float y) {
m_mouseCoordinates = std::make_pair(x, y);
registerInput(std::make_pair(x, y));
};
std::string MouseMotionEvent::toString() const {
std::stringstream ss;
ss << "MouseMoved: [" << m_mouseCoordinates.first << " : "
<< m_mouseCoordinates.second << "]";
return ss.str();
}
void MouseMotionEvent::registerInput(std::pair<float, float> p_mousePosition) {
Input::registerMousePosition(p_mousePosition);
}
/// Mouse Button Event
MouseButtonEvent::MouseButtonEvent(MouseButton p_button) {
m_button = p_button;
}
/// Mouse Button Pressed Event
MouseButtonPressedEvent::MouseButtonPressedEvent(MouseButton p_button)
: MouseButtonEvent(p_button) {
registerInput(p_button);
}
std::string MouseButtonPressedEvent::toString() const {
std::stringstream ss;
ss << "MouseButtonPressed: " << m_button;
return ss.str();
}
void MouseButtonPressedEvent::registerInput(MouseButton p_button) {
Input::registerMouseButton(p_button, true);
}
/// Mouse Button Release Event
MouseButtonReleasedEvent::MouseButtonReleasedEvent(MouseButton p_button)
: MouseButtonEvent(p_button) {
registerInput(p_button);
}
std::string MouseButtonReleasedEvent::toString() const {
std::stringstream ss;
ss << "MouseButtonReleased: " << m_button;
return ss.str();
}
void MouseButtonReleasedEvent::registerInput(MouseButton p_button) {
Input::registerMouseButton(p_button, false);
}
/// Mouse Wheel Event
MouseWheelEvent::MouseWheelEvent(std::pair<int, int> p_direction) {
m_direction = p_direction;
}
std::pair<int, int> MouseWheelEvent::getDirection() { return m_direction; }
std::string MouseWheelEvent::toString() const {
std::stringstream ss;
ss << "MouseWheelEvent - [x, y] = [" << m_direction.first << ", "
<< m_direction.second << "]";
return ss.str();
}
} // namespace bez | 23.464286 | 79 | 0.726027 | Gustvo |
d91c0500122a7a3f3517f87c43aff269db2af384 | 162 | hpp | C++ | WinApiFramework/OpenGL/Surface3.hpp | TonSharp/OpenWAPI | d61a8f006ea866c399e68f338c2661e9ef624369 | [
"MS-PL"
] | 3 | 2021-09-17T07:54:28.000Z | 2021-09-18T08:28:33.000Z | WinApiFramework/OpenGL/Surface3.hpp | TonSharp/WAPITIS | d61a8f006ea866c399e68f338c2661e9ef624369 | [
"MS-PL"
] | 21 | 2021-09-19T18:13:55.000Z | 2021-12-14T10:28:53.000Z | WinApiFramework/OpenGL/Surface3.hpp | TonSharp/OpenWAPI | d61a8f006ea866c399e68f338c2661e9ef624369 | [
"MS-PL"
] | null | null | null | #pragma once
#include <vector>
#include "GLContext.hpp"
using namespace std;
struct Surface3
{
Vertex normal;
Vertex points[3];
TextureCoord texCoords[3];
}; | 13.5 | 27 | 0.740741 | TonSharp |
d91cf6b58e0d9ef32c0b2003e5ae0186af652950 | 4,819 | cpp | C++ | src/libQts/QtsTimeStamper.cpp | qtlmovie/qtlmovie | 082ad5ea6522a02d5ac0d86f23cdd6152edff613 | [
"BSD-2-Clause"
] | 8 | 2016-08-09T14:05:58.000Z | 2020-09-05T14:43:36.000Z | src/libQts/QtsTimeStamper.cpp | qtlmovie/qtlmovie | 082ad5ea6522a02d5ac0d86f23cdd6152edff613 | [
"BSD-2-Clause"
] | 15 | 2016-08-09T14:11:21.000Z | 2022-01-15T23:39:07.000Z | src/libQts/QtsTimeStamper.cpp | qtlmovie/qtlmovie | 082ad5ea6522a02d5ac0d86f23cdd6152edff613 | [
"BSD-2-Clause"
] | 1 | 2017-08-26T22:08:58.000Z | 2017-08-26T22:08:58.000Z | //----------------------------------------------------------------------------
//
// Copyright (c) 2013-2017, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
//----------------------------------------------------------------------------
//
// Qts, the Qt MPEG Transport Stream library.
// Define the class QtsTimeStamper.
//
//----------------------------------------------------------------------------
#include "QtsTimeStamper.h"
//----------------------------------------------------------------------------
// Construction and reset.
//----------------------------------------------------------------------------
QtsTimeStamper::QtsTimeStamper(const QtsDemux* demux) :
_demux(demux)
{
reset();
}
void QtsTimeStamper::reset()
{
_pid = QTS_PID_NULL;
_source = UNDEFINED;
_lastTimeStamp = 0;
_previousClock = 0;
_delta = 0;
}
void QtsTimeStamper::setDemux(const QtsDemux* demux)
{
if (_demux != demux) {
_demux = demux;
if (_source == PCR) {
reset();
}
}
}
//----------------------------------------------------------------------------
// Process a new clock value in millisecond.
//----------------------------------------------------------------------------
void QtsTimeStamper::processClock(qint64 clock)
{
if (_source == UNDEFINED) {
// Source not yet set. The first timestamp is zero by definition.
// The first clock value shall be substracted to all subsequent clock values.
_delta = -clock;
}
else if (clock < _previousClock) {
// Our clock has wrapped up after the max value.
// The clock has restarted at zero and we must add the last
// time stamp before wrapping to all subsequent clock values.
_delta = _lastTimeStamp;
}
_lastTimeStamp = qMax<qint64>(0, clock + _delta);
_previousClock = clock;
}
//----------------------------------------------------------------------------
// Get the last timestamp in milliseconds, starting with zero.
//----------------------------------------------------------------------------
quint64 QtsTimeStamper::lastTimeStamp()
{
if ((_source == UNDEFINED || _source == PCR) && _demux != 0) {
const qint64 pcr = _demux->lastPcr();
if (pcr >= 0) {
// If previously undefined, our source is now PCR.
processClock(pcr / (QTS_SYSTEM_CLOCK_FREQ / 1000));
_source = PCR;
}
else {
// If previously PCR, our source is now undefined (problably a demux reset).
_source = UNDEFINED;
}
}
return _lastTimeStamp;
}
//----------------------------------------------------------------------------
// Process one PES packet from the reference PID.
//----------------------------------------------------------------------------
void QtsTimeStamper::processPesPacket(const QtsPesPacket& packet)
{
// If our source is PCR, we ignore all PES packets.
// If the packet has no PTS, it is useless anyway.
if (_source == PCR || !packet.hasPts()) {
return;
}
// Check or set the PID.
if (_pid == QTS_PID_NULL) {
_pid = packet.getSourcePid();
}
else if (packet.getSourcePid() != QTS_PID_NULL && packet.getSourcePid() != _pid) {
// Not the same PID, reject this packet.
return;
}
// We have a PTS on the right PID, PTS will now be our source (if not already).
processClock(packet.getPts() / (QTS_SYSTEM_CLOCK_SUBFREQ / 1000));
_source = PTS;
}
| 35.696296 | 88 | 0.550322 | qtlmovie |
0ba804d2e7625df0820087d850d2a864b2cf2882 | 16,584 | cpp | C++ | src/Window.cpp | Lehdari/evolution_simulator_2 | daf7e8699e29cc25964f3a4234e3a1385ee7b1cf | [
"CC0-1.0"
] | null | null | null | src/Window.cpp | Lehdari/evolution_simulator_2 | daf7e8699e29cc25964f3a4234e3a1385ee7b1cf | [
"CC0-1.0"
] | null | null | null | src/Window.cpp | Lehdari/evolution_simulator_2 | daf7e8699e29cc25964f3a4234e3a1385ee7b1cf | [
"CC0-1.0"
] | null | null | null | //
// Project: evolution_simulator_2
// File: Window.cpp
//
// Copyright (c) 2021 Miika 'Lehdari' Lehtimäki
// You may use, distribute and modify this code under the terms
// of the licence specified in file LICENSE which is distributed
// with this source code package.
//
#include <Window.hpp>
#include <Utils.hpp>
#include <Genome.hpp>
#include <CreatureComponent.hpp>
#include <FoodComponent.hpp>
#include <WorldSingleton.hpp>
#include <ConfigSingleton.hpp>
#include <LineSingleton.hpp>
#include <ResourceSingleton.hpp>
#include <MapSingleton.hpp>
#include <EventHandlers.hpp>
#include <imgui.h>
#include <backends/imgui_impl_sdl.h>
#include <backends/imgui_impl_opengl3.h>
#include <engine/LogicComponent.hpp>
#include <engine/EventComponent.hpp>
#include <graphics/SpriteSingleton.hpp>
Window::Window(
const Window::Settings &settings
) :
_settings (settings),
_window (nullptr),
_quit (false),
_paused (false),
_viewport (_settings.window.width, _settings.window.height,
Vec2f(_settings.window.width*0.5f, _settings.window.height*0.5f), 32.0f),
_cursorPosition (0.0f, 0.0f),
_activeCreature (-1),
_activeCreatureFollow (false),
_lastTicks (0),
_frameTicks (0),
_windowContext (*this),
_eventSystem (_ecs),
_creatureSystem (_ecs),
_foodSystem (_ecs),
_collisionSystem (_ecs, _eventSystem),
_spriteSystem (_ecs),
_spriteSheetId (-1)
{
int err;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Error: Could not initialize SDL!\n");
return;
}
_window = SDL_CreateWindow(
_settings.window.name.c_str(),
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
(int)_settings.window.width,
(int)_settings.window.height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
if (_window == nullptr) {
printf("Error: SDL Window could not be created! SDL_Error: %s\n", SDL_GetError());
return;
}
// Initialize OpenGL
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, _settings.gl.contextMajor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, _settings.gl.contextMinor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, _settings.gl.contextFlags);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, _settings.gl.profileMask);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, _settings.gl.doubleBuffer);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
_glCtx = SDL_GL_CreateContext(_window);
if (_glCtx == nullptr) {
printf("Error: SDL OpenGL context could not be created! SDL_Error: %s\n",
SDL_GetError());
return;
}
// Load OpenGL extensions
if (!gladLoadGL()) {
printf("Error: gladLoadGL failed\n");
return;
}
// Initialize OpenGL
glViewport(0, 0, _settings.window.width, _settings.window.height);
glClearColor(0.2f, 0.2f, 0.2f, 1.f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Initialize ImGui
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui_ImplSDL2_InitForOpenGL(_window, _glCtx);
ImGui_ImplOpenGL3_Init("#version 420");
// Initialize world
init();
}
Window::~Window()
{
// Destroy window and quit SDL subsystems
SDL_GL_DeleteContext(_glCtx);
SDL_DestroyWindow(_window);
SDL_Quit();
}
void Window::init(void)
{
_ecs.getSingleton<fug::SpriteSingleton>()->init();
_ecs.getSingleton<fug::SpriteSingleton>()->setWindowSize(
(int)_settings.window.width, (int)_settings.window.height);
_spriteSheetId = _ecs.getSingleton<fug::SpriteSingleton>()->addSpriteSheetFromFile(
EVOLUTION_SIMULATOR_RES("sprites/sprites.png"), 128, 128);
_ecs.getSingleton<LineSingleton>()->init();
_ecs.getSingleton<LineSingleton>()->setWindowSize(
(int)_settings.window.width, (int)_settings.window.height);
_ecs.getSingleton<ResourceSingleton>()->init(_spriteSheetId);
_ecs.getSingleton<MapSingleton>();
fug::SpriteComponent creatureSpriteComponent(_spriteSheetId, 0);
creatureSpriteComponent.setOrigin(Vec2f(ConfigSingleton::spriteRadius, ConfigSingleton::spriteRadius));
fug::SpriteComponent foodSpriteComponent(_spriteSheetId, 1);
foodSpriteComponent.setOrigin(Vec2f(ConfigSingleton::spriteRadius, ConfigSingleton::spriteRadius));
foodSpriteComponent.setColor(Vec3f(0.2f, 0.6f, 0.0f));
auto& config = *_ecs.getSingleton<ConfigSingleton>();
auto& map = *_ecs.getSingleton<MapSingleton>();
// Create creatures
constexpr int nCreatures = 2000;
for (int i=0; i<nCreatures; ++i) {
// get position using rejection sampling
Vec2f p(RNDS*1024.0f, RNDS*1024.0f);
while (gauss2(p, 256.0f) < RND)
p << RNDS*1024.0f, RNDS*1024.0f;
double mass = ConfigSingleton::minCreatureMass + RND*(
ConfigSingleton::maxCreatureMass-ConfigSingleton::minCreatureMass);
createCreature(_ecs, Genome(), mass, 1.0, p, RND*M_PI*2.0f, RND);
}
// Create food
constexpr int nFoods = 5000;
auto foodPositions = map.sampleFertility(nFoods);
for (auto& p : foodPositions) {
double mass = RNDRANGE(ConfigSingleton::minFoodMass, ConfigSingleton::maxFoodMass);
createFood(_ecs, FoodComponent::Type::PLANT, mass, p);
}
}
void Window::loop(void)
{
auto& map = *_ecs.getSingleton<MapSingleton>();
// Application main loop
while (!_quit) {
// Event handling
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
handleEvent(event);
}
// Render
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (!_paused)
updateWorld();
_creatureSystem.setStage(CreatureSystem::Stage::PROCESS_INPUTS);
_ecs.runSystem(_creatureSystem);
updateGUI();
// Render world
map.render(_viewport);
_ecs.runSystem(_spriteSystem);
_ecs.getSingleton<fug::SpriteSingleton>()->render(_viewport);
_ecs.getSingleton<LineSingleton>()->render(_viewport);
// Render ImGui
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Swap draw and display buffers
SDL_GL_SwapWindow(_window);
if (!_paused) {
// Map update (GPGPU pass)
map.diffuseFertility();
}
uint32_t curTicks = SDL_GetTicks();
_frameTicks = curTicks - _lastTicks;
_lastTicks = curTicks;
}
}
void Window::handleEvent(SDL_Event& event)
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
switch (event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_CLOSE:
_quit = true;
break;
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
_quit = true;
break;
case SDLK_PAUSE:
_paused = !_paused;
break;
case SDLK_F12:
SDL_SetWindowFullscreen(_window, SDL_GetWindowFlags(_window) ^ SDL_WINDOW_FULLSCREEN);
break;
}
case SDL_MOUSEWHEEL:
_viewport.zoom(std::pow(1.414213562373f, (float)event.wheel.y), _cursorPosition);
break;
case SDL_MOUSEMOTION:
_cursorPosition << (float)event.motion.x, (float)event.motion.y;
break;
case SDL_MOUSEBUTTONDOWN:
switch (event.button.button) {
case SDL_BUTTON_LEFT: {
Vec2f clickWorldPos = _viewport.toWorld(_cursorPosition);
static Vec2f maxRadiusVec(
ConfigSingleton::maxObjectRadius, ConfigSingleton::maxObjectRadius);
// Find the clicked creature (if any)
Vector<fug::EntityId> entities;
world.getEntities(entities, clickWorldPos-maxRadiusVec, clickWorldPos+maxRadiusVec);
for (auto& eId : entities) {
if (_ecs.getComponent<FoodComponent>(eId) != nullptr)
continue;
auto* oc = _ecs.getComponent<fug::Orientation2DComponent>(eId);
if ((oc->getPosition()-clickWorldPos).norm() <
oc->getScale()*ConfigSingleton::spriteRadius) {
_activeCreature = eId;
break;
}
}
} break;
}
}
}
void Window::updateGUI()
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
static auto& config = *_ecs.getSingleton<ConfigSingleton>();
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(_window);
ImGui::NewFrame();
{ // Main simulation controls
ImGui::Begin("Simulation Controls");
auto nCreatures = world.getNumberOf(WorldSingleton::EntityType::CREATURE);
auto nFood = world.getNumberOf(WorldSingleton::EntityType::FOOD);
ImGui::Text("N. Creatures: %lu\n", nCreatures);
ImGui::Text("N. Food: %lu\n", nFood);
ImGui::Checkbox("Paused", &_paused);
if (ImGui::CollapsingHeader("Food Controls")) {
static double foodPerTickMin = 0.001;
static double foodPerTickMax = 100.0;
ImGui::SliderScalar("foodPerTick", ImGuiDataType_Double, &config.foodPerTick,
&foodPerTickMin, &foodPerTickMax, "%.5f", ImGuiSliderFlags_Logarithmic);
static double foodGrowthRateMin = 0.0001;
static double foodGrowthRateMax = 0.1;
ImGui::SliderScalar("foodGrowthRate", ImGuiDataType_Double, &config.foodGrowthRate,
&foodGrowthRateMin, &foodGrowthRateMax, "%.5f", ImGuiSliderFlags_Logarithmic);
}
// mutation menu
if (ImGui::CollapsingHeader("Mutation")) {
// slider bounds and drop menu item names
static const float probabilityBounds[2] = { 0.0001f, 1.0f };
static const float amplitudeBounds[2] = { 0.0001f, 1.0f };
static const char* modeTitles[] = { "Additive", "Multiplicative" };
ImGui::Indent();
int stageId = 0;
// list all stages
for (auto stageIt = config.mutationStages.begin(); stageIt < config.mutationStages.end(); ++stageIt) {
auto& stage = *stageIt;
std::stringstream stageName;
stageName << "Stage " << ++stageId;
bool stageEnabled = true; // the following CollapsingHeader will set this to false to signify stage deletion
if (ImGui::CollapsingHeader(stageName.str().c_str(), &stageEnabled)) {
// element names
std::stringstream probabilityName, amplitudeName, modeName;
probabilityName << "Probability##evolution" << stageId;
amplitudeName << "Amplitude##evolution" << stageId;
modeName << "Mode##evolution" << stageId;
// sliders for probability and amplitude
ImGui::SliderScalar(probabilityName.str().c_str(), ImGuiDataType_Float, &stage.probability,
probabilityBounds, probabilityBounds+1, "%.5f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderScalar(amplitudeName.str().c_str(), ImGuiDataType_Float, &stage.amplitude,
amplitudeBounds, amplitudeBounds+1, "%.5f", ImGuiSliderFlags_Logarithmic);
// drop menu for the mutation mode
const char* currentModeTitle = modeTitles[stage.mode];
if (ImGui::BeginCombo(modeName.str().c_str(), currentModeTitle)) {
for (int n = 0; n < IM_ARRAYSIZE(modeTitles); n++)
{
bool isSelected = (currentModeTitle == modeTitles[n]);
if (ImGui::Selectable(modeTitles[n], isSelected))
stage.mode = static_cast<Genome::MutationMode>(n);
if (isSelected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
}
// stage is deleted
if (!stageEnabled)
stageIt = config.mutationStages.erase(stageIt);
}
// button for adding new stages
if (ImGui::Button("Add Stage")) {
config.mutationStages.emplace_back(0.1f, 0.1f, Genome::MutationMode::ADDITIVE);
}
ImGui::Unindent();
}
ImGui::End();
}
if (_activeCreature >= 0) {
// Selected creature controls
auto* cc = _ecs.getComponent<CreatureComponent>(_activeCreature);
auto* oc = _ecs.getComponent<fug::Orientation2DComponent>(_activeCreature);
auto* sc = _ecs.getComponent<fug::SpriteComponent>(_activeCreature);
if (cc != nullptr && sc != nullptr) {
ImGui::Begin("Creature");
ImGui::Text("Creature %lu", _activeCreature);
ImGui::Text("Energy: %0.5f", cc->energy);
ImGui::Checkbox("Follow", &_activeCreatureFollow);
if (_activeCreatureFollow)
_viewport.centerTo(oc->getPosition());
Vec3f color = sc->getColor();
ImGui::ColorPicker3("Creature color", color.data());
sc->setColor(color);
ImGui::End();
}
else // creature has been removed
_activeCreature = -1;
}
}
void Window::updateWorld(void)
{
static auto& world = *_ecs.getSingleton<WorldSingleton>();
static auto& config = *_ecs.getSingleton<ConfigSingleton>();
static auto& map = *_ecs.getSingleton<MapSingleton>();
// initiate pixel data transfer from GPU
map.prefetch();
_creatureSystem.setStage(CreatureSystem::Stage::COGNITION);
_ecs.runSystem(_creatureSystem);
_creatureSystem.setStage(CreatureSystem::Stage::DYNAMICS);
_ecs.runSystem(_creatureSystem);
// map the pixel data memory
map.map();
if (_activeCreature >= 0 && _ecs.getComponent<CreatureComponent>(_activeCreature) == nullptr)
_activeCreature = -1;
_creatureSystem.setStage(CreatureSystem::Stage::REPRODUCTION);
_ecs.runSystem(_creatureSystem);
{ // Create new food
static double nNewFood = 0.0;
nNewFood += config.foodPerTick;
auto foodPositions = map.sampleFertility((int)nNewFood);
for (auto& p : foodPositions) {
createFood(_ecs, FoodComponent::Type::PLANT, ConfigSingleton::minFoodMass, p);
}
nNewFood -= (int)nNewFood;
}
if (world.getNumberOf(WorldSingleton::EntityType::CREATURE) < 1000) {
for (int i = 0l; i < 1000; ++i) { // create a new creatures
if (RND > 0.0001) continue;
Vec2f p(RNDS * 1024.0f, RNDS * 1024.0f);
while (gauss2(p, 256.0f) < RND)
p << RNDS * 1024.0f, RNDS * 1024.0f;
double mass = ConfigSingleton::minCreatureMass + RND * (
ConfigSingleton::maxCreatureMass - ConfigSingleton::minCreatureMass);
createCreature(_ecs, Genome(1.0f, RNDRANGE(0.001f, 0.005f)),
mass, 1.0, p, RND * M_PI * 2.0f, RND);
}
}
_foodSystem.setStage(FoodSystem::Stage::GROW);
_ecs.runSystem(_foodSystem);
// unmap the pixel data memory
map.unmap();
addEntitiesToWorld();
_ecs.runSystem(_collisionSystem);
while (_eventSystem.swap())
_ecs.runSystem(_eventSystem);
addEntitiesToWorld();
}
void Window::addEntitiesToWorld(void)
{
_ecs.getSingleton<WorldSingleton>()->reset();
_creatureSystem.setStage(CreatureSystem::Stage::ADD_TO_WORLD);
_ecs.runSystem(_creatureSystem);
_foodSystem.setStage(FoodSystem::Stage::ADD_TO_WORLD);
_ecs.runSystem(_foodSystem);
}
| 35.435897 | 124 | 0.599855 | Lehdari |
0ba807b6f8d1c0b61363c1a49e899c37fdbce4e6 | 19,035 | cpp | C++ | plugin_cssrpg/cssrpg_misc.cpp | jameslk/cssrpg-archive | fecf7b04db3eb2edeb741cd379c0233229d38e1c | [
"Unlicense",
"MIT"
] | null | null | null | plugin_cssrpg/cssrpg_misc.cpp | jameslk/cssrpg-archive | fecf7b04db3eb2edeb741cd379c0233229d38e1c | [
"Unlicense",
"MIT"
] | null | null | null | plugin_cssrpg/cssrpg_misc.cpp | jameslk/cssrpg-archive | fecf7b04db3eb2edeb741cd379c0233229d38e1c | [
"Unlicense",
"MIT"
] | null | null | null | /*
# Copyright (c) 2005-2006 CSS:RPG Mod for Counter-Strike Source(TM) Developement Team
#
# zlib/libpng License
# This software is provided 'as-is', without any express or implied warranty. In no event
# will the authors be held liable for any damages arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose, including
# commercial applications, and to alter it and redistribute it freely, subject to the
# following restrictions:
# 1. The origin of this software must not be misrepresented; you must not claim that
# you wrote the original software. If you use this software in a product, an
# acknowledgment in the product documentation would be appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "interface.h"
#include "filesystem.h"
#include "engine/iserverplugin.h"
#include "engine/IEngineSound.h"
#include "dlls/iplayerinfo.h"
#include "eiface.h"
#include "convar.h"
#include "Color.h"
#include "vstdlib/random.h"
#include "engine/IEngineTrace.h"
#include "bitbuf.h"
#define GAME_DLL 1
#include "cbase.h"
#define GAME_DLL 1
#include "MRecipientFilter.h"
#include "MTraceFilterSimple.h"
#include "cssrpg.h"
#include "cssrpg_menu.h"
#include "cssrpg_textdb.h"
#include "cssrpg_misc.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
/* //////////////////////////////////////
CRPG_Utils Class
////////////////////////////////////// */
FILE* CRPG_Utils::dlog_fptr = NULL;
int CRPG_Utils::textmsg = -1;
int CRPG_Utils::hinttext = -1;
int CRPG_Utils::vguimenu = -1;
unsigned int CRPG_Utils::IsValidEdict(edict_t *e) {
if(e == NULL)
return 0;
if(s_engine->GetPlayerUserId(e) < 0)
return 0;
else
return 1;
}
unsigned int CRPG_Utils::IsValidIndex(int index) {
edict_t *e;
if((index < 0) || (index > maxClients()))
return 0;
e = s_engine->PEntityOfEntIndex(index);
if(s_engine->GetPlayerUserId(e) < 0)
return 0;
else
return 1;
}
int CRPG_Utils::UserIDtoIndex(int userid) {
edict_t *player;
IPlayerInfo *info;
for(int i = 1;i <= maxClients();i++) { //int maxplayers; has to be added after the includes and clientMax=maxplayers; in the ServerActivate function
player = s_engine->PEntityOfEntIndex(i);
if(!player || player->IsFree())
continue;
info = s_playerinfomanager->GetPlayerInfo(player);
if(info == NULL)
continue;
if(info->GetUserID() == userid)
return i;
}
ConsoleMsg("UserIDtoIndex failed", MTYPE_WARNING);
return -1;
}
edict_t* CRPG_Utils::UserIDtoEdict(int userid) {
edict_t *player;
IPlayerInfo *info;
int i;
for(i = 1;i <= maxClients();i++) { //int maxplayers; has to be added after the includes and clientMax=maxplayers; in the ServerActivate function
player = s_engine->PEntityOfEntIndex(i);
if(!player || player->IsFree())
continue;
info = s_playerinfomanager->GetPlayerInfo(player);
if(info == NULL)
continue;
if(info->GetUserID() == userid)
return player;
}
ConsoleMsg("UserIDtoEdict failed", MTYPE_WARNING);
return NULL;
}
int CRPG_Utils::UserMessageIndex(char *name) {
char cmpname[256];
int i, sizereturn = 0;
for(i = 1;i < 30;i++) {
s_gamedll->GetUserMessageInfo(i, cmpname, 256, sizereturn);
if(name && !strcmp(name, cmpname))
return i;
}
return -1;
}
int CRPG_Utils::FindPlayer(char *str) {
int userid = atoi(str), max = maxClients(), index = -1;
edict_t *player;
IPlayerInfo *info;
int i;
if(!userid) {
/* Search for player by name */
for(i = 1;i <= max;i++) {
player = s_engine->PEntityOfEntIndex(i);
if(!player || player->IsFree())
continue;
info = s_playerinfomanager->GetPlayerInfo(player);
if(info == NULL)
continue;
if(CRPG_Utils::istrcmp(str, (char*)info->GetNetworkIDString()))
return s_engine->IndexOfEdict(player);
else if(CRPG_Utils::istrstr((char*)info->GetName(), str) != NULL)
return s_engine->IndexOfEdict(player);
}
}
else {
/* Search for player by userid */
for(i = 1;i <= max;i++) {
player = s_engine->PEntityOfEntIndex(i);
if(!player || player->IsFree())
continue;
info = s_playerinfomanager->GetPlayerInfo(player);
if(info == NULL)
continue;
if(info->GetUserID() == userid)
return s_engine->IndexOfEdict(player);
}
}
return index;
}
void CRPG_Utils::ChatAreaMsg(int index, char *msgf, ...) {
MRecipientFilter filter;
char msg[1024];
bf_write *buffer;
va_list ap;
if (index > maxClients() || index < 0)
return ;
if (!index)
filter.AddAllPlayers();
else
filter.AddRecipient(index);
va_start(ap, msgf);
Q_vsnprintf(msg, 1024, msgf, ap);
va_end(ap);
sprintf(msg, "%s\n", msg);
buffer = s_engine->UserMessageBegin(static_cast<IRecipientFilter*>(&filter), textmsg);
buffer->WriteByte(3);
buffer->WriteString(msg);
s_engine->MessageEnd();
return ;
}
void CRPG_Utils::ChatAreaMsg(int index, unsigned int key_id, ...) {
CRPG_Player *player;
txtkey_t *key;
unsigned int i;
MRecipientFilter filter;
char msg[1024];
bf_write *buffer;
va_list ap;
if(index) {
player = IndextoRPGPlayer(index);
WARN_IF(player == NULL, return)
key = player->lang->IDtoKey(key_id);
WARN_IF(key == NULL, return)
va_start(ap, key_id);
Q_vsnprintf(msg, 1024, key->s, ap);
va_end(ap);
sprintf(msg, "%s\n", msg);
filter.AddRecipient(player->index);
buffer = s_engine->UserMessageBegin(static_cast<IRecipientFilter*>(&filter), textmsg);
buffer->WriteByte(3);
buffer->WriteString(msg);
s_engine->MessageEnd();
}
else {
i = CRPG_Player::player_count;
while(i--) {
if(CRPG_Player::players[i] != NULL) {
player = CRPG_Player::players[i];
key = player->lang->IDtoKey(key_id);
WARN_IF(key == NULL, return)
va_start(ap, key_id);
Q_vsnprintf(msg, 1024, key->s, ap);
va_end(ap);
sprintf(msg, "%s\n", msg);
filter.RemoveAllRecipients();
filter.AddRecipient(player->index);
buffer = s_engine->UserMessageBegin(static_cast<IRecipientFilter*>(&filter), textmsg);
buffer->WriteByte(3);
buffer->WriteString(msg);
s_engine->MessageEnd();
}
}
}
return ;
}
void CRPG_Utils::HintTextMsg(int index, char *msgf, ...) {
MRecipientFilter filter;
char msg[1024];
bf_write *buffer;
va_list ap;
if (index > maxClients() || index < 0)
return ;
if (!index)
filter.AddAllPlayers();
else
filter.AddRecipient(index);
va_start(ap, msgf);
Q_vsnprintf(msg, sizeof(msg)-1, msgf, ap);
va_end(ap);
buffer = s_engine->UserMessageBegin(static_cast<IRecipientFilter*>(&filter), hinttext);
buffer->WriteByte(-1);
buffer->WriteString(msg);
s_engine->MessageEnd();
return ;
}
void CRPG_Utils::EmitSound(int index, char *sound_path, float vol, CRPG_Player *follow) {
MRecipientFilter filter;
if (index > maxClients() || index < 0)
return ;
if (!index)
filter.AddAllPlayers();
else
filter.AddRecipient(index);
if(!s_esounds->IsSoundPrecached(sound_path))
s_esounds->PrecacheSound(sound_path, true);
if(follow == NULL)
s_esounds->EmitSound((IRecipientFilter&)filter, index, CHAN_AUTO,
sound_path, vol, 0);
else
s_esounds->EmitSound((IRecipientFilter&)filter, follow->index, CHAN_AUTO,
sound_path, vol, ATTN_NORM, 0, PITCH_NORM,
&follow->cbp()->m_vecAbsOrigin, //here
NULL, NULL, true, 0.0f, follow->index);
#pragma message("NOTICE: Implement offset here")
return ;
}
void CRPG_Utils::ShowMOTD(int index, char *title, char *msg, motd_type type, char *cmd) {
bf_write *buffer;
MRecipientFilter filter;
if(index > maxClients() || index < 0)
filter.AddAllPlayers();
else
filter.AddRecipient(index);
buffer = s_engine->UserMessageBegin(&filter, vguimenu);
buffer->WriteString("info");
buffer->WriteByte(1);
if(cmd != NULL)
buffer->WriteByte(4);
else
buffer->WriteByte(3);
buffer->WriteString("title");
buffer->WriteString(title);
buffer->WriteString("type");
switch(type) {
case motd_text:
buffer->WriteString("0"); //TYPE_TEXT = 0, just display this plain text
break;
case motd_index:
buffer->WriteString("1"); //TYPE_INDEX, lookup text & title in stringtable
break;
case motd_url:
buffer->WriteString("2"); //TYPE_URL, show this URL
break;
case motd_file:
buffer->WriteString("3"); //TYPE_FILE, show this local file
break;
}
buffer->WriteString("msg");
buffer->WriteString(msg);
if(cmd != NULL) {
buffer->WriteString("cmd");
buffer->WriteString(cmd); // exec this command if panel closed
}
s_engine->MessageEnd();
return ;
}
void CRPG_Utils::SetCheats(bool enable, bool temporary) {
static ConVar *cheats_cvar = (ConVar*)2;
static bool already_set = 0;
if(cheats_cvar == (ConVar*)2)
cheats_cvar = s_cvar->FindVar("sv_cheats");
WARN_IF(cheats_cvar == NULL, return)
if(enable) {
already_set = (char)cheats_cvar->GetBool();
cheats_cvar->m_nFlags &= ~FCVAR_NOTIFY;
cheats_cvar->SetValue(1);
}
else {
if(!temporary || !already_set) {
cheats_cvar->SetValue(0);
already_set = 0;
}
cheats_cvar->m_nFlags &= ~FCVAR_NOTIFY;
}
return ;
}
void CRPG_Utils::TraceLine(const Vector& vecAbsStart, const Vector& vecAbsEnd, unsigned int mask, const IHandleEntity *ignore, int collisionGroup, trace_t *ptr ) {
Ray_t ray;
MTraceFilterSimple traceFilter(ignore, collisionGroup);
ray.Init(vecAbsStart, vecAbsEnd);
s_enginetrace->TraceRay(ray, mask, &traceFilter, ptr);
return ;
}
void CRPG_Utils::ConsoleMsg(char *msgf, char *msg_type, ...) {
char msg[1024];
va_list ap;
unsigned int i = 0;
va_start(ap, msg_type);
Q_vsnprintf(msg, 1023, msgf, ap);
va_end(ap);
while(msg[i]) {
if(msg[i] == '\"') /* these are a no-no in a echo message */
msg[i] = '\'';
i++;
}
if(msg_type == NULL)
CRPG_Utils::snprintf(msg, 1023, "echo \"CSS:RPG Plugin: %s\"\n", msg);
else
CRPG_Utils::snprintf(msg, 1023, "echo \"CSS:RPG %s: %s\"\n", msg_type, msg);
s_engine->ServerCommand(msg);
return ;
}
void CRPG_Utils::DebugMsg(char *msgf, ...) {
char msg[1024];
va_list ap;
if(CRPG_GlobalSettings::debug_mode) {
va_start(ap, msgf);
Q_vsnprintf(msg, 1023, msgf, ap);
va_end(ap);
if(dlog_fptr) {
fprintf(dlog_fptr, "# %s\n", msg);
}
else {
dlog_fptr = fopen("cssrpg.log", "a");
if(dlog_fptr)
fprintf(dlog_fptr, "# %s\n", msg);
}
Msg("CSS:RPG Plugin: %s\n", msg);
}
return ;
}
void CRPG_Utils::DebugMsg(int nolog, char *msgf, ...) {
char msg[1024];
va_list ap;
if(CRPG_GlobalSettings::debug_mode) {
va_start(ap, msgf);
Q_vsnprintf(msg, 1023, msgf, ap);
va_end(ap);
Msg("CSS:RPG Plugin: %s\n", msg);
}
return ;
}
unsigned int CRPG_Utils::steamid_check(char *steamid) {
unsigned int repeats;
if(steamid == NULL)
return 0;
if(strlen(steamid) < 10)
return 0;
if(memcmp(steamid, "STEAM_", 6))
return 0;
steamid += 6;
for(repeats = 0;repeats < 3;repeats++) {
while(1) {
if(!*steamid) {
if(repeats != 2)
return 0;
else
break;
}
else if(isdigit(*steamid)) {
steamid++;
continue;
}
else if(*steamid == ':') {
steamid++;
break;
}
else {
return 0;
}
}
}
return 1;
}
/**
* @brief Convert an integer string to an unsigned long integer.
*/
unsigned long CRPG_Utils::atoul(char *str) {
int val = 0;
while((*str == ' ') || (*str == '\t'))
str++;
switch(*str) {
case '-':
case '+':
str++;
}
while(isdigit(*str))
val = (val*10) + (*str++ - '0');
return val;
}
/**
* @brief Convert a hex string to an unsigned long integer.
*/
unsigned long CRPG_Utils::hextoul(char *hex) {
int i, len;
unsigned long num = 0;
char chr;
len = strlen(hex);
for(i = 0;i < len;i++) {
if(i)
num <<= 4;
chr = toupper(hex[i]);
if(chr >= '0' && chr <= '9') /* Is this a number? */
num |= (chr - '0');
else if(chr >= 'A' && chr <= 'F') /* Between A and F */
num |= 10 + (chr - 'A');
else
return 0;
}
return num;
}
unsigned char* CRPG_Utils::ustrncpy(unsigned char *dest, const unsigned char *src, int len) {
while(len--)
dest[len] = src[len];
return dest;
}
unsigned int CRPG_Utils::istrcmp(char *str1, char *str2) {
unsigned int i, len1, len2;
if((str1 == NULL) || (str2 == NULL))
return 0;
if(!*str1 || !*str2)
return 0;
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 != len2)
return 0;
for(i = 0;i < len1;i++) {
if(tolower(str1[i]) != tolower(str2[i]))
return 0;
}
return 1;
}
/* Reverse compare */
unsigned int CRPG_Utils::memrcmp(void *mem_end1, void *mem_end2, size_t len) {
unsigned char *mem1 = (unsigned char*)mem_end1, *mem2 = (unsigned char*)mem_end2;
while(len--) {
if(*mem1-- != *mem2--)
return 0;
}
return 1;
}
char* CRPG_Utils::istrstr(char *str, char *substr) {
while(*str) {
if(tolower(*str++) == tolower(*substr)) {
if(!*++substr)
return str;
}
}
return NULL;
}
/* Non-retarded version of snprintf */
int CRPG_Utils::snprintf(char *buf, size_t buf_size, const char *format, ...) {
char *temp_buf;
int result;
va_list ap;
WARN_IF(buf == NULL, return 0)
temp_buf = (char*)calloc(buf_size, sizeof(char));
WARN_IF(temp_buf == NULL, return 0)
va_start(ap, format);
result = Q_vsnprintf(temp_buf, --buf_size, format, ap);
va_end(ap);
if(result < 1)
goto end;
strncpy(buf, temp_buf, buf_size);
buf[buf_size] = '\0';
end:
free(temp_buf);
return result;
}
unsigned int CRPG_Utils::traverse_dir(struct file_info &file, char *path, unsigned int position) {
#ifdef WIN32
char wc_path[MAX_PATH];
WIN32_FIND_DATA fdata;
HANDLE hfind;
unsigned int i = 0;
char *strptr;
CRPG_Utils::snprintf(wc_path, MAX_PATH-1, "%s*", path);
hfind = FindFirstFile(wc_path, &fdata);
if(hfind == INVALID_HANDLE_VALUE)
return 0;
memset(file.name, '\0', MAX_PATH);
memset(file.ext, '\0', MAX_PATH);
memset(file.fullpath, '\0', MAX_PATH);
do {
if(i++ == position) {
strncpy(file.name, fdata.cFileName, MAX_PATH-1);
CRPG_Utils::snprintf(file.fullpath, MAX_PATH-1, "%s%s", path, file.name);
if(!(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
file.type = file_normal;
strptr = strrchr(file.name, '.');
if(strptr != NULL)
strncpy(file.ext, strptr+1, MAX_PATH);
}
else {
file.type = file_dir;
}
FindClose(hfind);
return 1;
}
} while(FindNextFile(hfind, &fdata));
FindClose(hfind);
return END_OF_DIR;
#else
char filepath[MAX_PATH];
DIR *dirptr;
dirent *finfo;
struct stat buf;
unsigned int i = 0;
char *strptr;
dirptr = opendir(path);
if(dirptr == NULL)
return 0;
memset(file.name, '\0', MAX_PATH);
memset(file.ext, '\0', MAX_PATH);
memset(file.fullpath, '\0', MAX_PATH);
while((finfo = readdir(dirptr))) {
if(i++ == position) {
CRPG_Utils::snprintf(filepath, MAX_PATH, "%s%s", path, finfo->d_name);
if(stat(filepath, &buf))
return 0;
strncpy(file.name, finfo->d_name, MAX_PATH-1);
strcpy(file.fullpath, filepath);
if(!(buf.st_mode & S_IFDIR)) {
file.type = file_normal;
strptr = strrchr(file.name, '.');
if(strptr != NULL)
strncpy(file.ext, strptr+1, MAX_PATH);
}
else {
file.type = file_dir;
}
closedir(dirptr);
return 1;
}
}
closedir(dirptr);
return END_OF_DIR;
#endif
}
#ifdef WIN32
unsigned int CRPG_Utils::CreateThread(LPTHREAD_START_ROUTINE func, LPVOID param) {
DWORD thdId;
HANDLE thdHandle;
thdHandle = ::CreateThread(NULL, 0, func, param, 0, &thdId);
if(thdHandle == NULL) {
CRPG_Utils::DebugMsg("Failed to create new thread.");
return 0;
}
else {
CloseHandle(thdHandle);
}
return 1;
}
#else
unsigned int CRPG_Utils::CreateThread(void*(*func)(void*), void *param) {
pthread_t thread;
int retval;
retval = pthread_create(&thread, NULL, func, (void*)param);
if(retval != 0) {
CRPG_Utils::DebugMsg("Failed to create new thread.");
return 0;
}
return 1;
}
#endif
void CRPG_Utils::Init(void) {
textmsg = UserMessageIndex("TextMsg");
hinttext = UserMessageIndex("HintText");
vguimenu = UserMessageIndex("VGUIMenu");
return ;
}
void CRPG_Utils::ShutDown(void) {
if(dlog_fptr != NULL) {
fclose(dlog_fptr);
dlog_fptr = NULL;
}
return ;
}
/* //////////////////////////////////////
CRPG_Timer Class
////////////////////////////////////// */
template class CRPG_StaticLinkedList<CRPG_Timer>;
template<> CRPG_Timer* CRPG_StaticLinkedList<CRPG_Timer>::ll_first;
template<> CRPG_Timer* CRPG_StaticLinkedList<CRPG_Timer>::ll_last;
template<> unsigned int CRPG_StaticLinkedList<CRPG_Timer>::ll_count;
float CRPG_Timer::nextrun_tm;
bool comp_times(CRPG_Timer *timer1, CRPG_Timer *timer2) {
if(timer1->next_tm < timer2->next_tm)
return true;
return false;
}
void CRPG_Timer::Init() {
nextrun_tm = 0;
ll_init();
return ;
}
CRPG_Timer* CRPG_Timer::AddTimer(float secs, unsigned int repeats, timer_func *func, int argc, ...) {
float now;
CRPG_Timer *timer = new CRPG_Timer;
void **argv = NULL;
int i;
va_list ap;
now = s_globals->curtime;
timer->inc_tm = secs;
timer->next_tm = now+secs;
if((!nextrun_tm) || (nextrun_tm > timer->next_tm))
nextrun_tm = timer->next_tm;
timer->repeats = repeats;
timer->call_count = 0;
timer->func = func;
if(argc > 0) {
argv = new void *[argc];
va_start(ap, argc);
for(i = 0;i < argc;i++)
argv[i] = va_arg(ap, void*);
va_end(ap);
}
timer->argc = argc;
timer->argv = argv;
timer->ll_add();
ll_sort(comp_times);
return timer;
}
void CRPG_Timer::DelTimer(void) {
this->ll_del();
delete[] this->argv;
delete this;
return ;
}
void CRPG_Timer::RunEvents(void) {
register float now;
register CRPG_Timer *timer, *next;
if(!nextrun_tm)
return ;
now = s_globals->curtime;
if(now < nextrun_tm)
return ;
for(timer = ll_first;timer != NULL;timer = next) {
next = timer->ll_next; // in case we delete timer
if(now >= timer->next_tm) {
timer->func(timer->argv, timer->argc);
if(timer->repeats) {
if(++timer->call_count >= timer->repeats) {
timer->DelTimer();
continue;
}
}
timer->next_tm += timer->inc_tm;
}
else {
break;
}
}
if(!ll_count) {
nextrun_tm = 0;
}
else {
ll_sort(comp_times);
nextrun_tm = ll_first->next_tm;
}
return ;
}
void CRPG_Timer::FreeMemory(void) {
CRPG_Timer *timer, *next;
for(timer = ll_first;timer != NULL;timer = next) {
next = timer->ll_next;
timer->DelTimer();
}
return ;
}
| 21.411699 | 163 | 0.640872 | jameslk |
0ba95ca95977bdcd247d1625b254eb9ca1388f52 | 889 | cpp | C++ | Native/Framework/source/Tools/ModelPipeline/Program.cpp | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | Native/Framework/source/Tools/ModelPipeline/Program.cpp | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | Native/Framework/source/Tools/ModelPipeline/Program.cpp | btrowbridge/DirectX.2D.Bespoke.Games | 382728f7c9d50597f9fc84e222efd468c33716a5 | [
"MS-PL"
] | null | null | null | #include "pch.h"
using namespace std;
using namespace ModelPipeline;
using namespace Library;
int main(int argc, char* argv[])
{
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
try
{
if (argc < 2)
{
throw exception("Usage: ModelPipeline pathToInputFile");
}
string inputFile = argv[1];
string inputFilename;
string inputDirectory;
Library::Utility::GetFileNameAndDirectory(inputFile, inputDirectory, inputFilename);
if (inputDirectory.empty())
{
inputDirectory = UtilityWin32::CurrentDirectory();
}
SetCurrentDirectory(Library::Utility::ToWideString(inputDirectory).c_str());
Model model = ModelProcessor::LoadModel(inputFilename, true);
string outputFilename = inputFilename + ".bin";
model.Save(outputFilename);
}
catch (exception ex)
{
cout << ex.what();
}
return 0;
} | 21.682927 | 86 | 0.723285 | btrowbridge |
0bac7f19913e9e100fc4e8ba1ed065f99cb75a51 | 8,910 | cpp | C++ | framework/code/mesh/instanceGenerator.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | framework/code/mesh/instanceGenerator.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | framework/code/mesh/instanceGenerator.cpp | MikeCurrington/adreno-gpu-vulkan-code-sample-framework | 2807e6204f5fcbbe9ff9bcc783e4cc2d66ca79cb | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
#include "instanceGenerator.hpp"
#include "vulkan/MeshObject.h"
#include "system/crc32c.hpp"
#include <glm/gtx/norm.hpp>
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO
#include <eigen/Eigen/Dense>
#include <map>
#include <algorithm>
// Calculate the 'centroid' of the object mesh.
static glm::vec3 ComputeMeshCenter( const tcb::span<MeshObjectIntermediate::FatVertex> vertices )
{
glm::highp_dvec3 center(0.0); // calculate in 'doubles'
{
int i = 0;
for (; i < vertices.size() && i < 32; ++i)
{
const auto& v = vertices[i];
center += glm::highp_dvec3(v.position[0], v.position[1], v.position[2]);
}
center /= i;
}
return center;
}
static void TransformToCenter( const tcb::span<MeshObjectIntermediate::FatVertex> vertices, const glm::vec3 center )
{
for (auto& v: vertices)
{
v.position[0] -= center.x;
v.position[1] -= center.y;
v.position[2] -= center.z;
}
}
static glm::mat4x4 ComputeTransformationBetweenVertexPositions( const tcb::span<const MeshObjectIntermediate::FatVertex>& verticesFrom,
const tcb::span<const MeshObjectIntermediate::FatVertex>& verticesTo,
const glm::highp_dvec3 verticesFromCenter,
const glm::highp_dvec3 verticesToCenter )
{
// Dot product the two sets of positions!
Eigen::Matrix3d m33;
for (int i = 0; i < verticesFrom.size() && i < 32; ++i)
{
glm::highp_dvec3 p0 = glm::highp_dvec3(verticesFrom[i].position[0], verticesFrom[i].position[1], verticesFrom[i].position[2]) - verticesFromCenter;
glm::highp_dvec3 p1 = glm::highp_dvec3(verticesTo[i].position[0], verticesTo[i].position[1], verticesTo[i].position[2]) - verticesToCenter;
m33(0, 0) += p0[0] * p1[0];
m33(0, 1) += p0[0] * p1[1];
m33(0, 2) += p0[0] * p1[2];
m33(1, 0) += p0[1] * p1[0];
m33(1, 1) += p0[1] * p1[1];
m33(1, 2) += p0[1] * p1[2];
m33(2, 0) += p0[2] * p1[0];
m33(2, 1) += p0[2] * p1[1];
m33(2, 2) += p0[2] * p1[2];
}
// Decompose the 3x3
Eigen::JacobiSVD<Eigen::Matrix3d> svd;
svd.compute(m33, Eigen::ComputeFullU | Eigen::ComputeFullV);
auto V = svd.matrixV();
auto UT = svd.matrixU().transpose();
Eigen::MatrixXd rotation = V * UT;
// Make sure the rotation is not mirrored (can happen when using SVD this way).
if (rotation.determinant() < 0.0)
{
// Rotation mirrored, flip last column of V and regenerate the rotation matrix.
V(0,2) *= -1.0;
V(1,2) *= -1.0;
V(2,2) *= -1.0;
rotation = V * UT;
}
// Rotation is correct now (assuming the 2 sets of vertices are truely just translated and rotated versions of each other).
// Compose the final transform...
auto transform = Eigen::Translation3d(verticesToCenter.x, verticesToCenter.y, verticesToCenter.z) * rotation * Eigen::Translation3d(-verticesFromCenter.x, -verticesFromCenter.y, -verticesFromCenter.z);
//auto transform = Eigen::Translation3d(-verticesFromCenter.x, -verticesFromCenter.y, -verticesFromCenter.z) * rotation * Eigen::Translation3d(verticesToCenter.x, verticesToCenter.y, verticesToCenter.z);
glm::mat4x4 ret( *(glm::dmat4x4*)transform.matrix().data() );
static_assert(sizeof(glm::dmat4x4) == sizeof(double) * 4 * 4);
return ret;
}
std::vector<MeshInstance> MeshInstanceGenerator::NullFindInstances(std::vector<MeshObjectIntermediate> objects)
{
std::vector<MeshInstance> out;
for (auto& object : objects)
{
out.push_back( { std::move( object ), {} } );
}
return std::move(out);
}
std::vector<MeshInstance> MeshInstanceGenerator::FindInstances(std::vector<MeshObjectIntermediate> objects)
{
std::multimap<uint32_t, MeshObjectIntermediate> matchingSets;
// Go through and match based on a CRC (of UV positions and materials).
// Normals and postions are not a reliable indicator as they will be rotated/translated differently for matching instances.
// Move the objects in to this map!
for (auto& object : objects)
{
size_t bufferSize = object.m_VertexBuffer.size();
uint32_t crc = crc32c(0, { (uint8_t*)&bufferSize, sizeof(bufferSize) });
for (const auto& vert : object.m_VertexBuffer)
crc = crc32c(crc, { (uint8_t*)vert.uv0, sizeof(vert.uv0) });
for (const MeshObjectIntermediate::MaterialDef& material : object.m_Materials)
crc = crc32c(crc, material.diffuseFilename);
matchingSets.emplace( crc, std::move(object) );
}
// Find how many unique crc values there were (gives a good start for number of truely unique mesh instances).
uint32_t lastCrc = 0xffffffff;
uint32_t numUniqueCrc = 0;
for (const auto& [crc, object] : matchingSets)
{
if (crc == lastCrc)
++numUniqueCrc;
lastCrc = crc;
}
std::vector<MeshInstance> instances;
instances.reserve(numUniqueCrc);
// Go through the 'unique' sets and determine the transform for each instance (to map it to the position of the 'original').
// Build a list of unique MeshObjects and their instances (with transforms).
// We repeat until 'matchingSets' has been emptied. Worse case becomes N^2, where all the meshes have identical CRC values but their meshes dont match.
while (!matchingSets.empty())
{
uint32_t setCrc = 0xffffffff;
glm::vec3 setFirstCenter{};
for (auto it = matchingSets.begin(); it != matchingSets.end(); )
{
const auto crc = it->first;
auto& object = it->second;
glm::vec3 center = ComputeMeshCenter(object.m_VertexBuffer);
if (crc != setCrc)
{
// First item in a new set of matches.
// Add it as a new set of 'instances' and remove from the 'matchingSets'.
setCrc = crc;
setFirstCenter = center;
TransformToCenter( object.m_VertexBuffer, center );
glm::mat3x4 m = glm::identity<glm::mat3x4>();
m[0].w = center.x;
m[1].w = center.y;
m[2].w = center.z;
instances.push_back( { std::move( object ), {m} } );
it = matchingSets.erase(it);
}
else
{
// First 'duplicate' in the set.
//
// Use SVD to determine the rotation between the 2 sets of vertices.
//
const MeshObjectIntermediate& setFirstObject = instances.rbegin()->mesh;
auto transform = ComputeTransformationBetweenVertexPositions(setFirstObject.m_VertexBuffer, object.m_VertexBuffer, glm::vec3(0.0f), center);
//
// Sanity check that the transform really does map between the 2 sets of vertices.
// This will fail if the mesh positions are not truely identical (outside of translation/rotation).
//
bool verificationFailed = false;
for (int i = 0; i < object.m_VertexBuffer.size(); ++i)
{
const glm::vec3 p0 = glm::vec3(setFirstObject.m_VertexBuffer[i].position[0], setFirstObject.m_VertexBuffer[i].position[1], setFirstObject.m_VertexBuffer[i].position[2]);
const glm::vec3 ptest2 = transform * glm::vec4(p0, 1.0f);
const glm::vec3 p1 = glm::vec3(object.m_VertexBuffer[i].position[0], object.m_VertexBuffer[i].position[1], object.m_VertexBuffer[i].position[2]);
auto pdist2 = glm::distance2(p1, ptest2);
if (pdist2 > 1.0f)
{
// assume too much error!
verificationFailed = true;
break;
}
}
if (verificationFailed)
{
// Transform failed to transform vertices correctly - assume the meshes aren't matches (either aren't based on each other or are scaled, which we dont currently handle)
// Leave this instance in the 'matchSets' list.
++it;
}
else
{
// Transform looks good. Add this as a new instance of the current instances set.
instances.rbegin()->instances.push_back( glm::transpose(transform) );
it = matchingSets.erase(it);
}
}
}
}
return std::move(instances);
}
| 43.463415 | 207 | 0.588103 | MikeCurrington |
0bad188a8c9958ee5f94c4ca05a73f0cf8ef61b5 | 355 | cpp | C++ | codeforce3/580A. Kefa and First Steps.cpp | khaled-farouk/My_problem_solving_solutions | 46ed6481fc9b424d0714bc717cd0ba050a6638ef | [
"MIT"
] | null | null | null | codeforce3/580A. Kefa and First Steps.cpp | khaled-farouk/My_problem_solving_solutions | 46ed6481fc9b424d0714bc717cd0ba050a6638ef | [
"MIT"
] | null | null | null | codeforce3/580A. Kefa and First Steps.cpp | khaled-farouk/My_problem_solving_solutions | 46ed6481fc9b424d0714bc717cd0ba050a6638ef | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n, a[N];
int main() {
cin >> n;
for(int i = 0; i < n; ++i)
cin >> a[i];
a[n] = -1;
int lst = a[0], res = 0;
for(int i = 0, tmp; i < n; ++i) {
tmp = i;
while(a[i] <= a[i + 1])
++i;
res = max(res, i - tmp + 1);
}
cout << res << endl;
return 0;
}
| 13.653846 | 35 | 0.43662 | khaled-farouk |
0bad32c49e39045d506aed745a89a492e63810e4 | 1,062 | cpp | C++ | gmtl-0.6.1/examples/faqexample.cpp | Glitch0011/QuadTree-Example | 3558c999f68475bc98b8fa33b0f6d14076c9ec48 | [
"MIT"
] | null | null | null | gmtl-0.6.1/examples/faqexample.cpp | Glitch0011/QuadTree-Example | 3558c999f68475bc98b8fa33b0f6d14076c9ec48 | [
"MIT"
] | null | null | null | gmtl-0.6.1/examples/faqexample.cpp | Glitch0011/QuadTree-Example | 3558c999f68475bc98b8fa33b0f6d14076c9ec48 | [
"MIT"
] | null | null | null | /** This is an example about a lot of cool stuff.
* The comments in this example use a slightly special
* format to make them easy to process into
* doxygen backend stuff.
*/
/* These are the headers that we need to include.
* They are all needed because we say so.
*/
#include <gmtl/gmtl.h>
#include <gmtl/Matrix.h>
int main()
{
/* @exskip
* This is ugly stuff to skip for now.
*/
gmtl::somethingUgly();
/* @exendskip */
/**
* Example of creating a matrix and doing stuff
*/
// Test for allowing this type of comment through.
gmtl::Matrix44f test_matrix;
gmtl::invert(test_matrix);
/** Here is an example of creating a Vector */
gmtl::Vec3f test_vector;
test_vector += gmtl::Vec3f(1.0, 0.0f, 1.0f);
/** @subsection multexample Example of multiplication
*
* This is an example of matrix multiplication.
* We like to do this all the time in the code
*/
gmtl::Matrix44f mat1, mat2, mat3;
mat3 = mat1 * mat2;
// You can do it this way to.
gmtl::mult(mat3, mat1, mat2);
return 1;
}
| 24.697674 | 56 | 0.654426 | Glitch0011 |
0bafffdcacf0c86777b2a8d87836cb7357f7da4b | 127 | cpp | C++ | source/main/main.cpp | wilvk/pbec | 225e475cab70dc59fd5c060b97c9f521e021bc9c | [
"MIT"
] | 20 | 2018-01-05T07:39:11.000Z | 2022-03-28T07:07:54.000Z | source/main/main.cpp | wilvk/pbe-linux | 225e475cab70dc59fd5c060b97c9f521e021bc9c | [
"MIT"
] | 11 | 2018-01-04T11:01:22.000Z | 2020-03-04T11:07:57.000Z | source/main/main.cpp | wilvk/pbec | 225e475cab70dc59fd5c060b97c9f521e021bc9c | [
"MIT"
] | 2 | 2019-02-26T05:16:56.000Z | 2019-07-02T11:54:49.000Z | #include "headers.h"
int main(int argc, char** argv)
{
CliOptions options;
return options.ParseCommandLine(argc, argv);
}
| 15.875 | 46 | 0.716535 | wilvk |
0bb7a8234e4429790c908a27256cde3d8ba6f2a7 | 1,220 | cc | C++ | 10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc | OpenCreate/Play-with-DSA | 49de3eb3e54815d1ff6520e5933e467c1f56bdfc | [
"MIT"
] | 9 | 2020-08-10T03:43:54.000Z | 2021-11-12T06:26:32.000Z | 10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc | OpenCreate/Play-with-DSA | 49de3eb3e54815d1ff6520e5933e467c1f56bdfc | [
"MIT"
] | null | null | null | 10-More-about-MergeSort/cpp/09-Solving-Reverse-Pairs-Problem-by-MergeSort/Solution2.cc | OpenCreate/Play-with-DSA | 49de3eb3e54815d1ff6520e5933e467c1f56bdfc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution2 {
public:
int reversePairs(vector<int> &nums) {
int res = 0;
vector<int> temp(nums);
res = sort(nums, 0, nums.size() - 1, temp);
return res;
}
private:
int sort(vector<int> &nums, int l, int r, vector<int> &temp) {
if (l >= r) return 0;
int mid = l + (r - l) / 2;
int res = 0;
res += sort(nums, l, mid, temp);
res += sort(nums, mid + 1, r, temp);
if (nums[mid] > nums[mid + 1]) res += merge(nums, l, mid, r, temp);
return res;
}
int merge(vector<int> &nums, int l, int mid, int r, vector<int> &temp) {
copy(nums.begin() + l, nums.begin() + r + 1, temp.begin() + l);
int i = l, j = mid + 1;
int res = 0;
for (int k = l; k <= r; k++) {
if (i > mid) {
nums[k] = temp[j];
j++;
} else if (j > r) {
nums[k] = temp[i];
i++;
} else if (temp[i] > temp[j]) {
res += mid - i + 1;
nums[k] = temp[j];
j++;
} else {
nums[k] = temp[i];
i++;
}
}
return res;
}
};
int main() {
vector<int> vec{7, 5, 6, 4};
cout << Solution2().reversePairs(vec) << endl;
return 0;
} | 21.403509 | 74 | 0.47623 | OpenCreate |
0bb98d873e78976da89a6d136a3216e1db481ffe | 2,512 | cpp | C++ | DX11 Framework/utility/Vector3D.cpp | kyle-robinson/dx11-framework | 7e4f6517b4e7e3ddda405250c46815e6e970207d | [
"MIT"
] | 1 | 2021-04-22T03:15:56.000Z | 2021-04-22T03:15:56.000Z | DX11 Framework/utility/Vector3D.cpp | kyle-robinson/dx11-framework | 7e4f6517b4e7e3ddda405250c46815e6e970207d | [
"MIT"
] | null | null | null | DX11 Framework/utility/Vector3D.cpp | kyle-robinson/dx11-framework | 7e4f6517b4e7e3ddda405250c46815e6e970207d | [
"MIT"
] | null | null | null | #include "Vector3D.h"
#include <sstream>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <debugapi.h>
Vector3D::Vector3D() : x( 0 ), y( 0 ), z( 0 ) { }
Vector3D::Vector3D( float x, float y, float z ) : x( x ), y( y ), z( z ) { }
Vector3D::Vector3D( const Vector3D &vec ) : x( vec.x ), y( vec.y ), z( vec.z ) { }
Vector3D Vector3D::operator+( const Vector3D &vec )
{
return Vector3D( x + vec.x, y + vec.y, z + vec.z );
}
Vector3D& Vector3D::operator+=( const Vector3D &vec )
{
x += vec.x;
y += vec.y;
z += vec.z;
return *this;
}
Vector3D Vector3D::operator-( const Vector3D &vec )
{
return Vector3D( x - vec.x, y - vec.y, z - vec.z );
}
Vector3D& Vector3D::operator-=( const Vector3D &vec )
{
x -= vec.x;
y -= vec.y;
z -= vec.z;
return *this;
}
Vector3D Vector3D::operator*( float value )
{
return Vector3D( x * value, y * value, z * value );
}
Vector3D& Vector3D::operator*=( float value )
{
x *= value;
y *= value;
z *= value;
return *this;
}
Vector3D Vector3D::operator/( float value )
{
assert( value != 0, "Vector Division: Value was equal to 0!" );
return Vector3D( x / value, y / value, z / value );
}
Vector3D& Vector3D::operator/=( float value )
{
x *= value;
y *= value;
z *= value;
return *this;
}
Vector3D& Vector3D::operator=( const Vector3D &vec )
{
x = vec.x;
y = vec.y;
z = vec.z;
return Vector3D( x, y, z );
}
float Vector3D::DotProduct( const Vector3D &vec )
{
return ( x * vec.x + y + vec.y + x * vec.z );
}
Vector3D Vector3D::CrossProduct( const Vector3D &vec )
{
return Vector3D(
y * vec.z - z * vec.y,
z * vec.x - x * vec.z,
x * vec.y - y * vec.x
);
}
Vector3D Vector3D::Normalization()
{
float magnitude = this->Magnitude();
x /= magnitude;
y /= magnitude;
z /= magnitude;
return Vector3D( x, y, z );
}
float Vector3D::Square()
{
return pow( x, x ) + pow( y, y ) + pow( z, z );
}
float Vector3D::Distance( const Vector3D &vec )
{
return sqrt(
pow( x - ( -vec.x ), x - ( -vec.x ) ) +
pow( y - ( -vec.y ), y - ( -vec.y ) ) +
pow( z - ( -vec.z ), z - ( -vec.z ) )
);
}
float Vector3D::Magnitude()
{
float squared = this->Square();
return sqrt( squared );
}
float Vector3D::ShowX() const noexcept
{
return this->x;
}
float Vector3D::ShowY() const noexcept
{
return this->y;
}
float Vector3D::ShowZ() const noexcept
{
return this->z;
}
void Vector3D::Display() noexcept
{
std::ostringstream oss;
oss << "x: " << x;
oss << "\ty: " << y;
oss << "\tz: " << z;
OutputDebugStringA( oss.str().c_str() );
} | 17.942857 | 82 | 0.591959 | kyle-robinson |
0bbac2da2f5a4bbc70f66b97e89a02a9f7006025 | 328 | cpp | C++ | Algorithm/stack-based/TOH.cpp | Alquama00s/DS-Algo | 594b04e8d119a188763481209cbfcc49c62fc002 | [
"MIT"
] | null | null | null | Algorithm/stack-based/TOH.cpp | Alquama00s/DS-Algo | 594b04e8d119a188763481209cbfcc49c62fc002 | [
"MIT"
] | null | null | null | Algorithm/stack-based/TOH.cpp | Alquama00s/DS-Algo | 594b04e8d119a188763481209cbfcc49c62fc002 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
void TOH(int n,char I,char F,char A){
if(n==1){
cout<<"moving top disk from "<<I<<" to "<<F<<"\n";
}else{
TOH(n-1,I,A,F);
cout<<"move top disk from "<<I<<" to "<<F<<"\n";
TOH(n-1,A,F,I);
}
}
int main(){
TOH(3,'I','F','A');
return 0;
} | 21.866667 | 59 | 0.466463 | Alquama00s |
0bbada82b5dc6eab35eb9f20edb812a6463f4268 | 485 | cpp | C++ | src/Geometry/point3D.cpp | sebastiandaberdaku/PoCavEDT | bc4fa2d8c52d138d6eb1446f78a4162e05d97d6b | [
"BSD-3-Clause"
] | 1 | 2021-10-01T16:51:28.000Z | 2021-10-01T16:51:28.000Z | src/Geometry/point3D.cpp | sebastiandaberdaku/VoxMeshSurfOpenMP | dc5c13a6b3cb3d1b47fa2a195635063b19bf73d7 | [
"BSD-3-Clause"
] | null | null | null | src/Geometry/point3D.cpp | sebastiandaberdaku/VoxMeshSurfOpenMP | dc5c13a6b3cb3d1b47fa2a195635063b19bf73d7 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T18:14:51.000Z | 2022-03-29T18:14:51.000Z | /*
* point3D.cpp
*
* Created on: 01/dic/2014
* Author: sebastian
*/
#include "point3D.h"
#include "../PDB/atom.h"
point3D::point3D(atom const & atm) : x(atm.x), y(atm.y), z(atm.z) { }
/**
* Calculates the square of the distance between this point3D and the center of
* the argument.
*/
float point3D::s_distance(atom const & atm) const {
float dx = this->x - atm.x;
float dy = this->y - atm.y;
float dz = this->z - atm.z;
return (dx * dx + dy * dy + dz * dz);
};
| 20.208333 | 79 | 0.606186 | sebastiandaberdaku |
0bbc9ab21156b2a36a4ca9d986cd5d27e3909e95 | 5,910 | cpp | C++ | olp-cpp-sdk-core/src/logging/MessageFormatter.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 21 | 2019-07-03T07:26:52.000Z | 2019-09-04T08:35:07.000Z | olp-cpp-sdk-core/src/logging/MessageFormatter.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 639 | 2019-09-13T17:14:24.000Z | 2020-05-13T11:49:14.000Z | olp-cpp-sdk-core/src/logging/MessageFormatter.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 21 | 2020-05-14T15:32:28.000Z | 2022-03-15T13:52:33.000Z | /*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include <olp/core/logging/Format.h>
#include <olp/core/logging/MessageFormatter.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <functional>
#include <string>
namespace olp {
namespace logging {
static const char* limitString(std::string& tempStr, const char* str,
int limit) {
if (limit < 0) {
int length = static_cast<int>(std::strlen(str));
int start = std::max(length + limit, 0);
if (start == 0) {
return str;
}
if (length - start > 3) {
tempStr = "...";
start += 3;
} else {
tempStr.clear();
}
tempStr.append(str, start, length - start);
return tempStr.c_str();
} else if (limit > 0) {
std::size_t strLen = std::strlen(str);
std::size_t finalLength = std::min(strLen, static_cast<std::size_t>(limit));
if (finalLength == strLen) {
return str;
}
bool addElipses = false;
if (finalLength > 3) {
finalLength -= 3;
addElipses = true;
}
tempStr.assign(str, finalLength);
if (addElipses) {
tempStr += "...";
}
return tempStr.c_str();
} else {
return str;
}
}
MessageFormatter::Element::Element(ElementType type_) : type(type_), limit(0) {
switch (type) {
case ElementType::Level:
case ElementType::Tag:
case ElementType::Message:
case ElementType::File:
case ElementType::Function:
case ElementType::FullFunction:
format = "%s";
break;
case ElementType::Line:
format = "%u";
break;
case ElementType::Time:
format = "%Y-%m-%d %H:%M:%S";
break;
case ElementType::TimeMs:
format = "%u";
break;
case ElementType::ThreadId:
format = "%lu";
break;
default:
break;
}
}
const MessageFormatter::LevelNameMap& MessageFormatter::defaultLevelNameMap() {
static MessageFormatter::LevelNameMap defaultLevelNameMap = {
{"[TRACE]", "[DEBUG]", "[INFO]", "[WARN]", "[ERROR]", "[FATAL]"}};
return defaultLevelNameMap;
}
MessageFormatter MessageFormatter::createDefault() {
return MessageFormatter(
{Element(ElementType::Time, "%T"), Element(ElementType::TimeMs, ".%.3u "),
Element(ElementType::Level, "%s "), Element(ElementType::Tag, "%s - "),
Element(ElementType::Message)});
}
std::string MessageFormatter::format(const LogMessage& message) const {
std::string formattedMessage;
std::string tempStr;
FormatBuffer curElementBuffer;
for (const Element& element : m_elements) {
const char* curElement;
switch (element.type) {
case ElementType::String:
curElement = element.format.c_str();
break;
case ElementType::Level:
assert(static_cast<std::size_t>(message.level) < m_levelNameMap.size());
curElement = curElementBuffer.format(
element.format.c_str(),
m_levelNameMap[static_cast<std::size_t>(message.level)].c_str());
break;
case ElementType::Tag:
if (!message.tag || !*message.tag) {
continue;
}
curElement = curElementBuffer.format(
element.format.c_str(),
limitString(tempStr, message.tag, element.limit));
break;
case ElementType::Message:
curElement = curElementBuffer.format(
element.format.c_str(),
limitString(tempStr, message.message, element.limit));
break;
case ElementType::File:
curElement = curElementBuffer.format(
element.format.c_str(),
limitString(tempStr, message.file, element.limit));
break;
case ElementType::Line:
curElement =
curElementBuffer.format(element.format.c_str(), message.line);
break;
case ElementType::Function:
curElement = curElementBuffer.format(
element.format.c_str(),
limitString(tempStr, message.function, element.limit));
break;
case ElementType::FullFunction:
curElement = curElementBuffer.format(
element.format.c_str(),
limitString(tempStr, message.fullFunction, element.limit));
break;
case ElementType::Time:
if (m_timezone == Timezone::Local) {
curElement = curElementBuffer.formatLocalTime(message.time,
element.format.c_str());
} else {
curElement = curElementBuffer.formatUtcTime(message.time,
element.format.c_str());
}
break;
case ElementType::TimeMs: {
auto totalMs = std::chrono::duration_cast<std::chrono::milliseconds>(
message.time.time_since_epoch());
unsigned int msOffset =
static_cast<unsigned int>(totalMs.count() % 1000);
curElement = curElementBuffer.format(element.format.c_str(), msOffset);
break;
}
case ElementType::ThreadId:
curElement =
curElementBuffer.format(element.format.c_str(), message.threadId);
break;
default:
continue;
}
formattedMessage += curElement;
}
return formattedMessage;
}
} // namespace logging
} // namespace olp
| 30.307692 | 80 | 0.614721 | forslund |
0bbce92c471249cca5f10b7eb437600e68408103 | 11,997 | cpp | C++ | server/src/WSStreamer.cpp | urbenlegend/WebStreamer | 562b16a4b8e10cce25c4088e38e83f93bc87e1ee | [
"MIT"
] | 42 | 2015-09-19T13:33:02.000Z | 2021-08-12T18:36:51.000Z | server/src/WSStreamer.cpp | cqzhanghy/WebStreamer | 562b16a4b8e10cce25c4088e38e83f93bc87e1ee | [
"MIT"
] | 3 | 2015-08-05T19:09:03.000Z | 2017-08-08T18:30:53.000Z | server/src/WSStreamer.cpp | cqzhanghy/WebStreamer | 562b16a4b8e10cce25c4088e38e83f93bc87e1ee | [
"MIT"
] | 14 | 2015-09-20T14:01:56.000Z | 2020-01-06T17:26:28.000Z | #include <string>
#include <fstream>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/asio.hpp"
#include "websocketpp.hpp"
#include "websocket_connection_handler.hpp"
#include "utils.h"
#include "rtpdump.h"
#include "WSStreamer.h"
using namespace std;
extern ofstream debug;
vector<unsigned char> readNAL(ifstream& stream, int numOfUnits) {
vector<unsigned char> buffer;
char byte_read;
for (int i = 0; i < numOfUnits && stream.good(); i++) {
int end_count = 0;
bool extract = false;
// Extract bytes and put into vector for sending
while (true) {
stream.read(&byte_read, 1);
if (!stream.good()) {
break;
}
if (extract) {
buffer.push_back(byte_read);
}
// Check for NAL header 0 0 0 1
if (byte_read == 0 && end_count < 3 || byte_read == 1 && end_count == 3) {
end_count++;
}
else {
end_count = 0;
}
if (end_count == 4) {
// Reset NAL header count
end_count = 0;
if (extract) {
// Delete beginning of next NAL from current NAL array and decrement read pointer so that NAL is available for next read
stream.seekg(stream.tellg() - (streampos)4);
buffer.erase(buffer.end() - 4, buffer.end());
break;
}
else {
// Insert NAL header that's been detected into NAL array
for (int i = 0; i < 3; i++) {
buffer.push_back(0);
}
buffer.push_back(1);
extract = true;
}
}
}
}
return buffer;
}
int sendNAL(websocketpp::session_ptr client, shared_ptr<ifstream> file, int nals) {
if (file->good()) {
vector<unsigned char> buffer = readNAL(*file.get(), nals);
client->send(buffer);
//debug.write((char*)&buffer[0], buffer.size());
return buffer.size();
}
else {
return 0;
}
}
streamsize sendChunk(websocketpp::session_ptr client, shared_ptr<ifstream> file, int chunk_size) {
if (file->good()) {
char* read_buffer = new char[chunk_size];
vector<unsigned char> send_buffer;
file->read(read_buffer, chunk_size);
send_buffer.assign(read_buffer, read_buffer + file->gcount());
client->send(send_buffer);
delete [] read_buffer;
return file->gcount();
}
else {
return 0;
}
}
streamsize sendRTP(websocketpp::session_ptr client, shared_ptr<ifstream> file, int packets) {
if (file->good()) {
// Read file header
char packet_hdr_array[sizeof(RD_packet_t)];
file->read(packet_hdr_array, sizeof(packet_hdr_array));
RD_packet_t* packet_hdr = (RD_packet_t*)packet_hdr_array;
packet_hdr->length = ntohs(packet_hdr->length);
packet_hdr->plen = ntohs(packet_hdr->plen);
packet_hdr->offset = ntohl(packet_hdr->offset);
// Extract actual RTP packet
char* rtp_packet = new char[packet_hdr->plen];
file->read(rtp_packet, packet_hdr->plen);
vector<unsigned char> send_buffer;
send_buffer.assign(rtp_packet, rtp_packet + file->gcount());
client->send(send_buffer);
delete [] rtp_packet;
return file->gcount();
}
else {
return 0;
}
}
// Thread function that reads bytes
void wschunk_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int chunk_size, int sleep_time) {
vector<unsigned char> send_buffer;
while (sendChunk(client, file, chunk_size)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
// Thread function that reads NALS
void wsnal_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int nals, int sleep_time) {
while (sendNAL(client, file, nals)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
// Thread function that reads NALS
void wsrtp_thread_func(shared_ptr<guarded_var<bool>> thread_continue, websocketpp::session_ptr client, shared_ptr<ifstream> file, int packets, int sleep_time) {
while (sendRTP(client, file, packets)) {
if (thread_continue->get() == false) {
break;
}
Sleep(sleep_time);
}
}
WSStreamerHandler::WSStreamerHandler() {
}
WSStreamerHandler::~WSStreamerHandler() {
}
void WSStreamerHandler::validate(websocketpp::session_ptr client) {
// Check if requested resource exists
if (client->get_resource() == "/") {
cout << "INFO: Client is connecting without asking for a resource" << endl;
}
else {
ifstream resource(client->get_resource().substr(1).c_str(), ios::binary);
if (!resource.is_open()) {
string err = "Request for unknown resource " + client->get_resource();
cerr << err << endl;
throw(websocketpp::handshake_error(err, 404));
}
else {
cout << "INFO: Client request for " + client->get_resource() + " accepted" << endl;
resource.close();
}
}
}
void WSStreamerHandler::on_open(websocketpp::session_ptr client) {
if (client->get_resource() != "/") {
shared_ptr<ifstream> resource(new ifstream(client->get_resource().substr(1).c_str(), ios::binary));
if (resource->is_open()) {
cout << "INFO: Client has connected and opened " + client->get_resource() << endl;
// Check if it is a rtpdump file. If it is, fast foward past file header
if (resource->good()) {
streampos filestart = resource->tellg();
char* rtpdumphdr = new char[strlen(RTPPLAY_MAGIC)];
resource->read(rtpdumphdr, strlen(RTPPLAY_MAGIC));
if (resource->gcount() == strlen(RTPPLAY_MAGIC) && strncmp(rtpdumphdr, RTPPLAY_MAGIC, strlen(RTPPLAY_MAGIC)) == 0) {
cout << "INFO: Requested file is an rtpdump file. Fast forwarding past file header" << endl;
resource->ignore(sizeof(RD_hdr_t));
}
else {
// Reset file to beginning if we do not see rtpdump header
resource->seekg(filestart);
}
delete[] rtpdumphdr;
}
WSSClientInfo clientInfo;
clientInfo.resource = resource;
connections.insert(pair<websocketpp::session_ptr, WSSClientInfo>(client, clientInfo));
}
else {
cerr << "ERROR: Client has connected but server is unable to access " + client->get_resource() << endl;
client->send("ERROR: Failed to open resource");
}
}
}
void WSStreamerHandler::on_close(websocketpp::session_ptr client) {
map<websocketpp::session_ptr, WSSClientInfo>::iterator connection = connections.find(client);
if (connection != connections.end()) {
// Close file handle and remove connection from connections list.
if (connection->second.resource) {
connection->second.resource->close();
}
if (connection->second.thread) {
*(connection->second.thread_continue) = false;
connection->second.thread->join();
}
connections.erase(connection);
cout << "INFO: Client has disconnected" << endl;
}
}
void WSStreamerHandler::on_message(websocketpp::session_ptr client, const std::string &msg) {
cout << "CLIENTMSG: " << msg << endl;
// Find client info and file handle in connections map
map<websocketpp::session_ptr, WSSClientInfo>::iterator connection = connections.find(client);
if (connection == connections.end()) {
cerr << "ERROR: Received message from an unknown client" << endl;
}
WSSClientInfo& clientInfo = connection->second;
// Parse request from client and send data appropriately
vector<string> tokens;
tokenize(msg, tokens);
if (tokens.size() >= 2) {
bool continuous_stream;
if (tokens[0] == "REQUESTSTREAM") {
continuous_stream = true;
}
else if (tokens[0] == "REQUEST") {
continuous_stream = false;
}
else {
cerr << "ERROR: Client has sent an invalid request" << endl;
}
// Parse message size token
string chunk_type;
int temp_size = 0;
int byte_multiplier = 0;
int sleep_time = 0;
splitIntUnit(tokens[1], temp_size, chunk_type);
if (temp_size == 0) {
cerr << "ERROR: Client has specified an invalid request size" << endl;
return;
}
if (chunk_type == "MB") {
byte_multiplier = 1048576;
}
else if (chunk_type == "KB") {
byte_multiplier = 1024;
}
else if (chunk_type == "B") {
byte_multiplier = 1;
}
else if (chunk_type == "NAL") {
// For miscellaneous accepted units, do nothing
}
else if (chunk_type == "RTP") {
// For miscellaneous accepted units, do nothing
}
else {
cerr << "ERROR: Client has specified an invalid request unit" << endl;
return;
}
// Parse stream rate token
if (tokens.size() == 3) {
string unit;
splitIntUnit(tokens[2], sleep_time, unit);
if (sleep_time < 0 || unit != "MS") {
cerr << "ERROR: Client has specified an invalid delay time" << endl;
return;
}
}
// Initiate streaming
if (chunk_type == "MB" || chunk_type == "KB" || chunk_type == "B") {
// Send file in chunks of chunk_size bytes
unsigned int chunk_size = temp_size * byte_multiplier;
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << chunk_size << " byte chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wschunk_thread_func, clientInfo.thread_continue, client, clientInfo.resource, chunk_size, sleep_time));
}
}
else {
cout << "INFO: Sending a " << chunk_size << " byte chunk to client" << endl;
sendChunk(client, clientInfo.resource, chunk_size);
}
}
else if (chunk_type == "NAL") {
// Send file in NAL units
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << temp_size << " NAL chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wsnal_thread_func, clientInfo.thread_continue, client, clientInfo.resource, temp_size, sleep_time));
}
}
else {
cout << "INFO: Sending " << temp_size << " NAL chunk to client" << endl;
sendNAL(client, clientInfo.resource, temp_size);
}
}
else if (chunk_type == "RTP") {
if (continuous_stream) {
if (clientInfo.thread) {
cerr << "ERROR: Already streaming data to client" << endl;
}
else {
cout << "INFO: Streaming data to client in " << temp_size << " RTP chunks with " << sleep_time << " MS delay" << endl;
clientInfo.thread_continue.reset(new guarded_var<bool>(continuous_stream));
clientInfo.thread.reset(new boost::thread(wsrtp_thread_func, clientInfo.thread_continue, client, clientInfo.resource, temp_size, sleep_time));
}
}
else {
cout << "INFO: Sending " << temp_size << " RTP chunk to client" << endl;
sendRTP(client, clientInfo.resource, temp_size);
}
}
}
else if (tokens.size() == 1) {
if (tokens[0] == "STOPSTREAM") {
if (clientInfo.thread) {
*(clientInfo.thread_continue) = false;
clientInfo.thread->join();
clientInfo.thread = NULL;
}
}
}
else {
cerr << "ERROR: Invalid request from client" << endl;
}
}
void WSStreamerHandler::on_message(websocketpp::session_ptr client,
const std::vector<unsigned char> &data) {
// Ignore binary data
debug.write((char*)&data[0], data.size());
//char pad[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
//debug.write(pad, 6);
//cerr << "WARNING: Discarding binary data received from client" << endl;
}
WSStreamer::WSStreamer(string host, string port) : streamer(new WSStreamerHandler()),
endpoint(tcp::v4(), atoi(port.c_str())),
server(new websocketpp::server(io_service, endpoint, streamer))
{
string full_host = host + ":" + port;
// setup server settings
server->add_host(full_host);
server->add_host("localhost:" + port);
// start the server
server->start_accept();
}
WSStreamer::~WSStreamer() {
stop();
}
void WSStreamer::run() {
if (!iosrv_thread) {
iosrv_thread = shared_ptr<boost::thread>(new boost::thread(boost::ref(*this)));
}
}
void WSStreamer::runAndBlock() {
io_service.run();
}
void WSStreamer::stop() {
io_service.stop();
iosrv_thread->join();
iosrv_thread.reset();
}
void WSStreamer::operator()() {
io_service.run();
} | 30.372152 | 165 | 0.674752 | urbenlegend |
0bbe39564381d21ba4fd2d26747a8a2f4195b835 | 3,036 | cpp | C++ | src/RcsGraphics/RigidBodyTracker.cpp | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 37 | 2018-03-20T12:28:45.000Z | 2022-02-28T08:39:32.000Z | src/RcsGraphics/RigidBodyTracker.cpp | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 19 | 2018-04-19T08:49:53.000Z | 2021-06-11T09:47:09.000Z | src/RcsGraphics/RigidBodyTracker.cpp | famura/Rcs | 4f8b997d2649a2cd7a1945ea079e07a71ee215fc | [
"BSD-3-Clause"
] | 15 | 2018-03-28T11:52:39.000Z | 2022-02-04T19:34:01.000Z | /*******************************************************************************
Copyright (c) 2017, Honda Research Institute Europe GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "RigidBodyTracker.h"
#include <osgManipulator/TrackballDragger>
#include <osgManipulator/TranslateAxisDragger>
/*******************************************************************************
* RigidBodyTracker.
******************************************************************************/
Rcs::RigidBodyTracker::RigidBodyTracker(bool withSphericalTracker)
{
setName("RigidBodyTracker");
if (withSphericalTracker==true)
{
osg::ref_ptr<osgManipulator::TrackballDragger> oriDragger =
new osgManipulator::TrackballDragger();
// Scale down circles to 0.5 units so that grabbing the translation arrows
// gets easier.
osg::Matrix m2;
m2.makeScale(osg::Vec3(0.5, 0.5, 0.5));
oriDragger->setMatrix(m2);
addChild(oriDragger.get());
addDragger(oriDragger.get());
oriDragger->setupDefaultGeometry();
}
osg::ref_ptr<osgManipulator::TranslateAxisDragger> posDragger =
new osgManipulator::TranslateAxisDragger();
addChild(posDragger.get());
addDragger(posDragger.get());
posDragger->setupDefaultGeometry();
setParentDragger(getParentDragger());
}
/*******************************************************************************
*
******************************************************************************/
Rcs::RigidBodyTracker::~RigidBodyTracker()
{
}
| 37.95 | 80 | 0.644269 | famura |
0bbe6460148f47156b49021f25cf9ea43874ee2a | 369 | cpp | C++ | 2021.09.27_homework-3/Project3/Source.cpp | HudzievaPolina/programming-c-2021-1course- | f4e0c769419d12f95c42913980bbdc053302b7c6 | [
"Apache-2.0"
] | null | null | null | 2021.09.27_homework-3/Project3/Source.cpp | HudzievaPolina/programming-c-2021-1course- | f4e0c769419d12f95c42913980bbdc053302b7c6 | [
"Apache-2.0"
] | null | null | null | 2021.09.27_homework-3/Project3/Source.cpp | HudzievaPolina/programming-c-2021-1course- | f4e0c769419d12f95c42913980bbdc053302b7c6 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int a = 1;
int n = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
if (j == i || a == n)
{
cout << a << " " << endl;
a++;
break;
}
else
{
cout << a << " ";
a++;
}
}
if (a > n)
break;
}
return EXIT_SUCCESS;
} | 11.903226 | 32 | 0.401084 | HudzievaPolina |
0bbf5ad61ba8db5ba02b382b9c17078337aa6faa | 1,173 | cpp | C++ | Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp | jesushilarioh/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | 3 | 2019-02-02T16:59:48.000Z | 2019-02-28T14:50:08.000Z | Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | null | null | null | Chapter-4-Making-Decisions/Review Questions and Exercises/Algorithm Workbench/41.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | 4 | 2020-04-10T17:22:17.000Z | 2021-11-04T14:34:00.000Z | /********************************************************************
*
* 41. Match the conditional expression with the if/else
* statement that performs the same operation.
*
* A) q = x < y ? a + b : x * 2;
* B) q = x < y ? x * 2 : a + b;
* C) x < y ? q = 0 : q = 1;
* ____ if (x < y)
* q = 0;
* else
* q = 1;
*
* ____ if (x < y)
* q = a + b;
* else
* q = x * 2;
*
* ____ if (x < y)
* q = x * 2;
* else
* q = a + b;
*
* Jesus Hilario Hernandez
* February 1, 2018
*
********************************************************************/
#include <iostream>
using namespace std;
int main()
{
// Variables
int a, b, q, x, y;
// Solution for A) q = (x < y) ? (a + b) : (x * 2);
if (x < y)
q = a + b;
else
q = x * 2;
// Solution for B) q = x < y ? x * 2 : a + b;
if (x < y)
q = x * 2;
else
q = a + b;
// Solution for C) x < y ? q = 0 : q = 1;
if (x < y)
q = 0;
else
q = 1;
// Terminate program
return 0;
}
| 20.578947 | 69 | 0.311168 | jesushilarioh |
0bc2810b2261b1a9ce35f7563376965ba463f9f4 | 3,211 | cpp | C++ | Sesion2/main.cpp | Miguel445Ar/A-y-R-Algoritmos-1 | c9b64573965d5c4371d2de1a1fff1a9425c34388 | [
"CC0-1.0"
] | null | null | null | Sesion2/main.cpp | Miguel445Ar/A-y-R-Algoritmos-1 | c9b64573965d5c4371d2de1a1fff1a9425c34388 | [
"CC0-1.0"
] | null | null | null | Sesion2/main.cpp | Miguel445Ar/A-y-R-Algoritmos-1 | c9b64573965d5c4371d2de1a1fff1a9425c34388 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using std::cout;
using std::cin;
using std::function;
using std::vector;
using std::sort;
using std::string;
// Functores en C++ (Los de verdad)
class Inc
{
int num;
public:
Inc(int n) : num(n) { }
// This operator overloading enables calling
// operator function () on objects of increment
int operator () (int arr_num) const {
return num + arr_num;
}
int getNum(){
return num;
}
};
int sumar(int a, int b) {
int r = a + b;
return r;
}
void exec(int (*func)(int,int), int a, int b){
cout << func(a,b);
}
int sumar2(int a, int b) {
int r = a + b;
return r;
}
void exec2(function<int(int,int)> func, int a, int b){
cout << func(a,b);
}
template<class T>
struct Elem {
T value;
};
template<class T>
class MyVector {
Elem<T>** arreglo;
size_t size;
function<void(T)> show;
public:
MyVector(function<void(T)> show): show(show){
size = 0;
arreglo = nullptr;
}
void pushBack(T v){
Elem<T>* newValue = new Elem<T>;
newValue->value = v;
Elem<T>** aux = new Elem<T>*[size+1];
for(size_t i = 0; i<size;++i){
aux[i] = arreglo[i];
}
aux[size] = newValue;
if(!arreglo)
delete[] arreglo;
arreglo = aux;
++size;
}
T& operator[](size_t i){
return arreglo[i]->value;
}
size_t Size(){
return this->size;
}
void print(){
for(size_t i = 0; i<size;++i)
show(arreglo[i]->value);
}
};
class Persona {
int dni;
string nombre;
public:
Persona(int dni = 0, string nombre = ""): dni(dni), nombre(nombre){}
string mostrar(){
return std::to_string(dni) + " " + nombre;
}
};
int f(int n){
if (n == 1)
return 1;
return n * f(n-1);
}
// Serie de Fibonacci Recursiva
// Imprimir un triángulo rectángulo de * de forma recursiva
// Imprimir un triángulo equilátero de * de forma recursiva
int main(){
int a = 10;
int b = 8;
vector<int> numeros = {1,4,7,2,8,4,9};
auto comp = [](int a, int b) -> bool { return a < b;};
sort(numeros.begin(),numeros.end(), comp);
for (size_t i = 0;i <numeros.size();++i)
cout << numeros[i] << "\n";
auto show = [](Persona p) -> void {
cout << p.mostrar() << "\n";
};
MyVector<Persona> v(show);
v.pushBack(Persona(12134,"Miguel"));
v.pushBack(Persona(132454356,"Ana"));
v.print();
v.print();
v.print();
cout << "\n";
cout << f(5) << "\n";
//C++
// auto aux = sumar;
// auto aux = [](int a, int b) -> int {
//return a + b;
//};
//function<int(int,int)> aux = sumar;
//vector<function<int(int,int)>> funciones;
//function<int(int,int)> aux = [](int a, int b) -> int {
//return a + b;
//};
//exec2(aux,a,b);
//exec2([](int a, int b) -> int {return a + b; },a,b);
// C
//int (*ptr)(int,int);
//int (*ptr[2])(int,int);
//ptr[0] = sumar;
//ptr[1] = sumar2;
//ptr = &sumar;
//exec(sumar,a,b);
return 0;
} | 20.06875 | 72 | 0.521956 | Miguel445Ar |
0bc4950c55f86ccbab4a1d49be00e9152bf7f157 | 14,926 | cpp | C++ | src/test/UnsupportedAPITests.cpp | ipuustin/crypto-api-toolkit | 87ff5308200ac1b904e45e6778f69a4500ac0d6a | [
"BSD-2-Clause"
] | 28 | 2019-03-29T14:41:27.000Z | 2022-03-29T04:30:36.000Z | src/test/UnsupportedAPITests.cpp | ipuustin/crypto-api-toolkit | 87ff5308200ac1b904e45e6778f69a4500ac0d6a | [
"BSD-2-Clause"
] | 6 | 2021-01-15T19:28:06.000Z | 2022-03-27T15:00:42.000Z | src/test/UnsupportedAPITests.cpp | ipuustin/crypto-api-toolkit | 87ff5308200ac1b904e45e6778f69a4500ac0d6a | [
"BSD-2-Clause"
] | 15 | 2019-05-02T06:32:40.000Z | 2022-02-16T17:24:35.000Z | /*
* Copyright (C) 2019-2020 Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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.
*
*/
/*
* Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
UnsupportedAPITests.cpp
Contains test cases to test unsupported APIs to return errors
*****************************************************************************/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include "UnsupportedAPITests.h"
CPPUNIT_TEST_SUITE_REGISTRATION(UnsupportedAPITests);
void UnsupportedAPITests::testGetOperationState()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_GetOperationState(hSession, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testSetOperationState()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_SetOperationState(hSession, NULL_PTR, 0, 0, 0) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testDigestKey()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CK_OBJECT_HANDLE hObject{};
rv = CRYPTOKI_F_PTR( C_DigestKey(hSession, hObject) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testSignRecoverInit()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CK_OBJECT_HANDLE hObject{0};
CK_MECHANISM mech{};
rv = CRYPTOKI_F_PTR(C_SignRecoverInit (hSession, &mech, hObject) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testSignRecover()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_SignRecover(hSession, NULL_PTR, 0, NULL_PTR, 0) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testVerifyRecoverInit()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR(C_VerifyRecoverInit (hSession, NULL_PTR, 0) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testVerifyRecover()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_VerifyRecover(hSession, NULL_PTR, 0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testDigestEncryptUpdate()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_DigestEncryptUpdate(hSession, NULL_PTR, 0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testDecryptDigestUpdate()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_DecryptDigestUpdate(hSession, NULL_PTR, 0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testSignEncryptUpdate()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_SignEncryptUpdate(hSession, NULL_PTR, 0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testDecryptVerifyUpdate()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_DecryptVerifyUpdate(hSession, NULL_PTR, 0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testDeriveKey()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_DeriveKey(hSession, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testSeedRandom()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_SeedRandom(hSession, NULL_PTR, 0) );
CPPUNIT_ASSERT(rv == CKR_RANDOM_SEED_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
void UnsupportedAPITests::testWaitForSlotEvent()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_WaitForSlotEvent(0, NULL_PTR, NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_SUPPORTED);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
// This is not an unsupported function, but a legacy function returning a standard error code
void UnsupportedAPITests::testGetFunctionStatus()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_GetFunctionStatus(hSession) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_PARALLEL);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
// This is not an unsupported function, but a legacy function returning a standard error code
void UnsupportedAPITests::testCancelFunction()
{
CK_RV rv;
CK_SESSION_HANDLE hSession;
// Just make sure that we finalize any previous tests
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
rv = CRYPTOKI_F_PTR( C_Initialize(NULL_PTR) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_OpenSession(m_initializedTokenSlotID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
rv = CRYPTOKI_F_PTR( C_CancelFunction(hSession) );
CPPUNIT_ASSERT(rv == CKR_FUNCTION_NOT_PARALLEL);
rv = CRYPTOKI_F_PTR( C_CloseSession(hSession) );
CPPUNIT_ASSERT(rv == CKR_OK);
CRYPTOKI_F_PTR( C_Finalize(NULL_PTR) );
}
| 33.466368 | 118 | 0.726718 | ipuustin |
0bc71853638f5b80269dd0cd94279ff60a22cbf6 | 21,082 | cpp | C++ | source/main.cpp | io55/ART_IO55 | 8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7 | [
"Unlicense"
] | 1 | 2022-03-12T02:43:54.000Z | 2022-03-12T02:43:54.000Z | source/main.cpp | io55/ART_IO55 | 8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7 | [
"Unlicense"
] | null | null | null | source/main.cpp | io55/ART_IO55 | 8c7fa55955260a4ba4c780fa8ae8c0bba775e1b7 | [
"Unlicense"
] | null | null | null | #include <grrlib.h>
#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
#include "icon_jpg.h"
#include "terminus_ttf.h"
#include "game/scenegenerator.cpp"
#include "globals.h"
#include "math/camera.h"
#include "menu.h"
#include "options.h"
static inline void PopulateMenuWithStride(Menu& menu, u32 fontSize, math::Vector2u position, math::Vector2u stride,
std::vector<const char*> items)
{
math::Vector2u current = position;
for (const char* item : items) {
menu.addMenuItem({ { current.m_x, current.m_y }, item, fontSize, util::white, util::red });
current.m_x += stride.m_x;
current.m_y += stride.m_y;
}
}
enum class OptionMenuItems : u8 { ObjectCount = 0, WireframeObjectCount, SpawnMode, LightCount };
enum class MainMenuItems : u8 { Start, Options, Extra, Quit };
enum class ExtraMenuItems : u8 { ChangeLog, Controls, GX_S55_1, GX_S55_2 };
int main(int argc, char** argv)
{
srand(time(NULL));
GRRLIB_Init();
WPAD_Init();
WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS);
gMainCamera = new Camera({ 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 });
gFont.init(terminus_ttf, terminus_ttf_size);
GRRLIB_texImg* icon = GRRLIB_LoadTextureJPG(icon_jpg);
float fadeTimer = 0;
Menu mainMenu;
PopulateMenuWithStride(mainMenu, 46, math::Vector2u(64, 80 + static_cast<u32>(icon->h * 0.5f)),
math::Vector2u(0, 48), { "Start", "Options", "Extras", "Exit" });
mainMenu.reset(0);
Menu extraMenu;
PopulateMenuWithStride(extraMenu, 56, math::Vector2u(64, 64), math::Vector2u(32, 64),
{ "What's new?", "Controls", "GX_S55_S1", "GX_S55_S2" });
extraMenu.reset(0);
Menu gameMenu;
PopulateMenuWithStride(gameMenu, 26, math::Vector2u(32, 32), math::Vector2u(0, 24),
{ "Randomise scene", "Randomise size", "Randomise colours", "Randomise lights" });
gameMenu.addMenuItem({ math::Vector2u(32, 128), "PRESS 1 TO HIDE", 26, util::yellow, util::yellow, false });
gameMenu.reset(0);
Menu optionsMenu;
PopulateMenuWithStride(optionsMenu, 46, math::Vector2u(64, 64), math::Vector2u(0, 48),
{ "REPLACE", "REPLACE", "REPLACE", "REPLACE" });
optionsMenu.reset(0);
/* Main menu flow acts as such:
* -> Image fades in
* -> Image fade stops, waits for a second or two
* -> Image fades out
*
* Logo shows
* Main menu renders & updates
* Program state = ProgramState::MainMenu
*/
GRRLIB_SetBackgroundColour(0x00, 0x00, 0x00, 0xFF);
while (!gExit) {
WPAD_ScanPads();
u32 btns_down = WPAD_ButtonsDown(WPAD_CHAN_0);
u32 btns_held = WPAD_ButtonsHeld(WPAD_CHAN_0);
GRRLIB_2dMode();
if (gOptions.m_state != ProgramState::MainGame && gOptions.m_state != ProgramState::GX_S55_S1
&& gOptions.m_state != ProgramState::GX_S55_S2) {
/* Calculate the positional offset and size for each image to allow
* seamless tiled background, using the scaling of the image as well
* as an extra pane that is offset by 1 to fill a gap also generated
* by this algorithm
*/
f32 scale = 0.25f;
u32 amtX = std::ceil(rmode->fbWidth / (icon->w * scale)) + 1;
u32 amtY = std::ceil(rmode->xfbHeight / (icon->h * scale)) + 1;
static f32 scrollTimer = 0;
for (u32 x = 0; x < amtX; x++) {
for (u32 y = 0; y < amtY; y++) {
/* stepX should evaluate to 160 */
f32 stepX = rmode->fbWidth / (amtX - static_cast<f32>(1));
/* ((0 * 160) + {scrolling_offset}) - 160 = -160.? (fills
* the gap left by moving tiles)
* ((1 * 160) + {scrolling_offset}) - 160 = 0.?
* ((2 * 160) + {scrolling_offset}) - 160 = 160.?
* etc.
*/
f32 xPos = ((x * stepX) + scrollTimer) - stepX;
while (xPos > rmode->fbWidth) {
xPos -= rmode->fbWidth + stepX;
}
f32 stepY = rmode->xfbHeight / (amtY - static_cast<f32>(1));
f32 yPos = ((y * stepY) + scrollTimer) - stepY;
while (yPos > rmode->xfbHeight) {
yPos -= rmode->xfbHeight + stepY;
}
GRRLIB_DrawImg(xPos, yPos, icon, 0, scale, scale, util::getColour(0x55, 0x55, 0x55, 0x64));
}
}
scrollTimer += 0.25f;
}
switch (gOptions.m_state) {
case ProgramState::FadeInText: {
u8 alpha = std::min(255.0f, fadeTimer);
GRRLIB_DrawImg((rmode->fbWidth / static_cast<float>(2)) - (icon->w / 2),
(rmode->xfbHeight / static_cast<float>(2)) - (icon->h / 2), icon, 0, 1, 1,
util::getColour(0xFF, 0xFF, 0xFF, alpha));
if (alpha == 255) {
static u32 logoTimer = 0;
if (logoTimer > 64) {
fadeTimer = 255;
gOptions.m_state = ProgramState::FadeOutText;
}
logoTimer += 1;
break;
}
fadeTimer += 2.5f;
break;
}
case ProgramState::FadeOutText: {
u8 alpha = std::max(0.0f, fadeTimer);
GRRLIB_DrawImg((rmode->fbWidth / static_cast<float>(2)) - (icon->w / 2),
(rmode->xfbHeight / static_cast<float>(2)) - (icon->h / 2), icon, 0, 1, 1,
util::getColour(0xFF, 0xFF, 0xFF, alpha));
if (alpha == 0) {
gOptions.m_state = ProgramState::MainMenu;
}
fadeTimer -= 2.5f;
break;
}
case ProgramState::MainMenu: {
constexpr f32 scale = 0.5f;
/* Place image in the middle of the screen */
const u32 xpos = (rmode->fbWidth / static_cast<float>(2)) - ((icon->w * scale) / 2);
GRRLIB_DrawImg(xpos, 64, icon, 0, scale, scale, util::white);
for (MenuItem& item : mainMenu.getItems()) {
item.m_position.m_x = xpos;
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
mainMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
mainMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
const MenuItem& selected = mainMenu.getSelected();
switch ((MainMenuItems)selected.m_index) {
case MainMenuItems::Start:
gOptions.m_state = ProgramState::MainGame;
gSceneGenerator.setup();
break;
case MainMenuItems::Options:
gOptions.m_state = ProgramState::Options;
break;
case MainMenuItems::Extra:
gOptions.m_state = ProgramState::Extras;
break;
case MainMenuItems::Quit:
gExit = true;
break;
default:
break;
}
}
break;
}
case ProgramState::Options: {
for (MenuItem& item : optionsMenu.getItems()) {
char text[0x20];
memset(text, '\0', 0x20);
switch ((OptionMenuItems)item.m_index) {
case OptionMenuItems::ObjectCount:
sprintf(text, "Object count: [%d / %d]", gOptions.m_sceneObjCount.m_x,
gOptions.m_sceneObjCount.m_y);
break;
case OptionMenuItems::WireframeObjectCount:
sprintf(text, "WF obj count: [%d / %d]", gOptions.m_wfObjCount.m_x, gOptions.m_wfObjCount.m_y);
break;
case OptionMenuItems::LightCount:
sprintf(text, "Light count: [%d / %d]", gOptions.m_lightCount.m_x, gOptions.m_lightCount.m_y);
break;
case OptionMenuItems::SpawnMode: {
char type[0x10];
switch (gOptions.m_spawnMode) {
case ObjectSpawnMode::All:
sprintf(type, "All");
break;
case ObjectSpawnMode::Cube:
sprintf(type, "Cube");
break;
case ObjectSpawnMode::Torus:
sprintf(type, "Torus");
break;
case ObjectSpawnMode::Sphere:
sprintf(type, "Sphere");
break;
}
sprintf(text, "Spawn type: [%s]", type);
break;
}
default:
break;
}
item.m_text = text;
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
optionsMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
optionsMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
}
if (btns_down & WPAD_BUTTON_RIGHT) {
const MenuItem& item = optionsMenu.getSelected();
switch (item.m_index) {
case OptionMenuItems::ObjectCount:
gOptions.toggleOptionObjectCount(true);
break;
case OptionMenuItems::WireframeObjectCount:
gOptions.toggleOptionWfObjCount(true);
break;
case OptionMenuItems::SpawnMode:
gOptions.toggleOptionSpawnMode(true);
break;
case OptionMenuItems::LightCount:
gOptions.toggleOptionLightCount(true);
break;
default:
break;
}
} else if (btns_down & WPAD_BUTTON_LEFT) {
const MenuItem& item = optionsMenu.getSelected();
switch ((OptionMenuItems)item.m_index) {
case OptionMenuItems::ObjectCount:
gOptions.toggleOptionObjectCount(false);
break;
case OptionMenuItems::WireframeObjectCount:
gOptions.toggleOptionWfObjCount(false);
break;
case OptionMenuItems::SpawnMode:
gOptions.toggleOptionSpawnMode(false);
break;
case OptionMenuItems::LightCount:
gOptions.toggleOptionLightCount(false);
break;
default:
break;
}
}
break;
}
case ProgramState::Extras: {
for (MenuItem& item : extraMenu.getItems()) {
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
extraMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
extraMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
MenuItem& selected = extraMenu.getSelected();
switch ((ExtraMenuItems)selected.m_index) {
case ExtraMenuItems::ChangeLog:
gOptions.m_state = ProgramState::ChangeLog;
break;
case ExtraMenuItems::Controls:
gOptions.m_state = ProgramState::Controls;
break;
case ExtraMenuItems::GX_S55_1:
gOptions.m_state = ProgramState::GX_S55_S1;
break;
case ExtraMenuItems::GX_S55_2:
gOptions.m_state = ProgramState::GX_S55_S2;
break;
default:
break;
}
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
}
break;
}
case ProgramState::Controls: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
gFont.printf(64, 64, "Game Controls", 46, util::white);
gFont.printf(64, 96 + 28 * 1, "1) 1 - hide UI", 26, util::white);
gFont.printf(64, 96 + 28 * 2, " (after hiding UI)", 26, util::white);
gFont.printf(64, 96 + 28 * 3, "2) 2 - regenerate scene", 26, util::white);
gFont.printf(64, 96 + 28 * 4, "3) A - stop Camera rotation", 26, util::white);
gFont.printf(64, 244, "Menu-specific Controls", 46, util::white);
gFont.printf(64, (244 + 32) + 28 * 1, "1) DPAD Up / Down - change selection", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 2, "2) DPAD Right / Left - modify selection", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 3, "3) A - select", 26, util::white);
gFont.printf(64, (244 + 32) + 28 * 4, "4) B - back", 26, util::white);
break;
}
case ProgramState::ChangeLog: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
gFont.printf(64, 64, "What's new?", 56,
util::getColour(abs(sin(gTimer / 10)) * 255, abs(cos(gTimer / 10)) * 255, 0));
gFont.printf(64, 96 + 28 * 1, "Version 1.1", 36, util::white);
gFont.printf(64, 96 + 32 * 2, "- Added extras, changelog and controls", 26, util::white);
gFont.printf(64, 96 + 32 * 3, " screen", 26, util::white);
gFont.printf(64, 96 + 32 * 4, "- Added a pause button in the main scene", 26, util::white);
gFont.printf(64, 96 + 32 * 5, "- Added scenes from an old project (GX_S55)", 26, util::white);
gFont.printf(64, 96 + 32 * 6, "- Internal code clean-up", 26, util::white);
break;
}
case ProgramState::GX_S55_S1: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
static f32 gxTimer = 0;
const f32 xyBase = (sin(gxTimer / 17.5f) * 20);
gMainCamera->position() = { xyBase - 20, xyBase - 10, static_cast<f32>((cos(gxTimer / 17.5) * 20) - 20) };
gMainCamera->lookAt() = { 0, 0, 0 };
gMainCamera->applyCamera();
GRRLIB_SetLightAmbient(util::black);
GRRLIB_SetLightDiff(0, gMainCamera->position(), 5, 2, util::getColour(0xFF, 0xAA, 0x00));
for (u32 lanes = 0; lanes < 10; lanes++) {
for (u32 i = 0; i < 15; i++) {
GRRLIB_ObjectViewInv(lanes * 1.5f, 0, i * 2 / lanes, 0, 0, gxTimer * (3 + 1.15f * i), 1, 1, 1);
GRRLIB_DrawCube(1, true, 0xFFFFFFFF);
}
}
gxTimer += 0.05f;
break;
}
case ProgramState::GX_S55_S2: {
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::Extras;
}
static f32 cameraRotation = 0;
static f32 cameraYOffset = 7.5f;
constexpr f32 offset = 20.0f;
constexpr f32 cameraOffset = 25.0f;
if (btns_held & WPAD_BUTTON_LEFT) {
cameraRotation -= 0.025f;
} else if (btns_held & WPAD_BUTTON_RIGHT) {
cameraRotation += 0.025f;
}
if (btns_held & WPAD_BUTTON_UP) {
cameraYOffset = std::min(cameraYOffset + 0.1f, 42.5f);
} else if (btns_held & WPAD_BUTTON_DOWN) {
cameraYOffset = std::max(cameraYOffset - 0.1f, 2.5f);
}
gMainCamera->lookAt() = { offset, 0, offset };
gMainCamera->position() = { static_cast<f32>(offset + sin(cameraRotation) * cameraOffset), cameraYOffset,
static_cast<f32>(offset + cos(cameraRotation) * cameraOffset) };
gMainCamera->applyCamera();
GRRLIB_SetLightAmbient(0x000000FF);
guVector lightPos
= { static_cast<f32>(abs(sin(gTimer / 4) * cameraOffset)), static_cast<f32>(8 + abs(cos(gTimer))),
static_cast<f32>(abs(cos(gTimer / 4) * cameraOffset)) };
GRRLIB_ObjectViewInv(lightPos.x, lightPos.y - 2, lightPos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawSphere(1, 10, 10, true, util::white);
GRRLIB_SetLightDiff(0, lightPos, 10, 10, 0x623499FF);
static float timer = 0;
const f32 stride = 2;
for (u32 i = 0; i < 20; i++) {
for (u32 j = 0; j < 20; j++) {
guVector pos = { i * stride, 0, j * stride };
if (i == 10 && j == 10) {
GRRLIB_ObjectViewInv(pos.x, 3, pos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawCube(1, true, util::red);
}
pos.y += sin((gTimer * j) / 10) / 5;
pos.y += cos((gTimer * i) / 10) / 10;
GRRLIB_ObjectViewInv(pos.x, pos.y, pos.z, 0, 0, 0, 1, 1, 1);
GRRLIB_DrawCylinder(
1, 1.5f, 10, i % static_cast<u32>(timer) == 0 || j % static_cast<u32>(timer) == 0, util::white);
}
}
timer += 0.05f;
if (timer > 19.5f) {
timer = 0.5f;
}
break;
}
case ProgramState::MainGame: {
static f32 camRotTimer = 0;
static guVector camPos;
if (!(!gOptions.m_showUI && btns_held & WPAD_BUTTON_A)) {
camPos.x = sin(camRotTimer * 0.05f) * 20;
camPos.z = cos(camRotTimer * 0.05f) * 20;
camPos.y = 10 + sin(camRotTimer * 0.01f) * 5;
camRotTimer += 0.05f;
}
gMainCamera->position() = camPos;
gMainCamera->lookAt() = { 0, 0, 0 };
gMainCamera->applyCamera();
gSceneGenerator.render();
GRRLIB_2dMode();
if (gOptions.m_showUI) {
GRRLIB_Rectangle(32, 36, 226, 120, util::getColour(0x44, 0x44, 0x44), true);
for (MenuItem& item : gameMenu.getItems()) {
item.render(gFont);
}
if (btns_down & WPAD_BUTTON_UP) {
gameMenu.moveSelected(MenuDirection::Up);
} else if (btns_down & WPAD_BUTTON_DOWN) {
gameMenu.moveSelected(MenuDirection::Down);
}
if (btns_down & WPAD_BUTTON_A) {
const MenuItem& item = gameMenu.getSelected();
switch (item.m_index) {
case 0:
gSceneGenerator.setup();
break;
case 1:
for (auto& obj : gSceneGenerator.m_objects) {
obj.rngScaling();
}
for (auto& obj : gSceneGenerator.m_wfObjects) {
obj.rngScaling();
}
break;
case 2:
for (auto& obj : gSceneGenerator.m_objects) {
obj.rngColour();
}
for (auto& obj : gSceneGenerator.m_wfObjects) {
obj.rngColour();
}
break;
case 3:
gSceneGenerator.randomiseLights();
break;
default:
break;
}
}
} else if (btns_down & WPAD_BUTTON_2) {
gSceneGenerator.setup();
}
if (btns_down & WPAD_BUTTON_1) {
gOptions.m_showUI = !gOptions.m_showUI;
}
if (btns_down & WPAD_BUTTON_B) {
gOptions.m_state = ProgramState::MainMenu;
mainMenu.reset(0);
}
break;
}
}
GRRLIB_Render();
gTimer += 0.05f;
}
delete gMainCamera;
GRRLIB_FreeTexture(icon);
GRRLIB_Exit();
exit(0);
} | 39.040741 | 120 | 0.482592 | io55 |
0bca0f63f9af371a9f9df2a4d47ff4650e9eee5e | 378 | cpp | C++ | Security/2_Terminology_and_Concepts/Security-Message_Space_and_Ciphertext_Space/security-message-space-and-ciphertext-space.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | Security/2_Terminology_and_Concepts/Security-Message_Space_and_Ciphertext_Space/security-message-space-and-ciphertext-space.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | Security/2_Terminology_and_Concepts/Security-Message_Space_and_Ciphertext_Space/security-message-space-and-ciphertext-space.cpp | christosg88/hackerrank | 21bc44aac842325ad0a48265658f7674984aeff2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
int main()
{
std::ios_base::sync_with_stdio(false);
std::string plaintext;
std::cin >> plaintext;
std::string cyphertext(plaintext, 0);
for (size_t i = 0, length = cyphertext.length(); i < length; i++)
cyphertext[i] = (((int)(cyphertext[i] - '0') + 1) % 10) + '0';
std::cout << cyphertext << '\n';
return 0;
} | 21 | 67 | 0.592593 | christosg88 |
0bca657a0e975efae2c82aeab5fc93f3d027b8dc | 722 | hpp | C++ | test/openp2p/src/OpenP2P/Crypt/ECDSA/PrivateKey.hpp | goodspeed24e/2014iOT | 139f6e2131f8a94cb876328b5f733e3feef77707 | [
"MIT"
] | null | null | null | test/openp2p/src/OpenP2P/Crypt/ECDSA/PrivateKey.hpp | goodspeed24e/2014iOT | 139f6e2131f8a94cb876328b5f733e3feef77707 | [
"MIT"
] | null | null | null | test/openp2p/src/OpenP2P/Crypt/ECDSA/PrivateKey.hpp | goodspeed24e/2014iOT | 139f6e2131f8a94cb876328b5f733e3feef77707 | [
"MIT"
] | null | null | null | #ifndef OPENP2P_CRYPT_ECDSA_PRIVATEKEY_HPP
#define OPENP2P_CRYPT_ECDSA_PRIVATEKEY_HPP
#include <cryptopp/eccrypto.h>
#include <cryptopp/ecp.h>
#include <cryptopp/sha.h>
#include <OpenP2P/Crypt/ECDSA/Curve.hpp>
namespace OpenP2P {
namespace Crypt {
class RandomPool;
namespace ECDSA {
class PrivateKey {
public:
PrivateKey();
PrivateKey(RandomPool& pool, Curve curve);
operator CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey& ();
operator const CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey& () const;
private:
CryptoPP::ECDSA<CryptoPP::ECP, CryptoPP::SHA256>::PrivateKey privateKey_;
};
}
}
}
#endif
| 18.512821 | 91 | 0.680055 | goodspeed24e |
0bcc54ac82e17955fc42528cc2f78e58a1799faf | 350 | hpp | C++ | kernel/lib/bitmap.hpp | ethan4984/rock | 751b9af1009b622bedf384c1f80970b333c436c3 | [
"BSD-2-Clause"
] | 207 | 2020-05-27T21:57:28.000Z | 2022-02-26T15:17:27.000Z | kernel/lib/bitmap.hpp | ethan4984/crepOS | 751b9af1009b622bedf384c1f80970b333c436c3 | [
"BSD-2-Clause"
] | 3 | 2020-07-26T18:14:05.000Z | 2020-12-09T05:32:07.000Z | kernel/lib/bitmap.hpp | ethan4984/rock | 751b9af1009b622bedf384c1f80970b333c436c3 | [
"BSD-2-Clause"
] | 17 | 2020-07-05T19:08:48.000Z | 2021-10-13T12:30:13.000Z | #ifndef BITMAP_HPP_
#define BITMAP_HPP_
#include <cstddef>
#include <cstdint>
#include <types.hpp>
namespace lib {
class bitmap {
public:
bitmap(size_t inital_size, bool can_grow = false);
bitmap() = default;
ssize_t alloc();
void free(size_t index);
private:
uint8_t *bm;
size_t bm_size;
bool can_grow;
};
}
#endif
| 13.461538 | 54 | 0.674286 | ethan4984 |
0bd802c971a528be05a7c16576008aa2e15705f0 | 194 | cc | C++ | source/agent/addons/audioRanker/addon.cc | andreasunterhuber/owt-server | 128b83714361c0b543ec44fc841c9094f4267633 | [
"Apache-2.0"
] | 890 | 2019-03-08T08:04:10.000Z | 2022-03-30T03:07:44.000Z | source/agent/addons/audioRanker/addon.cc | vgemv/owt-server | fa6070af33feeeb79a962de08307ac5092991cbf | [
"Apache-2.0"
] | 583 | 2019-03-11T10:27:42.000Z | 2022-03-29T01:41:28.000Z | source/agent/addons/audioRanker/addon.cc | vgemv/owt-server | fa6070af33feeeb79a962de08307ac5092991cbf | [
"Apache-2.0"
] | 385 | 2019-03-08T07:50:13.000Z | 2022-03-29T06:36:28.000Z | // Copyright (C) <2019> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "AudioRankerWrapper.h"
#include <nan.h>
using namespace v8;
NODE_MODULE(addon, AudioRanker::Init)
| 17.636364 | 41 | 0.737113 | andreasunterhuber |
0bdcd1f139ccc1dbe76f6c6be173579a63dcd9ff | 3,009 | hxx | C++ | main/chart2/source/view/main/VTitle.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/chart2/source/view/main/VTitle.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/chart2/source/view/main/VTitle.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _CHART2_VTITLE_HXX
#define _CHART2_VTITLE_HXX
#include <com/sun/star/chart2/XTitle.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class VTitle
{
public:
VTitle( const ::com::sun::star::uno::Reference<
::com::sun::star::chart2::XTitle > & xTitle );
virtual ~VTitle();
void init( const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes >& xTargetPage
, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
, const rtl::OUString& rCID );
void createShapes( const ::com::sun::star::awt::Point& rPos
, const ::com::sun::star::awt::Size& rReferenceSize );
double getRotationAnglePi() const;
::com::sun::star::awt::Size getUnrotatedSize() const;
::com::sun::star::awt::Size getFinalSize() const;
void changePosition( const ::com::sun::star::awt::Point& rPos );
private:
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes > m_xTarget;
::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory> m_xShapeFactory;
::com::sun::star::uno::Reference<
::com::sun::star::chart2::XTitle > m_xTitle;
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape > m_xShape;
rtl::OUString m_aCID;
double m_fRotationAngleDegree;
sal_Int32 m_nXPos;
sal_Int32 m_nYPos;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
| 37.6125 | 111 | 0.52775 | Grosskopf |
0bdce7529632b1136276ef0cd58ec9ec58eade22 | 8,897 | cc | C++ | centreon-engine/src/configuration/daterange.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 8 | 2020-07-26T09:12:02.000Z | 2022-03-30T17:24:29.000Z | centreon-engine/src/configuration/daterange.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 47 | 2020-06-18T12:11:37.000Z | 2022-03-16T10:28:56.000Z | centreon-engine/src/configuration/daterange.cc | centreon/centreon-collect | e63fc4d888a120d588a93169e7d36b360616bdee | [
"Unlicense"
] | 5 | 2020-06-29T14:22:02.000Z | 2022-03-17T10:34:10.000Z | /*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine 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 Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include "com/centreon/engine/configuration/daterange.hh"
using namespace com::centreon::engine::configuration;
/**
* Constructor.
*
* @param[in] type The date range type.
*/
daterange::daterange(type_range type)
: _month_end(0),
_month_start(0),
_month_day_end(0),
_month_day_start(0),
_skip_interval(0),
_type(type),
_week_day_end(0),
_week_day_start(0),
_week_day_end_offset(0),
_week_day_start_offset(0),
_year_end(0),
_year_start(0) {}
/**
* Copy constructor.
*
* @param[in] right The object to copy.
*/
daterange::daterange(daterange const& right) {
operator=(right);
}
/**
* Destructor.
*/
daterange::~daterange() {}
/**
* Copy operator.
*
* @param[in] right The object to copy.
*
* @return This object.
*/
daterange& daterange::operator=(daterange const& right) {
if (this != &right) {
_month_end = right._month_end;
_month_start = right._month_start;
_month_day_end = right._month_day_end;
_month_day_start = right._month_day_start;
_skip_interval = right._skip_interval;
_timeranges = right._timeranges;
_type = right._type;
_week_day_end = right._week_day_end;
_week_day_start = right._week_day_start;
_week_day_end_offset = right._week_day_end_offset;
_week_day_start_offset = right._week_day_start_offset;
_year_end = right._year_end;
_year_start = right._year_start;
}
return (*this);
}
/**
* Equal operator.
*
* @param[in] right The object to compare.
*
* @return True if object is the same, otherwise false.
*/
bool daterange::operator==(daterange const& right) const throw() {
return (_month_end == right._month_end &&
_month_start == right._month_start &&
_month_day_end == right._month_day_end &&
_month_day_start == right._month_day_start &&
_skip_interval == right._skip_interval &&
_timeranges == right._timeranges && _type == right._type &&
_week_day_end == right._week_day_end &&
_week_day_start == right._week_day_start &&
_week_day_end_offset == right._week_day_end_offset &&
_week_day_start_offset == right._week_day_start_offset &&
_year_end == right._year_end && _year_start == right._year_start);
}
/**
* Not equal operator.
*
* @param[in] right The object to compare.
*
* @return True if object is not the same, otherwise false.
*/
bool daterange::operator!=(daterange const& right) const throw() {
return (!operator==(right));
}
/**
* Less-than operator.
*
* @param[in] right Object to compare to.
*
* @return True if this object is less than right.
*/
bool daterange::operator<(daterange const& right) const throw() {
if (_month_end != right._month_end)
return (_month_end < right._month_end);
else if (_month_start != right._month_start)
return (_month_start < right._month_start);
else if (_month_day_end != right._month_day_end)
return (_month_day_end < right._month_day_end);
else if (_month_day_start != right._month_day_start)
return (_month_day_start < right._month_day_start);
else if (_skip_interval != right._skip_interval)
return (_skip_interval < right._skip_interval);
else if (_type != right._type)
return (_type < right._type);
else if (_week_day_end != right._week_day_end)
return (_week_day_end < right._week_day_end);
else if (_week_day_start != right._week_day_start)
return (_week_day_start < right._week_day_start);
else if (_week_day_end_offset != right._week_day_end_offset)
return (_week_day_end_offset < right._week_day_end_offset);
else if (_week_day_start_offset != right._week_day_start_offset)
return (_week_day_start_offset < right._week_day_start_offset);
else if (_year_end != right._year_end)
return (_year_end < right._year_end);
else if (_year_start != right._year_start)
return (_year_start < right._year_start);
return (_timeranges < right._timeranges);
}
/**
* Set month_end value.
*
* @param[in] value The new month_end value.
*/
void daterange::month_end(unsigned int value) {
_month_end = value;
}
/**
* Get month_end value.
*
* @return The month_end value.
*/
unsigned int daterange::month_end() const throw() {
return (_month_end);
}
/**
* Set month_start value.
*
* @param[in] value The new month_start value.
*/
void daterange::month_start(unsigned int value) {
_month_start = value;
}
/**
* Get month_start value.
*
* @return The month_start value.
*/
unsigned int daterange::month_start() const throw() {
return (_month_start);
}
/**
* Set month_day_end value.
*
* @param[in] value The new month_day_end value.
*/
void daterange::month_day_end(int value) {
_month_day_end = value;
}
/**
* Get month_day_end value.
*
* @return The month_day_end value.
*/
int daterange::month_day_end() const throw() {
return (_month_day_end);
}
/**
* Set month_day_start value.
*
* @param[in] value The new month_day_start value.
*/
void daterange::month_day_start(int value) {
_month_day_start = value;
}
/**
* Get month_day_start value.
*
* @return The month_day_start value.
*/
int daterange::month_day_start() const throw() {
return (_month_day_start);
}
/**
* Set skip_interval value.
*
* @param[in] value The new skip_interval value.
*/
void daterange::skip_interval(unsigned int value) {
_skip_interval = value;
}
/**
* Get skip_interval value.
*
* @return The skip_interval value.
*/
unsigned int daterange::skip_interval() const throw() {
return (_skip_interval);
}
/**
* Get timeranges value.
*
* @return The timeranges value.
*/
void daterange::timeranges(std::list<timerange> const& value) {
_timeranges = value;
}
/**
* Set timeranges value.
*
* @param[in] value The new timeranges value.
*/
std::list<timerange> const& daterange::timeranges() const throw() {
return (_timeranges);
}
/**
* Set type value.
*
* @param[in] value The new type value.
*/
void daterange::type(type_range value) {
_type = value;
}
/**
* Get type value.
*
* @return The type value.
*/
daterange::type_range daterange::type() const throw() {
return (_type);
}
/**
* Set week_day_end value.
*
* @param[in] value The new week_day_end value.
*/
void daterange::week_day_end(unsigned int value) {
_week_day_end = value;
}
/**
* Get week_day_end value.
*
* @return The week_day_end value.
*/
unsigned int daterange::week_day_end() const throw() {
return (_week_day_end);
}
/**
* Set week_day_start value.
*
* @param[in] value The new week_day_start value.
*/
void daterange::week_day_start(unsigned int value) {
_week_day_start = value;
}
/**
* Get week_day_start value.
*
* @return The week_day_start value.
*/
unsigned int daterange::week_day_start() const throw() {
return (_week_day_start);
}
/**
* Set week_day_end_offset value.
*
* @param[in] value The new week_day_end_offset value.
*/
void daterange::week_day_end_offset(int value) {
_week_day_end_offset = value;
}
/**
* Get week_day_end_offset value.
*
* @return The week_day_end_offset value.
*/
int daterange::week_day_end_offset() const throw() {
return (_week_day_end_offset);
}
/**
* Set week_day_start_offset value.
*
* @param[in] value The new week_day_start_offset value.
*/
void daterange::week_day_start_offset(int value) {
_week_day_start_offset = value;
}
/**
* Get week_day_start_offset value.
*
* @return The week_day_start_offset value.
*/
int daterange::week_day_start_offset() const throw() {
return (_week_day_start_offset);
}
/**
* Set year_end value.
*
* @param[in] value The new year_end value.
*/
void daterange::year_end(unsigned int value) {
_year_end = value;
}
/**
* Get year_end value.
*
* @return The year_end value.
*/
unsigned int daterange::year_end() const throw() {
return (_year_end);
}
/**
* Set year_start value.
*
* @param[in] value The new year_start value.
*/
void daterange::year_start(unsigned int value) {
_year_start = value;
}
/**
* Get year_start value.
*
* @return The year_start value.
*/
unsigned int daterange::year_start() const throw() {
return (_year_start);
}
| 23.229765 | 76 | 0.688771 | centreon |
0be023d8a91bfd830b80ba1c0fccebe175f68e89 | 6,642 | cpp | C++ | Engine/source/gfx/gl/ggl/mac/aglBind.cpp | camporter/Torque3D | 938e28b6f36883cb420da4b04253b1394467a1f4 | [
"Unlicense"
] | 13 | 2015-04-13T21:46:01.000Z | 2017-11-20T22:12:04.000Z | Engine/source/gfx/gl/ggl/mac/aglBind.cpp | camporter/Torque3D | 938e28b6f36883cb420da4b04253b1394467a1f4 | [
"Unlicense"
] | 1 | 2015-11-16T23:57:12.000Z | 2015-12-01T03:24:08.000Z | Engine/source/gfx/gl/ggl/mac/aglBind.cpp | camporter/Torque3D | 938e28b6f36883cb420da4b04253b1394467a1f4 | [
"Unlicense"
] | 10 | 2015-01-05T15:58:31.000Z | 2021-11-20T14:05:46.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 <err.h>
#include "agl.h"
#include "platform/platform.h"
//-----------------------------------------------------------------------------
// Instantiation of function pointers.
#define GL_GROUP_BEGIN(name)
#define GL_FUNCTION(name, type, args) type (XGL_DLL *name) args;
#define GL_GROUP_END()
#include "../generated/glcfn.h"
#undef GL_GROUP_BEGIN
#undef GL_FUNCTION
#undef GL_GROUP_END
#define EXECUTE_ONLY_ONCE() \
static bool _doneOnce = false; \
if(_doneOnce) return; \
_doneOnce = true;
namespace GL
{
//-----------------------------------------------------------------------------
// The OpenGL Bundle is shared by all the devices.
static CFBundleRef _openglFrameworkRef;
// Unlike WGL, AGL does not require a set of function pointers per
// context pixel format. All functions in the DLL are bound in a single
// table and shared by all contexts.
static AGLExtensionPtrs _LibraryFunctions;
static AGLExtensionFlags _ExtensionFlags;
bool hasExtension(const char *name,const char* extensions);
bool hasVersion(const char *name,const char* prefix,int major,int minor);
//-----------------------------------------------------------------------------
void* MacGetProcAddress(CFBundleRef bundle,char* name)
{
CFStringRef cfName = CFStringCreateWithCString(kCFAllocatorDefault, name, CFStringGetSystemEncoding());
void* ret = CFBundleGetFunctionPointerForName(bundle, cfName);
CFRelease(cfName);
return ret;
}
//-----------------------------------------------------------------------------
bool bindFunction(CFBundleRef bundle,void *&fnAddress, const char *name)
{
CFStringRef cfName = CFStringCreateWithCString(0,name,CFStringGetSystemEncoding());
fnAddress = CFBundleGetFunctionPointerForName(bundle, cfName);
CFRelease(cfName);
return fnAddress != 0;
}
//-----------------------------------------------------------------------------
bool gglBindCoreFunctions(CFBundleRef bundle,AGLExtensionPtrs* glp)
{
bool bound = true;
// Bind static functions which are quarenteed to be part of the
// OpenGL library. In this case, OpenGL 1.0 and GLX 1.0 functions
#define GL_GROUP_BEGIN(name)
#define GL_GROUP_END()
#define GL_FUNCTION(fn_name, fn_return, fn_args) \
bound &= bindFunction(bundle,*(void**)&fn_name, #fn_name);
#include "../generated/glcfn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
// Try and bind all known extension functions. We'll check later to
// see which ones are actually valid for a context.
#define GL_GROUP_BEGIN(name)
#define GL_FUNCTION(fn_name, fn_return, fn_args) \
bindFunction(bundle,*(void**)&glp->_##fn_name, #fn_name);
#define GL_GROUP_END()
#include "../generated/glefn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
return bound;
}
//-----------------------------------------------------------------------------
bool gglBindExtensions(GLExtensionFlags* gl)
{
dMemset(gl,0,sizeof(GLExtensionFlags));
// Get GL version and extensions
const char* glExtensions = (const char*)glGetString(GL_EXTENSIONS);
const char* glVersion = (const char*) glGetString(GL_VERSION);
if (!glExtensions || !glVersion)
return false;
// Parse the GL version string "major.minor"
const char *itr = glVersion;
int glMajor = atoi(itr);
while (isdigit(*itr))
*itr++;
int glMinor = atoi(++itr);
// Check which extensions are available on the active context.
// GL and GLX versions ubove 1.0 are also tested here.
#define GL_GROUP_BEGIN(name) \
gl->has_##name = hasVersion(#name,"GL_VERSION",glMajor,glMinor) || \
hasExtension(#name,glExtensions);
#define GL_FUNCTION(fn_name, fn_return, fn_args)
#define GL_GROUP_END()
#include "../generated/glefn.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
gl->bound = true;
return true;
}
#define _hasGLXExtension(display,name) (display->glx.has_##name)
//-----------------------------------------------------------------------------
void gglPerformBinds()
{
// Some of the following code is copied from the Apple Opengl Documentation.
// Load and bind OpenGL bundle functions
if (!_openglFrameworkRef) {
// Load OpenGL.framework
_openglFrameworkRef = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
if (!_openglFrameworkRef) {
warn("Could not create OpenGL Framework bundle");
return;
}
if (!CFBundleLoadExecutable(_openglFrameworkRef)) {
warn("Could not load MachO executable");
return;
}
// Bind our functions.
if (!gglBindCoreFunctions(_openglFrameworkRef, &_LibraryFunctions)) {
warn("GLDevice: Failed to bind all core functions");
return;
}
// Save the pointer to the set of opengl functions
_GGLptr = &_LibraryFunctions;
}
}
//-----------------------------------------------------------------------------
void gglPerformExtensionBinds(void *context)
{
// we don't care about the passed context when binding the opengl functions,
// we only care about the current opengl context.
if( !_openglFrameworkRef || !_GGLptr )
{
gglPerformBinds();
}
gglBindExtensions( &_ExtensionFlags );
_GGLflag = &_ExtensionFlags;
}
} // Namespace
| 33.887755 | 106 | 0.631286 | camporter |
0be32f6e8335377b2d68fade9fd7747cca977aa9 | 3,832 | hpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | 3 | 2020-11-07T07:01:59.000Z | 2022-03-06T10:54:52.000Z | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | 1 | 2020-11-14T16:53:09.000Z | 2020-11-14T16:53:09.000Z | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/ToggleButton.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | 3 | 2020-03-15T14:35:38.000Z | 2021-04-07T14:55:42.000Z | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef TOGGLEBUTTON_HPP
#define TOGGLEBUTTON_HPP
#include <touchgfx/widgets/Button.hpp>
namespace touchgfx
{
/**
* @class ToggleButton ToggleButton.hpp touchgfx/widgets/ToggleButton.hpp
*
* @brief A ToggleButton is a Button specialization that swaps the two bitmaps when clicked.
*
* A ToggleButton is a Button specialization that swaps the two bitmaps when clicked,
* such that the previous "pressed" bitmap, now becomes the one displayed when button is
* not pressed.
*
* @see Button
*/
class ToggleButton : public Button
{
public:
/**
* @fn ToggleButton::ToggleButton();
*
* @brief Default constructor.
*
* Default constructor.
*/
ToggleButton();
/**
* @fn virtual void ToggleButton::setBitmaps(const Bitmap& bmpReleased, const Bitmap& bmpPressed)
*
* @brief Sets the bitmaps.
*
* Sets the bitmaps.
*
* @note This specific implementation remembers what bitmap was used as pressed, in order to
* support the ability to force the state.
*
* @param bmpReleased The bitmap to show in the "normal" state, ie when button is not pressed.
* @param bmpPressed The bitmap to show when the button is pressed.
*
* @see Button::setBitmaps
*/
virtual void setBitmaps(const Bitmap& bmpReleased, const Bitmap& bmpPressed)
{
originalPressed = bmpPressed;
Button::setBitmaps(bmpReleased, bmpPressed);
}
/**
* @fn void ToggleButton::forceState(bool activeState);
*
* @brief Force the button into a specific state.
*
* Use this function to force the button in one of the two possible states. If
* button is forced to the active state, then the pressed bitmap from the last call
* to setBitmaps becomes the one displayed when button is not pressed.
*
* @param activeState If true, display the bmpPressed bitmap when not pressed. If false display
* the bmpReleased bitmap.
*/
void forceState(bool activeState);
/**
* @fn bool ToggleButton::getState() const
*
* @brief Gets the state.
*
* Gets the state.
*
* @return true if state is currently active.
*/
bool getState() const
{
return up == originalPressed;
}
/**
* @fn virtual void ToggleButton::handleClickEvent(const ClickEvent& event);
*
* @brief Overrides handleClickEvent.
*
* Overrides handleClickEvent in order to swap the bitmaps after being clicked.
*
* @param event The event to handle.
*/
virtual void handleClickEvent(const ClickEvent& event);
/**
* @fn virtual uint16_t ToggleButton::getType() const
*
* @brief For GUI testing only.
*
* For GUI testing only. Returns type of this drawable.
*
* @return TYPE_TOGGLEBUTTON.
*/
virtual uint16_t getType() const
{
return (uint16_t)TYPE_TOGGLEBUTTON;
}
protected:
Bitmap originalPressed; ///< Contains the bitmap that was originally being displayed when button is pressed.
};
} // namespace touchgfx
#endif // TOGGLEBUTTON_HPP
| 30.412698 | 112 | 0.61143 | ramkumarkoppu |
0be56dc2b2cde2157428b68d2bcb3524a3dbcdb5 | 51 | hh | C++ | RAVL2/MSVC/include/Ravl/DList.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/DList.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/MSVC/include/Ravl/DList.hh | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null |
#include "../.././Core/Container/DList/DList.hh"
| 12.75 | 48 | 0.627451 | isuhao |
0be9e2f4b4680081b0905ea468680ce0b89a4f02 | 12,781 | hh | C++ | maps/mi.hh | krishna-beemanapalli/PlotSim | 5c90671798db323a6109e1cdfa6fbbf8b96fb713 | [
"MIT"
] | 6 | 2020-03-30T15:18:23.000Z | 2020-05-09T01:24:22.000Z | maps/mi.hh | krishna-beemanapalli/PlotSim | 5c90671798db323a6109e1cdfa6fbbf8b96fb713 | [
"MIT"
] | 1 | 2020-05-06T20:41:07.000Z | 2020-05-06T20:41:07.000Z | maps/mi.hh | krishna-beemanapalli/PlotSim | 5c90671798db323a6109e1cdfa6fbbf8b96fb713 | [
"MIT"
] | 4 | 2020-04-22T06:48:32.000Z | 2020-10-21T01:03:08.000Z | static short state[][3] =
{
0, -210, -403, 1, -211, -433, 1, -240, -432, 1, -239, -417, 1, -210, -403, 0, -157, -449, 1, -157, -469, 1, -191, -496,
1, -197, -468, 1, -187, -454, 1, -157, -449, 0, 108, -41, 1, 125, -45, 1, 136, -64, 1, 115, -66, 1, 105, -69,
1, 87, -51, 1, 108, -41, 0, 177, -120, 1, 178, -87, 1, 210, -84, 1, 211, -103, 1, 211, -123, 1, 208, -135,
1, 182, -145, 1, 170, -147, 1, 170, -141, 1, 177, -120, 0, 290, -357, 1, 263, -353, 1, 269, -328, 1, 274, -310,
1, 277, -306, 1, 284, -318, 1, 288, -341, 1, 290, -357, 0, 393, -462, 1, 413, -460, 1, 437, -460, 1, 440, -483,
1, 452, -487, 1, 464, -519, 1, 448, -562, 1, 461, -583, 1, 441, -617, 1, 422, -621, 1, 412, -617, 1, 412, -590,
1, 403, -567, 1, 387, -528, 1, 387, -499, 1, 393, -462, 0, 340, -583, 1, 347, -574, 1, 371, -581, 1, 374, -607,
1, 362, -612, 1, 348, -606, 1, 340, -583, 0, 447, -656, 1, 463, -654, 1, 466, -625, 1, 482, -630, 1, 492, -655,
1, 478, -668, 1, 461, -670, 1, 447, -656, 0, 532, -631, 1, 548, -640, 1, 551, -659, 1, 539, -660, 1, 532, -652,
1, 521, -635, 1, 532, -631, 0, 922, -743, 1, 927, -748, 1, 922, -761, 1, 911, -755, 1, 911, -749, 1, 922, -743,
0, 926, -669, 1, 931, -669, 1, 933, -675, 1, 924, -682, 1, 917, -694, 1, 904, -694, 1, 904, -684, 1, 926, -669,
0, 1009, -590, 1, 1039, -589, 1, 1052, -598, 1, 1070, -611, 1, 1050, -624, 1, 1041, -641, 1, 1027, -642, 1, 1007, -633,
1, 1000, -635, 1, 966, -650, 1, 952, -651, 1, 949, -651, 1, 967, -633, 1, 980, -605, 1, 993, -600, 1, 1009, -590,
0, 1052, -719, 1, 1069, -719, 1, 1084, -729, 1, 1085, -737, 1, 1081, -738, 1, 1057, -753, 1, 1041, -752, 1, 1029, -750,
1, 1036, -743, 1, 1052, -719, 0, 1445, -740, 1, 1467, -740, 1, 1482, -737, 1, 1514, -734, 1, 1534, -765, 1, 1535, -781,
1, 1515, -788, 1, 1502, -808, 1, 1494, -866, 1, 1468, -863, 1, 1441, -863, 1, 1437, -831, 1, 1419, -815, 1, 1397, -798,
1, 1371, -797, 1, 1358, -781, 1, 1375, -772, 1, 1385, -749, 1, 1416, -744, 1, 1445, -740, 0, 1660, -169, 1, 1653, -177,
1, 1652, -169, 1, 1667, -149, 1, 1668, -153, 1, 1660, -169, 0,-1543,-2189, 1,-1519,-2191, 1,-1485,-2206, 1,-1450,-2221,
1,-1403,-2225, 1,-1393,-2249, 1,-1394,-2261, 1,-1417,-2259, 1,-1441,-2257, 1,-1443,-2281, 1,-1408,-2296, 1,-1364,-2335,
1,-1366,-2359, 1,-1355,-2372, 1,-1331,-2373, 1,-1317,-2351, 1,-1295,-2364, 1,-1273,-2390, 1,-1215,-2418, 1,-1217,-2442,
1,-1230,-2453, 1,-1232,-2477, 1,-1196,-2480, 1,-1139,-2508, 1,-1117,-2534, 1,-1118,-2546, 1,-1166,-2542, 1,-1199,-2515,
1,-1211,-2514, 1,-1235,-2512, 1,-1279,-2473, 1,-1312,-2435, 1,-1348,-2432, 1,-1392,-2392, 1,-1451,-2376, 1,-1495,-2336,
1,-1542,-2321, 1,-1563,-2295, 1,-1608,-2256, 1,-1617,-2219, 1,-1616,-2208, 1,-1568,-2199, 1,-1543,-2189, 0,-1369, -890,
1,-1472, -974, 1,-2020,-1231, 0, -670, -116, 1, -707, -130, 1, -724, -163, 1, -748, -187, 1, -748, -210, 1, -735, -257,
1, -721, -285, 1, -721, -323, 1, -742, -337, 1, -769, -318, 1, -790, -304, 1, -810, -313, 1, -824, -309, 1, -838, -318,
1, -831, -341, 1, -810, -365, 1, -786, -374, 1, -786, -412, 1, -800, -449, 1, -779, -468, 1, -779, -496, 1, -793, -529,
1, -790, -543, 1, -772, -552, 1, -779, -585, 1, -814, -604, 1, -827, -651, 1, -848, -665, 1, -882, -655, 1, -899, -660,
1, -899, -683, 1, -910, -688, 1, -940, -674, 1, -954, -693, 1, -971, -702, 1, -971, -721, 1, -944, -730, 1, -944, -758,
1, -958, -754, 1, -968, -772, 1,-1030, -787, 1,-1064, -824, 1,-1108, -819, 1,-1153, -843, 1,-1204, -838, 1,-1228, -810,
1,-1252, -815, 1,-1283, -861, 1,-1321, -871, 1,-1369, -890, 0, 314, -375, 1, 304, -385, 1, 314, -395, 1, 334, -385,
1, 324, -375, 1, 314, -375, 0, -236, -505, 1, -256, -505, 1, -266, -525, 1, -236, -535, 1, -236, -505, 0, 1233, -965,
1, 1223,-1025, 1, 1233,-1085, 1, 1273,-1075, 1, 1293,-1035, 1, 1293,-1005, 1, 1273, -985, 1, 1233, -965, 0, 1207,-1225,
1, 1207,-1195, 1, 1217,-1165, 1, 1227,-1115, 1, 1247,-1105, 1, 1247,-1205, 1, 1287,-1225, 1, 1297,-1265, 1, 1257,-1285,
1, 1197,-1285, 1, 1187,-1265, 1, 1187,-1245, 1, 1207,-1225, 0,-2020,-1231, 1,-2047,-1268, 1,-2054,-1315, 1,-2082,-1352,
1,-2123,-1362, 1,-2136,-1390, 1,-2184,-1399, 1,-2191,-1418, 1,-2129,-1455, 1,-2116,-1436, 1,-2054,-1446, 1,-2034,-1483,
1,-1986,-1492, 1,-1897,-1539, 1,-1856,-1576, 1,-1788,-1595, 1,-1713,-1567, 1,-1686,-1567, 1,-1638,-1586, 1,-1590,-1576,
1,-1529,-1623, 1,-1481,-1623, 1,-1460,-1660, 1,-1433,-1651, 1,-1399,-1642, 1,-1372,-1679, 1,-1358,-1716, 1,-1303,-1744,
1,-1276,-1782, 1,-1235,-1810, 1,-1213,-1811, 0, 1028,-1216, 1, 1069,-1239, 1, 1093,-1239, 1, 1121,-1222, 1, 1141,-1222,
1, 1173,-1227, 1, 1180,-1216, 1, 1180,-1192, 1, 1199,-1136, 1, 1204,-1076, 1, 1195,-1047, 1, 1199,-1020, 1, 1193,-1011,
1, 1169,-1026, 1, 1156,-1008, 1, 1167, -984, 1, 1149, -970, 1, 1123, -961, 1, 1095, -961, 1, 1084, -949, 1, 1089, -931,
1, 1108, -922, 1, 1132, -937, 1, 1149, -937, 1, 1165, -925, 1, 1193, -937, 1, 1208, -925, 1, 1212, -896, 1, 1214, -872,
1, 1195, -851, 1, 1197, -827, 1, 1227, -804, 1, 1264, -798, 1, 1282, -810, 1, 1293, -801, 1, 1299, -786, 1, 1288, -756,
1, 1254, -738, 1, 1219, -741, 1, 1178, -762, 1, 1115, -750, 1, 1087, -756, 1, 1050, -780, 1, 1022, -777, 1, 1013, -765,
1, 993, -777, 1, 982, -762, 1, 978, -741, 1, 967, -759, 1, 959, -744, 1, 952, -747, 1, 948, -780, 1, 928, -798,
1, 909, -798, 1, 887, -815, 1, 870, -813, 1, 868, -795, 1, 881, -756, 1, 872, -741, 1, 872, -709, 1, 883, -682,
1, 872, -670, 1, 833, -682, 1, 809, -738, 1, 748, -818, 1, 696, -830, 1, 636, -833, 1, 610, -857, 1, 579, -872,
1, 540, -872, 1, 512, -890, 1, 482, -890, 1, 460, -872, 1, 430, -866, 1, 414, -842, 1, 414, -815, 1, 391, -786,
1, 360, -769, 1, 330, -769, 1, 309, -786, 1, 282, -790, 1, 264, -769, 1, 210, -782, 1, 154, -786, 1, 121, -774,
1, 106, -778, 1, 67, -778, 1, 64, -769, 1, 55, -749, 1, 40, -749, 1, 37, -737, 1, 37, -712, 1, 28, -688,
1, 20, -680, 1, 17, -659, 1, -10, -659, 1, -22, -651, 1, -34, -635, 1, -55, -635, 1, -73, -619, 1, -79, -586,
1, -88, -570, 1, -100, -578, 1, -106, -570, 1, -112, -545, 1, -103, -517, 1, -106, -509, 1, -130, -517, 1, -156, -557,
1, -156, -594, 1, -139, -602, 1, -127, -643, 1, -106, -659, 1, -97, -647, 1, -79, -659, 1, -88, -676, 1, -67, -708,
1, -73, -729, 1, -85, -741, 1, -106, -733, 1, -124, -708, 1, -142, -684, 1, -165, -692, 1, -186, -692, 1, -198, -716,
1, -213, -716, 1, -228, -688, 1, -225, -668, 1, -240, -651, 1, -240, -627, 1, -270, -602, 1, -288, -598, 1, -297, -574,
1, -309, -578, 1, -306, -627, 1, -320, -668, 1, -323, -684, 1, -312, -704, 1, -291, -725, 1, -300, -753, 1, -312, -753,
1, -326, -721, 1, -359, -704, 1, -368, -676, 1, -353, -631, 1, -356, -610, 1, -374, -598, 1, -413, -590, 1, -452, -545,
1, -499, -431, 1, -556, -305, 1, -598, -239, 1, -613, -191, 1, -670, -116, 0, -186, 2495, 1, 874, 2495, 1, 874, 2545,
1, 1644, 2545, 0, 1404, 755, 1, 1458, 753, 1, 1471, 742, 1, 1479, 713, 1, 1496, 713, 1, 1512, 724, 1, 1521, 713,
1, 1512, 679, 1, 1529, 645, 1, 1533, 588, 1, 1554, 548, 1, 1575, 536, 1, 1583, 548, 1, 1583, 565, 1, 1591, 559,
1, 1604, 525, 1, 1650, 491, 1, 1662, 497, 1, 1675, 457, 1, 1667, 388, 1, 1675, 343, 1, 1658, 291, 1, 1675, 229,
1, 1671, 195, 1, 1658, 189, 1, 1658, 149, 1, 1641, 86, 1, 1646, 35, 1, 1621, 41, 1, 1587, -5, 1, 1587, -33,
1, 1600, -68, 1, 1621, -73, 1, 1646, -50, 1, 1683, -45, 1, 1687, -68, 1, 1671, -79, 1, 1662, -125, 1, 1625, -147,
1, 1621, -193, 1, 1629, -199, 1, 1591, -239, 1, 1587, -273, 1, 1537, -301, 1, 1512, -284, 1, 1454, -313, 1, 1446, -335,
1, 1404, -335, 1, 1366, -387, 1, 1308, -404, 1, 1258, -409, 1, 1237, -392, 1, 1208, -409, 1, 1204, -455, 1, 1175, -472,
1, 1166, -495, 1, 1141, -512, 1, 1125, -541, 1, 1087, -546, 1, 1066, -518, 1, 1045, -535, 1, 979, -569, 1, 945, -580,
1, 920, -620, 1, 854, -637, 1, 845, -609, 1, 820, -609, 1, 779, -615, 1, 737, -620, 1, 741, -609, 1, 762, -575,
1, 737, -535, 1, 691, -512, 1, 666, -466, 1, 679, -415, 1, 674, -375, 1, 691, -341, 1, 737, -318, 1, 762, -324,
1, 770, -307, 1, 754, -290, 1, 691, -273, 1, 629, -278, 1, 599, -261, 1, 583, -233, 1, 537, -210, 1, 524, -159,
1, 541, -96, 1, 528, -22, 1, 512, 24, 1, 512, 69, 1, 491, 103, 1, 483, 115, 1, 474, 166, 1, 449, 189,
1, 437, 166, 1, 458, 120, 1, 478, 81, 1, 478, 46, 1, 487, -16, 1, 474, -28, 1, 462, -16, 1, 453, 52,
1, 428, 86, 1, 420, 132, 1, 408, 166, 1, 387, 166, 1, 391, 109, 1, 383, 86, 1, 412, 1, 1, 399, -79,
1, 416, -119, 1, 437, -113, 1, 453, -153, 1, 428, -176, 1, 403, -153, 1, 374, -142, 1, 362, -85, 1, 312, -50,
1, 312, -5, 1, 283, 24, 1, 262, 18, 1, 249, -5, 1, 233, 24, 1, 220, 52, 1, 183, 52, 1, 166, 40,
1, 154, 48, 1, 163, 92, 1, 157, 136, 1, 148, 160, 1, 151, 192, 1, 136, 217, 1, 113, 225, 1, 84, 221,
1, 57, 245, 1, 48, 277, 1, 57, 309, 1, 75, 337, 1, 75, 365, 1, 57, 401, 1, 60, 433, 1, 63, 478,
1, 54, 526, 1, 10, 566, 1, -5, 606, 1, -7, 654, 1, -25, 682, 1, -75, 727, 1, -81, 759, 1, -66, 763,
1, -54, 735, 1, -40, 731, 1, -40, 743, 1, -52, 767, 1, -78, 775, 1, -78, 795, 1, -63, 835, 1, -63, 863,
1, -57, 907, 1, -57, 935, 1, -46, 943, 1, -57, 947, 1, -66, 976, 1, -96, 1016, 1, -101, 1060, 1, -96, 1108,
0,-1213,-1811, 1,-1146,-1819, 1,-1099,-1884, 1,-1051,-1931, 1, -983,-1940, 1, -914,-1978, 1, -826,-1978, 1, -737,-1950,
1, -723,-1903, 1, -744,-1884, 1, -805,-1894, 1, -853,-1903, 1, -867,-1866, 1, -846,-1838, 1, -873,-1810, 1, -948,-1800,
1, -983,-1744, 1,-1044,-1726, 1,-1051,-1688, 1,-1051,-1651, 1,-1105,-1586, 1,-1132,-1518, 1,-1143,-1490, 1,-1138,-1432,
1,-1127,-1418, 1,-1090,-1504, 1,-1016,-1562, 1, -943,-1583, 1, -943,-1562, 1, -985,-1533, 1, -985,-1511, 1, -943,-1533,
1, -848,-1547, 1, -811,-1526, 1, -774,-1526, 1, -742,-1504, 1, -727,-1468, 1, -695,-1468, 1, -679,-1439, 1, -684,-1410,
1, -648,-1374, 1, -611,-1345, 1, -579,-1295, 1, -537,-1281, 1, -526,-1295, 1, -526,-1252, 1, -511,-1216, 1, -463,-1209,
1, -426,-1223, 1, -421,-1230, 1, -405,-1216, 1, -363,-1223, 1, -331,-1259, 1, -316,-1252, 1, -305,-1201, 1, -284,-1209,
1, -258,-1173, 1, -216,-1194, 1, -184,-1201, 1, -173,-1165, 1, -147,-1165, 1, -137,-1137, 1, -121,-1144, 1, -100,-1209,
1, -52,-1252, 1, -5,-1259, 1, 85,-1331, 1, 101,-1331, 1, 143,-1317, 1, 185,-1324, 1, 280,-1367, 1, 364,-1367,
1, 427,-1345, 1, 512,-1353, 1, 580,-1403, 1, 670,-1425, 1, 712,-1418, 1, 791,-1432, 1, 796,-1418, 1, 743,-1360,
1, 738,-1317, 1, 749,-1273, 1, 722,-1230, 1, 733,-1201, 1, 759,-1194, 1, 807,-1201, 1, 817,-1173, 1, 859,-1173,
1, 891,-1209, 1, 928,-1216, 1, 944,-1201, 1, 970,-1165, 1, 996,-1173, 1, 1028,-1216, 0, 2063, 1855, 1, 2087, 1843,
1, 2153, 1753, 1, 2162, 1707, 1, 2181, 1669, 1, 2176, 1617, 1, 2171, 1560, 1, 2190, 1521, 1, 2186, 1489, 1, 2148, 1437,
1, 2115, 1302, 1, 2091, 1083, 1, 2049, 993, 1, 2035, 897, 1, 2040, 820, 1, 1993, 736, 1, 1927, 710, 1, 1922, 684,
1, 1898, 697, 1, 1884, 691, 1, 1861, 723, 1, 1809, 723, 1, 1790, 755, 1, 1724, 762, 1, 1701, 768, 1, 1691, 807,
1, 1663, 813, 1, 1616, 813, 1, 1658, 820, 1, 1654, 865, 1, 1625, 955, 1, 1602, 961, 1, 1588, 948, 1, 1560, 974,
1, 1517, 1038, 1, 1470, 1064, 1, 1451, 1051, 1, 1432, 1013, 1, 1353, 994, 1, 1345, 955, 1, 1357, 916, 1, 1367, 813,
1, 1404, 755, 0, -96, 1108, 1, -75, 1144, 1, -58, 1232, 1, -34, 1218, 1, -48, 1246, 1, -34, 1306, 1, -11, 1366,
1, 13, 1348, 1, 23, 1352, 1, 30, 1371, 1, -4, 1385, 1, 6, 1412, 1, 30, 1445, 1, 40, 1509, 1, 43, 1542,
1, 60, 1518, 1, 74, 1518, 1, 74, 1523, 1, 54, 1542, 1, 67, 1551, 1, 47, 1551, 1, 47, 1569, 1, 60, 1643,
1, 74, 1722, 1, 74, 1791, 1, 60, 1777, 1, 54, 1786, 1, 60, 1860, 1, 43, 1943, 1, 23, 2082, 1, 13, 2156,
1, -28, 2202, 1, -48, 2257, 1, -95, 2289, 1, -105, 2317, 1, -112, 2373, 1, -142, 2442, 1, -186, 2495, 0, 1922, 2029,
1, 1964, 1997, 1, 1969, 1958, 1, 1955, 1901, 1, 1969, 1868, 1, 1993, 1855, 1, 1997, 1823, 1, 1983, 1810, 1, 1988, 1778,
1, 2026, 1753, 1, 2063, 1765, 1, 2059, 1810, 1, 2044, 1823, 1, 2063, 1855, 0, 1644, 2545, 1, 1663, 2447, 1, 1677, 2435,
1, 1682, 2473, 1, 1691, 2467, 1, 1677, 2422, 1, 1720, 2357, 1, 1757, 2357, 1, 1790, 2319, 1, 1781, 2287, 1, 1809, 2242,
1, 1809, 2164, 1, 1833, 2074, 1, 1884, 2055, 1, 1922, 2029, 0, 0, 0,
};
| 118.342593 | 122 | 0.493623 | krishna-beemanapalli |
0bebed57b3a5b50373572542065644ea862ca1f2 | 17,189 | cc | C++ | visitor/auto.test.cc | jssmith/stigdb | 4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104 | [
"Apache-2.0"
] | null | null | null | visitor/auto.test.cc | jssmith/stigdb | 4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104 | [
"Apache-2.0"
] | null | null | null | visitor/auto.test.cc | jssmith/stigdb | 4b4ade62299f8c6bc1d1aaf5f93dd4b77aa23104 | [
"Apache-2.0"
] | 1 | 2020-01-03T20:13:50.000Z | 2020-01-03T20:13:50.000Z | /* <visitor/auto.test.cc>
Unit test for <visitor/visitor.h>
This file demonstrates how to use the visitor library. It uses the template magic in the library to generate the
abstract visitors. If there are too many final types in the family, you can manually write out (probably code gen)
the abstract visitors. Take a look at <visitor/manual.test.cc>
Copyright 2010-2014 Stig LLC
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 <visitor/visitor.h>
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
#include <tuple>
#include <mpl/type_set.h>
#include <test/kit.h>
/* The demonstration is done with our typical/classic shape hierarchy. */
namespace Shape {
// shape.h
class TShape {
public:
/* 1. Forward declaration. The definition will follow after all of the final classes are fully defined. */
class TVisitor;
virtual ~TShape() {}
virtual void Accept(const TVisitor &visitor) const = 0;
}; // TShape
/* 2. Accept() functions of final classes are left to be defined later. */
// circle.h
class TCircle final : public TShape {
public:
TCircle(int radius) : Radius(radius) {}
virtual void Accept(const TVisitor &visitor) const override;
int GetRadius() const {
assert(this);
return Radius;
}
private:
int Radius;
}; // TCircle
// square.h
class TSquare final : public TShape {
public:
TSquare(int length) : Length(length) {}
virtual ~TSquare() {}
virtual void Accept(const TVisitor &visitor) const override;
int GetLength() const {
assert(this);
return Length;
}
private:
int Length;
}; // TSquare
// triangle.h
class TTriangle final : public TShape {
public:
TTriangle(int base, int height) : Base(base), Height(height) {}
virtual ~TTriangle() {}
virtual void Accept(const TVisitor &visitor) const override;
int GetBase() const {
assert(this);
return Base;
}
int GetHeight() const {
assert(this);
return Height;
}
private:
int Base, Height;
}; // TTriangle
// all_shapes.h
/* 3. Define TShape::TVisitor. Visitor::Single::TVisitor<> is the template magic class that generates the abstract visitor. */
class TShape::TVisitor : public Visitor::Single::TVisitor<Visitor::Cptr, Mpl::TTypeSet<TCircle, TSquare, TTriangle>> {};
/* 4. Visitor::Single creates an alias "namespace" for TComputer and TApplier. */
using Single = Visitor::Alias::Single<TShape::TVisitor>;
using Double = Visitor::Alias::Double<TShape::TVisitor, TShape::TVisitor>;
/* 5. Finish the definitions for the final classes' Accept() functions. */
void TCircle::Accept(const TVisitor &visitor) const {
assert(this);
assert(&visitor);
visitor(this);
}
void TSquare::Accept(const TVisitor &visitor) const {
assert(this);
assert(&visitor);
visitor(this);
}
void TTriangle::Accept(const TVisitor &visitor) const {
assert(this);
assert(&visitor);
visitor(this);
}
} // Shape
/* Above is our convention for defining a class hierarchy. */
/* Below is a demonstration of using these visitors similar to our classic style. */
using namespace Shape;
/* 1. Note the use of Shape::TFunction<void ()> instead of Shape::TShape::TVisitor. */
class TPrintVisitor : public Shape::Single::TComputer<void> {
public:
virtual void operator()(const TCircle *) const override { std::cout << "TCircle" << std::endl; }
virtual void operator()(const TSquare *) const override { std::cout << "TSquare" << std::endl; }
virtual void operator()(const TTriangle *) const override { std::cout << "TTriangle" << std::endl; }
};
FIXTURE(Print) {
std::unique_ptr<TShape> shape{new TSquare(5)};
/* 2. Second way of Accept() is useful when there is a non-void return type and/or when there are extra arguments. */
Visitor::Single::Accept(shape.get(), TPrintVisitor());
Visitor::Single::Accept<TPrintVisitor>(shape.get());
}
// Computes a result.
class TGetAreaVisitor : public Shape::Single::TComputer<double> {
public:
using TSuper = Shape::Single::TComputer<double>;
TGetAreaVisitor(TResult &result) : TSuper(result) {}
virtual void operator()(const TCircle *that) const override { Result = 3.14 * that->GetRadius() * that->GetRadius(); }
virtual void operator()(const TSquare *that) const override { Result = that->GetLength() * that->GetLength(); }
virtual void operator()(const TTriangle *that) const override { Result = that->GetBase() * that->GetHeight() / 2.0; }
};
FIXTURE(GetArea) {
/* Old. */ {
std::unique_ptr<TShape> shape{new TSquare(5)};
double result;
Visitor::Single::Accept(shape.get(), TGetAreaVisitor(result));
EXPECT_EQ(result, 25);
}
/* New. */ {
std::unique_ptr<TShape> shape{new TTriangle(10, 4)};
double result = Visitor::Single::Accept<TGetAreaVisitor>(shape.get());
EXPECT_EQ(result, 20);
}
}
/* No result, but takes extra arguments. */
class TWriteNameVisitor : public Shape::Single::TComputer<void> {
public:
TWriteNameVisitor(std::ostream &strm) : Strm(strm) {}
virtual void operator()(const TCircle *) const override { Strm << "TCircle"; }
virtual void operator()(const TSquare *) const override { Strm << "TSquare"; }
virtual void operator()(const TTriangle *) const override { Strm << "TTriangle"; }
private:
std::ostream &Strm;
};
FIXTURE(WriteName) {
/* Old */ {
std::unique_ptr<TShape> shape{new TCircle(12)};
std::ostringstream strm;
Visitor::Single::Accept(shape.get(), TWriteNameVisitor(strm));
EXPECT_EQ(strm.str(), "TCircle");
}
/* New */ {
std::unique_ptr<TShape> shape{new TTriangle(10, 4)};
std::ostringstream strm;
Visitor::Single::Accept<TWriteNameVisitor>(shape.get(), strm);
EXPECT_EQ(strm.str(), "TTriangle");
}
}
/* Computes a result, and takes extra arguments. */
class TGetAreaAndWriteVectorVisitor : public Shape::Single::TComputer<double> {
public:
using TSuper = Shape::Single::TComputer<double>;
TGetAreaAndWriteVectorVisitor(TResult &result, std::ostream &strm, const std::vector<int> &ints)
: TSuper(result), Strm(strm), Ints(ints) {}
virtual void operator()(const TCircle *that) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(that);
}
virtual void operator()(const TSquare *that) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(that);
}
virtual void operator()(const TTriangle *that) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(that);
}
private:
std::ostream &Strm;
const std::vector<int> &Ints;
};
FIXTURE(GetAreaAndWriteVector) {
/* Old */ {
std::unique_ptr<TShape> shape{new TCircle(23)};
std::ostringstream strm;
double result;
Visitor::Single::Accept(shape.get(), TGetAreaAndWriteVectorVisitor(result, strm, std::vector<int>{0, 1, 2}));
EXPECT_EQ(result, 3.14 * 23 * 23);
EXPECT_EQ(strm.str(), "012");
}
/* New */ {
std::unique_ptr<TShape> shape{new TSquare(50)};
std::ostringstream strm;
double result = Visitor::Single::Accept<TGetAreaAndWriteVectorVisitor>(shape.get(), strm, std::vector<int>{3, 4, 5});
EXPECT_EQ(result, 2500);
EXPECT_EQ(strm.str(), "345");
}
}
class TPrintDoubleVisitor : public Double::TComputer<void> {
public:
virtual void operator()(const TCircle *, const TCircle *) const override {
std::cout << "(TCircle, TCircle)" << std::endl;
}
virtual void operator()(const TCircle *, const TSquare *) const override {
std::cout << "(TCircle, TSquare)" << std::endl;
}
virtual void operator()(const TCircle *, const TTriangle *) const override {
std::cout << "(TCircle, TTriangle)" << std::endl;
}
virtual void operator()(const TSquare *, const TCircle *) const override {
std::cout << "(TSquare, TCircle)" << std::endl;
}
virtual void operator()(const TSquare *, const TSquare *) const override {
std::cout << "(TSquare, TSquare)" << std::endl;
}
virtual void operator()(const TSquare *, const TTriangle *) const override {
std::cout << "(TSquare, TTriangle)" << std::endl;
}
virtual void operator()(const TTriangle *, const TCircle *) const override {
std::cout << "(TTriangle, TCircle)" << std::endl;
}
virtual void operator()(const TTriangle *, const TSquare *) const override {
std::cout << "(TTriangle, TSquare)" << std::endl;
}
virtual void operator()(const TTriangle *, const TTriangle *) const override {
std::cout << "(TTriangle, TTriangle)" << std::endl;
}
};
FIXTURE(PrintDouble) {
std::unique_ptr<TShape> lhs{new TCircle(23)};
std::unique_ptr<TShape> rhs{new TSquare(34)};
/* Old */ Visitor::Double::Accept(lhs.get(), rhs.get(), TPrintDoubleVisitor());
/* New */ Visitor::Double::Accept<TPrintDoubleVisitor>(lhs.get(), rhs.get());
}
class TGetAreaDoubleVisitor : public Shape::Double::TComputer<std::pair<double, double>> {
public:
using TSuper = Shape::Double::TComputer<std::pair<double, double>>;
TGetAreaDoubleVisitor(TResult &result) : TSuper(result) {}
virtual void operator()(const TCircle *lhs, const TCircle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TCircle *lhs, const TSquare *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TCircle *lhs, const TTriangle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TSquare *lhs, const TCircle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TSquare *lhs, const TSquare *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TSquare *lhs, const TTriangle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TTriangle *lhs, const TCircle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TTriangle *lhs, const TSquare *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
virtual void operator()(const TTriangle *lhs, const TTriangle *rhs) const override {
Result = std::make_pair(Visitor::Single::Accept<TGetAreaVisitor>(lhs),
Visitor::Single::Accept<TGetAreaVisitor>(rhs));
}
};
FIXTURE(GetAreaDouble) {
/* Old */ {
std::unique_ptr<TShape> lhs{new TTriangle(10, 4)};
std::unique_ptr<TShape> rhs{new TSquare(30)};
typename TGetAreaDoubleVisitor::TResult result;
Visitor::Double::Accept(lhs.get(), rhs.get(), TGetAreaDoubleVisitor{result});
EXPECT_EQ(result.first, 20);
EXPECT_EQ(result.second, 900);
}
/* New */ {
std::unique_ptr<TShape> lhs{new TTriangle(10, 4)};
std::unique_ptr<TShape> rhs{new TSquare(30)};
auto result = Visitor::Double::Accept<TGetAreaDoubleVisitor>(lhs.get(), rhs.get());
EXPECT_EQ(result.first, 20);
EXPECT_EQ(result.second, 900);
}
}
class TWriteNameDoubleVisitor : public Shape::Double::TComputer<void> {
public:
using TSuper = Shape::Double::TComputer<void>;
TWriteNameDoubleVisitor(std::ostream &strm) : Strm(strm) {}
virtual void operator()(const TCircle *, const TCircle *) const override {
Strm << "(TCircle, TCircle)";
}
virtual void operator()(const TCircle *, const TSquare *) const override {
Strm << "(TCircle, TSquare)";
}
virtual void operator()(const TCircle *, const TTriangle *) const override {
Strm << "(TCircle, TTriangle)";
}
virtual void operator()(const TSquare *, const TCircle *) const override {
Strm << "(TSquare, TCircle)";
}
virtual void operator()(const TSquare *, const TSquare *) const override {
Strm << "(TSquare, TSquare)";
}
virtual void operator()(const TSquare *, const TTriangle *) const override {
Strm << "(TSquare, TTriangle)";
}
virtual void operator()(const TTriangle *, const TCircle *) const override {
Strm << "(TTriangle, TCircle)";
}
virtual void operator()(const TTriangle *, const TSquare *) const override {
Strm << "(TTriangle, TSquare)";
}
virtual void operator()(const TTriangle *, const TTriangle *) const override {
Strm << "(TTriangle, TTriangle)";
}
private:
std::ostream &Strm;
};
FIXTURE(WriteNameDouble) {
std::unique_ptr<TShape> lhs{new TTriangle(10, 4)};
std::unique_ptr<TShape> rhs{new TCircle(10)};
std::ostringstream strm;
Visitor::Double::Accept<TWriteNameDoubleVisitor>(lhs.get(), rhs.get(), strm);
EXPECT_EQ(strm.str(), "(TTriangle, TCircle)");
}
class TGetAreaAndWriteVectorDoubleVisitor
: public Shape::Double::TComputer<double> {
public:
using TSuper = Shape::Double::TComputer<double>;
TGetAreaAndWriteVectorDoubleVisitor(TResult &result, std::ostream &strm, const std::vector<int> &ints)
: TSuper(result), Strm(strm), Ints(ints) {}
virtual void operator()(const TCircle *lhs, const TCircle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TCircle *lhs, const TSquare *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TCircle *lhs, const TTriangle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TSquare *lhs, const TCircle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TSquare *lhs, const TSquare *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TSquare *lhs, const TTriangle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TTriangle *lhs, const TCircle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TTriangle *lhs, const TSquare *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
virtual void operator()(const TTriangle *lhs, const TTriangle *rhs) const override {
for (const auto &i : Ints) {
Strm << i;
}
Result = Visitor::Single::Accept<TGetAreaVisitor>(lhs) + Visitor::Single::Accept<TGetAreaVisitor>(rhs);
}
private:
std::ostream &Strm;
const std::vector<int> &Ints;
};
FIXTURE(GetAreaAndWriteVectorDouble) {
std::unique_ptr<TShape> lhs{new TSquare(50)};
std::unique_ptr<TShape> rhs{new TSquare(5)};
std::ostringstream strm;
double result = Visitor::Double::Accept<TGetAreaAndWriteVectorDoubleVisitor>(
lhs.get(), rhs.get(), strm, std::vector<int>{3, 4, 5});
EXPECT_EQ(result, 2525);
EXPECT_EQ(strm.str(), "345");
}
| 35.441237 | 128 | 0.667055 | jssmith |
0bf02dfc7db3196778d39d7f62a505c5e099aa56 | 695 | cpp | C++ | super-mario-dx10/05-SceneManager/GameObject.cpp | HoangTuan0611/Game | 64bbf4396ff38d17d3516c1eae687033f954d769 | [
"MIT"
] | null | null | null | super-mario-dx10/05-SceneManager/GameObject.cpp | HoangTuan0611/Game | 64bbf4396ff38d17d3516c1eae687033f954d769 | [
"MIT"
] | null | null | null | super-mario-dx10/05-SceneManager/GameObject.cpp | HoangTuan0611/Game | 64bbf4396ff38d17d3516c1eae687033f954d769 | [
"MIT"
] | null | null | null | #include <d3dx9.h>
#include <algorithm>
#include "debug.h"
#include "Textures.h"
#include "Game.h"
#include "GameObject.h"
#include "Sprites.h"
CGameObject::CGameObject()
{
x = y = 0;
vx = vy = 0;
nx = 1;
state = -1;
isDeleted = false;
}
void CGameObject::RenderBoundingBox()
{
D3DXVECTOR3 p(x, y, 0);
RECT rect;
LPTEXTURE bbox = CTextures::GetInstance()->Get(ID_TEX_BBOX);
float l, t, r, b;
GetBoundingBox(l, t, r, b);
rect.left = 0;
rect.top = 0;
rect.right = (int)r - (int)l;
rect.bottom = (int)b - (int)t;
float cx, cy;
CGame::GetInstance()->GetCamPos(cx, cy);
CGame::GetInstance()->Draw(x - cx, y - cy, bbox, &rect, BBOX_ALPHA);
}
CGameObject::~CGameObject()
{
} | 15.795455 | 69 | 0.634532 | HoangTuan0611 |
0bf0a1bbcc4da5111588ba61aaf135ad5712bb1e | 2,211 | cpp | C++ | sdk/boost_1_30_0/libs/thread/src/mac/st_scheduler.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2020-01-30T12:51:49.000Z | 2020-08-31T08:36:49.000Z | sdk/boost_1_30_0/libs/thread/src/mac/st_scheduler.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | sdk/boost_1_30_0/libs/thread/src/mac/st_scheduler.cpp | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | // Copyright (C) 2001
// Mac Murrett
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. Mac Murrett makes no representations
// about the suitability of this software for any purpose. It is
// provided "as is" without express or implied warranty.
//
// See http://www.boost.org for most recent version including documentation.
#include "st_scheduler.hpp"
#include <cassert>
namespace boost {
namespace threads {
namespace mac {
namespace detail {
#if TARGET_CARBON
st_scheduler::st_scheduler():
m_uppTask(NULL),
m_pTimer(NULL)
{
m_uppTask = NewEventLoopTimerUPP(task_entry);
// TODO - throw on error
assert(m_uppTask != NULL);
}
st_scheduler::~st_scheduler()
{
DisposeEventLoopTimerUPP(m_uppTask);
m_uppTask = NULL;
}
void st_scheduler::start_polling()
{
assert(m_pTimer == NULL);
OSStatus lStatus = InstallEventLoopTimer(GetMainEventLoop(),
0 * kEventDurationSecond,
kEventDurationMillisecond,
m_uppTask,
this,
&m_pTimer);
// TODO - throw on error
assert(lStatus == noErr);
}
void st_scheduler::stop_polling()
{
assert(m_pTimer != NULL);
OSStatus lStatus = RemoveEventLoopTimer(m_pTimer);
assert(lStatus == noErr);
m_pTimer = NULL;
}
/*static*/ pascal void st_scheduler::task_entry(EventLoopTimerRef /*pTimer*/, void *pRefCon)
{
st_scheduler *pThis = reinterpret_cast<st_scheduler *>(pRefCon);
assert(pThis != NULL);
pThis->task();
}
void st_scheduler::task()
{
periodic_function();
}
#else
# error st_scheduler unimplemented!
#endif
} // namespace detail
} // namespace mac
} // namespace threads
} // namespace boost
| 24.032609 | 93 | 0.613749 | acidicMercury8 |
0bf1b2ada0e24712623ad06b8779c4d9f0f5cd02 | 36,292 | cpp | C++ | XimaSSS/Win/GUI.cpp | Centril/XimaSSS | 80261052eba2e4b73bcfa2ad29f0087cd9dae9c8 | [
"Unlicense"
] | 1 | 2016-09-24T14:51:10.000Z | 2016-09-24T14:51:10.000Z | XimaSSS/Win/GUI.cpp | Centril/XimaSSS | 80261052eba2e4b73bcfa2ad29f0087cd9dae9c8 | [
"Unlicense"
] | null | null | null | XimaSSS/Win/GUI.cpp | Centril/XimaSSS | 80261052eba2e4b73bcfa2ad29f0087cd9dae9c8 | [
"Unlicense"
] | null | null | null | #ifdef WIN32
#include "..\StdAfx.hpp"
#include "Main.hpp"
#include "GUI.hpp"
#include "../Globals.func.hpp"
#include "XBrowseForFolder.hpp"
#include "../FTP/FTPUploader.class.hpp"
#include <commctrl.h>
#include <shlobj.h>
#include "makelink.h"
static Win::Options* g_opt = 0;
__inline int __stdcall generalproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
UNREFERENCED_PARAMETER(_lParam);
using namespace Win;
static Win::Dialog _d;
switch(_message)
{
case WM_INITDIALOG:
{
_d = Win::Dialog(_hWndDlg);
_d.setItemText(IDC_PATH, g_opt->path);
_d.setItemText(IDC_FORMAT, g_opt->filenameFormat);
char buff[260];
SHGetSpecialFolderPath(0, buff, 0x0007, 0);
if(filesystem::exists(filesystem::path(buff + string("\\XimaSSS.lnk"), filesystem::native)))
CheckDlgButton(_hWndDlg, IDC_AUTOSTART, 1);
return 1;
break;
}
case WM_COMMAND:
{
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_BROWSE)
{
char buffer[512];
if(XBrowseForFolder(_d, "C:\\", buffer, 512))
_d.setItemText(IDC_PATH, buffer);
}
break;
}
case GUI_SAVE:
{
Options* opt = reinterpret_cast<Options*>(_wParam);
if(_d.getItemText(IDC_PATH) == "")
return 1;
if(_d.getItemText(IDC_FORMAT) == "")
return 1;
try
{
filesystem::exists(filesystem::path(_d.getItemText(IDC_PATH), filesystem::native));
}
catch(filesystem::filesystem_error)
{
return 1;
}
regex expression("[<>|\"/?\\\\*:]", regex_constants::perl);
if(regex_search(_d.getItemText(IDC_FORMAT), expression))
return 1;
opt->path = _d.getItemText(IDC_PATH);
opt->filenameFormat = _d.getItemText(IDC_FORMAT);
break;
}
default:
return 0;
break;
}
return 0;
}
__inline int __stdcall imageproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
using namespace Win;
static map<HWND, string> prevWidthUnit, prevHeightUnit;
Win::Dialog _d(_hWndDlg);
switch(_message)
{
case WM_INITDIALOG:
{
Win::Options::Image* img;
if(_lParam == -1)
img = &g_opt->image;
else
if(g_opt->specialPrograms.find((char*)_lParam) != g_opt->specialPrograms.end())
img = &g_opt->specialPrograms[(char*)_lParam].image;
else
img = &g_opt->image;
_d.setItemText(IDC_FILETYPE, img->fileType);
CheckDlgButton(_hWndDlg, IDC_RESIZE, (int)img->resize);
_d.setItemText(IDC_DISPLAYQUALITY, itos(img->quality));
_d.setItemText(IDC_WIDTH, ftos(img->width));
_d.setItemText(IDC_WIDTHUNIT, img->unit);
_d.setItemText(IDC_HEIGHT, ftos(img->height));
_d.setItemText(IDC_HEIGHTUNIT, img->unit);
_d.setItemText(IDC_RESOLUTION, itos(img->resolution));
_d.setItemText(IDC_DISPLAYQUALITY, itos(img->quality));
_d.getItem(IDC_QUALITY).sendMessage(WM_USER + 6, 1, MAKELONG(1, 100));
_d.getItem(IDC_QUALITY).sendMessage(WM_USER + 5, 1, img->quality);
const char* _filetypes[] =
{
"Joint Photographic Experts Group | JPEG",
"Joint Photographic Experts Group | JPEG 2000",
"Joint Bi-level Image Experts Group | JBIG",
"Graphics Interchange Format | GIF",
"Portable Network Graphics | PNG",
"Bitmap | BMP",
"Portable Any Map Graphic Bitmap | PNM",
"Tagged Image File Format | TIFF",
"Truevision TARGA | TGA",
"Paint Shop Pro Compressed Graphic",
"Sun Raster Graphic | RAS",
"PCX",
};
const char* _units[] = { "pixels", "inches", "cm", "mm" };
for(int _i = 0; _i < 12; _i++)
_d.getItem(IDC_FILETYPE).sendMessage(CB_ADDSTRING, 0, reinterpret_cast<long>( (LPCTSTR)_filetypes[_i]));
for(int _i = 0; _i < 4; _i++)
{
_d.getItem(IDC_WIDTHUNIT).sendMessage(CB_ADDSTRING, 0, reinterpret_cast<long>( (LPCTSTR)_units[_i]));
_d.getItem(IDC_HEIGHTUNIT).sendMessage(CB_ADDSTRING, 0, reinterpret_cast<long>( (LPCTSTR)_units[_i]));
}
prevWidthUnit[_hWndDlg] = img->unit;
prevHeightUnit[_hWndDlg] = img->unit;
return 1;
break;
}
break;
case WM_COMMAND:
if(HIWORD(_wParam) == CBN_CLOSEUP && (LOWORD(_wParam) == IDC_HEIGHTUNIT || LOWORD(_wParam) == IDC_WIDTHUNIT))
{
const char* _units[] = { "pixels", "inches", "cm", "mm" };
double _cF;
string _text(_units[_d.getItem(LOWORD(_wParam)).sendMessage(CB_GETCURSEL, 0, 0)]);
if(_text == prevWidthUnit[_hWndDlg])
break;
if(_text == "pixels" && prevWidthUnit[_hWndDlg] == "cm")
_cF = 28.3553875;
else if(_text == "pixels" && prevWidthUnit[_hWndDlg] == "mm")
_cF = 2.83473495;
else if(_text == "pixels" && prevWidthUnit[_hWndDlg] == "inches")
_cF = 71.99424;
else if(_text == "cm" && prevWidthUnit[_hWndDlg] == "pixels")
_cF = 0.03526667;
else if(_text == "cm" && prevWidthUnit[_hWndDlg] == "mm")
_cF = 0.1;
else if(_text == "cm" && prevWidthUnit[_hWndDlg] == "inches")
_cF = 2.5389969;
else if(_text == "mm" && prevWidthUnit[_hWndDlg] == "pixels")
_cF = 0.35276667;
else if(_text == "mm" && prevWidthUnit[_hWndDlg] == "cm")
_cF = 10;
else if(_text == "mm" && prevWidthUnit[_hWndDlg] == "inches")
_cF = 25.389969;
else if(_text == "inches" && prevWidthUnit[_hWndDlg] == "pixels")
_cF = 0.01389;
else if(_text == "inches" && prevWidthUnit[_hWndDlg] == "cm")
_cF = 0.3938564;
else if(_text == "inches" && prevWidthUnit[_hWndDlg] == "mm")
_cF = 0.03938564;
else
break;
_d.setItemText(IDC_HEIGHT, ftos(round( (float)(_cF * stof(_d.getItemText(IDC_HEIGHT))), _text == "pixels" ? 0 : 3)));
_d.setItemText(IDC_WIDTH, ftos(round( (float)(_cF * stof(_d.getItemText(IDC_WIDTH))), _text == "pixels" ? 0 : 3)));
_d.setItemText(LOWORD(_wParam) == IDC_HEIGHTUNIT ? IDC_WIDTHUNIT : IDC_HEIGHTUNIT, _text);
prevWidthUnit[_hWndDlg] = prevHeightUnit[_hWndDlg] = _text;
}
break;
case WM_HSCROLL:
_d.setItemText(IDC_DISPLAYQUALITY, itos(_d.getItem(IDC_QUALITY).sendMessage(WM_USER, 0, 0)));
break;
case GUI_SAVE:
{
Options *opt = reinterpret_cast<Options*>(_wParam);
Win::Options::Image* img;
if(_lParam == -1)
img = &opt->image;
else
img = &opt->specialPrograms[(char*)_lParam].image;
regex expression("[^\\d.]", regex_constants::perl);
if(regex_search(_d.getItemText(IDC_WIDTH), expression))
return 1;
if(regex_search(_d.getItemText(IDC_HEIGHT), expression))
return 1;
if(regex_search(_d.getItemText(IDC_RESOLUTION), expression))
return 1;
if(_d.getItemText(IDC_HEIGHTUNIT) != _d.getItemText(IDC_WIDTHUNIT))
return 1;
string _units[] = { "pixels", "inches", "cm", "mm" };
const char* _filetypes[] =
{
"Joint Photographic Experts Group | JPEG",
"Joint Photographic Experts Group | JPEG 2000",
"Joint Bi-level Image Experts Group | JBIG",
"Graphics Interchange Format | GIF",
"Portable Network Graphics | PNG",
"Bitmap | BMP",
"Portable Any Map Graphic Bitmap | PNM",
"Tagged Image File Format | TIFF",
"Truevision TARGA | TGA",
"Paint Shop Pro Compressed Graphic",
"Sun Raster Graphic | RAS",
"PCX",
};
bool success = false;
for(int _i = 0; _i < 4; _i++)
if(_units[_i] == _d.getItemText(IDC_HEIGHTUNIT))
success = true;
if(!success)
return 1;
success = false;
for(int _i = 0; _i < 4; _i++)
if(_units[_i] == _d.getItemText(IDC_WIDTHUNIT))
success = true;
if(!success)
return 1;
success = false;
for(int _i = 0; _i < 12; _i++)
if(_filetypes[_i] == _d.getItemText(IDC_FILETYPE))
success = true;
if(!success)
return 1;
img->fileType = _d.getItemText(IDC_FILETYPE);
img->quality = stoi(_d.getItemText(IDC_DISPLAYQUALITY));
img->width = stof(_d.getItemText(IDC_WIDTH));
img->height = stof(_d.getItemText(IDC_HEIGHT));
img->resolution = stoi(_d.getItemText(IDC_RESOLUTION));
img->unit = _d.getItemText(IDC_WIDTHUNIT);
img->resize = IsDlgButtonChecked(*_d, IDC_RESIZE) == BST_CHECKED ? true : false;
break;
}
default:
return 0;
break;
}
return 0;
}
struct __tConStruct
{
HANDLE testThread, testDotter;
bool fResult;
int dots;
HWND hFTC;
__tConStruct() : testThread(0), testDotter(0), fResult(false), dots(0), hFTC(0)
{
}
__tConStruct(HWND _hFTC) : testThread(0), testDotter(0), fResult(false), dots(0), hFTC(_hFTC)
{
}
};
map<HWND, __tConStruct> tCons;
unsigned long __stdcall ftpTestConn(void* a)
{
HWND _id = reinterpret_cast<HWND>(a);
__tConStruct &tCon = tCons[_id];
tCon.fResult = false;
Win::Dialog pD(tCon.hFTC);
pD.setItemText(IDC_TESTCONN, "Abort");
pD.setItemText(IDC_CONNSTAT, "Connecting");
FTP::FTPUploader::initialize();
FTP::FTPUploader ftpClient(pD.getItemText(IDC_Adress), pD.getItemText(IDC_USERNAME), pD.getItemText(IDC_PASSWORD), stoi(pD.getItemText(IDC_PORT)));
if(ftpClient.login())
{
string _path = pD.getItemText(IDC_PATH);
if(_path[0] != '/')
_path = "/" + _path;
if(ftpClient.changeDirectory(_path))
pD.setItemText(IDC_CONNSTAT, "Connection succeeded");
else
pD.setItemText(IDC_CONNSTAT, "CWD Failed");
}
else
pD.setItemText(IDC_CONNSTAT, "Connection failed");
tCon.fResult = true;
ftpClient.close();
if(tCons.empty())
FTP::FTPUploader::cleanup();
pD.setItemText(IDC_TESTCONN, "Test Connection");
tCon.hFTC = 0;
tCon.testThread = 0;
tCons.erase(_id);
return 0;
}
__inline int __stdcall ftpproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
using namespace std;
Win::Dialog _d(_hWndDlg);
switch(_message)
{
case WM_INITDIALOG:
{
Win::Options::FTP* ftp;
if(_lParam == -1 || _lParam == 0)
ftp = &g_opt->ftp;
else
if(g_opt->specialPrograms.find((char*)_lParam) != g_opt->specialPrograms.end())
ftp = &g_opt->specialPrograms[(char*)_lParam].ftp;
else
ftp = &g_opt->ftp;
CheckDlgButton(*_d, IDC_FTPENABLE, (int)ftp->enable);
CheckDlgButton(*_d, IDC_AUTOSEND, (int)ftp->autosend);
_d.setItemText(IDC_Adress, ftp->server);
_d.setItemText(IDC_PORT, itos(ftp->port));
_d.setItemText(IDC_USERNAME, ftp->username);
_d.setItemText(IDC_PASSWORD, ftp->password);
_d.setItemText(IDC_PATH, ftp->path);
return 1;
break;
}
case WM_COMMAND:
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_TESTCONN)
{
if(_d.getItemText(IDC_TESTCONN) == "Abort")
{
__tConStruct &tCon = tCons[_d];
TerminateThread(tCon.testThread, 0);
_d.setItemText(IDC_TESTCONN, "Test Connection");
_d.setItemText(IDC_CONNSTAT, "");
tCons.erase(_d);
if(tCons.empty())
FTP::FTPUploader::cleanup();
}
else
{
__tConStruct tCon(_d);
tCons[_d] = tCon;
tCons[_d].testThread = CreateThread(0, 0, ftpTestConn, reinterpret_cast<void*>((HWND)_d), 0, 0);
}
}
break;
case GUI_SAVE:
{
Options *opt = reinterpret_cast<Options*>(_wParam);
Win::Options::FTP* ftp;
if(_lParam == -1)
ftp = &opt->ftp;
else
ftp = &opt->specialPrograms[(char*)_lParam].ftp;
ftp->enable = IsDlgButtonChecked(*_d, IDC_FTPENABLE) == BST_CHECKED ? true : false;
ftp->autosend = IsDlgButtonChecked(*_d, IDC_AUTOSEND) == BST_CHECKED ? true : false;
ftp->server = _d.getItemText(IDC_Adress);
ftp->port = stoi(_d.getItemText(IDC_PORT));
ftp->username = _d.getItemText(IDC_USERNAME);
ftp->password = _d.getItemText(IDC_PASSWORD);
ftp->path = _d.getItemText(IDC_FTPPATH);
break;
}
default:
return 0;
break;
}
return 0;
}
__inline int __stdcall dateproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
using namespace Win;
static map<HWND, CHOOSEFONT> _cfs;
static map<HWND, LOGFONT> _fonts;
static map<HWND, CHOOSECOLOR> _ccs;
static COLORREF _acrCustClr[16];
Win::Dialog _d(_hWndDlg);
switch(_message)
{
case WM_INITDIALOG:
{
Win::Options::Date* date;
if(_lParam == -1 || _lParam == 0)
date = &g_opt->date;
else
if(g_opt->specialPrograms.find((char*)_lParam) != g_opt->specialPrograms.end())
date = &g_opt->specialPrograms[(char*)_lParam].date;
else
date = &g_opt->date;
CheckDlgButton(*_d, IDC_DATEENABLE, (int)date->enable);
_d.setItemText(IDC_XPOS, itos(date->xPos));
_d.setItemText(IDC_YPOS, itos(date->yPos));
_d.setItemText(IDC_DATEFORMAT, date->textformat);
_d.setItemText(IDC_DISPLAYOPACITY, itos(date->opacity));
_d.getItem(IDC_OPACITY).sendMessage(WM_USER + 6, 1, MAKELONG(1, 100));
_d.getItem(IDC_OPACITY).sendMessage(WM_USER + 5, 1, date->opacity);
LOGFONT _font;
_font.lfCharSet = ANSI_CHARSET;
_font.lfItalic = isItalic(date->fontStyle);
_font.lfWeight = getWeight(date->fontStyle);
strcpy(_font.lfFaceName, date->fontName.c_str());
HDC hDC = GetDC(*_d);
_font.lfHeight = -MulDiv(date->fontSize, GetDeviceCaps(hDC, LOGPIXELSY), 72);
ReleaseDC(*_d, hDC);
_fonts[_hWndDlg] = _font;
CHOOSEFONT _cf;
memset((&_cf), 0, sizeof _cf );
_cf.lStructSize = sizeof _cf;
_cf.hwndOwner = *_d;
_cf.Flags = CF_SHOWHELP | CF_SCREENFONTS | CF_SELECTSCRIPT | CF_INITTOLOGFONTSTRUCT;
_cf.lpLogFont = &_fonts[_hWndDlg];
_cf.iPointSize = date->fontSize * 10;
_cfs[_hWndDlg] = _cf;
CHOOSECOLOR _cc;
memset((&_cc), 0, sizeof _cc);
_cc.lStructSize = sizeof _cc;
_cc.hwndOwner = *_d;
_cc.rgbResult = RGB(date->fontColor[0], date->fontColor[1], date->fontColor[2]);
_cc.lpCustColors = (LPDWORD)_acrCustClr;
_cc.Flags = CC_FULLOPEN | CC_ANYCOLOR | CC_RGBINIT;
_ccs[_hWndDlg] = _cc;
return 1;
break;
}
case WM_COMMAND:
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_FONT)
ChooseFont(&_cfs[_hWndDlg]);
else if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_FONTCOLOR)
ChooseColor(&_ccs[_hWndDlg]);
break;
case WM_HSCROLL:
{
int pos = _d.getItem(IDC_OPACITY).sendMessage(WM_USER, 0, 0);
_d.setItemText(IDC_DISPLAYOPACITY, itos(pos));
break;
}
case GUI_SAVE:
{
Options *opt = reinterpret_cast<Options*>(_wParam);
Win::Options::Date* date;
if(_lParam == -1 || _lParam == 0)
date = &opt->date;
else
date = &opt->specialPrograms[(char*)_lParam].date;
date->enable = IsDlgButtonChecked(*_d, IDC_DATEENABLE) == BST_CHECKED ? true : false;
date->opacity = stoi(_d.getItemText(IDC_DISPLAYOPACITY));
date->textformat = _d.getItemText(IDC_DATEFORMAT);
date->xPos = stoi(_d.getItemText(IDC_XPOS));
date->yPos = stoi(_d.getItemText(IDC_YPOS));
date->fontColor[0] = GetRValue(_ccs[_hWndDlg].rgbResult);
date->fontColor[1] = GetGValue(_ccs[_hWndDlg].rgbResult);
date->fontColor[2] = GetBValue(_ccs[_hWndDlg].rgbResult);
date->fontSize = _cfs[_hWndDlg].iPointSize / 10;
date->fontStyle = makeStyle(_fonts[_hWndDlg].lfItalic, _fonts[_hWndDlg].lfWeight);
date->fontName = _fonts[_hWndDlg].lfFaceName;
break;
}
default:
return 0;
break;
}
return 0;
}
struct tabInfo
{
private:
Win::Dialog _currActive;
public:
Win::Window _control;
Win::Dialog _general, _image, _ftp, _date;
tabInfo(void)
{
}
~tabInfo(void)
{
_control.destroy();
}
void fix(void)
{
_currActive = Dialog(*_general);
}
void show(void)
{
_control.show();
_control.update();
_currActive.show();
}
void hide(void)
{
_control.hide();
_currActive.hide();
}
void changeActive(void)
{
int i = TabCtrl_GetCurSel(*_control);
_currActive.hide();
if(i == 0)
_currActive = Dialog(*_general);
else if(i == 1)
_currActive = Dialog(*_image);
else if(i == 2)
_currActive = Dialog(*_ftp);
else if(i == 3)
_currActive = Dialog(*_date);
else
throw std::out_of_range("Can only be 0(General), 1(Image), 2(FTP), 3(Date)");
_currActive.show();
}
};
__inline int __stdcall generalspproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
using namespace std;
Win::Dialog _d(_hWndDlg);
switch(_message)
{
case WM_INITDIALOG:
{
if(g_opt->specialPrograms.find((char*)_lParam) != g_opt->specialPrograms.end())
{
Win::Options::SpecialProgram &general = g_opt->specialPrograms[(char*)_lParam];
CheckDlgButton(*_d, IDC_DEFIMG, (int)general.useDefaultImage);
CheckDlgButton(*_d, IDC_DEFDATE, (int)general.useDefaultDate);
CheckDlgButton(*_d, IDC_DEFFTP, (int)general.useDefaultFTP);
_d.setItemText(IDC_NAME, (char*)_lParam);
_d.setItemText(IDC_PATH, general.path);
_d.setItemText(IDC_EXPATH, general.executablePath);
_d.setItemText(IDC_FORMAT, general.filenameFormat);
}
else
{
CheckDlgButton(*_d, IDC_DEFIMG, 0);
CheckDlgButton(*_d, IDC_DEFDATE, 0);
CheckDlgButton(*_d, IDC_DEFFTP, 0);
_d.setItemText(IDC_NAME, (char*)_lParam);
_d.setItemText(IDC_PATH, g_opt->path);
_d.setItemText(IDC_FORMAT, g_opt->filenameFormat);
}
return 1;
break;
}
case WM_COMMAND:
{
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_BROWSE)
{
char buffer[512];
if(XBrowseForFolder(_d, "C:\\", buffer, 512))
_d.setItemText(IDC_PATH, buffer);
}
else if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_BROWSEX)
{
char buffer[256];
OPENFILENAME _ofn;
memset(&_ofn, 0, sizeof _ofn);
_ofn.lStructSize = sizeof _ofn;
_ofn.hwndOwner = _hWndDlg;
_ofn.lpstrFile = buffer;
_ofn.lpstrFile[0] = '\0';
_ofn.nMaxFile = sizeof buffer;
_ofn.lpstrFilter = "Executable\0*.EXE\0";
_ofn.nFilterIndex = 1;
_ofn.lpstrFileTitle = 0;
_ofn.nMaxFileTitle = 0;
_ofn.lpstrInitialDir = 0;
_ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | 0x02000000;
if(GetOpenFileName(&_ofn) == 1)
_d.setItemText(IDC_EXPATH, buffer);
}
break;
}
case GUI_SAVE:
{
Options *opt = reinterpret_cast<Options*>(_wParam);
Win::Options::SpecialProgram* general = &opt->specialPrograms[(char*)_lParam];
if(_d.getItemText(IDC_PATH) == "")
return 1;
if(_d.getItemText(IDC_EXPATH) == "")
return 1;
if(_d.getItemText(IDC_FORMAT) == "")
return 1;
try
{
filesystem::exists(filesystem::path(_d.getItemText(IDC_PATH), filesystem::native));
if(!filesystem::exists(filesystem::path(_d.getItemText(IDC_EXPATH), filesystem::native)))
return -1;
}
catch(filesystem::filesystem_error)
{
return -1;
}
regex expression("[<>|\"/?\\\\*:]", regex_constants::perl);
if(regex_search(_d.getItemText(IDC_FORMAT), expression))
return -1;
general->useDefaultImage = IsDlgButtonChecked(*_d, IDC_DEFIMG) == BST_CHECKED ? true : false;
general->useDefaultFTP = IsDlgButtonChecked(*_d, IDC_DEFFTP) == BST_CHECKED ? true : false;
general->useDefaultDate = IsDlgButtonChecked(*_d, IDC_DEFDATE) == BST_CHECKED ? true : false;
general->name = (char*)_lParam;
general->executablePath = _d.getItemText(IDC_EXPATH);
general->path = _d.getItemText(IDC_PATH);
general->filenameFormat = _d.getItemText(IDC_FORMAT);
bool *_rets = new bool[3];
_rets[0] = general->useDefaultImage;
_rets[1] = general->useDefaultFTP;
_rets[2] = general->useDefaultDate;
return (int)_rets;
break;
}
default:
return 0;
break;
}
return 0;
}
__inline int __stdcall spproc(HWND _hWndDlg, unsigned int _message, unsigned int _wParam, long _lParam)
{
using namespace Win;
static tabInfo* _currProgram;
static vector<tabInfo*> _programTabs;
static vector<string> _programNames;
static Win::Dialog _d;
static Win::Window _tab;
map<string, Win::Options::SpecialProgram> &sps = g_opt->specialPrograms;
switch(_message)
{
case WM_INITDIALOG:
{
_d = Win::Dialog(_hWndDlg);
_tab = _d.getItem(IDC_SPS);
char buffer[100];
TCITEM tab;
tab.mask = TCIF_TEXT | TCIF_IMAGE;
tab.iImage = -1;
tab.pszText = buffer;
map<string, Options::SpecialProgram>::iterator iter;
int count = 0;
for(iter = sps.begin(); iter != sps.end(); iter++)
{
Options::SpecialProgram &_program = iter->second;
tabInfo* _programTab = new tabInfo();
strcpy(tab.pszText, _program.name.c_str());
TabCtrl_InsertItem(*_tab, count, &tab);
_programTab->_control.create
(
0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
WC_TABCONTROL, "0",
7, 32, 458, 278,
0, *_tab
);
tab.mask = TCIF_TEXT | TCIF_IMAGE;
strcpy(tab.pszText, "General");
TabCtrl_InsertItem(_programTab->_control, 0, &tab);
_programTab->_general.create(_programTab->_control, MAKEINTRESOURCE(IDD_GENERALSP), (DLGPROC) generalspproc, (long)_program.name.c_str());
_programTab->_general.setPos(0, 5, 27, 449, 248);
tab.mask = TCIF_TEXT | TCIF_IMAGE;
strcpy(tab.pszText, "Image");
TabCtrl_InsertItem(_programTab->_control, 1, &tab);
_programTab->_image.create(_programTab->_control, MAKEINTRESOURCE(IDD_IMAGESP), (DLGPROC) imageproc, (long)_program.name.c_str());
_programTab->_image.setPos(0, 5, 27, 449, 248);
strcpy(tab.pszText, "FTP");
TabCtrl_InsertItem(_programTab->_control, 2, &tab);
_programTab->_ftp.create(_programTab->_control, MAKEINTRESOURCE(IDD_FTPSP), (DLGPROC) ftpproc, (long)_program.name.c_str());
_programTab->_ftp.setPos(0, 5, 27, 449, 248);
strcpy(tab.pszText, "Date");
TabCtrl_InsertItem(_programTab->_control, 3, &tab);
_programTab->_date.create(_programTab->_control, MAKEINTRESOURCE(IDD_DATESP), (DLGPROC) dateproc, (long)_program.name.c_str());
_programTab->_date.setPos(0, 5, 27, 449, 248);
_programTab->fix();
if(count == 0)
{
_currProgram = _programTab;
_currProgram->show();
}
_programTabs.push_back(_programTab);
_programNames.push_back(_program.name);
count++;
}
return 1;
break;
}
case WM_COMMAND:
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_ADD)
{
string name = _d.getItemText(IDC_NAME);
if(name == "") // NULL/"" == illegal && ~GENERAL~ IS RESERVED!!!
{
_d.setItemText(IDC_MESSAGE, "Invalid name");
return 0;
}
else if(name == "~GENERAL~") // NULL/"" == illegal && ~GENERAL~ IS RESERVED!!!
{
_d.setItemText(IDC_MESSAGE, "The entry: ~GENERAL~ is reserved!");
return 0;
}
if(binary_search(_programNames.begin(), _programNames.end(), name))
{
_d.setItemText(IDC_MESSAGE, "The entry: " + name + " already exists");
return 0;
}
char buffer[100];
int count = TabCtrl_GetItemCount(*_tab);
TCITEM tab;
tab.mask = TCIF_TEXT;
tab.cchTextMax = 100;
tab.pszText = buffer;
strcpy(tab.pszText, name.c_str());
TabCtrl_InsertItem(*_tab, count, &tab);
tabInfo* _programTab = new tabInfo();
_programTab->_control.create
(
0, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
WC_TABCONTROL, "0",
7, 32, 458, 278,
0, *_tab
);
tab.mask = TCIF_TEXT | TCIF_IMAGE;
strcpy(tab.pszText, "General");
TabCtrl_InsertItem(_programTab->_control, 0, &tab);
_programTab->_general.create(_programTab->_control, MAKEINTRESOURCE(IDD_GENERALSP), (DLGPROC) generalspproc, (long)name.c_str());
_programTab->_general.setPos(0, 5, 27, 449, 248);
tab.mask = TCIF_TEXT | TCIF_IMAGE;
strcpy(tab.pszText, "Image");
TabCtrl_InsertItem(_programTab->_control, 1, &tab);
_programTab->_image.create(_programTab->_control, MAKEINTRESOURCE(IDD_IMAGESP), (DLGPROC) imageproc, (long)name.c_str());
_programTab->_image.setPos(0, 5, 27, 449, 248);
strcpy(tab.pszText, "FTP");
TabCtrl_InsertItem(_programTab->_control, 2, &tab);
_programTab->_ftp.create(_programTab->_control, MAKEINTRESOURCE(IDD_FTPSP), (DLGPROC) ftpproc, (long)name.c_str());
_programTab->_ftp.setPos(0, 5, 27, 449, 248);
strcpy(tab.pszText, "Date");
TabCtrl_InsertItem(_programTab->_control, 3, &tab);
_programTab->_date.create(_programTab->_control, MAKEINTRESOURCE(IDD_DATESP), (DLGPROC) dateproc, (long)name.c_str());
_programTab->_date.setPos(0, 5, 27, 449, 248);
_programTab->fix();
_programTabs.push_back(_programTab);
_programNames.push_back(name);
if(!_currProgram)
_currProgram = _programTab;
_currProgram->hide();
_currProgram->show();
_d.setItemText(IDC_NAME, "");
}
else if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == IDC_REMOVE)
{
char buffer[100];
int _i = TabCtrl_GetCurSel(*_tab);
if(_d.getItemText(IDC_NAME) == "" && !_programTabs.empty() && _i > -1)
{
TCITEM chTab;
chTab.mask = TCIF_TEXT;
chTab.cchTextMax = 100;
chTab.pszText = buffer;
TabCtrl_GetItem(*_tab, _i, &chTab);
if(Win::Dialog::messageBox(*_d, string("Do you really want to remove the entry: ") + chTab.pszText + string(" ?"), "", MB_YESNO | MB_ICONQUESTION) == IDYES)
{
TabCtrl_DeleteItem(*_tab, _i);
delete _programTabs.at(_i);
_programTabs.erase(_programTabs.begin() + _i);
_programNames.erase(_programNames.begin() + _i);
if(TabCtrl_SetCurSel(*_tab, _i - 1) == -1)
if(TabCtrl_SetCurSel(*_tab, _i) != -1)
{
TabCtrl_SetCurSel(*_tab, _i + 1);
}
if(!_programTabs.empty())
{
_currProgram = _programTabs.at(TabCtrl_GetCurSel(*_tab));
_currProgram->show();
}
else
_currProgram = 0;
}
}
else if(_d.getItemText(IDC_NAME) != "" && !_programTabs.empty())
{
for(int _i = 0; _i < (int)_programNames.size(); _i++)
{
if(_d.getItemText(IDC_NAME) != _programNames[_i])
continue;
if(Win::Dialog::messageBox(*_d, "Do you really want to remove the entry: " + _d.getItemText(IDC_NAME) + " ?", "", MB_YESNO | MB_ICONQUESTION) != IDYES)
return 0;
delete _programTabs.at(_i);
_programTabs.erase(_programTabs.begin() + _i);
_programNames.erase(_programNames.begin() + _i);
if(_i == TabCtrl_GetCurSel(*_tab))
{
if(TabCtrl_SetCurSel(*_tab, _i - 1) == -1)
if(TabCtrl_SetCurSel(*_tab, _i) != -1)
{
TabCtrl_SetCurSel(*_tab, _i + 1);
}
if(!_programTabs.empty())
_currProgram = _programTabs.at(TabCtrl_GetCurSel(*_tab));
TabCtrl_DeleteItem(*_tab, _i);
}
else
{
TabCtrl_DeleteItem(*_tab, _i);
_currProgram->hide();
}
if(_programTabs.empty())
_currProgram = 0;
if(!_programTabs.empty())
_currProgram->show();
return 0;
}
_d.setItemText(IDC_MESSAGE, "The entry: " + _d.getItemText(IDC_NAME) + " doesn't exist");
return 0;
}
else
_d.setItemText(IDC_MESSAGE, "No item selected or no search phrase");
}
break;
case WM_NOTIFY:
{
NMHDR &info = *(NMHDR*)_lParam;
if(info.code == TCN_SELCHANGE && info.idFrom == IDC_SPS)
{
if(_currProgram)
_currProgram->hide();
_currProgram = _programTabs.at(TabCtrl_GetCurSel(*_tab));
_currProgram->show();
}
else if(info.code == TCN_SELCHANGE)
_programTabs.at(TabCtrl_GetCurSel(*_tab))->changeActive();
break;
}
case WM_DESTROY:
for(unsigned int _i = 0; _i < _programTabs.size(); _i++)
delete _programTabs.at(_i);
_programTabs.clear();
_programNames.clear();
_currProgram = 0;
_tab.destroy();
break;
case GUI_SAVE:
{
Options *opt = reinterpret_cast<Options*>(_wParam);
for(int _i = 0; _i < (int)_programTabs.size(); _i++)
{
{
if( _programNames.at(_i) == "~GENERAL~") // ~GENERAL~ IS RESERVED!!!
return 1;
}
tabInfo &_info = *_programTabs.at(_i);
const char* _name = _programNames.at(_i).c_str();
int _ret = generalspproc(*_info._general, GUI_SAVE, _wParam, (long)_name);
bool* _rets = (bool*)_ret;
if(_ret == -1)
{
delete[] _rets;
return 1;
}
if(_rets[0])
opt->specialPrograms[_name].image = opt->image;
else
if(imageproc(*_info._image, GUI_SAVE, _wParam, (long)_name) == 1)
{
delete[] _rets;
return 1;
}
if(_rets[1])
opt->specialPrograms[_name].ftp = opt->ftp;
else
if(ftpproc(*_info._ftp, GUI_SAVE, _wParam, (long)_name) == 1)
{
delete[] _rets;
return 1;
}
if(_rets[2])
opt->specialPrograms[_name].date = opt->date;
else
if(dateproc(*_info._date, GUI_SAVE, _wParam, (long)_name) == 1)
{
delete[] _rets;
return 1;
}
delete[] _rets;
}
break;
}
default:
return 0;
break;
}
return 0;
}
namespace Win
{
GUI::GUI(Win::Main &_refMain) :
m_refMain(_refMain), m_menu(Win::ImageMenuVertical<GUI>(5, 0, 50, 407, 50, 3)),
m_window(), _general(), _image(), _ftp(), _date(), _sp()
{
g_opt = &this->m_refMain.options;
{
INITCOMMONCONTROLSEX _iccex;
_iccex.dwSize = sizeof INITCOMMONCONTROLSEX;
_iccex.dwICC = ICC_WIN95_CLASSES | ICC_BAR_CLASSES | ICC_TAB_CLASSES;
InitCommonControlsEx(&_iccex);
}
try
{
{
int _w = 550;
int _h = 435;
int x = (GetSystemMetrics(SM_CXSCREEN) / 2) - (_w / 2);
int y = (GetSystemMetrics(SM_CYSCREEN) / 2) - (_h / 2);
this->m_window.create
(
0, WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
this->m_refMain.m_window.getClassName(), "XimaSSS Options",
x, y, _w, _h,
this
);
}
this->_general.create(this->m_window, MAKEINTRESOURCE(IDD_GENERAL), (DLGPROC)generalproc);
this->_image.create(this->m_window, MAKEINTRESOURCE(IDD_IMAGE), (DLGPROC)imageproc);
this->_ftp.create(this->m_window, MAKEINTRESOURCE(IDD_FTP), (DLGPROC)ftpproc);
this->_date.create(this->m_window, MAKEINTRESOURCE(IDD_DATE), (DLGPROC)dateproc);
this->_sp.create(this->m_window, MAKEINTRESOURCE(IDD_SPECIALPROGRAMS), (DLGPROC)spproc);
this->_save.create(0, WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, WC_BUTTON, "Save", 260, 375, 80, 25, 0, *this->m_window, (HMENU) 1);
}
catch(WindowException&)
{
delete this;
}
this->m_menu.insert(IDR_PNG1, *this, &GUI::onClickGeneral, 0, &GUI::onLeaveGeneral);
this->m_menu.insert(IDR_PNG2, *this, &GUI::onClickImage, 0, &GUI::onLeaveImage);
this->m_menu.insert(IDR_PNG3, *this, &GUI::onClickFTP, 0, &GUI::onLeaveFTP);
this->m_menu.insert(IDR_PNG4, *this, &GUI::onClickDate, 0, &GUI::onLeaveDate);
this->m_menu.insert(IDR_PNG5, *this, &GUI::onClickSP, 0, &GUI::onLeaveSP);
this->m_menu.setDefault(0);
this->m_menu.align(CENTER);
this->m_menu.initiate(Color(255, 255, 255), Color(193, 210, 238), Color(224, 232, 246));
this->m_window.show();
this->m_window.toForeground();
}
GUI::~GUI(void)
{
this->_general.destroy();
this->_image.destroy();
this->_ftp.destroy();
this->_date.destroy();
this->_sp.destroy();
this->_save.destroy();
this->m_window.destroy();
map<HWND, __tConStruct>::iterator iter;
for(iter = tCons.begin(); iter != tCons.end(); iter++)
{
TerminateThread(iter->second.testThread, 0);
TerminateThread(iter->second.testDotter, 0);
}
tCons.clear();
FTP::FTPUploader::cleanup();
this->m_refMain.m_refGUI = 0;
g_opt = 0;
}
GUI& GUI::operator=(const GUI& _rhs)
{
if(this == &_rhs)
return *this;
this->m_refMain = _rhs.m_refMain;
this->is_saving = _rhs.is_saving;
this->m_menu = _rhs.m_menu;
this->m_window = _rhs.m_window;
this->_date = _rhs._date;
this->_ftp = _rhs._ftp;
this->_general = _rhs._general;
this->_image = _rhs._image;
this->_sp = _rhs._sp;
return *this;
}
__inline long GUI::proc(Window &_window, const unsigned int &_message, const unsigned int &_wParam, const long &_lParam)
{
switch(_message)
{
case WM_KEYUP:
if(_wParam == VK_TAB)
{
HDC _dc = GetDC(*_window);
Graphics _gfx(_dc);
this->m_menu.tab(_gfx);
ReleaseDC(*_window, _dc);
}
break;
case WM_COMMAND:
if(HIWORD(_wParam) == BN_CLICKED && LOWORD(_wParam) == 1)
this->save();
break;
case WM_LBUTTONUP:
{
HDC _dc = GetDC(*_window);
Graphics _gfx(_dc);
this->m_menu.routeClick(_gfx, GET_X_LPARAM(_lParam), GET_Y_LPARAM(_lParam));
ReleaseDC(*_window, _dc);
break;
}
case WM_MOUSEMOVE:
{
int xPos = GET_X_LPARAM(_lParam);
int yPos = GET_Y_LPARAM(_lParam);
if(!this->m_window.containsPoint(xPos, yPos))
return 0;
if(this->m_menu.isHoveredItemLeft(xPos, yPos))
{
HDC _dc = GetDC(*_window);
Graphics _gfx(_dc);
this->m_menu.routeLeave(_gfx);
ReleaseDC(*_window, _dc);
return 0;
}
if(this->m_menu.hasBounds(xPos, yPos))
{
HDC _dc = GetDC(*_window);
Graphics _gfx(_dc);
this->m_menu.routeHover(_gfx, xPos, yPos);
ReleaseDC(*_window, _dc);
return 0;
}
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC _dc = BeginPaint(*_window, &ps);
this->paint(_dc);
EndPaint(*_window, &ps);
break;
}
case WM_CLOSE:
return this->close();
break;
case WM_DESTROY:
break;
default:
return DefWindowProc(*_window, _message, _wParam, _lParam);
break;
}
return 0;
}
__inline void GUI::paint(HDC& _dc)
{
// Make graphics object linked to the screen
Graphics _gfx(_dc);
{
// Menu/Content Separator
Pen _blackPen(Color(132, 132, 132), 1);
Pen _whitePen(Color(200, 200, 200), 1);
SolidBrush wBrush(Color(255, 255, 255));
// Horizontal line
_gfx.FillRectangle(&wBrush, 63, 366, 494, 41);
_gfx.DrawLine(&_blackPen, 63, 363, 543, 363);
_gfx.DrawLine(&_whitePen, 63, 364, 543, 364);
_gfx.DrawLine(&_blackPen, 63, 365, 543, 365);
_gfx.DrawLine(&_whitePen, 63, 366, 543, 366);
// Vertical Line
_gfx.FillRectangle(&wBrush, 55, 0, 5, 407);
_gfx.DrawLine(&_blackPen, 60, 0, 60, 366);
_gfx.DrawLine(&_whitePen, 61, 0, 61, 366);
_gfx.DrawLine(&_blackPen, 62, 0, 62, 366);
_gfx.DrawLine(&_whitePen, 63, 0, 63, 366);
}
// Paint the Menu
this->m_menu.paint(_gfx);
}
__inline void GUI::onClickGeneral(void)
{
this->_general.show();
}
__inline void GUI::onLeaveGeneral(void)
{
this->_general.hide();
}
__inline void GUI::onClickImage(void)
{
this->_image.show();
}
__inline void GUI::onLeaveImage(void)
{
this->_image.hide();
}
__inline void GUI::onClickFTP(void)
{
this->_ftp.show();
}
__inline void GUI::onLeaveFTP(void)
{
this->_ftp.hide();
}
__inline void GUI::onClickDate(void)
{
this->_date.show();
}
__inline void GUI::onLeaveDate(void)
{
this->_date.hide();
}
__inline void GUI::onClickSP(void)
{
this->_sp.show();
}
__inline void GUI::onLeaveSP(void)
{
this->_sp.hide();
}
bool GUI::is_saving = false;
__inline void GUI::save(void)
{
// is_saving critical section: avoiding duplication of method!
if(is_saving)
return;
is_saving = true;
{
Options temp_options(this->m_refMain.options);
{
bool success = true;
if(generalproc(*this->_general, GUI_SAVE, (unsigned int)&temp_options, 0) == 1)
{
Dialog::messageBox(this->m_window, "One or more options in the general section is incorrect", "Invalid value", MB_ICONQUESTION);
success = false;
}
if(success && imageproc(*this->_image, GUI_SAVE, (unsigned int)&temp_options, -1) == 1)
{
Dialog::messageBox(this->m_window, "One or more options in the image section is incorrect", "Invalid value", MB_ICONQUESTION);
success = false;
}
if(success && ftpproc(*this->_ftp, GUI_SAVE, (unsigned int)&temp_options, -1) == 1)
{
Dialog::messageBox(this->m_window, "One or more options in the ftp section is incorrect", "Invalid value", MB_ICONQUESTION);
success = false;
}
if(success && dateproc(*this->_date, GUI_SAVE, (unsigned int)&temp_options, -1) == 1)
{
Dialog::messageBox(this->m_window, "One or more options in the date section is incorrect", "Invalid value", MB_ICONQUESTION);
success = false;
}
if(success && spproc(*this->_sp, GUI_SAVE, (unsigned int)&temp_options, 0) == 1)
{
Dialog::messageBox(this->m_window, "One or more options in the special applications section is incorrect", "Invalid value", MB_ICONQUESTION);
success = false;
}
if(!success) // failure, rewind save
{
is_saving = false;
return;
}
}
this->m_refMain.options = temp_options;
const filesystem::path p = filesystem::initial_path();
this->m_refMain.options.save(p.string() + "/options.xml");
}
if(IsDlgButtonChecked(*this->_general, IDC_AUTOSTART))
{
char buff[260];
SHGetSpecialFolderPath(0, buff, 0x0007, 0);
if(!filesystem::exists(filesystem::path(buff + string("\\XimaSSS.lnk"), filesystem::native)))
{
char PPath[100];
GetModuleFileName(GetModuleHandle(0), PPath, 100);
strcat_s(buff, sizeof buff, "\\XimaSSS.lnk");
CreateShortCut(PPath, "", buff, "", SW_SHOWNORMAL, const_cast<char*>(filesystem::initial_path().string().c_str()), PPath, 0);
}
}
else
{
char buff[260];
SHGetSpecialFolderPath(0, buff, 0x0007, 0);
filesystem::path p(buff + string("\\XimaSSS.lnk"), filesystem::native);
if(filesystem::exists(p))
filesystem::remove(p);
}
is_saving = false;
}
__inline bool GUI::close(void)
{
if(is_saving)
return false;
delete this;
return true;
}
}
#endif | 27.852648 | 160 | 0.66629 | Centril |
0bf371ce31423b5c6a8edb3d7129277e4e48b770 | 3,759 | cc | C++ | auxil/binpac/src/pac_decl.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | 1 | 2021-03-06T19:51:07.000Z | 2021-03-06T19:51:07.000Z | auxil/binpac/src/pac_decl.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | auxil/binpac/src/pac_decl.cc | hugolin615/zeek-4.0.0-ele420520-spring2021 | 258e9b2ee1f2a4bd45c6332a75304793b7d44d40 | [
"Apache-2.0"
] | null | null | null | #include "pac_attr.h"
#include "pac_context.h"
#include "pac_dataptr.h"
#include "pac_embedded.h"
#include "pac_exception.h"
#include "pac_expr.h"
#include "pac_exttype.h"
#include "pac_id.h"
#include "pac_output.h"
#include "pac_param.h"
#include "pac_record.h"
#include "pac_type.h"
#include "pac_utils.h"
#include "pac_decl.h"
DeclList *Decl::decl_list_ = 0;
Decl::DeclMap Decl::decl_map_;
Decl::Decl(ID* id, DeclType decl_type)
: id_(id), decl_type_(decl_type), attrlist_(0)
{
decl_map_[id_] = this;
if ( ! decl_list_ )
decl_list_ = new DeclList();
decl_list_->push_back(this);
DEBUG_MSG("Finished Decl %s\n", id_->Name());
analyzer_context_ = 0;
}
Decl::~Decl()
{
delete id_;
delete_list(AttrList, attrlist_);
}
void Decl::AddAttrs(AttrList* attrs)
{
if ( ! attrs )
return;
if ( ! attrlist_ )
attrlist_ = new AttrList();
foreach ( i, AttrList, attrs )
{
attrlist_->push_back(*i);
ProcessAttr(*i);
}
}
void Decl::ProcessAttr(Attr *attr)
{
throw Exception(attr, "unhandled attribute");
}
void Decl::SetAnalyzerContext()
{
analyzer_context_ =
AnalyzerContextDecl::current_analyzer_context();
if ( ! analyzer_context_ )
{
throw Exception(this,
"analyzer context not defined");
}
}
void Decl::ProcessDecls(Output *out_h, Output *out_cc)
{
if ( ! decl_list_ )
return;
foreach(i, DeclList, decl_list_)
{
Decl *decl = *i;
current_decl_id = decl->id();
decl->Prepare();
}
foreach(i, DeclList, decl_list_)
{
Decl *decl = *i;
current_decl_id = decl->id();
decl->GenExternDeclaration(out_h);
}
out_h->println("namespace binpac {\n");
out_cc->println("namespace binpac {\n");
AnalyzerContextDecl *analyzer_context =
AnalyzerContextDecl::current_analyzer_context();
foreach(i, DeclList, decl_list_)
{
Decl *decl = *i;
current_decl_id = decl->id();
decl->GenForwardDeclaration(out_h);
}
if ( analyzer_context )
analyzer_context->GenNamespaceEnd(out_h);
out_h->println("");
foreach(i, DeclList, decl_list_)
{
Decl *decl = *i;
current_decl_id = decl->id();
decl->GenCode(out_h, out_cc);
}
if ( analyzer_context )
{
analyzer_context->GenNamespaceEnd(out_h);
analyzer_context->GenNamespaceEnd(out_cc);
}
out_h->println("} // namespace binpac");
out_cc->println("} // namespace binpac");
}
Decl* Decl::LookUpDecl(const ID* id)
{
DeclMap::iterator it = decl_map_.find(id);
if ( it == decl_map_.end() )
return 0;
return it->second;
}
int HelperDecl::helper_id_seq = 0;
HelperDecl::HelperDecl(HelperType helper_type,
ID* context_id,
EmbeddedCode* code)
: Decl(new ID(strfmt("helper_%d", ++helper_id_seq)), HELPER),
helper_type_(helper_type),
context_id_(context_id),
code_(code)
{
}
HelperDecl::~HelperDecl()
{
delete context_id_;
delete code_;
}
void HelperDecl::Prepare()
{
// Do nothing
}
void HelperDecl::GenExternDeclaration(Output *out_h)
{
if ( helper_type_ == EXTERN )
code_->GenCode(out_h, global_env());
}
void HelperDecl::GenCode(Output *out_h, Output *out_cc)
{
Env *env = global_env();
#if 0
if ( context_id_ )
{
Decl *decl = Decl::LookUpDecl(context_id_);
if ( ! decl )
{
throw Exception(context_id_,
fmt("cannot find declaration for %s",
context_id_->Name()));
}
env = decl->env();
if ( ! env )
{
throw Exception(context_id_,
fmt("not a type or analyzer: %s",
context_id_->Name()));
}
}
#endif
if ( helper_type_ == HEADER )
code_->GenCode(out_h, env);
else if ( helper_type_ == CODE )
code_->GenCode(out_cc, env);
else if ( helper_type_ == EXTERN )
; // do nothing
else
ASSERT(0);
}
| 19.578125 | 64 | 0.646449 | hugolin615 |
0bf3c04d24efd8fc163ffca218251295659579b9 | 614 | cpp | C++ | test/ui/test-item-vector.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 9 | 2016-01-10T20:59:02.000Z | 2019-01-09T14:18:13.000Z | test/ui/test-item-vector.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 31 | 2015-01-30T17:46:17.000Z | 2017-03-04T17:33:50.000Z | test/ui/test-item-vector.cpp | antonvw/wxExtension | d5523346cf0b1dbd45fd20dc33bf8d679299676c | [
"MIT"
] | 2 | 2015-04-05T08:45:22.000Z | 2018-08-24T06:43:24.000Z | ////////////////////////////////////////////////////////////////////////////////
// Name: test-item-vector.cpp
// Purpose: Implementation for wex unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2020 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include "../test.h"
#include <wex/ui/item-vector.h>
#include <wex/ui/item.h>
TEST_SUITE_BEGIN("wex::item");
TEST_CASE("wex::item_vector")
{
const std::vector<wex::item> v({{"spin1", 0, 10, 0}});
wex::item_vector iv(&v);
REQUIRE(iv.find<int>("spin1") == 0);
}
TEST_SUITE_END();
| 25.583333 | 80 | 0.480456 | antonvw |
0bf994f35b0d7ff227e0729fff5bf868543f3641 | 82,546 | cpp | C++ | src/3rdparty/sheets/odf/SheetsOdfSheet.cpp | afarcat/QtSheetView | 6d5ef3418238e9402c5a263a6f499557cc7215bf | [
"Apache-2.0"
] | null | null | null | src/3rdparty/sheets/odf/SheetsOdfSheet.cpp | afarcat/QtSheetView | 6d5ef3418238e9402c5a263a6f499557cc7215bf | [
"Apache-2.0"
] | null | null | null | src/3rdparty/sheets/odf/SheetsOdfSheet.cpp | afarcat/QtSheetView | 6d5ef3418238e9402c5a263a6f499557cc7215bf | [
"Apache-2.0"
] | null | null | null | /* This file is part of the KDE project
Copyright 1998-2016 The Calligra Team <calligra-devel@kde.org>
Copyright 2016 Tomas Mecir <mecirt@gmail.com>
Copyright 2010 Marijn Kruisselbrink <mkruisselbrink@kde.org>
Copyright 2007 Stefan Nikolaus <stefan.nikolaus@kdemail.net>
Copyright 2007 Thorsten Zachmann <zachmann@kde.org>
Copyright 2005-2006 Inge Wallin <inge@lysator.liu.se>
Copyright 2004 Ariya Hidayat <ariya@kde.org>
Copyright 2002-2003 Norbert Andres <nandres@web.de>
Copyright 2000-2002 Laurent Montel <montel@kde.org>
Copyright 2002 John Dailey <dailey@vt.edu>
Copyright 2002 Phillip Mueller <philipp.mueller@gmx.de>
Copyright 2000 Werner Trobin <trobin@kde.org>
Copyright 1999-2000 Simon Hausmann <hausmann@kde.org>
Copyright 1999 David Faure <faure@kde.org>
Copyright 1998-2000 Torben Weis <weis@kde.org>
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; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "SheetsOdf.h"
#include "SheetsOdfPrivate.h"
#include <kcodecs.h>
#include <KoDocumentInfo.h>
#include <KoGenStyles.h>
#include <KoProgressUpdater.h>
#include <KoShape.h>
#include <KoShapeRegistry.h>
#include "KoStore.h"
#include <KoStyleStack.h>
#include "KoUnit.h"
#include <KoUpdater.h>
#include <KoXmlNS.h>
#include <KoXmlWriter.h>
#include "CellStorage.h"
#include "Condition.h"
#include "DocBase.h"
#include "Formula.h"
#include "HeaderFooter.h"
#include "LoadingInfo.h"
#include "Map.h"
#include "PrintSettings.h"
#include "RowColumnFormat.h"
#include "RowFormatStorage.h"
#include "Sheet.h"
#include "SheetPrint.h"
#include "ShapeApplicationData.h"
#include "StyleManager.h"
#include "StyleStorage.h"
#include "Validity.h"
// This file contains functionality to load/save a Sheet
namespace Calligra {
namespace Sheets {
class Cell;
template<typename T> class IntervalMap
{
public:
IntervalMap() {}
// from and to are inclusive, assumes no overlapping ranges
// even though no checks are done
void insert(int from, int to, const T& data) {
m_data.insert(to, qMakePair(from, data));
}
T get(int idx) const {
typename QMap<int, QPair<int, T> >::ConstIterator it = m_data.lowerBound(idx);
if (it != m_data.end() && it.value().first <= idx) {
return it.value().second;
}
return T();
}
private:
QMap<int, QPair<int, T> > m_data;
};
namespace Odf {
// Sheet loading - helper functions
/**
* Inserts the styles contained in \p styleRegions into the style storage.
* Looks automatic styles up in the map of preloaded automatic styles,
* \p autoStyles , and custom styles in the StyleManager.
* The region is restricted to \p usedArea .
*/
void loadSheetInsertStyles(Sheet *sheet, const Styles& autoStyles,
const QHash<QString, QRegion>& styleRegions,
const QHash<QString, Conditions>& conditionalStyles,
const QRect& usedArea,
QList<QPair<QRegion, Style> >& outStyleRegions,
QList<QPair<QRegion, Conditions> >& outConditionalStyles);
bool loadStyleFormat(Sheet *sheet, KoXmlElement *style);
void loadMasterLayoutPage(Sheet *sheet, KoStyleStack &styleStack);
void loadRowNodes(Sheet *sheet, const KoXmlElement& parent,
int& rowIndex,
int& maxColumn,
OdfLoadingContext& tableContext,
QHash<QString, QRegion>& rowStyleRegions,
QHash<QString, QRegion>& cellStyleRegions,
const IntervalMap<QString>& columnStyles,
const Styles& autoStyles,
QList<ShapeLoadingData>& shapeData);
void loadColumnNodes(Sheet *sheet, const KoXmlElement& parent,
int& indexCol,
int& maxColumn,
KoOdfLoadingContext& odfContext,
QHash<QString, QRegion>& columnStyleRegions,
IntervalMap<QString>& columnStyles);
bool loadColumnFormat(Sheet *sheet, const KoXmlElement& column,
const KoOdfStylesReader& stylesReader, int & indexCol,
QHash<QString, QRegion>& columnStyleRegions, IntervalMap<QString>& columnStyles);
int loadRowFormat(Sheet *sheet, const KoXmlElement& row, int &rowIndex,
OdfLoadingContext& tableContext,
QHash<QString, QRegion>& rowStyleRegions,
QHash<QString, QRegion>& cellStyleRegions,
const IntervalMap<QString>& columnStyles,
const Styles& autoStyles,
QList<ShapeLoadingData>& shapeData);
QString getPart(const KoXmlNode & part);
void replaceMacro(QString & text, const QString & old, const QString & newS);
// Sheet saving - helper functions
QString saveSheetStyleName(Sheet *sheet, KoGenStyles &mainStyles);
void saveColRowCell(Sheet *sheet, int maxCols, int maxRows, OdfSavingContext& tableContext);
void saveCells(Sheet *sheet, int row, int maxCols, OdfSavingContext& tableContext);
void saveHeaderFooter(Sheet *sheet, KoXmlWriter &xmlWriter);
void saveBackgroundImage(Sheet *sheet, KoXmlWriter& xmlWriter);
void addText(const QString & text, KoXmlWriter & writer);
void convertPart(Sheet *sheet, const QString & part, KoXmlWriter & xmlWriter);
bool compareRows(Sheet *sheet, int row1, int row2, int maxCols, OdfSavingContext& tableContext);
QString savePageLayout(PrintSettings *settings, KoGenStyles &mainStyles, bool formulas, bool zeros);
}
// *************** Loading *****************
bool Odf::loadSheet(Sheet *sheet, const KoXmlElement& sheetElement, OdfLoadingContext& tableContext, const Styles& autoStyles, const QHash<QString, Conditions>& conditionalStyles)
{
QPointer<KoUpdater> updater;
if (sheet->doc() && sheet->doc()->progressUpdater()) {
updater = sheet->doc()->progressUpdater()->startSubtask(1,
"Calligra::Sheets::Odf::loadSheet");
updater->setProgress(0);
}
KoOdfLoadingContext& odfContext = tableContext.odfContext;
if (sheetElement.hasAttributeNS(KoXmlNS::table, "style-name")) {
QString stylename = sheetElement.attributeNS(KoXmlNS::table, "style-name", QString());
//debugSheetsODF<<" style of table :"<<stylename;
const KoXmlElement *style = odfContext.stylesReader().findStyle(stylename, "table");
Q_ASSERT(style);
//debugSheetsODF<<" style :"<<style;
if (style) {
KoXmlElement properties(KoXml::namedItemNS(*style, KoXmlNS::style, "table-properties"));
if (!properties.isNull()) {
if (properties.hasAttributeNS(KoXmlNS::table, "display")) {
bool visible = (properties.attributeNS(KoXmlNS::table, "display", QString()) == "true" ? true : false);
sheet->setHidden(!visible);
}
}
if (style->hasAttributeNS(KoXmlNS::style, "master-page-name")) {
QString masterPageStyleName = style->attributeNS(KoXmlNS::style, "master-page-name", QString());
//debugSheets<<"style->attribute( style:master-page-name ) :"<<masterPageStyleName;
KoXmlElement *masterStyle = odfContext.stylesReader().masterPages()[masterPageStyleName];
//debugSheets<<"stylesReader.styles()[masterPageStyleName] :"<<masterStyle;
if (masterStyle) {
loadStyleFormat(sheet, masterStyle);
if (masterStyle->hasAttributeNS(KoXmlNS::style, "page-layout-name")) {
QString masterPageLayoutStyleName = masterStyle->attributeNS(KoXmlNS::style, "page-layout-name", QString());
//debugSheetsODF<<"masterPageLayoutStyleName :"<<masterPageLayoutStyleName;
const KoXmlElement *masterLayoutStyle = odfContext.stylesReader().findStyle(masterPageLayoutStyleName);
if (masterLayoutStyle) {
//debugSheetsODF<<"masterLayoutStyle :"<<masterLayoutStyle;
KoStyleStack styleStack;
styleStack.setTypeProperties("page-layout");
styleStack.push(*masterLayoutStyle);
loadMasterLayoutPage(sheet, styleStack);
}
}
}
}
if (style->hasChildNodes() ) {
KoXmlElement element;
forEachElement(element, properties) {
if (element.nodeName() == "style:background-image") {
QString imagePath = element.attributeNS(KoXmlNS::xlink, "href");
KoStore* store = tableContext.odfContext.store();
if (store->hasFile(imagePath)) {
QByteArray data;
store->extractFile(imagePath, data);
QImage image = QImage::fromData(data);
if( image.isNull() ) {
continue;
}
sheet->setBackgroundImage(image);
Sheet::BackgroundImageProperties bgProperties;
if( element.hasAttribute("draw:opacity") ) {
QString opacity = element.attribute("draw:opacity", "");
if( opacity.endsWith(QLatin1Char('%')) ) {
opacity.chop(1);
}
bool ok;
float opacityFloat = opacity.toFloat( &ok );
if( ok ) {
bgProperties.opacity = opacityFloat;
}
}
//TODO
//if( element.hasAttribute("style:filterName") ) {
//}
if( element.hasAttribute("style:position") ) {
const QString positionAttribute = element.attribute("style:position","");
const QStringList positionList = positionAttribute.split(' ', QString::SkipEmptyParts);
if( positionList.size() == 1) {
const QString position = positionList.at(0);
if( position == "left" ) {
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::Left;
}
if( position == "center" ) {
//NOTE the standard is too vague to know what center alone means, we assume that it means both centered
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::HorizontalCenter;
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::VerticalCenter;
}
if( position == "right" ) {
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::Right;
}
if( position == "top" ) {
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::Top;
}
if( position == "bottom" ) {
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::Bottom;
}
}
else if (positionList.size() == 2) {
const QString verticalPosition = positionList.at(0);
const QString horizontalPosition = positionList.at(1);
if( horizontalPosition == "left" ) {
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::Left;
}
if( horizontalPosition == "center" ) {
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::HorizontalCenter;
}
if( horizontalPosition == "right" ) {
bgProperties.horizontalPosition = Sheet::BackgroundImageProperties::Right;
}
if( verticalPosition == "top" ) {
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::Top;
}
if( verticalPosition == "center" ) {
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::VerticalCenter;
}
if( verticalPosition == "bottom" ) {
bgProperties.verticalPosition = Sheet::BackgroundImageProperties::Bottom;
}
}
}
if( element.hasAttribute("style:repeat") ) {
const QString repeat = element.attribute("style:repeat");
if( repeat == "no-repeat" ) {
bgProperties.repeat = Sheet::BackgroundImageProperties::NoRepeat;
}
if( repeat == "repeat" ) {
bgProperties.repeat = Sheet::BackgroundImageProperties::Repeat;
}
if( repeat == "stretch" ) {
bgProperties.repeat = Sheet::BackgroundImageProperties::Stretch;
}
}
sheet->setBackgroundImageProperties(bgProperties);
}
}
}
}
}
}
// Cell style regions
QHash<QString, QRegion> cellStyleRegions;
// Cell style regions (row defaults)
QHash<QString, QRegion> rowStyleRegions;
// Cell style regions (column defaults)
QHash<QString, QRegion> columnStyleRegions;
IntervalMap<QString> columnStyles;
// List of shapes that need to have their size recalculated after loading is complete
QList<ShapeLoadingData> shapeData;
int rowIndex = 1;
int indexCol = 1;
int maxColumn = 1;
KoXmlNode rowNode = sheetElement.firstChild();
// Some spreadsheet programs may support more rows than
// Calligra Sheets so limit the number of repeated rows.
// FIXME POSSIBLE DATA LOSS!
// First load all style information for rows, columns and cells
while (!rowNode.isNull() && rowIndex <= KS_rowMax) {
//debugSheetsODF << " rowIndex :" << rowIndex << " indexCol :" << indexCol;
KoXmlElement rowElement = rowNode.toElement();
if (!rowElement.isNull()) {
// slightly faster
KoXml::load(rowElement);
//debugSheetsODF << " Odf::loadSheet rowElement.tagName() :" << rowElement.localName();
if (rowElement.namespaceURI() == KoXmlNS::table) {
if (rowElement.localName() == "table-header-columns") {
// NOTE Handle header cols as ordinary ones
// as long as they're not supported.
loadColumnNodes(sheet, rowElement, indexCol, maxColumn, odfContext, columnStyleRegions, columnStyles);
} else if (rowElement.localName() == "table-column-group") {
loadColumnNodes(sheet, rowElement, indexCol, maxColumn, odfContext, columnStyleRegions, columnStyles);
} else if (rowElement.localName() == "table-column" && indexCol <= KS_colMax) {
//debugSheetsODF << " table-column found : index column before" << indexCol;
loadColumnFormat(sheet, rowElement, odfContext.stylesReader(), indexCol, columnStyleRegions, columnStyles);
//debugSheetsODF << " table-column found : index column after" << indexCol;
maxColumn = qMax(maxColumn, indexCol - 1);
} else if (rowElement.localName() == "table-header-rows") {
// NOTE Handle header rows as ordinary ones
// as long as they're not supported.
loadRowNodes(sheet, rowElement, rowIndex, maxColumn, tableContext, rowStyleRegions, cellStyleRegions, columnStyles, autoStyles, shapeData);
} else if (rowElement.localName() == "table-row-group") {
loadRowNodes(sheet, rowElement, rowIndex, maxColumn, tableContext, rowStyleRegions, cellStyleRegions, columnStyles, autoStyles, shapeData);
} else if (rowElement.localName() == "table-row") {
//debugSheetsODF << " table-row found :index row before" << rowIndex;
int columnMaximal = loadRowFormat(sheet, rowElement, rowIndex, tableContext,
rowStyleRegions, cellStyleRegions, columnStyles, autoStyles, shapeData);
// allow the row to define more columns then defined via table-column
maxColumn = qMax(maxColumn, columnMaximal);
//debugSheetsODF << " table-row found :index row after" << rowIndex;
} else if (rowElement.localName() == "shapes") {
// OpenDocument v1.1, 8.3.4 Shapes:
// The <table:shapes> element contains all graphic shapes
// with an anchor on the table this element is a child of.
KoShapeLoadingContext* shapeLoadingContext = tableContext.shapeContext;
KoXmlElement element;
forEachElement(element, rowElement) {
if (element.namespaceURI() != KoXmlNS::draw)
continue;
loadSheetObject(sheet, element, *shapeLoadingContext);
}
}
}
// don't need it anymore
KoXml::unload(rowElement);
}
rowNode = rowNode.nextSibling();
int count = sheet->map()->increaseLoadedRowsCounter();
if (updater && count >= 0) updater->setProgress(count);
}
// now recalculate the size for embedded shapes that had sizes specified relative to a bottom-right corner cell
foreach (const ShapeLoadingData& sd, shapeData) {
// subtract offset because the accumulated width and height we calculate below starts
// at the top-left corner of this cell, but the shape can have an offset to that corner
QSizeF size = QSizeF( sd.endPoint.x() - sd.offset.x(), sd.endPoint.y() - sd.offset.y());
for (int col = sd.startCell.x(); col < sd.endCell.firstRange().left(); ++col)
size += QSizeF(sheet->columnFormat(col)->width(), 0.0);
if (sd.endCell.firstRange().top() > sd.startCell.y())
size += QSizeF(0.0, sheet->rowFormats()->totalRowHeight(sd.startCell.y(), sd.endCell.firstRange().top() - 1));
sd.shape->setSize(size);
}
QList<QPair<QRegion, Style> > styleRegions;
QList<QPair<QRegion, Conditions> > conditionRegions;
// insert the styles into the storage (column defaults)
debugSheetsODF << "Inserting column default cell styles ...";
loadSheetInsertStyles(sheet, autoStyles, columnStyleRegions, conditionalStyles,
QRect(1, 1, maxColumn, rowIndex - 1), styleRegions, conditionRegions);
// insert the styles into the storage (row defaults)
debugSheetsODF << "Inserting row default cell styles ...";
loadSheetInsertStyles(sheet, autoStyles, rowStyleRegions, conditionalStyles,
QRect(1, 1, maxColumn, rowIndex - 1), styleRegions, conditionRegions);
// insert the styles into the storage
debugSheetsODF << "Inserting cell styles ...";
loadSheetInsertStyles(sheet, autoStyles, cellStyleRegions, conditionalStyles,
QRect(1, 1, maxColumn, rowIndex - 1), styleRegions, conditionRegions);
sheet->cellStorage()->loadStyles(styleRegions);
sheet->cellStorage()->loadConditions(conditionRegions);
if (sheetElement.hasAttributeNS(KoXmlNS::table, "print-ranges")) {
// e.g.: Sheet4.A1:Sheet4.E28
QString range = sheetElement.attributeNS(KoXmlNS::table, "print-ranges", QString());
Region region(loadRegion(range));
if (!region.firstSheet() || sheet->sheetName() == region.firstSheet()->sheetName())
sheet->printSettings()->setPrintRegion(region);
}
if (sheetElement.attributeNS(KoXmlNS::table, "protected", QString()) == "true") {
loadProtection(sheet, sheetElement);
}
return true;
}
void Odf::loadSheetObject(Sheet *sheet, const KoXmlElement& element, KoShapeLoadingContext& shapeContext)
{
KoShape* shape = KoShapeRegistry::instance()->createShapeFromOdf(element, shapeContext);
if (!shape)
return;
sheet->addShape(shape);
dynamic_cast<ShapeApplicationData*>(shape->applicationData())->setAnchoredToCell(false);
}
void Odf::loadRowNodes(Sheet *sheet, const KoXmlElement& parent,
int& rowIndex,
int& maxColumn,
OdfLoadingContext& tableContext,
QHash<QString, QRegion>& rowStyleRegions,
QHash<QString, QRegion>& cellStyleRegions,
const IntervalMap<QString>& columnStyles,
const Styles& autoStyles,
QList<ShapeLoadingData>& shapeData
)
{
KoXmlNode node = parent.firstChild();
while (!node.isNull()) {
KoXmlElement elem = node.toElement();
if (!elem.isNull() && elem.namespaceURI() == KoXmlNS::table) {
if (elem.localName() == "table-row") {
int columnMaximal = loadRowFormat(sheet, elem, rowIndex, tableContext,
rowStyleRegions, cellStyleRegions,
columnStyles, autoStyles, shapeData);
// allow the row to define more columns then defined via table-column
maxColumn = qMax(maxColumn, columnMaximal);
} else if (elem.localName() == "table-row-group") {
loadRowNodes(sheet, elem, rowIndex, maxColumn, tableContext, rowStyleRegions, cellStyleRegions, columnStyles, autoStyles, shapeData);
}
}
node = node.nextSibling();
}
}
void Odf::loadColumnNodes(Sheet *sheet, const KoXmlElement& parent,
int& indexCol,
int& maxColumn,
KoOdfLoadingContext& odfContext,
QHash<QString, QRegion>& columnStyleRegions,
IntervalMap<QString>& columnStyles
)
{
KoXmlNode node = parent.firstChild();
while (!node.isNull()) {
KoXmlElement elem = node.toElement();
if (!elem.isNull() && elem.namespaceURI() == KoXmlNS::table) {
if (elem.localName() == "table-column") {
loadColumnFormat(sheet, elem, odfContext.stylesReader(), indexCol, columnStyleRegions, columnStyles);
maxColumn = qMax(maxColumn, indexCol - 1);
} else if (elem.localName() == "table-column-group") {
loadColumnNodes(sheet, elem, indexCol, maxColumn, odfContext, columnStyleRegions, columnStyles);
}
}
node = node.nextSibling();
}
}
void Odf::loadSheetInsertStyles(Sheet *sheet, const Styles& autoStyles,
const QHash<QString, QRegion>& styleRegions,
const QHash<QString, Conditions>& conditionalStyles,
const QRect& usedArea,
QList<QPair<QRegion, Style> >& outStyleRegions,
QList<QPair<QRegion, Conditions> >& outConditionalStyles)
{
const QList<QString> styleNames = styleRegions.keys();
for (int i = 0; i < styleNames.count(); ++i) {
if (!autoStyles.contains(styleNames[i]) && !sheet->map()->styleManager()->style(styleNames[i])) {
warnSheetsODF << "\t" << styleNames[i] << " not used";
continue;
}
const bool hasConditions = conditionalStyles.contains(styleNames[i]);
const QRegion styleRegion = styleRegions[styleNames[i]] & QRegion(usedArea);
if (hasConditions)
outConditionalStyles.append(qMakePair(styleRegion, conditionalStyles[styleNames[i]]));
if (autoStyles.contains(styleNames[i])) {
//debugSheetsODF << "\tautomatic:" << styleNames[i] << " at" << styleRegion.rectCount() << "rects";
Style style;
style.setDefault(); // "overwrite" existing style
style.merge(autoStyles[styleNames[i]]);
outStyleRegions.append(qMakePair(styleRegion, style));
} else {
const CustomStyle* namedStyle = sheet->map()->styleManager()->style(styleNames[i]);
//debugSheetsODF << "\tcustom:" << namedStyle->name() << " at" << styleRegion.rectCount() << "rects";
Style style;
style.setDefault(); // "overwrite" existing style
style.merge(*namedStyle);
outStyleRegions.append(qMakePair(styleRegion, style));
}
}
}
void Odf::replaceMacro(QString & text, const QString & old, const QString & newS)
{
int n = text.indexOf(old);
if (n != -1)
text = text.replace(n, old.length(), newS);
}
QString Odf::getPart(const KoXmlNode & part)
{
QString result;
KoXmlElement e = KoXml::namedItemNS(part, KoXmlNS::text, "p");
while (!e.isNull()) {
QString text = e.text();
KoXmlElement macro = KoXml::namedItemNS(e, KoXmlNS::text, "time");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<time>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "date");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<date>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "page-number");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<page>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "page-count");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<pages>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "sheet-name");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<sheet>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "title");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<name>");
macro = KoXml::namedItemNS(e, KoXmlNS::text, "file-name");
if (!macro.isNull())
replaceMacro(text, macro.text(), "<file>");
//add support for multi line into kspread
if (!result.isEmpty())
result += '\n';
result += text;
e = e.nextSibling().toElement();
}
return result;
}
bool Odf::loadStyleFormat(Sheet *sheet, KoXmlElement *style)
{
QString hleft, hmiddle, hright;
QString fleft, fmiddle, fright;
KoXmlNode header = KoXml::namedItemNS(*style, KoXmlNS::style, "header");
if (!header.isNull()) {
debugSheetsODF << "Header exists";
KoXmlNode part = KoXml::namedItemNS(header, KoXmlNS::style, "region-left");
if (!part.isNull()) {
hleft = getPart(part);
debugSheetsODF << "Header left:" << hleft;
} else
debugSheetsODF << "Style:region:left doesn't exist!";
part = KoXml::namedItemNS(header, KoXmlNS::style, "region-center");
if (!part.isNull()) {
hmiddle = getPart(part);
debugSheetsODF << "Header middle:" << hmiddle;
}
part = KoXml::namedItemNS(header, KoXmlNS::style, "region-right");
if (!part.isNull()) {
hright = getPart(part);
debugSheetsODF << "Header right:" << hright;
}
//If Header doesn't have region tag add it to Left
hleft.append(getPart(header));
}
//TODO implement it under kspread
KoXmlNode headerleft = KoXml::namedItemNS(*style, KoXmlNS::style, "header-left");
if (!headerleft.isNull()) {
KoXmlElement e = headerleft.toElement();
if (e.hasAttributeNS(KoXmlNS::style, "display"))
debugSheetsODF << "header.hasAttribute( style:display ) :" << e.hasAttributeNS(KoXmlNS::style, "display");
else
debugSheetsODF << "header left doesn't has attribute style:display";
}
//TODO implement it under kspread
KoXmlNode footerleft = KoXml::namedItemNS(*style, KoXmlNS::style, "footer-left");
if (!footerleft.isNull()) {
KoXmlElement e = footerleft.toElement();
if (e.hasAttributeNS(KoXmlNS::style, "display"))
debugSheetsODF << "footer.hasAttribute( style:display ) :" << e.hasAttributeNS(KoXmlNS::style, "display");
else
debugSheetsODF << "footer left doesn't has attribute style:display";
}
KoXmlNode footer = KoXml::namedItemNS(*style, KoXmlNS::style, "footer");
if (!footer.isNull()) {
KoXmlNode part = KoXml::namedItemNS(footer, KoXmlNS::style, "region-left");
if (!part.isNull()) {
fleft = getPart(part);
debugSheetsODF << "Footer left:" << fleft;
}
part = KoXml::namedItemNS(footer, KoXmlNS::style, "region-center");
if (!part.isNull()) {
fmiddle = getPart(part);
debugSheetsODF << "Footer middle:" << fmiddle;
}
part = KoXml::namedItemNS(footer, KoXmlNS::style, "region-right");
if (!part.isNull()) {
fright = getPart(part);
debugSheetsODF << "Footer right:" << fright;
}
//If Footer doesn't have region tag add it to Left
fleft.append(getPart(footer));
}
sheet->print()->headerFooter()->setHeadFootLine(hleft, hmiddle, hright,
fleft, fmiddle, fright);
return true;
}
void Odf::loadMasterLayoutPage(Sheet *sheet, KoStyleStack &styleStack)
{
KoPageLayout pageLayout;
if (styleStack.hasProperty(KoXmlNS::fo, "page-width")) {
pageLayout.width = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "page-width"));
}
if (styleStack.hasProperty(KoXmlNS::fo, "page-height")) {
pageLayout.height = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "page-height"));
}
if (styleStack.hasProperty(KoXmlNS::fo, "margin-top")) {
pageLayout.topMargin = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "margin-top"));
}
if (styleStack.hasProperty(KoXmlNS::fo, "margin-bottom")) {
pageLayout.bottomMargin = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "margin-bottom"));
}
if (styleStack.hasProperty(KoXmlNS::fo, "margin-left")) {
pageLayout.leftMargin = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "margin-left"));
}
if (styleStack.hasProperty(KoXmlNS::fo, "margin-right")) {
pageLayout.rightMargin = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "margin-right"));
}
/* set sheet's direction to RTL if sheet name is an RTL string */
Qt::LayoutDirection ldir = sheet->sheetName().isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
if (styleStack.hasProperty(KoXmlNS::style, "writing-mode")) {
debugSheetsODF << "styleStack.hasAttribute( style:writing-mode ) :" << styleStack.hasProperty(KoXmlNS::style, "writing-mode");
const QString writingMode = styleStack.property(KoXmlNS::style, "writing-mode");
if (writingMode == "lr-tb") {
ldir = Qt::LeftToRight;
} else if (writingMode == "rl-tb") {
ldir = Qt::RightToLeft;
}
//TODO
//<value>lr-tb</value>
//<value>rl-tb</value>
//<value>tb-rl</value>
//<value>tb-lr</value>
//<value>lr</value>
//<value>rl</value>
//<value>tb</value>
//<value>page</value>
}
sheet->setLayoutDirection(ldir);
if (styleStack.hasProperty(KoXmlNS::style, "print-orientation")) {
pageLayout.orientation = (styleStack.property(KoXmlNS::style, "print-orientation") == "landscape")
? KoPageFormat::Landscape : KoPageFormat::Portrait;
}
if (styleStack.hasProperty(KoXmlNS::style, "num-format")) {
//not implemented into kspread
//These attributes specify the numbering style to use.
//If a numbering style is not specified, the numbering style is inherited from
//the page style. See section 6.7.8 for information on these attributes
debugSheetsODF << " num-format :" << styleStack.property(KoXmlNS::style, "num-format");
}
if (styleStack.hasProperty(KoXmlNS::fo, "background-color")) {
//TODO
debugSheetsODF << " fo:background-color :" << styleStack.property(KoXmlNS::fo, "background-color");
}
if (styleStack.hasProperty(KoXmlNS::style, "print")) {
//todo parsing
QString str = styleStack.property(KoXmlNS::style, "print");
debugSheetsODF << " style:print :" << str;
if (str.contains("headers")) {
//TODO implement it into kspread
}
if (str.contains("grid")) {
sheet->print()->settings()->setPrintGrid(true);
}
if (str.contains("annotations")) {
//TODO it's not implemented
}
if (str.contains("objects")) {
//TODO it's not implemented
}
if (str.contains("charts")) {
//TODO it's not implemented
}
if (str.contains("drawings")) {
//TODO it's not implemented
}
if (str.contains("formulas")) {
sheet->setShowFormula(true);
}
if (str.contains("zero-values")) {
//TODO it's not implemented
}
}
if (styleStack.hasProperty(KoXmlNS::style, "table-centering")) {
QString str = styleStack.property(KoXmlNS::style, "table-centering");
//TODO not implemented into kspread
debugSheetsODF << " styleStack.attribute( style:table-centering ) :" << str;
#if 0
if (str == "horizontal") {
} else if (str == "vertical") {
} else if (str == "both") {
} else if (str == "none") {
} else
debugSheetsODF << " table-centering unknown :" << str;
#endif
}
sheet->print()->settings()->setPageLayout(pageLayout);
}
bool Odf::loadColumnFormat(Sheet *sheet, const KoXmlElement& column,
const KoOdfStylesReader& stylesReader, int & indexCol,
QHash<QString, QRegion>& columnStyleRegions, IntervalMap<QString>& columnStyles)
{
// debugSheetsODF<<"bool Odf::loadColumnFormat(const KoXmlElement& column, const KoOdfStylesReader& stylesReader, unsigned int & indexCol ) index Col :"<<indexCol;
bool isNonDefaultColumn = false;
int number = 1;
if (column.hasAttributeNS(KoXmlNS::table, "number-columns-repeated")) {
bool ok = true;
int n = column.attributeNS(KoXmlNS::table, "number-columns-repeated", QString()).toInt(&ok);
if (ok)
// Some spreadsheet programs may support more rows than Calligra Sheets so
// limit the number of repeated rows.
// FIXME POSSIBLE DATA LOSS!
number = qMin(n, KS_colMax - indexCol + 1);
//debugSheetsODF << "Repeated:" << number;
}
if (column.hasAttributeNS(KoXmlNS::table, "default-cell-style-name")) {
const QString styleName = column.attributeNS(KoXmlNS::table, "default-cell-style-name", QString());
if (!styleName.isEmpty()) {
columnStyleRegions[styleName] += QRect(indexCol, 1, number, KS_rowMax);
columnStyles.insert(indexCol, indexCol+number-1, styleName);
}
}
enum { Visible, Collapsed, Filtered } visibility = Visible;
if (column.hasAttributeNS(KoXmlNS::table, "visibility")) {
const QString string = column.attributeNS(KoXmlNS::table, "visibility", "visible");
if (string == "collapse")
visibility = Collapsed;
else if (string == "filter")
visibility = Filtered;
isNonDefaultColumn = true;
}
KoStyleStack styleStack;
if (column.hasAttributeNS(KoXmlNS::table, "style-name")) {
QString str = column.attributeNS(KoXmlNS::table, "style-name", QString());
const KoXmlElement *style = stylesReader.findStyle(str, "table-column");
if (style) {
styleStack.push(*style);
isNonDefaultColumn = true;
}
}
styleStack.setTypeProperties("table-column"); //style for column
double width = -1.0;
if (styleStack.hasProperty(KoXmlNS::style, "column-width")) {
width = KoUnit::parseValue(styleStack.property(KoXmlNS::style, "column-width") , -1.0);
//debugSheetsODF << " style:column-width : width :" << width;
isNonDefaultColumn = true;
}
bool insertPageBreak = false;
if (styleStack.hasProperty(KoXmlNS::fo, "break-before")) {
QString str = styleStack.property(KoXmlNS::fo, "break-before");
if (str == "page") {
insertPageBreak = true;
} else {
// debugSheetsODF << " str :" << str;
}
isNonDefaultColumn = true;
} else if (styleStack.hasProperty(KoXmlNS::fo, "break-after")) {
// TODO
}
// If it's a default column, we can return here.
// This saves the iteration, which can be caused by column cell default styles,
// but which are not inserted here.
if (!isNonDefaultColumn) {
indexCol += number;
return true;
}
for (int i = 0; i < number; ++i) {
//debugSheetsODF << " insert new column: pos :" << indexCol << " width :" << width << " hidden ?" << visibility;
if (isNonDefaultColumn) {
ColumnFormat* cf = sheet->nonDefaultColumnFormat(indexCol);
if (width != -1.0) //safe
cf->setWidth(width);
if (insertPageBreak) {
cf->setPageBreak(true);
}
if (visibility == Collapsed)
cf->setHidden(true);
else if (visibility == Filtered)
cf->setFiltered(true);
cf->setPageBreak(insertPageBreak);
}
++indexCol;
}
// debugSheetsODF<<" after index column !!!!!!!!!!!!!!!!!! :"<<indexCol;
return true;
}
int Odf::loadRowFormat(Sheet *sheet, const KoXmlElement& row, int &rowIndex,
OdfLoadingContext& tableContext,
QHash<QString, QRegion>& rowStyleRegions,
QHash<QString, QRegion>& cellStyleRegions,
const IntervalMap<QString>& columnStyles,
const Styles& autoStyles,
QList<ShapeLoadingData>& shapeData)
{
static const QString sStyleName = QString::fromLatin1("style-name");
static const QString sNumberRowsRepeated = QString::fromLatin1("number-rows-repeated");
static const QString sDefaultCellStyleName = QString::fromLatin1("default-cell-style-name");
static const QString sVisibility = QString::fromLatin1("visibility");
static const QString sVisible = QString::fromLatin1("visible");
static const QString sCollapse = QString::fromLatin1("collapse");
static const QString sFilter = QString::fromLatin1("filter");
static const QString sPage = QString::fromLatin1("page");
static const QString sTableCell = QString::fromLatin1("table-cell");
static const QString sCoveredTableCell = QString::fromLatin1("covered-table-cell");
static const QString sNumberColumnsRepeated = QString::fromLatin1("number-columns-repeated");
// debugSheetsODF<<"Odf::loadRowFormat( const KoXmlElement& row, int &rowIndex,const KoOdfStylesReader& stylesReader, bool isLast )***********";
KoOdfLoadingContext& odfContext = tableContext.odfContext;
bool isNonDefaultRow = false;
KoStyleStack styleStack;
if (row.hasAttributeNS(KoXmlNS::table, sStyleName)) {
QString str = row.attributeNS(KoXmlNS::table, sStyleName, QString());
const KoXmlElement *style = odfContext.stylesReader().findStyle(str, "table-row");
if (style) {
styleStack.push(*style);
isNonDefaultRow = true;
}
}
styleStack.setTypeProperties("table-row");
int number = 1;
if (row.hasAttributeNS(KoXmlNS::table, sNumberRowsRepeated)) {
bool ok = true;
int n = row.attributeNS(KoXmlNS::table, sNumberRowsRepeated, QString()).toInt(&ok);
if (ok)
// Some spreadsheet programs may support more rows than Calligra Sheets so
// limit the number of repeated rows.
// FIXME POSSIBLE DATA LOSS!
number = qMin(n, KS_rowMax - rowIndex + 1);
}
QString rowCellStyleName;
if (row.hasAttributeNS(KoXmlNS::table, sDefaultCellStyleName)) {
rowCellStyleName = row.attributeNS(KoXmlNS::table, sDefaultCellStyleName, QString());
if (!rowCellStyleName.isEmpty()) {
rowStyleRegions[rowCellStyleName] += QRect(1, rowIndex, KS_colMax, number);
}
}
double height = -1.0;
if (styleStack.hasProperty(KoXmlNS::style, "row-height")) {
height = KoUnit::parseValue(styleStack.property(KoXmlNS::style, "row-height") , -1.0);
// debugSheetsODF<<" properties style:row-height : height :"<<height;
isNonDefaultRow = true;
}
enum { Visible, Collapsed, Filtered } visibility = Visible;
if (row.hasAttributeNS(KoXmlNS::table, sVisibility)) {
const QString string = row.attributeNS(KoXmlNS::table, sVisibility, sVisible);
if (string == sCollapse)
visibility = Collapsed;
else if (string == sFilter)
visibility = Filtered;
isNonDefaultRow = true;
}
bool insertPageBreak = false;
if (styleStack.hasProperty(KoXmlNS::fo, "break-before")) {
QString str = styleStack.property(KoXmlNS::fo, "break-before");
if (str == sPage) {
insertPageBreak = true;
}
// else
// debugSheetsODF<<" str :"<<str;
isNonDefaultRow = true;
} else if (styleStack.hasProperty(KoXmlNS::fo, "break-after")) {
// TODO
}
// debugSheetsODF<<" create non defaultrow format :"<<rowIndex<<" repeate :"<<number<<" height :"<<height;
if (isNonDefaultRow) {
if (height != -1.0)
sheet->rowFormats()->setRowHeight(rowIndex, rowIndex + number - 1, height);
sheet->rowFormats()->setPageBreak(rowIndex, rowIndex + number - 1, insertPageBreak);
if (visibility == Collapsed)
sheet->rowFormats()->setHidden(rowIndex, rowIndex + number - 1, true);
else if (visibility == Filtered)
sheet->rowFormats()->setFiltered(rowIndex, rowIndex + number - 1, true);
}
int columnIndex = 1;
int columnMaximal = 0;
const int endRow = qMin(rowIndex + number - 1, KS_rowMax);
KoXmlElement cellElement;
forEachElement(cellElement, row) {
if (cellElement.namespaceURI() != KoXmlNS::table)
continue;
if (cellElement.localName() != sTableCell && cellElement.localName() != sCoveredTableCell)
continue;
bool ok = false;
const int n = cellElement.attributeNS(KoXmlNS::table, sNumberColumnsRepeated, QString()).toInt(&ok);
// Some spreadsheet programs may support more columns than
// Calligra Sheets so limit the number of repeated columns.
const int numberColumns = ok ? qMin(n, KS_colMax - columnIndex + 1) : 1;
columnMaximal = qMax(numberColumns, columnMaximal);
// Styles are inserted at the end of the loading process, so check the XML directly here.
const QString styleName = cellElement.attributeNS(KoXmlNS::table , sStyleName, QString());
if (!styleName.isEmpty())
cellStyleRegions[styleName] += QRect(columnIndex, rowIndex, numberColumns, number);
// figure out exact cell style for loading of cell content
QString cellStyleName = styleName;
if (cellStyleName.isEmpty())
cellStyleName = rowCellStyleName;
if (cellStyleName.isEmpty())
cellStyleName = columnStyles.get(columnIndex);
Cell cell(sheet, columnIndex, rowIndex);
loadCell(&cell, cellElement, tableContext, autoStyles, cellStyleName, shapeData);
if (!cell.comment().isEmpty())
sheet->cellStorage()->setComment(Region(columnIndex, rowIndex, numberColumns, number, sheet), cell.comment());
if (!cell.conditions().isEmpty())
sheet->cellStorage()->setConditions(Region(columnIndex, rowIndex, numberColumns, number, sheet), cell.conditions());
if (!cell.validity().isEmpty())
sheet->cellStorage()->setValidity(Region(columnIndex, rowIndex, numberColumns, number, sheet), cell.validity());
if (!cell.hasDefaultContent()) {
// Row-wise filling of PointStorages is faster than column-wise filling.
QSharedPointer<QTextDocument> richText = cell.richText();
for (int r = rowIndex; r <= endRow; ++r) {
for (int c = 0; c < numberColumns; ++c) {
Cell target(sheet, columnIndex + c, r);
target.setFormula(cell.formula());
target.setUserInput(cell.userInput());
target.setRichText(richText);
target.setValue(cell.value());
if (cell.doesMergeCells()) {
target.mergeCells(columnIndex + c, r, cell.mergedXCells(), cell.mergedYCells());
}
}
}
}
columnIndex += numberColumns;
}
sheet->cellStorage()->setRowsRepeated(rowIndex, number);
rowIndex += number;
return columnMaximal;
}
// *************** Saving *****************
bool Odf::saveSheet(Sheet *sheet, OdfSavingContext& tableContext)
{
KoXmlWriter & xmlWriter = tableContext.shapeContext.xmlWriter();
KoGenStyles & mainStyles = tableContext.shapeContext.mainStyles();
xmlWriter.startElement("table:table");
xmlWriter.addAttribute("table:name", sheet->sheetName());
xmlWriter.addAttribute("table:style-name", saveSheetStyleName(sheet, mainStyles));
QByteArray pwd;
sheet->password(pwd);
if (!pwd.isNull()) {
xmlWriter.addAttribute("table:protected", "true");
QByteArray str = KCodecs::base64Encode(pwd);
// FIXME Stefan: see OpenDocument spec, ch. 17.3 Encryption
xmlWriter.addAttribute("table:protection-key", QString(str));
}
QRect _printRange = sheet->printSettings()->printRegion().lastRange();
if (!_printRange.isNull() &&_printRange != (QRect(QPoint(1, 1), QPoint(KS_colMax, KS_rowMax)))) {
const Region region(_printRange, sheet);
if (region.isValid()) {
debugSheetsODF << region;
xmlWriter.addAttribute("table:print-ranges", saveRegion(region.name()));
}
}
// flake
// Create a dict of cell anchored shapes with the cell as key.
int sheetAnchoredCount = 0;
foreach(KoShape* shape, sheet->shapes()) {
if (dynamic_cast<ShapeApplicationData*>(shape->applicationData())->isAnchoredToCell()) {
qreal dummy;
const QPointF position = shape->position();
const int col = sheet->leftColumn(position.x(), dummy);
const int row = sheet->topRow(position.y(), dummy);
tableContext.insertCellAnchoredShape(sheet, row, col, shape);
} else {
sheetAnchoredCount++;
}
}
// flake
// Save the remaining shapes, those that are anchored in the page.
if (sheetAnchoredCount) {
xmlWriter.startElement("table:shapes");
foreach(KoShape* shape, sheet->shapes()) {
if (dynamic_cast<ShapeApplicationData*>(shape->applicationData())->isAnchoredToCell())
continue;
shape->saveOdf(tableContext.shapeContext);
}
xmlWriter.endElement();
}
const QRect usedArea = sheet->usedArea();
saveColRowCell(sheet, usedArea.width(), usedArea.height(), tableContext);
xmlWriter.endElement();
return true;
}
QString Odf::saveSheetStyleName(Sheet *sheet, KoGenStyles &mainStyles)
{
KoGenStyle pageStyle(KoGenStyle::TableAutoStyle, "table"/*FIXME I don't know if name is sheet*/);
KoGenStyle pageMaster(KoGenStyle::MasterPageStyle);
const QString pageLayoutName = savePageLayout(sheet->printSettings(), mainStyles,
sheet->getShowFormula(),
!sheet->getHideZero());
pageMaster.addAttribute("style:page-layout-name", pageLayoutName);
QBuffer buffer;
buffer.open(QIODevice::WriteOnly);
KoXmlWriter elementWriter(&buffer); // TODO pass indentation level
saveHeaderFooter(sheet, elementWriter);
QString elementContents = QString::fromUtf8(buffer.buffer(), buffer.buffer().size());
pageMaster.addChildElement("headerfooter", elementContents);
pageStyle.addAttribute("style:master-page-name", mainStyles.insert(pageMaster, "Standard"));
pageStyle.addProperty("table:display", !sheet->isHidden());
if( !sheet->backgroundImage().isNull() ) {
QBuffer bgBuffer;
bgBuffer.open(QIODevice::WriteOnly);
KoXmlWriter bgWriter(&bgBuffer); //TODO pass identation level
saveBackgroundImage(sheet, bgWriter);
const QString bgContent = QString::fromUtf8(bgBuffer.buffer(), bgBuffer.size());
pageMaster.addChildElement("backgroundImage", bgContent);
}
return mainStyles.insert(pageStyle, "ta");
}
void Odf::saveColRowCell(Sheet *sheet, int maxCols, int maxRows, OdfSavingContext& tableContext)
{
debugSheetsODF << "Odf::saveColRowCell:" << sheet->sheetName();
KoXmlWriter & xmlWriter = tableContext.shapeContext.xmlWriter();
KoGenStyles & mainStyles = tableContext.shapeContext.mainStyles();
// calculate the column/row default cell styles
int maxMaxRows = maxRows; // includes the max row a column default style occupies
// also extends the maximum column/row to include column/row styles
sheet->styleStorage()->saveCreateDefaultStyles(maxCols, maxMaxRows, tableContext.columnDefaultStyles, tableContext.rowDefaultStyles);
if (tableContext.rowDefaultStyles.count() != 0)
maxRows = qMax(maxRows, (--tableContext.rowDefaultStyles.constEnd()).key());
// Take the actual used area into account so we also catch shapes that are
// anchored after any content.
QRect r = sheet->usedArea(false);
maxRows = qMax(maxRows, r.bottom());
maxCols = qMax(maxCols, r.right());
// OpenDocument needs at least one cell per sheet.
maxCols = qMin(KS_colMax, qMax(1, maxCols));
maxRows = qMin(KS_rowMax, qMax(1, maxRows));
maxMaxRows = maxMaxRows;
debugSheetsODF << "\t Sheet dimension:" << maxCols << " x" << maxRows;
// saving the columns
//
int i = 1;
while (i <= maxCols) {
const ColumnFormat* column = sheet->columnFormat(i);
// debugSheetsODF << "Odf::saveColRowCell: first col loop:"
// << "i:" << i
// << "column:" << (column ? column->column() : 0)
// << "default:" << (column ? column->isDefault() : false);
//style default layout for column
const Style style = tableContext.columnDefaultStyles.value(i);
int j = i;
int count = 1;
while (j <= maxCols) {
const ColumnFormat* nextColumn = sheet->nextColumn(j);
const int nextColumnIndex = nextColumn ? nextColumn->column() : 0;
const QMap<int, Style>::iterator nextColumnDefaultStyle = tableContext.columnDefaultStyles.upperBound(j);
const int nextStyleColumnIndex = nextColumnDefaultStyle == tableContext.columnDefaultStyles.end()
? 0 : nextColumnDefaultStyle.key();
// j becomes the index of the adjacent column
++j;
// debugSheetsODF <<"Odf::saveColRowCell: second col loop:"
// << "j:" << j
// << "next column:" << (nextColumn ? nextColumn->column() : 0)
// << "next styled column:" << nextStyleColumnIndex;
// no next or not the adjacent column?
if ((!nextColumn && !nextStyleColumnIndex) ||
(nextColumnIndex != j && nextStyleColumnIndex != j)) {
// if the origin column was a default column,
if (column->isDefault() && style.isDefault()) {
// we count the default columns
if (!nextColumn && !nextStyleColumnIndex)
count = maxCols - i + 1;
else if (nextColumn && (!nextStyleColumnIndex || nextColumn->column() <= nextStyleColumnIndex))
count = nextColumn->column() - i;
else
count = nextStyleColumnIndex - i;
}
// otherwise we just stop here to process the adjacent
// column in the next iteration of the outer loop
break;
}
// stop, if the next column differs from the current one
if ((nextColumn && (*column != *nextColumn)) || (!nextColumn && !column->isDefault()))
break;
if (style != tableContext.columnDefaultStyles.value(j))
break;
++count;
}
xmlWriter.startElement("table:table-column");
if (!column->isDefault()) {
KoGenStyle currentColumnStyle(KoGenStyle::TableColumnAutoStyle, "table-column");
currentColumnStyle.addPropertyPt("style:column-width", column->width());
if (column->hasPageBreak()) {
currentColumnStyle.addProperty("fo:break-before", "page");
}
xmlWriter.addAttribute("table:style-name", mainStyles.insert(currentColumnStyle, "co"));
}
if (!column->isDefault() || !style.isDefault()) {
if (!style.isDefault()) {
KoGenStyle currentDefaultCellStyle; // the type is determined in saveOdfStyle
const QString name = saveStyle(&style, currentDefaultCellStyle, mainStyles,
sheet->map()->styleManager());
xmlWriter.addAttribute("table:default-cell-style-name", name);
}
if (column->isHidden())
xmlWriter.addAttribute("table:visibility", "collapse");
else if (column->isFiltered())
xmlWriter.addAttribute("table:visibility", "filter");
}
if (count > 1)
xmlWriter.addAttribute("table:number-columns-repeated", count);
xmlWriter.endElement();
debugSheetsODF << "Odf::saveColRowCell: column" << i
<< "repeated" << count - 1 << "time(s)";
i += count;
}
// saving the rows and the cells
// we have to loop through all rows of the used area
for (i = 1; i <= maxRows; ++i) {
// default cell style for row
const Style style = tableContext.rowDefaultStyles.value(i);
xmlWriter.startElement("table:table-row");
const bool rowIsDefault = sheet->rowFormats()->isDefaultRow(i);
if (!rowIsDefault) {
KoGenStyle currentRowStyle(KoGenStyle::TableRowAutoStyle, "table-row");
currentRowStyle.addPropertyPt("style:row-height", sheet->rowFormats()->rowHeight(i));
if (sheet->rowFormats()->hasPageBreak(i)) {
currentRowStyle.addProperty("fo:break-before", "page");
}
xmlWriter.addAttribute("table:style-name", mainStyles.insert(currentRowStyle, "ro"));
}
// We cannot use cellStorage()->rowRepeat(i) here cause the RowRepeatStorage only knows
// about the content but not about the shapes anchored to a cell. So, we need to check
// for them here to be sure to catch them even when the content in the cell is repeated.
int repeated = 1;
// empty row?
if (!sheet->cellStorage()->firstInRow(i) && !tableContext.rowHasCellAnchoredShapes(sheet, i)) { // row is empty
// debugSheetsODF <<"Odf::saveColRowCell: first row loop:"
// << " i: " << i
// << " row: " << row->row();
int j = i + 1;
// search for
// next non-empty row
// or
// next row with different Format
while (j <= maxRows && !sheet->cellStorage()->firstInRow(j) && !tableContext.rowHasCellAnchoredShapes(sheet, j)) {
// debugSheetsODF <<"Odf::saveColRowCell: second row loop:"
// << " j: " << j
// << " row: " << nextRow->row();
// if the reference row has the default row format
if (rowIsDefault && style.isDefault()) {
// if the next is not default, stop here
if (!sheet->rowFormats()->isDefaultRow(j) || !tableContext.rowDefaultStyles.value(j).isDefault())
break;
// otherwise, jump to the next
++j;
continue;
}
// stop, if the next row differs from the current one
if (!sheet->rowFormats()->rowsAreEqual(i, j))
break;
if (style != tableContext.rowDefaultStyles.value(j))
break;
// otherwise, process the next
++j;
}
repeated = j - i;
if (repeated > 1)
xmlWriter.addAttribute("table:number-rows-repeated", repeated);
if (!style.isDefault()) {
KoGenStyle currentDefaultCellStyle; // the type is determined in saveCellStyle
const QString name = saveStyle(&style, currentDefaultCellStyle, mainStyles,
sheet->map()->styleManager());
xmlWriter.addAttribute("table:default-cell-style-name", name);
}
if (sheet->rowFormats()->isHidden(i)) // never true for the default row
xmlWriter.addAttribute("table:visibility", "collapse");
else if (sheet->rowFormats()->isFiltered(i)) // never true for the default row
xmlWriter.addAttribute("table:visibility", "filter");
// NOTE Stefan: Even if paragraph 8.1 states, that rows may be empty, the
// RelaxNG schema does not allow that.
xmlWriter.startElement("table:table-cell");
// Fill the row with empty cells, if there's a row default cell style.
if (!style.isDefault())
xmlWriter.addAttribute("table:number-columns-repeated", QString::number(maxCols));
// Fill the row with empty cells up to the last column with a default cell style.
else if (!tableContext.columnDefaultStyles.isEmpty()) {
const int col = (--tableContext.columnDefaultStyles.constEnd()).key();
xmlWriter.addAttribute("table:number-columns-repeated", QString::number(col));
}
xmlWriter.endElement();
debugSheetsODF << "Odf::saveColRowCell: empty row" << i
<< "repeated" << repeated << "time(s)";
// copy the index for the next row to process
i = j - 1; /*it's already incremented in the for loop*/
} else { // row is not empty
if (!style.isDefault()) {
KoGenStyle currentDefaultCellStyle; // the type is determined in saveCellStyle
const QString name = saveStyle(&style, currentDefaultCellStyle, mainStyles,
sheet->map()->styleManager());
xmlWriter.addAttribute("table:default-cell-style-name", name);
}
if (sheet->rowFormats()->isHidden(i)) // never true for the default row
xmlWriter.addAttribute("table:visibility", "collapse");
else if (sheet->rowFormats()->isFiltered(i)) // never true for the default row
xmlWriter.addAttribute("table:visibility", "filter");
int j = i + 1;
while (j <= maxRows && compareRows(sheet, i, j, maxCols, tableContext)) {
j++;
repeated++;
}
repeated = j - i;
if (repeated > 1) {
debugSheetsODF << "Odf::saveColRowCell: NON-empty row" << i
<< "repeated" << repeated << "times";
xmlWriter.addAttribute("table:number-rows-repeated", repeated);
}
saveCells(sheet, i, maxCols, tableContext);
// copy the index for the next row to process
i = j - 1; /*it's already incremented in the for loop*/
}
xmlWriter.endElement();
}
// Fill in rows with empty cells, if there's a column default cell style.
if (!tableContext.columnDefaultStyles.isEmpty()) {
if (maxMaxRows > maxRows) {
xmlWriter.startElement("table:table-row");
if (maxMaxRows > maxRows + 1)
xmlWriter.addAttribute("table:number-rows-repeated", maxMaxRows - maxRows);
xmlWriter.startElement("table:table-cell");
const int col = qMin(maxCols, (--tableContext.columnDefaultStyles.constEnd()).key());
xmlWriter.addAttribute("table:number-columns-repeated", QString::number(col));
xmlWriter.endElement();
xmlWriter.endElement();
}
}
}
void Odf::saveCells(Sheet *sheet, int row, int maxCols, OdfSavingContext& tableContext)
{
KoXmlWriter & xmlWriter = tableContext.shapeContext.xmlWriter();
int i = 1;
Cell cell(sheet, i, row);
Cell nextCell = sheet->cellStorage()->nextInRow(i, row);
// handle situations where the row contains shapes and nothing else
if (cell.isDefault() && nextCell.isNull()) {
int nextShape = tableContext.nextAnchoredShape(sheet, row, i);
if (nextShape)
nextCell = Cell(sheet, nextShape, row);
}
// while
// the current cell is not a default one
// or
// we have a further cell in this row
do {
// debugSheetsODF <<"Odf::saveCells:"
// << " i: " << i
// << " column: " << cell.column() << endl;
int repeated = 1;
int column = i;
saveCell(&cell, repeated, tableContext);
i += repeated;
// stop if we reached the end column
if (i > maxCols || nextCell.isNull())
break;
cell = Cell(sheet, i, row);
// if we have a shape anchored to an empty cell, ensure that the cell gets also processed
int nextShape = tableContext.nextAnchoredShape(sheet, row, column);
if (nextShape && ((nextShape < i) || cell.isDefault())) {
cell = Cell(sheet, nextShape, row);
i = nextShape;
}
nextCell = sheet->cellStorage()->nextInRow(i, row);
} while (!cell.isDefault() || tableContext.cellHasAnchoredShapes(sheet, cell.row(), cell.column()) || !nextCell.isNull());
// Fill the row with empty cells, if there's a row default cell style.
if (tableContext.rowDefaultStyles.contains(row)) {
if (maxCols >= i) {
xmlWriter.startElement("table:table-cell");
if (maxCols > i)
xmlWriter.addAttribute("table:number-columns-repeated", QString::number(maxCols - i + 1));
xmlWriter.endElement();
}
}
// Fill the row with empty cells up to the last column with a default cell style.
else if (!tableContext.columnDefaultStyles.isEmpty()) {
const int col = (--tableContext.columnDefaultStyles.constEnd()).key();
if (col >= i) {
xmlWriter.startElement("table:table-cell");
if (col > i)
xmlWriter.addAttribute("table:number-columns-repeated", QString::number(col - i + 1));
xmlWriter.endElement();
}
}
}
void Odf::saveBackgroundImage(Sheet *sheet, KoXmlWriter& xmlWriter)
{
const Sheet::BackgroundImageProperties& properties = sheet->backgroundImageProperties();
xmlWriter.startElement("style:backgroundImage");
//xmlWriter.addAttribute("xlink:href", fileName);
xmlWriter.addAttribute("xlink:type", "simple");
xmlWriter.addAttribute("xlink:show", "embed");
xmlWriter.addAttribute("xlink:actuate", "onLoad");
QString opacity = QString("%1%").arg(properties.opacity);
xmlWriter.addAttribute("draw:opacity", opacity);
QString position;
if(properties.horizontalPosition == Sheet::BackgroundImageProperties::Left) {
position += "left";
}
else if(properties.horizontalPosition == Sheet::BackgroundImageProperties::HorizontalCenter) {
position += "center";
}
else if(properties.horizontalPosition == Sheet::BackgroundImageProperties::Right) {
position += "right";
}
position += ' ';
if(properties.verticalPosition == Sheet::BackgroundImageProperties::Top) {
position += "top";
}
else if(properties.verticalPosition == Sheet::BackgroundImageProperties::VerticalCenter) {
position += "center";
}
else if(properties.verticalPosition == Sheet::BackgroundImageProperties::Bottom) {
position += "right";
}
xmlWriter.addAttribute("style:position", position);
QString repeat;
if(properties.repeat == Sheet::BackgroundImageProperties::NoRepeat) {
repeat = "no-repeat";
}
else if(properties.repeat == Sheet::BackgroundImageProperties::Repeat) {
repeat = "repeat";
}
else if(properties.repeat == Sheet::BackgroundImageProperties::Stretch) {
repeat = "stretch";
}
xmlWriter.addAttribute("style:repeat", repeat);
xmlWriter.endElement();
}
void Odf::addText(const QString & text, KoXmlWriter & writer)
{
if (!text.isEmpty())
writer.addTextNode(text);
}
void Odf::convertPart(Sheet *sheet, const QString & part, KoXmlWriter & xmlWriter)
{
QString text;
QString var;
bool inVar = false;
uint i = 0;
uint l = part.length();
while (i < l) {
if (inVar || part[i] == '<') {
inVar = true;
var += part[i];
if (part[i] == '>') {
inVar = false;
if (var == "<page>") {
addText(text, xmlWriter);
xmlWriter.startElement("text:page-number");
xmlWriter.addTextNode("1");
xmlWriter.endElement();
} else if (var == "<pages>") {
addText(text, xmlWriter);
xmlWriter.startElement("text:page-count");
xmlWriter.addTextNode("99"); //TODO I think that it can be different from 99
xmlWriter.endElement();
} else if (var == "<date>") {
addText(text, xmlWriter);
//text:p><text:date style:data-style-name="N2" text:date-value="2005-10-02">02/10/2005</text:date>, <text:time>10:20:12</text:time></text:p> "add style" => create new style
#if 0 //FIXME
KoXmlElement t = dd.createElement("text:date");
t.setAttribute("text:date-value", "0-00-00");
// todo: "style:data-style-name", "N2"
t.appendChild(dd.createTextNode(QDate::currentDate().toString()));
parent.appendChild(t);
#endif
} else if (var == "<time>") {
addText(text, xmlWriter);
xmlWriter.startElement("text:time");
xmlWriter.addTextNode(QTime::currentTime().toString());
xmlWriter.endElement();
} else if (var == "<file>") { // filepath + name
addText(text, xmlWriter);
xmlWriter.startElement("text:file-name");
xmlWriter.addAttribute("text:display", "full");
xmlWriter.addTextNode("???");
xmlWriter.endElement();
} else if (var == "<name>") { // filename
addText(text, xmlWriter);
xmlWriter.startElement("text:title");
xmlWriter.addTextNode("???");
xmlWriter.endElement();
} else if (var == "<author>") {
DocBase* sdoc = sheet->doc();
KoDocumentInfo* docInfo = sdoc->documentInfo();
text += docInfo->authorInfo("creator");
addText(text, xmlWriter);
} else if (var == "<email>") {
DocBase* sdoc = sheet->doc();
KoDocumentInfo* docInfo = sdoc->documentInfo();
text += docInfo->authorInfo("email");
addText(text, xmlWriter);
} else if (var == "<org>") {
DocBase* sdoc = sheet->doc();
KoDocumentInfo* docInfo = sdoc->documentInfo();
text += docInfo->authorInfo("company");
addText(text, xmlWriter);
} else if (var == "<sheet>") {
addText(text, xmlWriter);
xmlWriter.startElement("text:sheet-name");
xmlWriter.addTextNode("???");
xmlWriter.endElement();
} else {
// no known variable:
text += var;
addText(text, xmlWriter);
}
text.clear();
var.clear();
}
} else {
text += part[i];
}
++i;
}
if (!text.isEmpty() || !var.isEmpty()) {
//we don't have var at the end =>store it
addText(text + var, xmlWriter);
}
debugSheetsODF << " text end :" << text << " var :" << var;
}
void Odf::saveHeaderFooter(Sheet *sheet, KoXmlWriter &xmlWriter)
{
HeaderFooter *hf = sheet->print()->headerFooter();
QString headerLeft = hf->headLeft();
QString headerCenter = hf->headMid();
QString headerRight = hf->headRight();
QString footerLeft = hf->footLeft();
QString footerCenter = hf->footMid();
QString footerRight =hf->footRight();
xmlWriter.startElement("style:header");
if ((!headerLeft.isEmpty())
|| (!headerCenter.isEmpty())
|| (!headerRight.isEmpty())) {
xmlWriter.startElement("style:region-left");
xmlWriter.startElement("text:p");
convertPart(sheet, headerLeft, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement();
xmlWriter.startElement("style:region-center");
xmlWriter.startElement("text:p");
convertPart(sheet, headerCenter, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement();
xmlWriter.startElement("style:region-right");
xmlWriter.startElement("text:p");
convertPart(sheet, headerRight, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement();
} else {
xmlWriter.startElement("text:p");
xmlWriter.startElement("text:sheet-name");
xmlWriter.addTextNode("???");
xmlWriter.endElement();
xmlWriter.endElement();
}
xmlWriter.endElement();
xmlWriter.startElement("style:footer");
if ((!footerLeft.isEmpty())
|| (!footerCenter.isEmpty())
|| (!footerRight.isEmpty())) {
xmlWriter.startElement("style:region-left");
xmlWriter.startElement("text:p");
convertPart(sheet, footerLeft, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement(); //style:region-left
xmlWriter.startElement("style:region-center");
xmlWriter.startElement("text:p");
convertPart(sheet, footerCenter, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement();
xmlWriter.startElement("style:region-right");
xmlWriter.startElement("text:p");
convertPart(sheet, footerRight, xmlWriter);
xmlWriter.endElement();
xmlWriter.endElement();
} else {
xmlWriter.startElement("text:p");
xmlWriter.startElement("text:sheet-name");
xmlWriter.addTextNode("Page "); // ???
xmlWriter.endElement();
xmlWriter.startElement("text:page-number");
xmlWriter.addTextNode("1"); // ???
xmlWriter.endElement();
xmlWriter.endElement();
}
xmlWriter.endElement();
}
inline int compareCellInRow(const Cell &cell1, const Cell &cell2, int maxCols)
{
if (cell1.isNull() != cell2.isNull())
return 0;
if (cell1.isNull())
return 2;
if (maxCols >= 0 && cell1.column() > maxCols)
return 3;
if (cell1.column() != cell2.column())
return 0;
if (!cell1.compareData(cell2))
return 0;
return 1;
}
inline bool compareCellsInRows(CellStorage *cellStorage, int row1, int row2, int maxCols)
{
Cell cell1 = cellStorage->firstInRow(row1);
Cell cell2 = cellStorage->firstInRow(row2);
while (true) {
int r = compareCellInRow(cell1, cell2, maxCols);
if (r == 0)
return false;
if (r != 1)
break;
cell1 = cellStorage->nextInRow(cell1.column(), cell1.row());
cell2 = cellStorage->nextInRow(cell2.column(), cell2.row());
}
return true;
}
bool Odf::compareRows(Sheet *sheet, int row1, int row2, int maxCols, OdfSavingContext& tableContext)
{
#if 0
if (!sheet->rowFormats()->rowsAreEqual(row1, row2)) {
return false;
}
if (tableContext.rowHasCellAnchoredShapes(sheet, row1) != tableContext.rowHasCellAnchoredShapes(sheet, row2)) {
return false;
}
return compareCellsInRows(sheet->cellStorage(), row1, row2, maxCols);
#else
Q_UNUSED(maxCols);
// Optimized comparison by using the RowRepeatStorage to compare the content
// rather then an expensive loop like compareCellsInRows.
int row1repeated = sheet->cellStorage()->rowRepeat(row1);
Q_ASSERT( row2 > row1 );
if (row2 - row1 >= row1repeated) {
return false;
}
// The RowRepeatStorage does not take to-cell anchored shapes into account
// so we need to check for them explicit.
if (tableContext.rowHasCellAnchoredShapes(sheet, row1) != tableContext.rowHasCellAnchoredShapes(sheet, row2)) {
return false;
}
// Some sanity-checks to be sure our RowRepeatStorage works as expected.
Q_ASSERT_X( sheet->rowFormats()->rowsAreEqual(row1, row2), __FUNCTION__, QString("Bug in RowRepeatStorage").toLocal8Bit() );
//Q_ASSERT_X( compareCellsInRows(sheet->cellStorage(), row1, row2, maxCols), __FUNCTION__, QString("Bug in RowRepeatStorage").toLocal8Bit() );
Q_ASSERT_X( compareCellInRow(sheet->cellStorage()->lastInRow(row1), sheet->cellStorage()->lastInRow(row2), -1), __FUNCTION__, QString("Bug in RowRepeatStorage").toLocal8Bit() );
// If we reached that point then the both rows are equal.
return true;
#endif
}
// *************** Settings *****************
void Odf::loadSheetSettings(Sheet *sheet, const KoOasisSettings::NamedMap &settings)
{
// Find the entry in the map that applies to this sheet (by name)
KoOasisSettings::Items items = settings.entry(sheet->sheetName());
if (items.isNull())
return;
sheet->setHideZero(!items.parseConfigItemBool("ShowZeroValues"));
sheet->setShowGrid(items.parseConfigItemBool("ShowGrid"));
sheet->setFirstLetterUpper(items.parseConfigItemBool("FirstLetterUpper"));
int cursorX = qMin(KS_colMax, qMax(1, items.parseConfigItemInt("CursorPositionX") + 1));
int cursorY = qMin(KS_rowMax, qMax(1, items.parseConfigItemInt("CursorPositionY") + 1));
sheet->map()->loadingInfo()->setCursorPosition(sheet, QPoint(cursorX, cursorY));
double offsetX = items.parseConfigItemDouble("xOffset");
double offsetY = items.parseConfigItemDouble("yOffset");
sheet->map()->loadingInfo()->setScrollingOffset(sheet, QPointF(offsetX, offsetY));
sheet->setShowFormulaIndicator(items.parseConfigItemBool("ShowFormulaIndicator"));
sheet->setShowCommentIndicator(items.parseConfigItemBool("ShowCommentIndicator"));
sheet->setShowPageOutline(items.parseConfigItemBool("ShowPageOutline"));
sheet->setLcMode(items.parseConfigItemBool("lcmode"));
sheet->setAutoCalculationEnabled(items.parseConfigItemBool("autoCalc"));
sheet->setShowColumnNumber(items.parseConfigItemBool("ShowColumnNumber"));
}
void Odf::saveSheetSettings(Sheet *sheet, KoXmlWriter &settingsWriter)
{
//not into each page into oo spec
settingsWriter.addConfigItem("ShowZeroValues", !sheet->getHideZero());
settingsWriter.addConfigItem("ShowGrid", sheet->getShowGrid());
//not define into oo spec
settingsWriter.addConfigItem("FirstLetterUpper", sheet->getFirstLetterUpper());
settingsWriter.addConfigItem("ShowFormulaIndicator", sheet->getShowFormulaIndicator());
settingsWriter.addConfigItem("ShowCommentIndicator", sheet->getShowCommentIndicator());
settingsWriter.addConfigItem("ShowPageOutline", sheet->isShowPageOutline());
settingsWriter.addConfigItem("lcmode", sheet->getLcMode());
settingsWriter.addConfigItem("autoCalc", sheet->isAutoCalculationEnabled());
settingsWriter.addConfigItem("ShowColumnNumber", sheet->getShowColumnNumber());
}
QString Odf::savePageLayout(PrintSettings *settings, KoGenStyles &mainStyles, bool formulas, bool zeros)
{
// Create a page layout style.
// 15.2.1 Page Size
// 15.2.4 Print Orientation
// 15.2.5 Margins
KoGenStyle pageLayout = settings->pageLayout().saveOdf();
// 15.2.13 Print
QString printParameter;
if (settings->printHeaders()) {
printParameter = "headers ";
}
if (settings->printGrid()) {
printParameter += "grid ";
}
/* if (settings->printComments()) {
printParameter += "annotations ";
}*/
if (settings->printObjects()) {
printParameter += "objects ";
}
if (settings->printCharts()) {
printParameter += "charts ";
}
/* if (settings->printDrawings()) {
printParameter += "drawings ";
}*/
if (formulas) {
printParameter += "formulas ";
}
if (zeros) {
printParameter += "zero-values ";
}
if (!printParameter.isEmpty()) {
printParameter += "drawings"; //default print style attributes in OO
pageLayout.addProperty("style:print", printParameter);
}
// 15.2.14 Print Page Order
const QString pageOrder = (settings->pageOrder() == PrintSettings::LeftToRight) ? "ltr" : "ttb";
pageLayout.addProperty("style:print-page-order", pageOrder);
// 15.2.16 Scale
// FIXME handle cases where only one direction is limited
if (settings->pageLimits().width() > 0 && settings->pageLimits().height() > 0) {
const int pages = settings->pageLimits().width() * settings->pageLimits().height();
pageLayout.addProperty("style:scale-to-pages", pages);
} else if (settings->zoom() != 1.0) {
pageLayout.addProperty("style:scale-to", qRound(settings->zoom() * 100)); // in %
}
// 15.2.17 Table Centering
if (settings->centerHorizontally() && settings->centerVertically()) {
pageLayout.addProperty("style:table-centering", "both");
} else if (settings->centerHorizontally()) {
pageLayout.addProperty("style:table-centering", "horizontal");
} else if (settings->centerVertically()) {
pageLayout.addProperty("style:table-centering", "vertical");
} else {
pageLayout.addProperty("style:table-centering", "none");
}
// this is called from Sheet::saveOdfSheetStyleName for writing the SytleMaster so
// the style has to be in the styles.xml file and only there
pageLayout.setAutoStyleInStylesDotXml(true);
return mainStyles.insert(pageLayout, "pm");
}
} // Sheets
} // Calligra
| 44.667749 | 192 | 0.586667 | afarcat |
0bfd32a2b6d8c545ab700009809831d72b393531 | 8,038 | cxx | C++ | main/dbaccess/source/core/recovery/subcomponentloader.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/dbaccess/source/core/recovery/subcomponentloader.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/dbaccess/source/core/recovery/subcomponentloader.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_dbaccess.hxx"
#include "subcomponentloader.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/ucb/Command.hpp>
#include <com/sun/star/frame/XController2.hpp>
/** === end UNO includes === **/
#include <tools/diagnose_ex.h>
//........................................................................
namespace dbaccess
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::UNO_SET_THROW;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Type;
using ::com::sun::star::frame::XController;
using ::com::sun::star::frame::XFrame;
using ::com::sun::star::awt::XWindow;
using ::com::sun::star::awt::WindowEvent;
using ::com::sun::star::lang::EventObject;
using ::com::sun::star::ucb::Command;
using ::com::sun::star::ucb::XCommandProcessor;
using ::com::sun::star::frame::XController2;
using ::com::sun::star::lang::XComponent;
/** === end UNO using === **/
//====================================================================
//= SubComponentLoader
//====================================================================
struct DBACCESS_DLLPRIVATE SubComponentLoader_Data
{
const Reference< XCommandProcessor > xDocDefCommands;
const Reference< XComponent > xNonDocComponent;
Reference< XWindow > xAppComponentWindow;
SubComponentLoader_Data( const Reference< XCommandProcessor >& i_rDocumentDefinition )
:xDocDefCommands( i_rDocumentDefinition, UNO_SET_THROW )
,xNonDocComponent()
{
}
SubComponentLoader_Data( const Reference< XComponent >& i_rNonDocumentComponent )
:xDocDefCommands()
,xNonDocComponent( i_rNonDocumentComponent, UNO_SET_THROW )
{
}
};
//====================================================================
//= helper
//====================================================================
namespace
{
//................................................................
void lcl_onWindowShown_nothrow( const SubComponentLoader_Data& i_rData )
{
try
{
if ( i_rData.xDocDefCommands.is() )
{
Command aCommandOpen;
aCommandOpen.Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "show" ) );
const sal_Int32 nCommandIdentifier = i_rData.xDocDefCommands->createCommandIdentifier();
i_rData.xDocDefCommands->execute( aCommandOpen, nCommandIdentifier, NULL );
}
else
{
const Reference< XController > xController( i_rData.xNonDocComponent, UNO_QUERY_THROW );
const Reference< XFrame > xFrame( xController->getFrame(), UNO_SET_THROW );
const Reference< XWindow > xWindow( xFrame->getContainerWindow(), UNO_SET_THROW );
xWindow->setVisible( sal_True );
}
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
}
//====================================================================
//= SubComponentLoader
//====================================================================
//--------------------------------------------------------------------
SubComponentLoader::SubComponentLoader( const Reference< XController >& i_rApplicationController,
const Reference< XCommandProcessor >& i_rSubDocumentDefinition )
:m_pData( new SubComponentLoader_Data( i_rSubDocumentDefinition ) )
{
// add as window listener to the controller's container window, so we get notified when it is shown
Reference< XController2 > xController( i_rApplicationController, UNO_QUERY_THROW );
m_pData->xAppComponentWindow.set( xController->getComponentWindow(), UNO_SET_THROW );
osl_incrementInterlockedCount( &m_refCount );
{
m_pData->xAppComponentWindow->addWindowListener( this );
}
osl_decrementInterlockedCount( &m_refCount );
}
//--------------------------------------------------------------------
SubComponentLoader::SubComponentLoader( const Reference< XController >& i_rApplicationController,
const Reference< XComponent >& i_rNonDocumentComponent )
:m_pData( new SubComponentLoader_Data( i_rNonDocumentComponent ) )
{
// add as window listener to the controller's container window, so we get notified when it is shown
Reference< XController2 > xController( i_rApplicationController, UNO_QUERY_THROW );
m_pData->xAppComponentWindow.set( xController->getComponentWindow(), UNO_SET_THROW );
osl_incrementInterlockedCount( &m_refCount );
{
m_pData->xAppComponentWindow->addWindowListener( this );
}
osl_decrementInterlockedCount( &m_refCount );
}
//--------------------------------------------------------------------
SubComponentLoader::~SubComponentLoader()
{
delete m_pData, m_pData = NULL;
}
//--------------------------------------------------------------------
void SAL_CALL SubComponentLoader::windowResized( const WindowEvent& i_rEvent ) throw (RuntimeException)
{
// not interested in
(void)i_rEvent;
}
//--------------------------------------------------------------------
void SAL_CALL SubComponentLoader::windowMoved( const WindowEvent& i_rEvent ) throw (RuntimeException)
{
// not interested in
(void)i_rEvent;
}
//--------------------------------------------------------------------
void SAL_CALL SubComponentLoader::windowShown( const EventObject& i_rEvent ) throw (RuntimeException)
{
(void)i_rEvent;
lcl_onWindowShown_nothrow( *m_pData );
m_pData->xAppComponentWindow->removeWindowListener( this );
}
//--------------------------------------------------------------------
void SAL_CALL SubComponentLoader::windowHidden( const EventObject& i_rEvent ) throw (RuntimeException)
{
// not interested in
(void)i_rEvent;
}
//--------------------------------------------------------------------
void SAL_CALL SubComponentLoader::disposing( const EventObject& i_rEvent ) throw (RuntimeException)
{
// not interested in
(void)i_rEvent;
}
//........................................................................
} // namespace dbaccess
//........................................................................
| 40.39196 | 108 | 0.528738 | Grosskopf |
0bffc3dc70fd8e9de9cccdb7f0c8eb6b65cae632 | 579 | cpp | C++ | demos/exchange_manager_clean.cpp | MaximilienNaveau/shared_memory | 1440454759cdd19e0d898753d86b8714c1aefa84 | [
"BSD-3-Clause"
] | 2 | 2020-09-08T04:01:02.000Z | 2021-01-28T15:02:11.000Z | demos/exchange_manager_clean.cpp | MaximilienNaveau/shared_memory | 1440454759cdd19e0d898753d86b8714c1aefa84 | [
"BSD-3-Clause"
] | 13 | 2019-09-24T17:21:49.000Z | 2021-03-02T10:09:03.000Z | demos/exchange_manager_clean.cpp | MaximilienNaveau/shared_memory | 1440454759cdd19e0d898753d86b8714c1aefa84 | [
"BSD-3-Clause"
] | 2 | 2019-05-06T08:25:35.000Z | 2020-04-14T11:49:02.000Z | #include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <iostream>
#include "shared_memory/demos/four_int_values.hpp"
#include "shared_memory/exchange_manager_producer.hpp"
#define SEGMENT_ID "exchange_demo_segment"
#define QUEUE_SIZE 2000
int main()
{
shared_memory::Exchange_manager_producer<
shared_memory::Four_int_values,
QUEUE_SIZE>::clean_mutex(std::string(SEGMENT_ID));
shared_memory::Exchange_manager_producer<
shared_memory::Four_int_values,
QUEUE_SIZE>::clean_memory(std::string(SEGMENT_ID));
}
| 27.571429 | 59 | 0.75475 | MaximilienNaveau |
0403c640059b4859021c1f971e08408d502920e4 | 6,216 | cc | C++ | third_party/blink/renderer/bindings/tests/results/core/element_sequence_or_byte_string_double_or_string_record.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | third_party/blink/renderer/bindings/tests/results/core/element_sequence_or_byte_string_double_or_string_record.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | third_party/blink/renderer/bindings/tests/results/core/element_sequence_or_byte_string_double_or_string_record.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/union_container.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/tests/results/core/element_sequence_or_byte_string_double_or_string_record.h"
#include "base/stl_util.h"
#include "third_party/blink/renderer/bindings/core/v8/double_or_string.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/script_iterator.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_element.h"
#include "third_party/blink/renderer/core/css/cssom/element_computed_style_map.h"
#include "third_party/blink/renderer/core/dom/child_node.h"
#include "third_party/blink/renderer/core/dom/non_document_type_child_node.h"
#include "third_party/blink/renderer/core/dom/parent_node.h"
#include "third_party/blink/renderer/core/fullscreen/element_fullscreen.h"
namespace blink {
ElementSequenceOrByteStringDoubleOrStringRecord::ElementSequenceOrByteStringDoubleOrStringRecord() : type_(SpecificType::kNone) {}
const HeapVector<std::pair<String, DoubleOrString>>& ElementSequenceOrByteStringDoubleOrStringRecord::GetAsByteStringDoubleOrStringRecord() const {
DCHECK(IsByteStringDoubleOrStringRecord());
return byte_string_double_or_string_record_;
}
void ElementSequenceOrByteStringDoubleOrStringRecord::SetByteStringDoubleOrStringRecord(const HeapVector<std::pair<String, DoubleOrString>>& value) {
DCHECK(IsNull());
byte_string_double_or_string_record_ = value;
type_ = SpecificType::kByteStringDoubleOrStringRecord;
}
ElementSequenceOrByteStringDoubleOrStringRecord ElementSequenceOrByteStringDoubleOrStringRecord::FromByteStringDoubleOrStringRecord(const HeapVector<std::pair<String, DoubleOrString>>& value) {
ElementSequenceOrByteStringDoubleOrStringRecord container;
container.SetByteStringDoubleOrStringRecord(value);
return container;
}
const HeapVector<Member<Element>>& ElementSequenceOrByteStringDoubleOrStringRecord::GetAsElementSequence() const {
DCHECK(IsElementSequence());
return element_sequence_;
}
void ElementSequenceOrByteStringDoubleOrStringRecord::SetElementSequence(const HeapVector<Member<Element>>& value) {
DCHECK(IsNull());
element_sequence_ = value;
type_ = SpecificType::kElementSequence;
}
ElementSequenceOrByteStringDoubleOrStringRecord ElementSequenceOrByteStringDoubleOrStringRecord::FromElementSequence(const HeapVector<Member<Element>>& value) {
ElementSequenceOrByteStringDoubleOrStringRecord container;
container.SetElementSequence(value);
return container;
}
ElementSequenceOrByteStringDoubleOrStringRecord::ElementSequenceOrByteStringDoubleOrStringRecord(const ElementSequenceOrByteStringDoubleOrStringRecord&) = default;
ElementSequenceOrByteStringDoubleOrStringRecord::~ElementSequenceOrByteStringDoubleOrStringRecord() = default;
ElementSequenceOrByteStringDoubleOrStringRecord& ElementSequenceOrByteStringDoubleOrStringRecord::operator=(const ElementSequenceOrByteStringDoubleOrStringRecord&) = default;
void ElementSequenceOrByteStringDoubleOrStringRecord::Trace(Visitor* visitor) const {
visitor->Trace(byte_string_double_or_string_record_);
visitor->Trace(element_sequence_);
}
void V8ElementSequenceOrByteStringDoubleOrStringRecord::ToImpl(
v8::Isolate* isolate,
v8::Local<v8::Value> v8_value,
ElementSequenceOrByteStringDoubleOrStringRecord& impl,
UnionTypeConversionMode conversion_mode,
ExceptionState& exception_state) {
if (v8_value.IsEmpty())
return;
if (conversion_mode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8_value))
return;
if (v8_value->IsObject()) {
ScriptIterator script_iterator = ScriptIterator::FromIterable(
isolate, v8_value.As<v8::Object>(), exception_state);
if (exception_state.HadException())
return;
if (!script_iterator.IsNull()) {
HeapVector<Member<Element>> cpp_value{ NativeValueTraits<IDLSequence<Element>>::NativeValue(isolate, std::move(script_iterator), exception_state) };
if (exception_state.HadException())
return;
impl.SetElementSequence(cpp_value);
return;
}
}
if (v8_value->IsObject()) {
HeapVector<std::pair<String, DoubleOrString>> cpp_value{ NativeValueTraits<IDLRecord<IDLByteString, DoubleOrString>>::NativeValue(isolate, v8_value, exception_state) };
if (exception_state.HadException())
return;
impl.SetByteStringDoubleOrStringRecord(cpp_value);
return;
}
exception_state.ThrowTypeError("The provided value is not of type '(sequence<Element> or record<ByteString, (double or DOMString)>)'");
}
v8::Local<v8::Value> ToV8(const ElementSequenceOrByteStringDoubleOrStringRecord& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
switch (impl.type_) {
case ElementSequenceOrByteStringDoubleOrStringRecord::SpecificType::kNone:
return v8::Null(isolate);
case ElementSequenceOrByteStringDoubleOrStringRecord::SpecificType::kByteStringDoubleOrStringRecord:
return ToV8(impl.GetAsByteStringDoubleOrStringRecord(), creationContext, isolate);
case ElementSequenceOrByteStringDoubleOrStringRecord::SpecificType::kElementSequence:
return ToV8(impl.GetAsElementSequence(), creationContext, isolate);
default:
NOTREACHED();
}
return v8::Local<v8::Value>();
}
ElementSequenceOrByteStringDoubleOrStringRecord NativeValueTraits<ElementSequenceOrByteStringDoubleOrStringRecord>::NativeValue(
v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
ElementSequenceOrByteStringDoubleOrStringRecord impl;
V8ElementSequenceOrByteStringDoubleOrStringRecord::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exception_state);
return impl;
}
} // namespace blink
| 46.736842 | 193 | 0.813385 | mghgroup |
0404cb6280df53ce68fcbb7349b9781d68959ed2 | 2,258 | cpp | C++ | Unix/UnixDirectoryReader.cpp | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | Unix/UnixDirectoryReader.cpp | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | Unix/UnixDirectoryReader.cpp | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | // Copyright 2000-2021 Mark H. P. Lord
#include "UnixDirectoryReader.h"
#include "../Path.h"
#include "UnixCloseOnExec.h"
#include <errno.h>
namespace Prime {
UnixDirectoryReader::UnixDirectoryReader()
{
_dir = NULL;
_ent = NULL;
_preventInherit = false;
}
UnixDirectoryReader::~UnixDirectoryReader()
{
close();
}
bool UnixDirectoryReader::open(const char* path, Log* log, const Options& options)
{
if (Path::hasTrailingSlashes(path)) {
return open(Path::stripTrailingSlashes(path).c_str(), log, options);
}
if (!path || !*path) {
path = ".";
}
close();
_preventInherit = !options.getChildProcessInherit();
if (_preventInherit) {
UnixCloseOnExec::lock();
}
for (;;) {
_dir = opendir(path);
if (_dir) {
#ifdef PRIME_DIRENT_MISSING_D_TYPE
_path = path;
#endif
return true;
}
if (errno != EINTR) {
if (_preventInherit) {
UnixCloseOnExec::unlock();
}
log->logErrno(errno);
return false;
}
}
}
void UnixDirectoryReader::close()
{
if (_dir) {
closedir(_dir);
_dir = NULL;
if (_preventInherit) {
UnixCloseOnExec::unlock();
}
}
_ent = NULL;
}
bool UnixDirectoryReader::read(Log*, bool* error)
{
if (error) {
*error = false;
}
if (!_dir) {
return false;
}
for (;;) {
_ent = readdir(_dir);
if (_ent) {
return true;
}
if (errno == EINTR) {
continue;
}
close();
return false;
}
}
#ifdef PRIME_DIRENT_MISSING_D_TYPE
struct stat* UnixDirectoryReader::needStat() const
{
PRIME_ASSERT(_ent);
PRIME_ASSERT(!_path.empty());
if (_stat.get()) {
return _stat.get();
}
_stat.reset(new struct stat);
char buffer[PRIME_BIG_STACK_BUFFER_SIZE];
if (StringCopy(buffer, sizeof(buffer), _path)) {
Path::joinInPlace(buffer, sizeof(buffer), _ent->d_name);
if (::stat(buffer, _stat.get()) == 0) {
return _stat.get();
}
}
memset(_stat.get(), 0, sizeof(struct stat));
return _stat.get();
}
#endif
}
| 18.209677 | 82 | 0.54783 | malord |
0405eeac55d49dc3fb9f801220a850c5c48fcb26 | 1,201 | cpp | C++ | lib/src/io/Stream.cpp | tuanphuc/Viry3D | 8f6e141f222ce01372ffd2183a4d39e7a076aad2 | [
"Apache-2.0"
] | null | null | null | lib/src/io/Stream.cpp | tuanphuc/Viry3D | 8f6e141f222ce01372ffd2183a4d39e7a076aad2 | [
"Apache-2.0"
] | null | null | null | lib/src/io/Stream.cpp | tuanphuc/Viry3D | 8f6e141f222ce01372ffd2183a4d39e7a076aad2 | [
"Apache-2.0"
] | 1 | 2020-09-04T07:38:32.000Z | 2020-09-04T07:38:32.000Z | /*
* Viry3D
* Copyright 2014-2019 by Stack - stackos@qq.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Stream.h"
namespace Viry3D
{
Stream::Stream():
m_position(0),
m_closed(false),
m_length(0)
{
}
void Stream::Close()
{
m_closed = true;
}
int Stream::Read(void* buffer, int size)
{
int read;
if (m_position + size <= m_length)
{
read = size;
}
else
{
read = m_length - m_position;
}
m_position += read;
return read;
}
int Stream::Write(void* buffer, int size)
{
int write;
if (m_position + size <= m_length)
{
write = size;
}
else
{
write = m_length - m_position;
}
m_position += write;
return write;
}
}
| 17.157143 | 74 | 0.668609 | tuanphuc |
040700cc399337a7b35ef964523fd9bd98b6c7a1 | 1,469 | hpp | C++ | lib/aoc2021/include/aoc2021/day3/part2.hpp | bencodestx/aoc-2021-cpp | 41518858a6ec4af65754d0170f4d6bfbe4d9548d | [
"MIT"
] | null | null | null | lib/aoc2021/include/aoc2021/day3/part2.hpp | bencodestx/aoc-2021-cpp | 41518858a6ec4af65754d0170f4d6bfbe4d9548d | [
"MIT"
] | null | null | null | lib/aoc2021/include/aoc2021/day3/part2.hpp | bencodestx/aoc-2021-cpp | 41518858a6ec4af65754d0170f4d6bfbe4d9548d | [
"MIT"
] | null | null | null | #pragma once
#include "aoc2021/day3/operators.hpp"
#include "aoc2021/read_vector.hpp"
#include <array>
#include <bitset>
#include <cstddef>
#include <functional>
#include <istream>
namespace aoc2021::day3 {
template <std::size_t bit_count>
auto count_bits_in_position(const std::size_t bit, const auto &reports) {
std::size_t count{};
for (const auto &report : reports) {
if (report[bit]) {
++count;
}
}
return count;
}
template <std::size_t bit_count, typename Comparison> auto rating(auto values) {
Comparison comparison{};
for (std::size_t bit = 0; bit < bit_count; ++bit) {
if (std::size(values) == 1) {
break;
}
const auto count =
count_bits_in_position<bit_count>(bit_count - bit - 1, values);
bool value_to_erase;
if (comparison(count, std::size(values) - count)) {
value_to_erase = false;
} else {
value_to_erase = true;
}
std::erase_if(values, [&](const auto &x) {
return x[bit_count - bit - 1] == value_to_erase;
});
}
return values[0].to_ulong();
}
template <std::size_t bit_count> auto part2(auto &in) {
const auto reports = read_vector<std::bitset<bit_count>>(in);
const auto oxygen_generator_rating =
rating<bit_count, std::greater_equal<std::size_t>>(reports);
const auto co2_scrubber_rating =
rating<bit_count, std::less<std::size_t>>(reports);
return oxygen_generator_rating * co2_scrubber_rating;
}
} // namespace aoc2021::day3 | 27.203704 | 80 | 0.671205 | bencodestx |
040942e8a5f9792ace3579338f93c58f580a870a | 842 | cpp | C++ | to edit/menu/title.cpp | wengxxaa/Ninja | a7e11b6db16fd614234c4a282411bd80cbfb5ad3 | [
"Apache-2.0"
] | 1 | 2019-10-23T04:39:51.000Z | 2019-10-23T04:39:51.000Z | to edit/menu/title.cpp | wengxxaa/Ninja | a7e11b6db16fd614234c4a282411bd80cbfb5ad3 | [
"Apache-2.0"
] | null | null | null | to edit/menu/title.cpp | wengxxaa/Ninja | a7e11b6db16fd614234c4a282411bd80cbfb5ad3 | [
"Apache-2.0"
] | 1 | 2019-10-23T04:39:52.000Z | 2019-10-23T04:39:52.000Z | #include "title.h"
#include <stdlib.h>
Title::Title()
{
// empty
}
Title::~Title()
{
belt.free();
title.free();
}
void Title::load( const int& screen_w )
{
belt.setName( "title-belt" );
belt.load( "data/sprites/menu/belt.png" );
belt.setPosition( screen_w/2 - belt.getWidth()/2, 10 );
title.setName( "title-title" );
title.setFont( "data/fonts/BADABB__.TTF", 110, 0x7F, 0x99, 0x95 );
title.setText( "Ninja" );
title.setPosition( screen_w/2 - title.getWidth()/2, -8 );
}
void Title::draw( sf::RenderWindow &window )
{
window.draw( belt.get() );
window.draw( title.get() );
}
const int& Title::getBot()
{
return belt.getBot();
}
void Title::fadein( int i, int max )
{
belt.fadein( i, max );
title.fadein( i, max );
}
void Title::fadeout( int i, int min )
{
belt.fadeout( i, min );
title.fadeout( i, min );
}
| 16.84 | 67 | 0.625891 | wengxxaa |
040ba98d9766871e116a3362d484b066a11fd83d | 282 | cpp | C++ | Basic-Programming/Recursion/variable 2.cpp | arifparvez14/Basic-and-competetive-programming | 4cb9ee7fbed3c70307d0f63499fcede86ed3c732 | [
"MIT"
] | null | null | null | Basic-Programming/Recursion/variable 2.cpp | arifparvez14/Basic-and-competetive-programming | 4cb9ee7fbed3c70307d0f63499fcede86ed3c732 | [
"MIT"
] | null | null | null | Basic-Programming/Recursion/variable 2.cpp | arifparvez14/Basic-and-competetive-programming | 4cb9ee7fbed3c70307d0f63499fcede86ed3c732 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int x=1;
void myfunc(int y)
{
y = y * 2;
x = x + 10;
printf("Value inside myfunc,x:%d and y:%d\n",x,y);
}
int main()
{
int y=5;
x=10;
myfunc(y);
printf("Value inside main,x:%d and y:%d",x,y);
return 0;
}
| 14.842105 | 54 | 0.535461 | arifparvez14 |
040f916f455594c396309ad8c777580543648548 | 8,934 | cpp | C++ | src/apps/network/main.cpp | inviwo/sgct | 1b81860af3d8493526fe03343cfc49218830c9ef | [
"libpng-2.0"
] | null | null | null | src/apps/network/main.cpp | inviwo/sgct | 1b81860af3d8493526fe03343cfc49218830c9ef | [
"libpng-2.0"
] | null | null | null | src/apps/network/main.cpp | inviwo/sgct | 1b81860af3d8493526fe03343cfc49218830c9ef | [
"libpng-2.0"
] | null | null | null | /*****************************************************************************************
* SGCT *
* Simple Graphics Cluster Toolkit *
* *
* Copyright (c) 2012-2020 *
* For conditions of distribution and use, see copyright notice in LICENSE.md *
****************************************************************************************/
#include <sgct/sgct.h>
#include <sgct/opengl.h>
#include <sgct/utils/box.h>
#include <fmt/format.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace {
std::unique_ptr<std::thread> connectionThread;
std::atomic_bool connected = false;
std::atomic_bool running = true;
unsigned int textureId = 0;
std::unique_ptr<sgct::utils::Box> box;
GLint matrixLoc = -1;
double currentTime(0.0);
int port;
std::string address;
bool isServer = false;
std::unique_ptr<sgct::Network> networkPtr;
std::pair<double, int> timerData;
constexpr const char* vertexShader = R"(
#version 330 core
layout(location = 0) in vec2 texCoords;
layout(location = 1) in vec3 normals;
layout(location = 2) in vec3 vertPositions;
uniform mat4 mvp;
out vec2 uv;
void main() {
gl_Position = mvp * vec4(vertPositions, 1.0);
uv = texCoords;
})";
constexpr const char* fragmentShader = R"(
#version 330 core
uniform sampler2D tex;
in vec2 uv;
out vec4 color;
void main() { color = texture(tex, uv); }
)";
} // namespace
using namespace sgct;
void networkConnectionUpdated(Network* conn) {
if (conn->isServer()) {
// wake up the connection handler thread on server if node disconnects to enable
// reconnection
conn->startConnectionConditionVar().notify_all();
}
connected = conn->isConnected();
Log::Info(fmt::format(
"Network is {}", conn->isConnected() ? "connected" : "disconneced"
));
}
void networkAck(int packageId, int) {
Log::Info(fmt::format("Network package {} is received", packageId));
if (timerData.second == packageId) {
Log::Info(fmt::format(
"Loop time: {} ms", (Engine::getTime() - timerData.first) * 1000.0
));
}
}
void networkDecode(void* receivedData, int receivedLength, int packageId, int) {
Log::Info(fmt::format("Network decoding package {}", packageId));
std::string test(reinterpret_cast<char*>(receivedData), receivedLength);
Log::Info(fmt::format("Message: \"{}\"", test));
}
void connect() {
if (!Engine::instance().isMaster()) {
return;
}
// no need to specify the address on the host/server
if (!isServer && address.empty()) {
Log::Error("Network error: No address set");
return;
}
networkPtr = std::make_unique<Network>(
port,
address,
isServer,
Network::ConnectionType::DataTransfer
);
// init
try {
Log::Debug(fmt::format("Initiating network connection at port {}", port));
networkPtr->setUpdateFunction(networkConnectionUpdated);
networkPtr->setPackageDecodeFunction(networkDecode);
networkPtr->setAcknowledgeFunction(networkAck);
networkPtr->initialize();
}
catch (const std::runtime_error& err) {
Log::Error(fmt::format("Network error: {}", err.what()));
networkPtr->initShutdown();
std::this_thread::sleep_for(std::chrono::seconds(1));
networkPtr->closeNetwork(true);
return;
}
connected = true;
}
void networkLoop() {
connect();
// if client try to connect to server even after disconnection
if (!isServer) {
while (running.load()) {
if (connected.load() == false) {
connect();
}
else {
// just check if connected once per second
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
}
void disconnect() {
if (networkPtr) {
networkPtr->initShutdown();
// wait for all nodes callbacks to run
std::this_thread::sleep_for(std::chrono::milliseconds(250));
// wait for threads to die
networkPtr->closeNetwork(false);
networkPtr = nullptr;
}
}
void sendData(const void* data, int length, int id) {
if (networkPtr) {
NetworkManager::instance().transferData(data, length, id, *networkPtr);
timerData.first = Engine::getTime();
timerData.second = id;
}
}
void sendTestMessage() {
std::string test = "What's up?";
static int counter = 0;
sendData(test.data(), static_cast<int>(test.size()), counter);
counter++;
}
void draw(const RenderData& data) {
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
constexpr const double Speed = 0.44;
//create scene transform (animation)
glm::mat4 scene = glm::translate(glm::mat4(1.f), glm::vec3(0.f, 0.f, -3.f));
scene = glm::rotate(
scene,
static_cast<float>(currentTime * Speed),
glm::vec3(0.f, -1.f, 0.f)
);
scene = glm::rotate(
scene,
static_cast<float>(currentTime * (Speed / 2.0)),
glm::vec3(1.f, 0.f, 0.f)
);
const glm::mat4 mvp = glm::make_mat4(data.modelViewProjectionMatrix.values) * scene;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId);
ShaderManager::instance().shaderProgram("xform").bind();
glUniformMatrix4fv(matrixLoc, 1, GL_FALSE, glm::value_ptr(mvp));
box->draw();
ShaderManager::instance().shaderProgram("xform").unbind();
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
}
void preSync() {
if (Engine::instance().isMaster()) {
currentTime = Engine::getTime();
}
}
void initOGL(GLFWwindow*) {
textureId = TextureManager::instance().loadTexture("box.png", true, 8.f);
box = std::make_unique<utils::Box>(2.f, utils::Box::TextureMappingMode::Regular);
// Set up backface culling
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
ShaderManager::instance().addShaderProgram(
"xform",
vertexShader,
fragmentShader
);
const ShaderProgram& prg = ShaderManager::instance().shaderProgram("xform");
prg.bind();
matrixLoc = glGetUniformLocation(prg.id(), "mvp");
glUniform1i(glGetUniformLocation(prg.id(), "tex"), 0 );
prg.unbind();
for (const std::unique_ptr<Window>& win : Engine::instance().windows()) {
win->setWindowTitle(isServer ? "SERVER" : "CLIENT");
}
}
std::vector<std::byte> encode() {
std::vector<std::byte> data;
serializeObject(data, currentTime);
return data;
}
void decode(const std::vector<std::byte>& data, unsigned int pos) {
deserializeObject(data, pos, currentTime);
}
void cleanup() {
box = nullptr;
running = false;
if (connectionThread) {
if (networkPtr) {
networkPtr->initShutdown();
}
connectionThread->join();
connectionThread = nullptr;
}
disconnect();
}
void keyboard(Key key, Modifier, Action action, int) {
if (Engine::instance().isMaster() && action == Action::Press) {
if (key == Key::Esc) {
Engine::instance().terminate();
}
else if (key == Key::Space) {
sendTestMessage();
}
}
}
int main(int argc, char** argv) {
std::vector<std::string> arg(argv + 1, argv + argc);
Configuration config = parseArguments(arg);
config::Cluster cluster = loadCluster(config.configFilename);
for (int i = 0; i < argc; i++) {
std::string_view v(argv[i]);
if (v == "-port" && argc > (i + 1)) {
port = std::stoi(argv[i + 1]);
Log::Info(fmt::format("Setting port to: {}", port));
}
else if (v == "-address" && argc > (i + 1)) {
address = argv[i + 1];
Log::Info(fmt::format("Setting address to: {}", address));
}
else if (v == "--server") {
isServer = true;
Log::Info("This computer will host the connection");
}
}
Engine::Callbacks callbacks;
callbacks.initOpenGL = initOGL;
callbacks.preSync = preSync;
callbacks.encode = encode;
callbacks.decode = decode;
callbacks.draw = draw;
callbacks.cleanup = cleanup;
callbacks.keyboard = keyboard;
try {
Engine::create(cluster, callbacks, config);
}
catch (const std::runtime_error& e) {
Log::Error(e.what());
Engine::destroy();
return EXIT_FAILURE;
}
connectionThread = std::make_unique<std::thread>(networkLoop);
Engine::instance().render();
Engine::destroy();
exit(EXIT_SUCCESS);
}
| 27.831776 | 90 | 0.573763 | inviwo |
040ff9a27996e5b157c1e640a86a2a797cf7a4e4 | 344 | cpp | C++ | Framework/mainmenu.cpp | huangdgm/lost-in-zombies | 56c62510436fe8a64a83772829240523dbb5abee | [
"Apache-2.0"
] | null | null | null | Framework/mainmenu.cpp | huangdgm/lost-in-zombies | 56c62510436fe8a64a83772829240523dbb5abee | [
"Apache-2.0"
] | 1 | 2017-11-17T23:56:47.000Z | 2017-11-17T23:56:47.000Z | Framework/mainmenu.cpp | huangdgm/lost-in-zombies | 56c62510436fe8a64a83772829240523dbb5abee | [
"Apache-2.0"
] | null | null | null | // This include:
#include "mainmenu.h"
// Local includes:
// Library includes:
MainMenu::MainMenu()
: Entity()
{
}
MainMenu::~MainMenu()
{
}
void
MainMenu::Initialise(Sprite* sprite)
{
Entity::Initialise(sprite);
m_dead = false;
this->SetPosition(0, 0);
}
void
MainMenu::SetSprite(Sprite* sprite)
{
Entity::Initialise(sprite);
}
| 9.828571 | 36 | 0.674419 | huangdgm |
04119933a8ffff68b1ebbbfee2b0c6812d42b967 | 24,325 | cc | C++ | crv/crvQuality.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 138 | 2015-01-05T15:50:20.000Z | 2022-02-25T01:09:58.000Z | crv/crvQuality.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 337 | 2015-08-07T18:24:58.000Z | 2022-03-31T14:39:03.000Z | crv/crvQuality.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 70 | 2015-01-17T00:58:41.000Z | 2022-02-13T04:58:20.000Z | /*
* Copyright 2015 Scientific Computation Research Center
*
* This work is open source software, licensed under the terms of the
* BSD license as described in the LICENSE file in the top-level directory.
*/
#include "crv.h"
#include "crvBezier.h"
#include "crvBezierShapes.h"
#include "crvMath.h"
#include "crvTables.h"
#include "crvQuality.h"
namespace crv {
static int maxAdaptiveIter = 5;
static int maxElevationLevel = 19;
static double minAcceptable = 0.0;
static double convergenceTolerance = 0.01;
class Quality2D : public Quality
{
public:
Quality2D(apf::Mesh* m, int algorithm) : Quality(m,algorithm)
{
blendingOrder = getBlendingOrder(apf::Mesh::TRIANGLE);
if ( blendingOrder > 0 &&
getNumInternalControlPoints(apf::Mesh::TRIANGLE,order)){
getInternalBezierTransformationCoefficients(mesh,order,
blendingOrder,apf::Mesh::TRIANGLE,blendingCoeffs);
}
n = getNumControlPoints(apf::Mesh::TRIANGLE,2*(order-1));
if (algorithm == 0 || algorithm == 2){
for (int d = 1; d <= 2; ++d)
getBezierJacobianDetSubdivisionCoefficients(
2*(order-1),apf::Mesh::simplexTypes[d],subdivisionCoeffs[d]);
}
};
virtual ~Quality2D() {};
double getQuality(apf::MeshEntity* e);
int checkValidity(apf::MeshEntity* e);
int blendingOrder;
int n;
apf::NewArray<double> blendingCoeffs;
apf::NewArray<double> subdivisionCoeffs[3];
};
class Quality3D : public Quality
{
public:
Quality3D(apf::Mesh* m, int algorithm) : Quality(m,algorithm)
{
if (algorithm == 0 || algorithm == 2){
for (int d = 1; d <= 3; ++d)
getBezierJacobianDetSubdivisionCoefficients(
3*(order-1),apf::Mesh::simplexTypes[d],subdivisionCoeffs[d]);
}
n = getNumControlPoints(apf::Mesh::TET,3*(order-1));
xi.allocate(n);
transformationMatrix.resize(n,n);
mth::Matrix<double> A(n,n);
collectNodeXi(apf::Mesh::TET,apf::Mesh::TET,3*(order-1),
elem_vert_xi[apf::Mesh::TET],xi);
getBezierTransformationMatrix(apf::Mesh::TET,3*(order-1),A,
elem_vert_xi[apf::Mesh::TET]);
invertMatrixWithPLU(n,A,transformationMatrix);
}
virtual ~Quality3D() {};
double getQuality(apf::MeshEntity* e);
int checkValidity(apf::MeshEntity* e);
// 3D uses an alternate method of computing these
// returns a validity tag so both quality and validity can
// quit early if this function thinks they should
// if validity = true, quit if its obvious the element is invalid
int computeJacDetNodes(apf::MeshEntity* e,
apf::NewArray<double>& nodes, bool validity);
int n;
apf::NewArray<double> subdivisionCoeffs[4];
apf::NewArray<apf::Vector3> xi;
mth::Matrix<double> transformationMatrix;
};
Quality* makeQuality(apf::Mesh* m, int algorithm)
{
if (m->getDimension() == 2)
return new Quality2D(m,algorithm);
else if (m->getDimension() == 3)
return new Quality3D(m,algorithm);
return 0;
}
/* Set up quality object, computing matrices that are used frequently */
Quality::Quality(apf::Mesh* m, int algorithm_) :
mesh(m), algorithm(algorithm_)
{
PCU_ALWAYS_ASSERT(algorithm >= 0 && algorithm <= 2);
order = mesh->getShape()->getOrder();
PCU_ALWAYS_ASSERT(order >= 1);
};
/* This work is based on the approach of Geometric Validity of high-order
* lagrange finite elements, theory and practical guidance,
* by George, Borouchaki, and Barral. (2014)
*
* The notation follows theirs, almost exactly.
*/
static double getTriPartialJacobianDet(apf::NewArray<apf::Vector3>& nodes,
int P, int i1, int j1, int i2, int j2)
{
int p00 = getTriNodeIndex(P,i1+1,j1);
int p01 = getTriNodeIndex(P,i1,j1+1);
int p10 = getTriNodeIndex(P,i2+1,j2);
int p11 = getTriNodeIndex(P,i2,j2);
return apf::cross(nodes[p01]-nodes[p00],
nodes[p11]-nodes[p10])[2];
}
static double getTetPartialJacobianDet(apf::NewArray<apf::Vector3>& nodes,
int P, int i1, int j1, int k1, int i2, int j2, int k2,
int i3, int j3, int k3)
{
int p00 = getTetNodeIndex(P,i1+1,j1,k1);
int p01 = getTetNodeIndex(P,i1,j1+1,k1);
int p10 = getTetNodeIndex(P,i2+1,j2,k2);
int p11 = getTetNodeIndex(P,i2,j2,k2+1);
int p20 = getTetNodeIndex(P,i3+1,j3,k3);
int p21 = getTetNodeIndex(P,i3,j3,k3);
return apf::cross(nodes[p01]-nodes[p00],nodes[p11]-nodes[p10])
*(nodes[p21]-nodes[p20]);
}
/* These two functions are in George, Borouchaki, and Barral. (2014)
*
* The math is not fun, and they are for loop madness. They exist
* because it was the first implementation, I have since switched
* to a different approach to computing jacobian determinant
* control points
*
* the 2D one exists, because the other approach does not quite work for
* 2D planar meshes.
*
*/
static double Nijk(apf::NewArray<apf::Vector3>& nodes,
int d, int I, int J)
{
double sum = 0.;
int CD = trinomial(2*(d-1),I,J);
for(int j1 = 0; j1 <= J; ++j1){
int i1start = std::max(0,I+J-j1-(d-1));
int i1end = std::min(I,d-1-j1);
for(int i1 = i1start; i1 <= i1end; ++i1){
sum += trinomial(d-1,i1,j1)*trinomial(d-1,I-i1,J-j1)
*getTriPartialJacobianDet(nodes,d,i1,j1,I-i1,J-j1);
}
}
return sum*d*d/CD;
}
static double Nijkl(apf::NewArray<apf::Vector3>& nodes,
int d, int I, int J, int K)
{
double sum = 0.;
int CD = quadnomial(3*(d-1),I,J,K);
for(int k1 = 0; k1 <= K; ++k1){
int k2start = std::max(0,K-k1-(d-1));
for (int k2 = k2start; k2 <= K-k1; ++k2){
for (int j1 = 0; j1 <= J; ++j1){
int j2start = std::max(0,J-j1-(d-1));
for (int j2 = j2start; j2 <= J-j1; ++j2){
int i1end = std::min(I,d-1-j1-k1);
for (int i1 = 0; i1 <= i1end; ++i1){
int i2start = std::max(0,I+J+K-i1-j1-k1-j2-k2-(d-1));
int i2end = std::min(I-i1,d-1-j2-k2);
for (int i2 = i2start; i2 <= i2end; ++i2){
int i3 = I-i1-i2;
int j3 = J-j1-j2;
int k3 = K-k1-k2;
sum += quadnomial(d-1,i1,j1,k1)*quadnomial(d-1,i2,j2,k2)
*quadnomial(d-1,i3,j3,k3)
*getTetPartialJacobianDet(nodes,d,i1,j1,k1,i2,j2,k2,i3,j3,k3);
}
}
}
}
}
}
return sum*d*d*d/CD;
}
static double calcMinJacDet(int n, apf::NewArray<double>& nodes)
{
double minJ = 1e10;
for (int i = 0; i < n; ++i)
minJ = std::min(minJ,nodes[i]);
return minJ;
}
static double calcMaxJacDet(int n, apf::NewArray<double>& nodes)
{
double maxJ = -1e10;
for (int i = 0; i < n; ++i)
maxJ = std::max(maxJ,nodes[i]);
return maxJ;
}
/* nodes is (2(P-1)+1)(2(P-1)+2)/2 = P(2P-1)
* except for P = 1, which has size 3 due to numbering convention used,
* such that i=j=k=0 results in index 2
*
* these are not actively used, other than to debug and double check other
* algorithms. The cost of compute Nijkl is significant (and the for loops
* are ugly), so for now, lets compute things using Remacle's approach.
*/
static void getTriJacDetNodes(int P, apf::NewArray<apf::Vector3>& elemNodes,
apf::NewArray<double>& nodes)
{
for (int I = 0; I <= 2*(P-1); ++I)
for (int J = 0; J <= 2*(P-1)-I; ++J)
nodes[getTriNodeIndex(2*(P-1),I,J)] = Nijk(elemNodes,P,I,J);
}
//static void getTetJacDetNodes(int P, apf::NewArray<apf::Vector3>& elemNodes,
// apf::NewArray<double>& nodes)
//{
// for (int I = 0; I <= 3*(P-1); ++I)
// for (int J = 0; J <= 3*(P-1)-I; ++J)
// for (int K = 0; K <= 3*(P-1)-I-J; ++K)
// nodes[getTetNodeIndex(3*(P-1),I,J,K)] = Nijkl(elemNodes,P,I,J,K);
//}
/*
* This is the elevation version of this algorithm
* There is no recursion needed, at least not yet
*
*/
static void getJacDetByElevation(int type, int P,
apf::NewArray<double>& nodes, double& minJ, double& maxJ)
{
/*
* as a convergence check, use the max dist between points
*/
double maxDist[2] = {0.,1e10};
int n = getNumControlPoints(type,P);
minJ = calcMinJacDet(n,nodes);
maxJ = calcMaxJacDet(n,nodes);
maxDist[0] = nodes[1]-nodes[0];
for (int j = 1; j < n-1; ++j)
maxDist[0] = std::max(maxDist[0],nodes[j+1]-nodes[j]);
// declare these two arrays, never need to reallocate
apf::NewArray<double> elevatedNodes[2];
elevatedNodes[0].allocate(getNumControlPoints(type,maxElevationLevel));
elevatedNodes[1].allocate(getNumControlPoints(type,maxElevationLevel));
// copy for the start
for(int i = 0; i < n; ++i)
elevatedNodes[0][i] = nodes[i];
int i = 0;
while(P+i < maxElevationLevel && minJ/maxJ < minAcceptable
&& std::fabs(maxDist[(i+1) % 2] - maxDist[i % 2]) > convergenceTolerance){
// use the modulus to alternate between them,
// never needing to increase storage
// for now, only elevate by 1
elevateBezierJacobianDet(type,P+i,1,
elevatedNodes[i % 2],
elevatedNodes[(i+1) % 2]);
int ni = getNumControlPoints(type,P+i);
maxDist[(i+1) % 2] = elevatedNodes[(i+1) % 2][1]-elevatedNodes[(i+1) % 2][0];
for (int j = 1; j < ni-1; ++j)
maxDist[(i+1) % 2] = std::max(elevatedNodes[(i+1) % 2][j+1]
- elevatedNodes[(i+1) % 2][j],maxDist[(i+1) % 2]);
minJ = calcMinJacDet(ni,elevatedNodes[(i+1) % 2]);
maxJ = calcMaxJacDet(ni,elevatedNodes[(i+1) % 2]);
++i;
}
}
/*
* This is the subdivision version, with recursion
*
*/
static int numSplits[apf::Mesh::TYPES] =
{0,2,4,0,8,0,0,0};
static void getJacDetBySubdivision(int type, int P,
int iter, apf::NewArray<double>& nodes,
double& minJ, double& maxJ, bool& done)
{
int n = getNumControlPoints(type,P);
double change = minJ;
if(!done){
minJ = calcMinJacDet(n,nodes);
maxJ = calcMaxJacDet(n,nodes);
change = minJ - change;
}
if(!done && iter < maxAdaptiveIter && minJ/maxJ < minAcceptable
&& std::fabs(change) > convergenceTolerance){
iter++;
apf::NewArray<double> subNodes[8];
for (int i = 0; i < numSplits[type]; ++i)
subNodes[i].allocate(n);
subdivideBezierJacobianDet[type](P,nodes,subNodes);
apf::NewArray<double> newMinJ(numSplits[type]);
apf::NewArray<double> newMaxJ(numSplits[type]);
for (int i = 0; i < numSplits[type]; ++i){
newMinJ[i] = 1e10;
newMaxJ[i] = -1e10;
}
for (int i = 0; i < numSplits[type]; ++i)
getJacDetBySubdivision(type,P,iter,subNodes[i],
newMinJ[i],newMaxJ[i],done);
minJ = newMinJ[0];
maxJ = newMaxJ[0];
for (int i = 1; i < numSplits[type]; ++i){
minJ = std::min(newMinJ[i],minJ);
maxJ = std::max(newMaxJ[i],maxJ);
}
} else if (minJ/maxJ < minAcceptable){
done = true;
}
}
static void getJacDetBySubdivisionMatrices(int type, int P,
int iter, apf::NewArray<double>& c,apf::NewArray<double>& nodes,
double& minJ, double& maxJ, bool& done, bool& quality)
{
int n = getNumControlPoints(type,P);
double change = minJ;
if(!done){
minJ = calcMinJacDet(n,nodes);
maxJ = calcMaxJacDet(n,nodes);
change = minJ - change;
}
if(!done && iter < maxAdaptiveIter && (quality || minJ/maxJ < minAcceptable)
&& std::fabs(change) > convergenceTolerance){
iter++;
apf::NewArray<double> subNodes[8];
for (int i = 0; i < numSplits[type]; ++i)
subNodes[i].allocate(n);
subdivideBezierEntityJacobianDet(P,type,c,nodes,subNodes);
apf::NewArray<double> newMinJ(numSplits[type]);
apf::NewArray<double> newMaxJ(numSplits[type]);
for (int i = 0; i < numSplits[type]; ++i){
newMinJ[i] = 1e10;
newMaxJ[i] = -1e10;
}
for (int i = 0; i < numSplits[type]; ++i)
getJacDetBySubdivisionMatrices(type,P,iter,c,subNodes[i],
newMinJ[i],newMaxJ[i],done,quality);
minJ = newMinJ[0];
maxJ = newMaxJ[0];
for (int i = 1; i < numSplits[type]; ++i){
minJ = std::min(newMinJ[i],minJ);
maxJ = std::max(newMaxJ[i],maxJ);
}
} else if (minJ/maxJ < minAcceptable){
done = true;
}
}
int Quality2D::checkValidity(apf::MeshEntity* e)
{
apf::Element* elem = apf::createElement(mesh->getCoordinateField(),e);
apf::NewArray<apf::Vector3> elemNodes;
apf::getVectorNodes(elem,elemNodes);
// if we are blended, we need to create a full representation
if (blendingOrder > 0 &&
getNumInternalControlPoints(apf::Mesh::TRIANGLE,order)) {
getFullRepFromBlended(apf::Mesh::TRIANGLE,blendingCoeffs,elemNodes);
}
apf::destroyElement(elem);
apf::NewArray<double> nodes(order*(2*order-1));
// have to use this function because its for x-y plane, and
// the other method used in 3D does not work in those cases
getTriJacDetNodes(order,elemNodes,nodes);
// check vertices
apf::Downward verts;
mesh->getDownward(e,0,verts);
for (int i = 0; i < 3; ++i){
if(nodes[i] < minAcceptable){
return i+2;
}
}
apf::MeshEntity* edges[3];
mesh->getDownward(e,1,edges);
double minJ = 0, maxJ = 0;
// Vertices will already be flagged in the first check
for (int edge = 0; edge < 3; ++edge){
for (int i = 0; i < 2*(order-1)-1; ++i){
if (nodes[3+edge*(2*(order-1)-1)+i] < minAcceptable){
minJ = -1e10;
apf::NewArray<double> edgeNodes(2*(order-1)+1);
if(algorithm < 2){
edgeNodes[0] = nodes[apf::tri_edge_verts[edge][0]];
edgeNodes[2*(order-1)] = nodes[apf::tri_edge_verts[edge][1]];
for (int j = 0; j < 2*(order-1)-1; ++j)
edgeNodes[j+1] = nodes[3+edge*(2*(order-1)-1)+j];
if(algorithm == 1){
getJacDetByElevation(apf::Mesh::EDGE,2*(order-1),edgeNodes,minJ,maxJ);
} else {
// allows recursion stop on first "conclusive" invalidity
bool done = false;
getJacDetBySubdivision(apf::Mesh::EDGE,2*(order-1),
0,edgeNodes,minJ,maxJ,done);
}
} else {
edgeNodes[0] = nodes[apf::tri_edge_verts[edge][0]];
edgeNodes[1] = nodes[apf::tri_edge_verts[edge][1]];
for (int j = 0; j < 2*(order-1)-1; ++j)
edgeNodes[j+2] = nodes[3+edge*(2*(order-1)-1)+j];
bool done = false;
bool quality = false;
getJacDetBySubdivisionMatrices(apf::Mesh::EDGE,2*(order-1),
0,subdivisionCoeffs[1],edgeNodes,minJ,maxJ,done,quality);
}
if(minJ < minAcceptable){
return 8+edge;
}
}
}
}
bool done = false;
for (int i = 0; i < (2*order-3)*(2*order-4)/2; ++i){
if (nodes[6*(order-1)+i] < minAcceptable){
minJ = -1e10;
if(algorithm == 1)
getJacDetByElevation(apf::Mesh::TRIANGLE,2*(order-1),nodes,minJ,maxJ);
else if(algorithm == 2){
bool quality = false;
getJacDetBySubdivisionMatrices(apf::Mesh::TRIANGLE,2*(order-1),
0,subdivisionCoeffs[2],nodes,minJ,maxJ,done,quality);
} else {
getJacDetBySubdivision(apf::Mesh::TRIANGLE,2*(order-1),
0,nodes,minJ,maxJ,done);
}
if(minJ < minAcceptable){
return 14;
}
}
}
return 1;
}
int Quality3D::checkValidity(apf::MeshEntity* e)
{
apf::NewArray<double> nodes(n);
// apf::Element* elem = apf::createElement(mesh->getCoordinateField(),e);
// apf::NewArray<apf::Vector3> elemNodes;
// apf::getVectorNodes(elem,elemNodes);
// apf::destroyElement(elem);
// getTetJacDetNodes(order,elemNodes,nodes);
int validityTag = computeJacDetNodes(e,nodes,true);
if (validityTag > 1)
return validityTag;
// check verts
apf::Downward verts;
mesh->getDownward(e,0,verts);
for (int i = 0; i < 4; ++i){
if(nodes[i] < minAcceptable){
return 2+i;
}
}
apf::MeshEntity* edges[6];
mesh->getDownward(e,1,edges);
double minJ = 0, maxJ = 0;
// Vertices will already be flagged in the first check
for (int edge = 0; edge < 6; ++edge){
for (int i = 0; i < 3*(order-1)-1; ++i){
if (nodes[4+edge*(3*(order-1)-1)+i] < minAcceptable){
minJ = -1e10;
apf::NewArray<double> edgeNodes(3*(order-1)+1);
if(algorithm < 2){
edgeNodes[0] = nodes[apf::tet_edge_verts[edge][0]];
edgeNodes[3*(order-1)] = nodes[apf::tet_edge_verts[edge][1]];
for (int j = 0; j < 3*(order-1)-1; ++j)
edgeNodes[j+1] = nodes[4+edge*(3*(order-1)-1)+j];
// allows recursion stop on first "conclusive" invalidity
if(algorithm == 1)
getJacDetByElevation(apf::Mesh::EDGE,3*(order-1),
edgeNodes,minJ,maxJ);
else {
bool done = false;
getJacDetBySubdivision(apf::Mesh::EDGE,3*(order-1),
0,edgeNodes,minJ,maxJ,done);
}
} else {
edgeNodes[0] = nodes[apf::tet_edge_verts[edge][0]];
edgeNodes[1] = nodes[apf::tet_edge_verts[edge][1]];
for (int j = 0; j < 3*(order-1)-1; ++j)
edgeNodes[j+2] = nodes[4+edge*(3*(order-1)-1)+j];
bool done = false;
bool quality = false;
getJacDetBySubdivisionMatrices(apf::Mesh::EDGE,3*(order-1),
0,subdivisionCoeffs[1],edgeNodes,minJ,maxJ,done,quality);
}
if(minJ < minAcceptable){
return 8+edge;
}
}
}
}
apf::MeshEntity* faces[4];
mesh->getDownward(e,2,faces);
for (int face = 0; face < 4; ++face){
double minJ = -1e10;
for (int i = 0; i < (3*order-4)*(3*order-5)/2; ++i){
if (nodes[18*order-20+face*(3*order-4)*(3*order-5)/2+i] < minAcceptable){
minJ = -1e10;
apf::NewArray<double> triNodes((3*order-2)*(3*order-1)/2);
getTriDetJacNodesFromTetDetJacNodes(face,3*(order-1),nodes,triNodes);
if(algorithm == 2){
bool done = false;
bool quality = false;
getJacDetBySubdivisionMatrices(apf::Mesh::TRIANGLE,3*(order-1),
0,subdivisionCoeffs[2],triNodes,minJ,maxJ,done,quality);
} else if(algorithm == 1)
getJacDetByElevation(apf::Mesh::TRIANGLE,3*(order-1),
triNodes,minJ,maxJ);
else {
bool done = false;
getJacDetBySubdivision(apf::Mesh::TRIANGLE,3*(order-1),
0,triNodes,minJ,maxJ,done);
}
if(minJ < minAcceptable){
return 14+face;
}
}
}
}
for (int i = 0; i < (3*order-4)*(3*order-5)*(3*order-6)/6; ++i){
if (nodes[18*order*order-36*order+20+i] < minAcceptable){
minJ = -1e10;
if(algorithm == 1){
getJacDetByElevation(apf::Mesh::TET,3*(order-1),nodes,minJ,maxJ);
} else {
bool done = false;
bool quality = false;
getJacDetBySubdivisionMatrices(apf::Mesh::TET,3*(order-1),
0,subdivisionCoeffs[3],nodes,minJ,maxJ,done,quality);
}
if(minJ < minAcceptable){
return 20;
}
}
}
return 1;
}
double computeTriJacobianDetFromBezierFormulation(apf::Mesh* m,
apf::MeshEntity* e, apf::Vector3& xi)
{
double detJ = 0.;
int P = m->getShape()->getOrder();
apf::Element* elem = apf::createElement(m->getCoordinateField(),e);
apf::NewArray<apf::Vector3> nodes;
apf::getVectorNodes(elem,nodes);
for (int I = 0; I <= 2*(P-1); ++I){
for (int J = 0; J <= 2*(P-1)-I; ++J){
detJ += trinomial(2*(P-1),I,J)
*Bijk(I,J,2*(P-1)-I-J,1.-xi[0]-xi[1],xi[0],xi[1])
*Nijk(nodes,P,I,J);
}
}
apf::destroyElement(elem);
return detJ;
}
double computeTetJacobianDetFromBezierFormulation(apf::Mesh* m,
apf::MeshEntity* e, apf::Vector3& xi)
{
int P = m->getShape()->getOrder();
apf::Element* elem = apf::createElement(m->getCoordinateField(),e);
apf::NewArray<apf::Vector3> nodes;
apf::getVectorNodes(elem,nodes);
double detJ = 0.;
for (int I = 0; I <= 3*(P-1); ++I){
for (int J = 0; J <= 3*(P-1)-I; ++J){
for (int K = 0; K <= 3*(P-1)-I-J; ++K){
detJ += quadnomial(3*(P-1),I,J,K)*Bijkl(I,J,K,3*(P-1)-I-J-K,
1.-xi[0]-xi[1]-xi[2],xi[0],xi[1],xi[2])
*Nijkl(nodes,P,I,J,K);
}
}
}
apf::destroyElement(elem);
return detJ;
}
int Quality3D::computeJacDetNodes(apf::MeshEntity* e,
apf::NewArray<double>& nodes, bool validity)
{
apf::NewArray<double> interNodes(n);
apf::MeshElement* me = apf::createMeshElement(mesh,e);
if (validity == false)
{
for (int i = 0; i < n; ++i){
interNodes[i] = apf::getDV(me,xi[i]);
}
}
for (int i = 0; i < 4; ++i){
interNodes[i] = apf::getDV(me,xi[i]);
if(interNodes[i] < 1e-10){
apf::destroyMeshElement(me);
return i+2;
}
}
for (int edge = 0; edge < 6; ++edge){
for (int i = 0; i < 3*(order-1)-1; ++i){
int index = 4+edge*(3*(order-1)-1)+i;
interNodes[index] = apf::getDV(me,xi[index]);
if(interNodes[index] < 1e-10){
apf::destroyMeshElement(me);
return edge+8;
}
}
}
for (int face = 0; face < 4; ++face){
for (int i = 0; i < (3*order-4)*(3*order-5)/2; ++i){
int index = 18*order-20+face*(3*order-4)*(3*order-5)/2+i;
interNodes[index] = apf::getDV(me,xi[index]);
if(interNodes[index] < 1e-10){
apf::destroyMeshElement(me);
return face+14;
}
}
}
for (int i = 0; i < (3*order-4)*(3*order-5)*(3*order-6)/6; ++i){
int index = 18*order*order-36*order+20+i;
interNodes[index] = apf::getDV(me,xi[index]);
if(interNodes[index] < 1e-10){
apf::destroyMeshElement(me);
return 20;
}
}
apf::destroyMeshElement(me);
for( int i = 0; i < n; ++i){
nodes[i] = 0.;
for( int j = 0; j < n; ++j)
nodes[i] += interNodes[j]*transformationMatrix(i,j);
}
return 1;
}
double Quality2D::getQuality(apf::MeshEntity* e)
{
apf::Element* elem = apf::createElement(mesh->getCoordinateField(),e);
apf::NewArray<apf::Vector3> elemNodes;
apf::getVectorNodes(elem,elemNodes);
if(blendingOrder > 0
&& mesh->getShape()->hasNodesIn(2)){
getFullRepFromBlended(apf::Mesh::TRIANGLE,blendingCoeffs,elemNodes);
}
apf::destroyElement(elem);
apf::NewArray<double> nodes(n);
getTriJacDetNodes(order,elemNodes,nodes);
bool done = false;
double minJ = -1e10, maxJ = -1e10;
double oldAcceptable = minAcceptable;
int oldIter = maxAdaptiveIter;
maxAdaptiveIter = 1;
minAcceptable = -1e10;
bool quality = true;
getJacDetBySubdivisionMatrices(apf::Mesh::TRIANGLE,2*(order-1),
0,subdivisionCoeffs[2],nodes,minJ,maxJ,done,quality);
done = false;
minAcceptable = oldAcceptable;
maxAdaptiveIter = oldIter;
if(std::fabs(maxJ) > 1e-8)
return minJ/maxJ;
else return minJ;
}
double Quality3D::getQuality(apf::MeshEntity* e)
{
// this is the old way of computing things, don't do it anymore
// apf::Element* elem = apf::createElement(mesh->getCoordinateField(),e);
//
// apf::NewArray<apf::Vector3> elemNodes;
// apf::getVectorNodes(elem,elemNodes);
//
// if(blendingOrder > 0
// && mesh->getShape()->hasNodesIn(mesh->getDimension())){
// getFullRepFromBlended(type,blendingCoeffs,elemNodes);
// }
// apf::destroyElement(elem);
// getTetJacDetNodes(order,elemNodes,nodes);
apf::NewArray<double> nodes(n);
/* This part is optional, if we use the validity tag,
* we can decide the entity is invalid, and just return some
* negative number. While not a true assessment of quality,
* this is enough to convince swapping/coarsening to give up
* on the configuration its looking at, which is good.
* There is some downside to this, I'm sure.
*/
int validityTag =
computeJacDetNodes(e,nodes,false);
if (validityTag > 1)
return -1e-10;
bool done = false;
double minJ = -1e10, maxJ = -1e10;
double oldAcceptable = minAcceptable;
int oldIter = maxAdaptiveIter;
maxAdaptiveIter = 1; // just do one interation, thats enough
minAcceptable = -1e10;
bool quality = true;
getJacDetBySubdivisionMatrices(apf::Mesh::TET,3*(order-1),
0,subdivisionCoeffs[3],nodes,minJ,maxJ,done,quality);
done = false;
minAcceptable = oldAcceptable;
maxAdaptiveIter = oldIter;
if(std::fabs(maxJ) > 1e-8)
return minJ/maxJ;
else return minJ;
}
int checkValidity(apf::Mesh* m, apf::MeshEntity* e,
int algorithm)
{
Quality* qual = makeQuality(m,algorithm);
int validity = qual->checkValidity(e);
delete qual;
return validity;
}
double getQuality(apf::Mesh* m, apf::MeshEntity* e)
{
Quality* qual = makeQuality(m,2);
double quality = qual->getQuality(e);
delete qual;
return quality;
}
}
| 31.468305 | 82 | 0.61073 | cwsmith |
041313275ba2334ac0cbe059dc09eb138a69087e | 1,623 | cpp | C++ | Game/Source/Game/src/MY_ResourceManager.cpp | PureBread/Game | 957dd9f9450f0576ec5cc73c13525f5f47a9c4c9 | [
"MIT"
] | null | null | null | Game/Source/Game/src/MY_ResourceManager.cpp | PureBread/Game | 957dd9f9450f0576ec5cc73c13525f5f47a9c4c9 | [
"MIT"
] | 67 | 2015-10-14T12:15:52.000Z | 2021-08-06T07:20:42.000Z | Game/Source/Game/src/MY_ResourceManager.cpp | PureBread/Game | 957dd9f9450f0576ec5cc73c13525f5f47a9c4c9 | [
"MIT"
] | null | null | null | #pragma once
#include <MY_ResourceManager.h>
Scenario * MY_ResourceManager::scenario = nullptr;
std::vector<Scenario *> MY_ResourceManager::randomEvents;
std::vector<Scenario *> MY_ResourceManager::lossEvents;
std::vector<Scenario *> MY_ResourceManager::destinationEvents;
void MY_ResourceManager::init(){
Json::Value root;
Json::Reader reader;
std::string jsonLoaded = FileUtils::readFile("assets/events/scenarioListing.json");
bool parsingSuccessful = reader.parse( jsonLoaded, root );
if(!parsingSuccessful){
Log::error("JSON parse failed: " + reader.getFormattedErrorMessages()/* + "\n" + jsonLoaded*/);
}else{
Json::Value randomEventsJson = root["randomEvents"];
for(Json::Value::ArrayIndex i = 0; i < randomEventsJson.size(); ++i) {
Scenario * s = new Scenario("assets/events/random/" + randomEventsJson[i].asString() + ".json");
randomEvents.push_back(s);
resources.push_back(s);
}
Json::Value lossEventsJson = root["lossEvents"];
for(Json::Value::ArrayIndex i = 0; i < lossEventsJson.size(); ++i) {
Scenario * s = new Scenario("assets/events/loss/" + lossEventsJson[i].asString() + ".json");
lossEvents.push_back(s);
resources.push_back(s);
}
Json::Value destinationEventsJson = root["destinationEvents"];
for(Json::Value::ArrayIndex i = 0; i < destinationEventsJson.size(); ++i) {
Scenario * s = new Scenario("assets/events/destination/" + destinationEventsJson[i].asString() + ".json");
destinationEvents.push_back(s);
resources.push_back(s);
}
}
scenario = new Scenario("assets/scenarioGlobal.json");
resources.push_back(scenario);
} | 39.585366 | 110 | 0.707948 | PureBread |
041365df87c48879c21861554c04f58cc97b0376 | 2,722 | cpp | C++ | ZOJ/4102/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | ZOJ/4102/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | ZOJ/4102/greedy.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 100010
#define DIGIT_SIZE 10
int arr[SIZE], orig[SIZE], ava[SIZE];
int ans[SIZE], ansPt;
bool lazy[SIZE];
priority_queue<pair<int, int> > pq;
set<int> avaList;
void updatePq() {
int cntPt = pq.top().second;
pq.pop();
if (ava[cntPt] > 0)
pq.push(make_pair(ava[cntPt] + orig[cntPt], cntPt));
lazy[cntPt] = false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int caseNum;
cin >> caseNum;
while (caseNum--) {
memset(orig, 0, sizeof(orig));
memset(ava, 0, sizeof(ava));
memset(lazy, false, sizeof(lazy));
avaList.clear();
pq = priority_queue<pair<int, int> >();
int len;
cin >> len;
for (int i = 0; i < len; i++) {
cin >> arr[i]; arr[i]--;
orig[arr[i]]++; ava[arr[i]]++;
}
for (int i = 0; i < len; i++) {
if (ava[arr[i]] > 0) {
pq.push(make_pair(orig[i] + ava[i], i));
avaList.insert(i);
}
}
bool hasAns = true; int ansPt = 0;
for (int i = 0; i < len; i++) {
while (!pq.empty() && lazy[pq.top().second])
updatePq();
if (pq.empty() || pq.top().first > len - i) {
hasAns = false;
break;
}
int dangPt = pq.top().second, dangSum = pq.top().first;
if (dangSum == len - i && dangPt != arr[i]) {
// Can't decrease orig(dangPt), must decrease ava(dangPt)
ans[ansPt++] = dangPt;
ava[dangPt]--; lazy[dangPt] = true;
orig[arr[i]]--; lazy[arr[i]] = true;
} else {
// Select smallest available
auto it = avaList.begin();
while (it != avaList.end()) {
if (ava[*it] == 0) {
++it;
avaList.erase(prev(it));
} else if (*it == arr[i]) {
++it;
} else {
break;
}
}
if (it == avaList.end()) {
hasAns = false;
break;
}
ans[ansPt++] = *it;
ava[*it]--; lazy[*it] = true;
orig[arr[i]]--; lazy[arr[i]] = true;
}
}
if (hasAns) {
cout << ans[0] + 1;
for (int i = 1; i < ansPt; i++)
cout << " " << ans[i] + 1;
cout << '\n';
} else {
cout << "Impossible\n";
}
}
return 0;
} | 27.22 | 73 | 0.3964 | codgician |
04161e31d1c66952000bf55e21753351563b674b | 96 | hpp | C++ | src/scenes/scenes.hpp | seanbutler/engine | 7fa38f43f61c97fc1df28f3a666d90628b699e91 | [
"MIT"
] | null | null | null | src/scenes/scenes.hpp | seanbutler/engine | 7fa38f43f61c97fc1df28f3a666d90628b699e91 | [
"MIT"
] | null | null | null | src/scenes/scenes.hpp | seanbutler/engine | 7fa38f43f61c97fc1df28f3a666d90628b699e91 | [
"MIT"
] | null | null | null | #pragma once
#include "./mainmenu.hpp"
#include "./splashscene.hpp"
#include "./testscene.hpp"
| 16 | 28 | 0.708333 | seanbutler |
041771075e4012550ddbdc91e23f392324821fbd | 595 | hpp | C++ | Engine/Src/Ancona/Platformer/Actions/ScaleAction.hpp | ild-games/Ancona | 6a4f520f97d17648a6dd3ba0582cd51da4f9e809 | [
"MIT"
] | 11 | 2018-04-15T21:00:48.000Z | 2021-12-30T20:55:21.000Z | Engine/Src/Ancona/Platformer/Actions/ScaleAction.hpp | tlein/Ancona | 6a4f520f97d17648a6dd3ba0582cd51da4f9e809 | [
"MIT"
] | 58 | 2016-04-17T20:41:25.000Z | 2017-02-27T01:21:46.000Z | Engine/Src/Ancona/Platformer/Actions/ScaleAction.hpp | ild-games/Ancona | 6a4f520f97d17648a6dd3ba0582cd51da4f9e809 | [
"MIT"
] | 4 | 2018-05-04T17:03:20.000Z | 2021-02-12T21:26:57.000Z | #ifndef Ancona_Platformer_Action_ScaleAction_hpp
#define Ancona_Platformer_Action_ScaleAction_hpp
#include <SFML/System.hpp>
#include "ValueAction.hpp"
namespace ild
{
template<typename T>
class ScaleAction : public ValueAction<T>
{
public:
ScaleAction(std::string drawableKey = "") : _drawableKey(drawableKey)
{
}
/* getters and setters */
std::string drawableKey() { return _drawableKey; }
void drawableKey(std::string newDrawableKey) { _drawableKey = newDrawableKey; }
private:
std::string _drawableKey = "";
};
}
#endif
| 20.517241 | 87 | 0.685714 | ild-games |
04183465a7a336ec50ded1424e177fd3453cf548 | 8,982 | cpp | C++ | Base/src/cts/UserCmd.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | Base/src/cts/UserCmd.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | Base/src/cts/UserCmd.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name :
// Author : Avi
// Revision : $Revision: #65 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <stdexcept>
#include <iostream>
#include <cstdio> /* tolower */
#include "ClientToServerCmd.hpp"
#include "AbstractServer.hpp"
#include "AbstractClientEnv.hpp"
#include "Str.hpp"
#include "User.hpp"
using namespace std;
using namespace boost;
using namespace ecf;
bool UserCmd::equals(ClientToServerCmd* rhs) const
{
auto* the_rhs = dynamic_cast< UserCmd* > ( rhs );
if ( !the_rhs ) return false;
if (user_ != the_rhs->user()) return false;
return ClientToServerCmd::equals(rhs);
}
bool UserCmd::authenticate(AbstractServer* as, STC_Cmd_ptr& cmd) const
{
// The user should NOT be empty. Rather than asserting and killing the server, fail authentication
// ECFLOW-577 and ECFLOW-512. When user_ empty ??
if (!user_.empty() && as->authenticateReadAccess(user_,cu_,pswd_)) {
// Does this user command require write access
if ( isWrite() ) {
// command requires write access. Check user has write access
if ( as->authenticateWriteAccess(user_) ) {
return true;
}
std::string msg = "[ authentication failed ] User ";
msg += user_;
msg += " has no *write* access. Please see your administrator.";
throw std::runtime_error( msg );
}
else {
// read request, and we have read access
return true;
}
}
std::string msg = "[ authentication failed ] User '";
msg += user_;
msg += "' is not allowed any access.";
throw std::runtime_error( msg );
return false;
}
bool UserCmd::do_authenticate(AbstractServer* as, STC_Cmd_ptr&, const std::string& path) const
{
if (!user_.empty() && as->authenticateReadAccess(user_,cu_,pswd_,path)) {
// Does this user command require write access
if ( isWrite() ) {
// command requires write access. Check user has write access, add access to suite/node/path
if ( as->authenticateWriteAccess(user_,path) ) {
return true;
}
std::string msg = "[ authentication failed ] User ";
msg += user_;
msg += " has no *write* access. path(";msg += path; msg += ")Please see your administrator.";
throw std::runtime_error( msg );
}
else {
// read request, and we have read access
return true;
}
}
std::string msg = "[ authentication failed ] User '";
msg += user_;
msg += "' is not allowed any access. path(";
msg += path;
msg += ")";
throw std::runtime_error( msg );
return false;
}
bool UserCmd::do_authenticate(AbstractServer* as, STC_Cmd_ptr&, const std::vector<std::string>& paths) const
{
if (!user_.empty() && as->authenticateReadAccess(user_,cu_,pswd_,paths)) {
// Does this user command require write access
if ( isWrite() ) {
// command requires write access. Check user has write access
if ( as->authenticateWriteAccess(user_,paths) ) {
return true;
}
std::string msg = "[ authentication failed ] User ";
msg += user_;
msg += " has no *write* access to paths(";
for(const auto & path : paths) { msg += path;msg += ",";}
msg += ") Please see your administrator.";
throw std::runtime_error( msg );
}
else {
// read request, and we have read access
return true;
}
}
std::string msg = "[ authentication failed ] User '";
msg += user_;
msg += "' is not allowed any access. paths(";
for(const auto & path : paths) { msg += path;msg += ",";}
msg += ")";
throw std::runtime_error( msg );
return false;
}
void UserCmd::setup_user_authentification(const std::string& user, const std::string& passwd)
{
user_ = user;
pswd_ = passwd; // assumes this has been crypted()
assert(!hostname().empty());
assert(!user_.empty());
}
bool UserCmd::setup_user_authentification(AbstractClientEnv& clientEnv)
{
// A Custom user is one where:
// o/ ECF_USER environment used
// o/ --user on the command line
// o/ ClientInvoker::set_user_name()
// Having a custom user name is an exception, to avoid having ALL user to provide a password
// we have a CUSTOM password file ECF_CUSTOM_PASSWD, <host>.<port>.ecf.custom_passwd
const std::string& user_name = clientEnv.get_user_name(); // Using ECF_USER || --user <user> || set_user_name()/GUI
if (!user_name.empty()) {
cu_ = true; // inform server side custom USER used, server will expect password in ECF_CUSTOM_PASSWD files
const std::string& passwd = clientEnv.get_custom_user_password(user_name);
if (passwd.empty()) {
// cout << "invalid user as password is empty, must have a password when user specified \n";
return false; // invalid user as password is empty, must have a password when user specified
}
setup_user_authentification(user_name,passwd);
return true;
}
// User name is same as login name, if ECF_PASSWD is defined on server side *ALL* user must provide a password.
std::string the_user = User::login_name();
const std::string& passwd = clientEnv.get_user_password( the_user );
setup_user_authentification(the_user,passwd);
return true;
}
void UserCmd::setup_user_authentification()
{
if (user_.empty()) {
setup_user_authentification(User::login_name(),Str::EMPTY());
}
}
void UserCmd::prompt_for_confirmation(const std::string& prompt)
{
cout << prompt;
char reply[256];
cin.getline (reply,256);
if (reply[0] != 'y' && reply[0] != 'Y') {
exit(1);
}
}
void UserCmd::user_cmd(std::string& os, const std::string& the_cmd) const
{
os += the_cmd;
os += " :";
os += user_;
os += '@';
os += hostname();
}
//#define DEBUG_ME 1
void UserCmd::split_args_to_options_and_paths(
const std::vector<std::string>& args,
std::vector<std::string>& options,
std::vector<std::string>& paths,
bool treat_colon_in_path_as_path)
{
// ** ECFLOW-137 **, if the trigger expression have a leading '/' then it gets parsed into the paths
// vector and not options
// This is because boost program options does *NOT* seem to preserve the leading quotes around the
// trigger/complete expression, i.e "/suite/t2 == complete" is read as /suite/t2 == complete
// However in paths we do not expect to see any spaces
// Note: Node names are not allowed ':', hence ':' in a node path is always to reference a node attribute, event,limit in this case
// However we need to deal with special situations:
// o --alter add inlimit /path/to/node/withlimit:limit_name 10 /s1 # TREAT /path/to/node/withlimit:limit_name as a OPTION
// o --change trigger "/suite/task:a" /path/to/a/node # TREAT "/suite/task:a" as a OPTION
// o --force=clear /suite/task:ev # TREAT /suite/task:ev as a PATH
// We need to distinguish between the two, hence use treat_colon_in_path_as_path
size_t vec_size = args.size();
if (treat_colon_in_path_as_path ) {
for(size_t i = 0; i < vec_size; i++) {
if (args[i].empty()) continue;
if (args[i][0] == '/' && args[i].find(" ") == std::string::npos) {
// --force=clear /suite/task:ev -> treat '/suite/task:ev' as a path
paths.push_back(args[i]);
}
else {
options.push_back(args[i]);
}
}
}
else {
// Treat ':' is path as a option, TREAT '/path/to/node/withlimit:limit_name' as a option
for(size_t i = 0; i < vec_size; i++) {
if (args[i].empty()) continue;
if (args[i][0] == '/' && args[i].find(" ") == std::string::npos && args[i].find(":") == std::string::npos) {
paths.push_back(args[i]);
}
else {
options.push_back(args[i]);
}
}
}
#ifdef DEBUG_ME
std::cout << "split_args_to_options_and_paths\n";
for(size_t i = 0; i < args.size(); ++i) { std::cout << "args[" << i << "]=" <<args[i] << "\n"; }
for(size_t i = 0; i < options.size(); ++i) { std::cout << "options[" << i << "]=" << options[i] << "\n"; }
for(size_t i = 0; i < paths.size(); ++i) { std::cout << "paths[" << i << "]=" << paths[i] << "\n"; }
#endif
}
int UserCmd::time_out_for_load_sync_and_get() { return 600; }
| 35.928 | 134 | 0.60599 | mpartio |